Merge branch 'main' into slorber/defer-poc

This commit is contained in:
Joshua Chen 2022-04-08 14:46:29 +08:00
commit 0423acf493
No known key found for this signature in database
GPG Key ID: C37145B818BDB68F
1407 changed files with 65226 additions and 43921 deletions

View File

@ -21,16 +21,17 @@
],
"ignorePaths": [
"CHANGELOG.md",
"examples",
"packages/docusaurus-theme-translations/locales",
"__tests__",
"package.json",
"yarn.lock",
"project-words.txt",
"__snapshots__",
"website/src/data/users.tsx",
"website/src/data/tweets.tsx",
"*.xyz",
"*.docx",
"versioned_docs"
"versioned_docs",
"*.min.*"
],
"ignoreRegExpList": ["Email", "Urls", "#[\\w-]*"]
}

View File

@ -1,10 +1,33 @@
{
"name": "Docusaurus Dev Container",
"image": "mcr.microsoft.com/vscode/devcontainers/typescript-node:14-buster",
"image": "mcr.microsoft.com/vscode/devcontainers/base:ubuntu-20.04",
"settings": {
"terminal.integrated.shell.linux": "/bin/bash"
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}
},
"extensions": ["dbaeumer.vscode-eslint", "orta.vscode-jest"],
"extensions": [
"dbaeumer.vscode-eslint",
"orta.vscode-jest",
"esbenp.prettier-vscode",
"streetsidesoftware.code-spell-checker"
],
"forwardPorts": [3000],
"postCreateCommand": "yarn install"
"containerUser": "vscode",
"postCreateCommand": "yarn install",
"waitFor": "postCreateCommand", // otherwise automated jest tests fail
"features": {
"node": {
"version": "14"
},
"github-cli": "latest"
}
}

View File

@ -16,4 +16,6 @@ packages/stylelint-copyright/lib/
copyUntypedFiles.mjs
packages/create-docusaurus/lib/*
packages/create-docusaurus/templates/facebook/.eslintrc.js
packages/create-docusaurus/templates/facebook
website/_dogfooding/_swizzle_theme_tests

View File

@ -22,15 +22,15 @@ module.exports = {
allowImportExportEverywhere: true,
},
globals: {
testStylelintRule: true,
JSX: true,
},
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
'plugin:jest/recommended',
'airbnb',
'plugin:@typescript-eslint/recommended',
'plugin:regexp/recommended',
'prettier',
],
settings: {
@ -41,21 +41,149 @@ module.exports = {
},
},
reportUnusedDisableDirectives: true,
plugins: ['react-hooks', 'header', 'jest'],
plugins: ['react-hooks', 'header', 'jest', '@typescript-eslint', 'regexp'],
rules: {
'react-hooks/rules-of-hooks': ERROR,
'react-hooks/exhaustive-deps': ERROR,
'array-callback-return': WARNING,
camelcase: WARNING,
'class-methods-use-this': OFF, // It's a way of allowing private variables.
'func-names': OFF,
// Ignore certain webpack alias because it can't be resolved
'import/no-unresolved': [
ERROR,
curly: [WARNING, 'all'],
'global-require': WARNING,
'lines-between-class-members': OFF,
'max-classes-per-file': OFF,
'max-len': [
WARNING,
{
ignore: ['^@theme', '^@docusaurus', '^@generated', '^@site'],
code: Infinity, // Code width is already enforced by Prettier
tabWidth: 2,
comments: 80,
ignoreUrls: true,
ignorePattern: '(eslint-disable|@)',
},
],
'import/extensions': OFF,
'no-await-in-loop': OFF,
'no-case-declarations': WARNING,
'no-console': OFF,
'no-continue': OFF,
'no-control-regex': WARNING,
'no-else-return': [WARNING, {allowElseIf: true}],
'no-empty': [WARNING, {allowEmptyCatch: true}],
'no-lonely-if': WARNING,
'no-nested-ternary': WARNING,
'no-param-reassign': [WARNING, {props: false}],
'no-prototype-builtins': WARNING,
'no-restricted-exports': OFF,
'no-restricted-properties': [
ERROR,
...[
// TODO: TS doesn't make Boolean a narrowing function yet,
// so filter(Boolean) is problematic type-wise
// ['compact', 'Array#filter(Boolean)'],
['concat', 'Array#concat'],
['drop', 'Array#slice(n)'],
['dropRight', 'Array#slice(0, -n)'],
['fill', 'Array#fill'],
['filter', 'Array#filter'],
['find', 'Array#find'],
['findIndex', 'Array#findIndex'],
['first', 'foo[0]'],
['flatten', 'Array#flat'],
['flattenDeep', 'Array#flat(Infinity)'],
['flatMap', 'Array#flatMap'],
['fromPairs', 'Object.fromEntries'],
['head', 'foo[0]'],
['indexOf', 'Array#indexOf'],
['initial', 'Array#slice(0, -1)'],
['join', 'Array#join'],
// Unfortunately there's no great alternative to _.last yet
// Candidates: foo.slice(-1)[0]; foo[foo.length - 1]
// Array#at is ES2022; could replace _.nth as well
// ['last'],
['map', 'Array#map'],
['reduce', 'Array#reduce'],
['reverse', 'Array#reverse'],
['slice', 'Array#slice'],
['take', 'Array#slice(0, n)'],
['takeRight', 'Array#slice(-n)'],
['tail', 'Array#slice(1)'],
].map(([property, alternative]) => ({
object: '_',
property,
message: `Use ${alternative} instead.`,
})),
...[
'readdirSync',
'readFileSync',
'statSync',
'lstatSync',
'existsSync',
'pathExistsSync',
'realpathSync',
'mkdirSync',
'mkdirpSync',
'mkdirsSync',
'writeFileSync',
'writeJsonSync',
'outputFileSync',
'outputJsonSync',
'moveSync',
'copySync',
'copyFileSync',
'ensureFileSync',
'ensureDirSync',
'ensureLinkSync',
'ensureSymlinkSync',
'unlinkSync',
'removeSync',
'emptyDirSync',
].map((property) => ({
object: 'fs',
property,
message: 'Do not use sync fs methods.',
})),
],
'no-restricted-syntax': [
WARNING,
// Copied from airbnb, removed for...of statement, added export all
{
selector: 'ForInStatement',
message:
'for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.',
},
{
selector: 'LabeledStatement',
message:
'Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand.',
},
{
selector: 'WithStatement',
message:
'`with` is disallowed in strict mode because it makes code impossible to predict and optimize.',
},
{
selector: 'ExportAllDeclaration',
message:
"Export all does't work well if imported in ESM due to how they are transpiled, and they can also lead to unexpected exposure of internal methods.",
},
// TODO make an internal plugin to ensure this
// {
// selector:
// @ 'ExportDefaultDeclaration > Identifier, ExportNamedDeclaration[source=null] > ExportSpecifier',
// message: 'Export in one statement'
// },
...['path', 'fs-extra', 'webpack', 'lodash'].map((m) => ({
selector: `ImportDeclaration[importKind=value]:has(Literal[value=${m}]) > ImportSpecifier[importKind=value]`,
message:
'Default-import this, both for readability and interoperability with ESM',
})),
],
'no-template-curly-in-string': WARNING,
'no-unused-expressions': [WARNING, {allowTaggedTemplates: true}],
'no-useless-escape': WARNING,
'prefer-destructuring': WARNING,
'prefer-named-capture-group': WARNING,
'prefer-template': WARNING,
yoda: WARNING,
'header/header': [
ERROR,
'block',
@ -68,21 +196,58 @@ module.exports = {
' ',
],
],
'import/extensions': OFF,
// Ignore certain webpack aliases because they can't be resolved
'import/no-unresolved': [
ERROR,
{
ignore: [
'^@theme',
'^@docusaurus',
'^@generated',
'^@site',
'^@testing-utils',
],
},
],
'import/order': OFF,
'import/prefer-default-export': OFF,
'jest/consistent-test-it': WARNING,
'jest/expect-expect': OFF,
'jest/no-large-snapshots': [
WARNING,
{maxSize: Infinity, inlineMaxSize: 10},
],
'jest/no-test-return-statement': ERROR,
'jest/prefer-expect-resolves': WARNING,
'jest/prefer-lowercase-title': [WARNING, {ignore: ['describe']}],
'jest/prefer-spy-on': WARNING,
'jest/prefer-to-be': WARNING,
'jest/prefer-to-have-length': WARNING,
'jest/require-top-level-describe': ERROR,
'jest/valid-title': [
ERROR,
{
mustNotMatch: {
it: [
'^should|\\.$',
'Titles should not begin with "should" or end with a full-stop',
],
},
},
],
'jsx-a11y/click-events-have-key-events': WARNING,
'jsx-a11y/no-noninteractive-element-interactions': WARNING,
'jsx-a11y/html-has-lang': OFF,
'no-console': OFF,
'no-else-return': OFF,
'no-param-reassign': [WARNING, {props: false}],
'no-underscore-dangle': OFF,
curly: [WARNING, 'all'],
'react/jsx-filename-extension': OFF,
'react/no-array-index-key': OFF, // Sometimes its ok, e.g. non-changing data.
'react/prop-types': OFF,
'react/destructuring-assignment': OFF, // Too many lines.
'react/prefer-stateless-function': WARNING,
'react/jsx-props-no-spreading': OFF,
'react/require-default-props': [ERROR, {ignoreFunctionalComponents: true}],
'react-hooks/rules-of-hooks': ERROR,
'react-hooks/exhaustive-deps': ERROR,
// Sometimes we do need the props as a whole, e.g. when spreading
'react/destructuring-assignment': OFF,
'react/function-component-definition': [
WARNING,
{
@ -90,96 +255,62 @@ module.exports = {
unnamedComponents: 'arrow-function',
},
],
'react/jsx-filename-extension': OFF,
'react/jsx-key': [ERROR, {checkFragmentShorthand: true}],
'react/jsx-no-useless-fragment': [ERROR, {allowExpressions: true}],
'react/jsx-props-no-spreading': OFF,
'react/no-array-index-key': OFF, // We build a static site, and nearly all components don't change.
'react/no-unstable-nested-components': [WARNING, {allowAsProps: true}],
'@typescript-eslint/no-inferrable-types': OFF,
'@typescript-eslint/consistent-type-imports': [
WARNING,
{disallowTypeAnnotations: false},
],
'import/order': OFF,
'import/prefer-default-export': OFF,
'lines-between-class-members': OFF,
'no-lonely-if': WARNING,
'no-use-before-define': OFF,
'@typescript-eslint/no-use-before-define': [
ERROR,
{functions: false, classes: false, variables: true},
],
'no-unused-vars': OFF,
'no-nested-ternary': WARNING,
'@typescript-eslint/no-empty-function': OFF,
'@typescript-eslint/no-non-null-assertion': OFF,
'@typescript-eslint/no-unused-vars': [
ERROR,
{argsIgnorePattern: '^_', ignoreRestSiblings: true},
],
'@typescript-eslint/explicit-module-boundary-types': WARNING,
'react/prefer-stateless-function': WARNING,
'react/prop-types': OFF,
'react/require-default-props': [ERROR, {ignoreFunctionalComponents: true}],
'@typescript-eslint/ban-ts-comment': [
ERROR,
{'ts-expect-error': 'allow-with-description'},
],
'import/no-extraneous-dependencies': ERROR,
'no-useless-escape': WARNING,
'prefer-template': WARNING,
'no-template-curly-in-string': WARNING,
'array-callback-return': WARNING,
camelcase: WARNING,
'no-restricted-syntax': WARNING,
'no-unused-expressions': [WARNING, {allowTaggedTemplates: true}],
'global-require': WARNING,
'prefer-destructuring': WARNING,
yoda: WARNING,
'no-await-in-loop': OFF,
'no-control-regex': WARNING,
'no-empty': [WARNING, {allowEmptyCatch: true}],
'no-prototype-builtins': WARNING,
'no-case-declarations': WARNING,
'no-undef': OFF,
'no-shadow': OFF,
'@typescript-eslint/no-shadow': ERROR,
'no-redeclare': OFF,
'@typescript-eslint/no-redeclare': ERROR,
'@typescript-eslint/consistent-indexed-object-style': [
WARNING,
'index-signature',
],
'@typescript-eslint/consistent-type-imports': [
WARNING,
{disallowTypeAnnotations: false},
],
'@typescript-eslint/explicit-module-boundary-types': WARNING,
'@typescript-eslint/method-signature-style': ERROR,
'@typescript-eslint/no-empty-function': OFF,
'@typescript-eslint/no-empty-interface': [
ERROR,
{
allowSingleExtends: true,
},
],
'@typescript-eslint/method-signature-style': ERROR,
'no-restricted-imports': [
'@typescript-eslint/no-inferrable-types': OFF,
'@typescript-eslint/no-namespace': [WARNING, {allowDeclarations: true}],
'no-use-before-define': OFF,
'@typescript-eslint/no-use-before-define': [
ERROR,
{
paths: [
{
name: 'lodash',
importNames: [
// 'compact', // TODO: TS doesn't make Boolean a narrowing function yet, so filter(Boolean) is problematic type-wise
'filter',
'flatten',
'flatMap',
'map',
'reduce',
'take',
'takeRight',
'head',
'tail',
'initial',
],
message: 'These APIs have their ES counterparts.',
},
],
},
{functions: false, classes: false, variables: true},
],
'jest/prefer-expect-resolves': WARNING,
'jest/expect-expect': OFF,
'jest/valid-title': OFF,
'@typescript-eslint/no-non-null-assertion': OFF,
'no-redeclare': OFF,
'@typescript-eslint/no-redeclare': ERROR,
'no-shadow': OFF,
'@typescript-eslint/no-shadow': ERROR,
'no-unused-vars': OFF,
// We don't provide any escape hatches for this rule. Rest siblings and
// function placeholder params are always ignored, and any other unused
// locals must be justified with a disable comment.
'@typescript-eslint/no-unused-vars': [ERROR, {ignoreRestSiblings: true}],
'@typescript-eslint/prefer-optional-chain': ERROR,
},
overrides: [
{
files: [
'packages/docusaurus-theme-*/src/theme/**/*.js',
'packages/docusaurus-theme-*/src/theme/**/*.ts',
'packages/docusaurus-theme-*/src/theme/**/*.tsx',
'packages/docusaurus-*/src/theme/**/*.js',
'packages/docusaurus-*/src/theme/**/*.ts',
'packages/docusaurus-*/src/theme/**/*.tsx',
],
rules: {
'import/no-named-export': ERROR,
@ -206,6 +337,7 @@ module.exports = {
{
files: ['*.ts', '*.tsx'],
rules: {
'no-undef': OFF,
'import/no-import-module-exports': OFF,
},
},
@ -217,5 +349,21 @@ module.exports = {
'@typescript-eslint/explicit-module-boundary-types': OFF,
},
},
{
// Internal files where extraneous deps don't matter much at long as
// they run
files: [
'*.test.ts',
'*.test.tsx',
'admin/**',
'jest/**',
'website/**',
'packages/docusaurus-theme-translations/update.mjs',
'packages/docusaurus-theme-translations/src/utils.ts',
],
rules: {
'import/no-extraneous-dependencies': OFF,
},
},
],
};

9
.gitattributes vendored
View File

@ -27,3 +27,12 @@
*.bz2 binary
*.swp binary
*.webp binary
# Make GitHub not index certain files in the languages overview
# See https://github.com/github/linguist/blob/master/docs/overrides.md
# generated files' diff will be minimized
**/__fixtures__/** linguist-generated
.husky/** linguist-vendored
jest/** linguist-vendored
admin/** linguist-documentation
website/** linguist-documentation

View File

@ -1,3 +0,0 @@
## 👉 [Please follow one of these issue templates](https://github.com/facebook/docusaurus/issues/new/choose) 👈
Note: to keep the backlog clean and actionable, issues may be immediately closed if they do not follow one of the above issue templates.

View File

@ -7,7 +7,14 @@ body:
value: |
## Please help us help you!
Make it obvious to understand and reproduce this bug. Ideally, we should be able to understand it without running any code.
Before filing your issue, ask yourself:
- Is this clearly a Docusaurus defect?
- Do I have basic ideas about where it goes wrong? (For example, if there are stack traces, are they pointing to one file?)
- Could it be because of my own mistakes?
**The GitHub issue tracker is not a support forum**. If you are not sure whether it could be your mistakes, ask in the [Discord server](https://discord.gg/docusaurus) or [GitHub discussions](https://github.com/facebook/docusaurus/discussions) first. The quickest way to verify whether it's a Docusaurus defect is through a **reproduction**, starting with a fresh installation and making changes until the bug is reproduced.
Make the bug obvious. Ideally, we should be able to understand it without running any code.
Bugs are fixed faster if you include:
- A repro repository to inspect the code
@ -41,13 +48,27 @@ body:
validations:
required: true
- type: input
attributes:
label: Reproducible demo
description: |
Paste the link to an example repo, including a `docusaurus.config.js`, and exact instructions to reproduce the issue. It can either be a playground link created from https://new.docusaurus.io, or a git repository.
> **What happens if you skip this step?** Someone will read your bug report, and maybe will be able to help you, but its unlikely that it will get much attention from the team. Eventually, the issue will likely get closed in favor of issues that have reproducible demos.
Please remember that:
- Issues without reproducible demos have a very low priority.
- The person fixing the bug would have to do that anyway. Please be respectful of their time.
- You might figure out the issues yourself as you work on extracting it.
Thanks for helping us help you!
- type: textarea
attributes:
label: Steps to reproduce
description: Use https://new.docusaurus.io to create a CodeSandbox reproducible demo of the bug.
description: Write down the steps to reproduce the bug. You should start with a fresh installation, or your git repository linked above.
placeholder: |
Write your steps here.
1. Step 1...
2. Step 2...
3. Step 3...
@ -55,7 +76,6 @@ body:
required: true
- type: textarea
attributes:
label: Expected behavior
description: |
@ -87,22 +107,6 @@ body:
- Environment name and version (e.g. Chrome 89, Node.js 16.4):
- Operating system and version (e.g. Ubuntu 20.04.2 LTS):
- type: input
attributes:
label: Reproducible demo
description: |
Paste the link to an example repo, including a `docusaurus.config.js`, and exact instructions to reproduce the issue. Use https://new.docusaurus.io to create a CodeSandbox reproducible demo of the bug.
> **What happens if you skip this step?** Someone will read your bug report, and maybe will be able to help you, but its unlikely that it will get much attention from the team. Eventually, the issue will likely get closed in favor of issues that have reproducible demos.
Please remember that:
- Issues without reproducible demos have a very low priority.
- The person fixing the bug would have to do that anyway. Please be respectful of their time.
- You might figure out the issues yourself as you work on extracting it.
Thanks for helping us help you!
- type: checkboxes
attributes:
label: Self-service

View File

@ -5,22 +5,24 @@ Help us understand your motivation by explaining why you decided to make this ch
You can learn more about contributing to Docusaurus here: https://github.com/facebook/docusaurus/blob/main/CONTRIBUTING.md
If this PR adds or changes functionality, please take some time to update the docs.
Happy contributing!
-->
## Motivation
(Write your motivation here.)
<!-- Write your motivation here. -->
### Have you read the [Contributing Guidelines on pull requests](https://github.com/facebook/docusaurus/blob/main/CONTRIBUTING.md#pull-requests)?
(Write your answer here.)
<!-- Write your answer here. -->
## Test Plan
(Write your test plan here. If you changed any code, please provide us with clear instructions on how you verified your changes work. Bonus points for screenshots and videos!)
<!-- Write your test plan here. If you changed any code, please provide us with clear instructions on how you verified your changes work. Bonus points for screenshots and videos! -->
## Related PRs
(If this PR adds or changes functionality, please take some time to update the docs at https://github.com/facebook/docusaurus, and link to your PR here.)
<!-- If you haven't already, link to issues/PRs that are related to this change. This helps us develop the context and keep a rich repo history. -->

View File

@ -13,8 +13,8 @@ jobs:
timeout-minutes: 30
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '16'
cache: yarn

View File

@ -18,8 +18,8 @@ jobs:
timeout-minutes: 30
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '16'
cache: yarn
@ -27,6 +27,7 @@ jobs:
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
build-script: build:website:en
clean-script: clear:website # see https://github.com/facebook/docusaurus/pull/6838
pattern: '{website/build/assets/js/main*js,website/build/assets/css/styles*css,website/.docusaurus/globalData.json,website/build/index.html,website/build/blog/index.html,website/build/blog/**/introducing-docusaurus/*,website/build/docs/index.html,website/build/docs/installation/index.html,website/build/tests/docs/index.html,website/build/tests/docs/standalone/index.html}'
strip-hash: '\.([^;]\w{7})\.'
minimum-change-threshold: 30
@ -36,8 +37,8 @@ jobs:
timeout-minutes: 30
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
cache: yarn
- name: Installation
@ -52,4 +53,4 @@ jobs:
- name: Build (warm cache)
run: yarn workspace website build --locale en
timeout-minutes: 2
# TODO post a Github comment with build with perf warnings?
# TODO post a GitHub comment with build with perf warnings?

View File

@ -12,11 +12,11 @@ jobs:
name: Publish Canary
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
with:
fetch-depth: 0 # Needed to get the commit number with "git rev-list --count HEAD"
- name: Set up Node
uses: actions/setup-node@v2
uses: actions/setup-node@v3
with:
node-version: '16'
cache: yarn

View File

@ -27,7 +27,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Initialize CodeQL
uses: github/codeql-action/init@v1

View File

@ -10,7 +10,7 @@ jobs:
name: Lighthouse Report
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Wait for the Netlify Preview
uses: jakepartusch/wait-for-netlify-action@v1
id: netlify
@ -19,7 +19,7 @@ jobs:
max_timeout: 600
- name: Audit URLs using Lighthouse
id: lighthouse_audit
uses: treosh/lighthouse-ci-action@8.2.0
uses: treosh/lighthouse-ci-action@9.3.0
with:
urls: |
https://deploy-preview-$PR_NUMBER--docusaurus-2.netlify.app/
@ -30,7 +30,7 @@ jobs:
PR_NUMBER: ${{ github.event.pull_request.number}}
- name: Format lighthouse score
id: format_lighthouse_score
uses: actions/github-script@v5
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |

View File

@ -11,8 +11,8 @@ jobs:
timeout-minutes: 30
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '16'
cache: yarn

View File

@ -13,9 +13,9 @@ jobs:
timeout-minutes: 30
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Set up Node
uses: actions/setup-node@v2
uses: actions/setup-node@v3
with:
node-version: '16'
cache: yarn

View File

@ -21,9 +21,9 @@ jobs:
matrix:
node: ['14', '16', '17']
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node }}
uses: actions/setup-node@v2
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node }}
cache: yarn
@ -31,8 +31,6 @@ jobs:
run: yarn
- name: Generate test-website project against main branch
run: yarn test:build:website -s
env:
KEEP_CONTAINER: true
- name: Install test-website project with Yarn v1
run: yarn install
working-directory: ../test-website
@ -54,25 +52,26 @@ jobs:
strategy:
matrix:
nodeLinker: [pnp, node-modules]
variant: [-s, -st]
exclude:
# Running tsc on PnP requires additional installations, which is not
# worthwhile for a simple E2E test
- variant: -st
nodeLinker: pnp
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Use Node.js 16
uses: actions/setup-node@v2
uses: actions/setup-node@v3
with:
node-version: '16'
cache: yarn
- name: Installation
run: yarn
- name: Generate test-website project against main branch
run: yarn test:build:website -s
env:
KEEP_CONTAINER: true
- name: Generate test-website project with ${{ matrix.variant }} against main branch
run: yarn test:build:website ${{ matrix.variant }}
- name: Install test-website project with Yarn Berry and nodeLinker = ${{ matrix.nodeLinker }}
run: |
yarn set version berry
# https://github.com/facebook/docusaurus/pull/6350#issuecomment-1013214763
# Remove this after Yarn 3.2
yarn set version canary
yarn config set nodeLinker ${{ matrix.nodeLinker }}
yarn config set npmRegistryServer http://localhost:4873
@ -83,10 +82,6 @@ jobs:
# https://yarnpkg.com/features/pnp#fallback-mode
yarn config set pnpFallbackMode none
# Patch package so that peer deps are provided. This has been fixed in terser by making acorn a direct dependency
# TODO watch out for the next terser release. Commit: https://github.com/terser/terser/commit/05b23eeb682d732484ad51b19bf528258fd5dc2a
yarn config set packageExtensions --json '{"terser-webpack-plugin@*": {"dependencies": {"acorn": "^8.6.0"}}, "html-minifier-terser@*": {"dependencies": {"acorn": "^8.6.0"}}}'
yarn install
working-directory: ../test-website
env:
@ -96,18 +91,22 @@ jobs:
working-directory: ../test-website
env:
E2E_TEST: true
- name: Type check
if: matrix.variant == '-st'
run: yarn typecheck
working-directory: ../test-website
- name: Build test-website project
run: yarn build
working-directory: ../test-website
npm:
name: E2E — NPM
name: E2E — npm
timeout-minutes: 30
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Use Node.js 16
uses: actions/setup-node@v2
uses: actions/setup-node@v3
with:
node-version: '16'
cache: yarn
@ -115,9 +114,7 @@ jobs:
run: yarn
- name: Generate test-website project against main branch
run: yarn test:build:website -s
env:
KEEP_CONTAINER: true
- name: Install test-website project with NPM
- name: Install test-website project with npm
run: npm install
working-directory: ../test-website
env:
@ -132,13 +129,13 @@ jobs:
working-directory: ../test-website
pnpm:
name: E2E — PNPM
name: E2E — pnpm
timeout-minutes: 30
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Use Node.js 16
uses: actions/setup-node@v2
uses: actions/setup-node@v3
with:
node-version: '16'
cache: yarn
@ -146,9 +143,7 @@ jobs:
run: yarn
- name: Generate test-website project against main branch
run: yarn test:build:website -s
env:
KEEP_CONTAINER: true
- name: Install test-website project with PNPM
- name: Install test-website project with pnpm
run: |
curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm
pnpm install

37
.github/workflows/tests-swizzle.yml vendored Normal file
View File

@ -0,0 +1,37 @@
name: Swizzle Tests
on:
pull_request:
branches:
- main
paths:
- packages/**
jobs:
test:
name: Swizzle
timeout-minutes: 30
runs-on: ubuntu-latest
strategy:
matrix:
action: ['eject', 'wrap']
variant: ['js', 'ts']
steps:
- uses: actions/checkout@v3
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: 14
cache: yarn
- name: Installation
run: yarn
# Swizzle all the theme components
- name: Swizzle (${{matrix.action}} - ${{matrix.variant}})
run: yarn workspace website test:swizzle:${{matrix.action}}:${{matrix.variant}}
# Build swizzled site
- name: Build website
run: yarn build:website:fast
# Ensure swizzled site still typechecks
- name: TypeCheck website
run: yarn workspace website typecheck

View File

@ -18,9 +18,9 @@ jobs:
steps:
- name: Support longpaths
run: git config --system core.longpaths true
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node }}
uses: actions/setup-node@v2
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node }}
- name: Installation
@ -34,5 +34,10 @@ jobs:
mkdir -p "website/_dogfooding/_pages tests/deep-file-path-test/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar/foo/bar"
cd "$_"
echo "# hello" > test-file.md
# Lightweight version of tests-swizzle.yml workflow, but for Windows
- name: Swizzle Wrap TS
run: yarn workspace website test:swizzle:wrap:ts
- name: Docusaurus Build
run: yarn build:website --locale en
run: yarn build:website:fast
- name: TypeCheck website
run: yarn workspace website typecheck

View File

@ -16,9 +16,9 @@ jobs:
matrix:
node: ['14', '16', '17']
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node }}
uses: actions/setup-node@v2
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node }}
cache: yarn

3
.gitignore vendored
View File

@ -27,9 +27,12 @@ packages/stylelint-copyright/lib/
packages/docusaurus-*/lib-next/
website/netlifyDeployPreview/*
website/changelog
!website/netlifyDeployPreview/index.html
!website/netlifyDeployPreview/_redirects
website/_dogfooding/_swizzle_theme_tests
website/i18n/**/*
#!website/i18n/fr
#!website/i18n/fr/**/*

8
.lintstagedrc.json Normal file
View File

@ -0,0 +1,8 @@
{
"*.{js,jsx,ts,tsx,mjs}": ["eslint --fix"],
"*.css": ["stylelint --allow-empty-input --fix"],
"*": [
"prettier --ignore-unknown --write",
"cspell --no-must-find-files --no-progress"
]
}

2
.nvmrc
View File

@ -1 +1 @@
14.17.0
16.14.0

View File

@ -19,3 +19,7 @@ website/docusaurus.config.js
website/versioned_sidebars/*.json
examples/
website/static/katex/katex.min.css
website/changelog/_swizzle_theme_tests
website/_dogfooding/_swizzle_theme_tests

View File

@ -1,3 +1,8 @@
# Stylelint runs on everything by default; we only lint CSS files.
*
!*/
!*.css
__tests__/
build
coverage
examples/
@ -8,3 +13,4 @@ packages/docusaurus-*/lib/*
packages/docusaurus-*/lib-next/
packages/create-docusaurus/lib/*
packages/create-docusaurus/templates/
website/static/katex/katex.min.css

File diff suppressed because it is too large Load Diff

View File

@ -46,24 +46,20 @@ All pull requests will be checked by the continuous integration system, GitHub a
Docusaurus has one primary branch `main` and we use feature branches with deploy previews to deliver new features with pull requests.
## Proposing a Change
If you would like to request a new feature or enhancement but are not yet thinking about opening a pull request, you can also file an issue with the [feature template](https://github.com/facebook/docusaurus/issues/new?assignees=&labels=feature%2Cneeds+triage&template=feature.yml).
If you intend to change the public API (e.g., something in `siteConfig.js`) or make any non-trivial changes to the implementation, we recommend filing an issue with the [proposal template](https://github.com/facebook/docusaurus/issues/new?assignees=&labels=proposal%2Cneeds+triage&template=proposal.yml). This lets us reach an agreement on your proposal before you put significant effort into it. These types of issues should be rare.
If you're only fixing a bug, it's fine to submit a pull request right away but we still recommend [filing an issue](https://github.com/facebook/docusaurus/issues/new?assignees=&labels=bug%2Cneeds+triage&template=bug.yml) detailing what you're fixing. This is helpful in case we don't accept that specific fix but want to keep track of the issue.
### Reporting New Issues
## Issues
When [opening a new issue](https://github.com/facebook/docusaurus/issues/new/choose), always make sure to fill out the issue template. **This step is very important!** Not doing so may result in your issue not being managed in a timely fashion. Don't take this personally if this happens, and feel free to open a new issue once you've gathered all the information required by the template.
**Please don't use the GitHub issue tracker for questions.** If you have questions about using Docusaurus, use any of our [support channels](https://docusaurus.io/community/support), and we will do our best to answer your questions.
### Bugs
We use [GitHub Issues](https://github.com/facebook/docusaurus/issues) for our public bugs. If you would like to report a problem, take a look around and see if someone already opened an issue about it. If you are certain this is a new, unreported bug, you can submit a [bug report](https://github.com/facebook/docusaurus/issues/new?assignees=&labels=bug%2Cstatus%3A+needs+triage&template=bug.yml).
- **One issue, one bug:** Please report a single bug per issue.
- **Provide reproduction steps:** List all the steps necessary to reproduce the issue. The person reading your bug report should be able to follow these steps to reproduce your issue with minimal effort.
### Bugs
We use [GitHub Issues](https://github.com/facebook/docusaurus/issues) for our public bugs. If you would like to report a problem, take a look around and see if someone already opened an issue about it. If you are certain this is a new, unreported bug, you can submit a [bug report](#reporting-new-issues).
If you're only fixing a bug, it's fine to submit a pull request right away but we still recommend filing an issue detailing what you're fixing. This is helpful in case we don't accept that specific fix but want to keep track of the issue.
### Security Bugs
@ -71,40 +67,26 @@ Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
### Feature requests
You can also file issues as [feature requests or enhancements](https://github.com/facebook/docusaurus/labels/feature%20request) in the form of an **elaborated RFC**. If you see anything you'd like to be implemented, create an issue with [feature template](https://raw.githubusercontent.com/facebook/docusaurus/main/.github/ISSUE_TEMPLATE/feature.md)
If you would like to request a new feature or enhancement but are not yet thinking about opening a pull request, you can file an issue with the [feature template](https://github.com/facebook/docusaurus/issues/new?assignees=&labels=feature%2Cstatus%3A+needs+triage&template=feature.yml) in the form of an **elaborated RFC**. Alternatively, you can use the [Canny board](https://docusaurus.io/feature-requests) for more casual feature requests and gain enough traction before proposing an RFC.
### Questions
### Proposals
If you have questions about using Docusaurus, contact the Docusaurus Twitter account at [@docusaurus](https://twitter.com/docusaurus), and we will do our best to answer your questions.
If you intend to make any non-trivial changes to existing implementations, we recommend filing an issue with the [proposal template](https://github.com/facebook/docusaurus/issues/new?assignees=&labels=proposal%2Cstatus%3A+needs+triage&template=proposal.yml). This lets us reach an agreement on your proposal before you put significant effort into it. These types of issues should be rare.
## Pull Requests
### Your First Pull Request
So you have decided to contribute code back to upstream by opening a pull request. You've invested a good chunk of time, and we appreciate it. We will do our best to work with you and get the PR looked at.
Working on your first Pull Request? You can learn how from this free video series:
[**How to Contribute to an Open Source Project on GitHub**](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)
### Claiming issues
We have a list of [beginner-friendly issues](https://github.com/facebook/docusaurus/labels/good%20first%20issue) to help you get your feet wet in the Docusaurus codebase and familiar with our contribution process. This is a great place to get started.
### Versioned Docs
Apart from the `good first issue`, the following labels are also worth looking at:
If you only want to make content changes you just need to be aware of versioned docs.
- [`help wanted`](https://github.com/facebook/docusaurus/labels/help%20wanted): if you have specific knowledge in one domain, working on these issues can make your expertise shine.
- [`status: accepting pr`](https://github.com/facebook/docusaurus/labels/status%3A%20accepting%20pr): community contributors can feel free to claim any of these.
- `website/docs` - The files here are responsible for the "next" version at https://docusaurus.io/docs/next/installation.
- `website/versioned_docs/version-X.Y.Z` - These are the docs for the X.Y.Z version at https://docusaurus.io/docs/X.Y.Z/installation.
If you want to work on any of these issues, just drop a message saying "I'd like to work on this", and we will assign the issue to you and update the issue's status as "claimed". **You are expected to send a pull request within seven days** after that, so we can still delegate the issue to someone else if you are unavailable.
To make a fix to the published versions you must edit the corresponding markdown file in both folders. If you only made changes in `docs`, be sure to be viewing the `next` version to see the updates (ensure there's `next` in the URL).
Alternatively, when opening an issue, you can also click the "self service" checkbox to indicate that you'd like to work on the issue yourself, which will also make us see the issue as "claimed".
> Do not edit the auto-generated files within `versioned_docs/` or `versioned_sidebars/` unless you are sure it is necessary. For example, information about new features should not be documented in versioned docs. Edits made to older versions will not be propagated to newer versions of the docs.
### Installation
1. Ensure you have [Yarn](https://yarnpkg.com/) installed.
1. After cloning the repository, run `yarn install` in the root of the repository.
1. To start a development server, run `yarn workspace website start`.
## Development
### Online one-click setup for contributing
@ -120,74 +102,41 @@ So that you can start contributing straight away.
You can also try using the new [github.dev](https://github.dev/facebook/docusaurus) feature. While you are browsing any file, changing the domain name from `github.com` to `github.dev` will turn your browser into an online editor. You can start making changes and send pull requests right away.
### Sending a Pull Request
### Installation
Small pull requests are much easier to review and more likely to get merged. Make sure the PR does only one thing, otherwise please split it. It is recommended to follow this [commit message style](#semantic-commit-messages).
1. Ensure you have [Yarn](https://yarnpkg.com/) installed.
2. After cloning the repository, run `yarn install` in the root of the repository. This will install all dependencies as well as build all local packages.
3. To start a development server, run `yarn workspace website start`.
### Code Conventions
- **Most important: Look around.** Match the style you see used in the rest of the project. This includes formatting, naming files, naming things in code, naming things in documentation, etc.
- "Attractive"
- We do have Prettier (a formatter) and ESLint (a syntax linter) to catch most stylistic problems. If you are working locally, they should automatically fix some issues during every git commit.
- **For documentation**: Do not wrap lines at 80 characters - configure your editor to soft-wrap when editing documentation.
Don't worry too much about styles in general—the maintainers will help you fix them as they review your code.
## Pull Requests
So you have decided to contribute code back to upstream by opening a pull request. You've invested a good chunk of time, and we appreciate it. We will do our best to work with you and get the PR looked at.
Working on your first Pull Request? You can learn how from this free video series:
[**How to Contribute to an Open Source Project on GitHub**](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)
Please make sure the following is done when submitting a pull request:
1. Fork [the repository](https://github.com/facebook/docusaurus) and create your branch from `main`.
1. Add the [copyright notice](#copyright-header-for-source-code) to the top of any code new files you've added.
1. Describe your [**test plan**](#test-plan) in your pull request description. Make sure to [test your changes](https://github.com/facebook/docusaurus/blob/main/admin/testing-changes-on-Docusaurus-itself.md)!
1. Make sure your code lints (`yarn prettier && yarn lint`).
1. Make sure your Jest tests pass (`yarn test`).
1. If you haven't already, [sign the CLA](https://code.facebook.com/cla).
1. **Keep your PR small.** Small pull requests (~300 lines of diff) are much easier to review and more likely to get merged. Make sure the PR does only one thing, otherwise please split it.
2. **Use descriptive titles.** It is recommended to follow this [commit message style](#semantic-commit-messages).
3. **Test your changes.** Describe your [**test plan**](#test-plan) in your pull request description.
4. **CLA.** If you haven't already, [sign the CLA](https://code.facebook.com/cla).
All pull requests should be opened against the `main` branch.
#### Test Plan
We have a lot of integration systems that run automated tests to guard against mistakes. The maintainers will also review your code and fix obvious issues for you. These systems' duty is to make you worry as little about the chores as possible. Your code contributions are more important than sticking to any procedures, although completing the checklist will surely save everyone's time.
A good test plan has the exact commands you ran and their output and provides screenshots or videos if the pull request changes UI. If you've changed APIs, update the documentation.
If you need help testing your changes locally, you can check out the doc on doing [local third-party testing](https://github.com/facebook/docusaurus/blob/main/admin/local-third-party-project-testing.md).
#### Breaking Changes
When adding a new breaking change, follow this template in your pull request:
```md
### New breaking change here
- **Who does this affect**:
- **How to migrate**:
- **Why make this breaking change**:
- **Severity (number of people affected x effort)**:
```
#### Copyright Header for Source Code
Copy and paste this to the top of your new file(s):
```js
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
```
#### Contributor License Agreement (CLA)
In order to accept your pull request, we need you to submit a CLA. You only need to do this once, so if you've done this for another Facebook open source project, you're good to go. If you are submitting a pull request for the first time, the Facebook GitHub Bot will reply with a link to the CLA form. You may also [complete your CLA here](https://code.facebook.com/cla).
After you have signed the CLA, the CLA bot would automatically update the PR status. There's no need to open a new PR.
**CLAs are required for us to merge your pull request.** While we value your effort and are willing to wait for you to come back and address the reviews in case you are unavailable after sending the pull request, pull requests that are ready to merge but have CLA missing and no response from the author **will be closed within two weeks of opening**. If you have further questions about the CLA, please stay in touch with us.
If it happens that you were unavailable and your PR gets closed, feel free to reopen once it's ready! We are still happy to review it, help you complete it, and eventually merge it.
### What Happens Next?
The core Docusaurus team will be monitoring for pull requests. Do help us by keeping pull requests consistent by following the guidelines above.
## Style Guide
[Prettier](https://prettier.io) will catch most styling issues that may exist in your code. You can check the status of your code styling by simply running `yarn prettier`.
However, there are still some styles that Prettier cannot pick up.
## Semantic Commit Messages
### Semantic Commit Messages
See how a minor change to your commit message style can make you a better programmer.
@ -205,35 +154,79 @@ The various types of commits:
- `chore`: upgrading dependencies, releasing new versions... Chores that are **regularly done** for maintenance purposes.
- `misc`: anything else that doesn't change production code, yet is not `test` or `chore`. e.g. updating GitHub actions workflow.
Do not get too stressed about PR titles, however. The maintainers will help you get them right, and we also have a PR label system that doesn't equate with the commit message types. Your code is more important than conventions!
Do not get too stressed about PR titles, however. Your PR will be squash-merged and your commit to the `main` branch will get the title of your PR, so commits within a branch don't need to be semantically named. The maintainers will help you get the PR title right, and we also have a PR label system that doesn't equate with the commit message types. Your code is more important than conventions!
### Example
Example:
```
feat(core): allow overriding of webpack config
^--^^----^ ^------------^
| | |
| | +-> Summary in present tense.
| | +-> Summary in present tense. Use lower case not title case!
| |
| +-> The package(s) that this change affected.
|
+-------> Type: see below for the list we use.
```
Use lower case not title case!
### Versioned Docs
## Code Conventions
If you only want to make doc changes, you just need to be aware of versioned docs.
### General
- `website/docs` - The files here are responsible for the "next" version at https://docusaurus.io/docs/next/installation.
- `website/versioned_docs/version-X.Y.Z` - These are the docs for the X.Y.Z version at https://docusaurus.io/docs/X.Y.Z/installation.
- **Most important: Look around.** Match the style you see used in the rest of the project. This includes formatting, naming files, naming things in code, naming things in documentation, etc.
- "Attractive"
- We do have Prettier (a formatter) and ESLint (a syntax linter) to catch most stylistic problems. If you are working locally, they should automatically fix some issues during every git commit.
Do not edit the auto-generated files within `versioned_docs/` or `versioned_sidebars/` unless you are sure it is necessary. For example, information about new features should not be documented in versioned docs. Edits made to older versions will not be propagated to newer versions of the docs.
### Documentation
### Test Plan
- Do not wrap lines at 80 characters - configure your editor to soft-wrap when editing documentation.
A good test plan has the exact commands you ran and their output and provides screenshots or videos if the pull request changes UI. If you've changed APIs, update the documentation.
## License
Tests are integrated into our continuous integration system, so you don't always need to run local tests. However, for significant code changes, it's saves both your and the maintainers' time if you can do exhaustive tests locally first to make sure your PR is in good shape. There are many types of tests:
By contributing to Docusaurus, you agree that your contributions will be licensed under its MIT license.
- **Build and typecheck.** We use TypeScript in our codebase, which can make sure your code is consistent and catches some obvious mistakes early.
- **Unit tests.** We use [Jest](https://jestjs.io/) for unit tests of API endpoints' behavior. You can run `yarn test` in the root directory to run all tests, or `yarn test path/to/your/file.test.ts` to run a specific test.
- **Dogfooding.** Our website itself covers all kinds of potential configuration cases and we even have a dedicated [tests area](https://docusaurus.io/tests). Don't be afraid to update our website's configuration in your PR—it can help the maintainers preview the effects. We can decide if the website change should be kept when merging and deploying for production.
- **E2E tests.** You can simulate the distribution and installation of the code with your fresh changes. If you need help testing your changes locally, you can check out the doc on doing [local third-party testing](https://github.com/facebook/docusaurus/blob/main/admin/local-third-party-project-testing.md).
### Licensing
By contributing to Docusaurus, you agree that your contributions will be licensed under its MIT license. Copy and paste this to the top of your new file(s):
```js
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
```
This is also auto-fixable with the `header/header` ESLint rule.
### Contributor License Agreement (CLA)
In order to accept your pull request, we need you to submit a CLA. You only need to do this once, so if you've done this for another Facebook open source project, you're good to go. If you are submitting a pull request for the first time, the Facebook GitHub Bot will reply with a link to the CLA form. You may also [complete your CLA here](https://code.facebook.com/cla).
After you have signed the CLA, the CLA bot would automatically update the PR status. There's no need to open a new PR.
**CLAs are required for us to merge your pull request.** While we value your effort and are willing to wait for you to come back and address the reviews in case you are unavailable after sending the pull request, pull requests that are ready to merge but have CLA missing and no response from the author **will be closed within two weeks of opening**. If you have further questions about the CLA, please stay in touch with us.
If it happens that you were unavailable and your PR gets closed, feel free to reopen once it's ready! We are still happy to review it, help you complete it, and eventually merge it.
### Breaking Changes
When adding a new breaking change, follow this template in your pull request:
```md
### New breaking change here
- **Who does this affect**:
- **How to migrate**:
- **Why make this breaking change**:
- **Severity (number of people affected x effort)**:
```
### What Happens Next?
The core Docusaurus team will be monitoring for pull requests. Do help us by keeping pull requests consistent by following the guidelines above.

View File

@ -8,7 +8,7 @@
<a href="#backers" alt="sponsors on Open Collective"><img src="https://opencollective.com/Docusaurus/backers/badge.svg" /></a>
<a href="#sponsors" alt="Sponsors on Open Collective"><img src="https://opencollective.com/Docusaurus/sponsors/badge.svg" /></a>
<a href="https://www.npmjs.com/package/@docusaurus/core"><img src="https://img.shields.io/npm/v/@docusaurus/core.svg?style=flat" alt="npm version"></a>
<a href="https://github.com/facebook/docusaurus/actions/workflows/tests.yml"><img src="https://github.com/facebook/docusaurus/actions/workflows/tests.yml/badge.svg" alt="Github Actions status"></a>
<a href="https://github.com/facebook/docusaurus/actions/workflows/tests.yml"><img src="https://github.com/facebook/docusaurus/actions/workflows/tests.yml/badge.svg" alt="GitHub Actions status"></a>
<a href="CONTRIBUTING.md#pull-requests"><img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" alt="PRs Welcome"></a>
<a href="https://discord.gg/docusaurus"><img src="https://img.shields.io/discord/102860784329052160.svg" align="right" alt="Discord Chat" /></a>
<a href= "https://github.com/prettier/prettier"><img alt="code style: prettier" src="https://img.shields.io/badge/code_style-prettier-ff69b4.svg"></a>
@ -17,6 +17,8 @@
<a href="https://gitpod.io/#https://github.com/facebook/docusaurus"><img src="https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod" alt="Gitpod Ready-to-Code"/></a>
<a href="https://app.netlify.com/sites/docusaurus-2/deploys"><img src="https://api.netlify.com/api/v1/badges/9e1ff559-4405-4ebe-8718-5e21c0774bc8/deploy-status" alt="Netlify Status"></a>
<a href="https://meercode.io/facebook/docusaurus"><img src="https://meercode.io/badge/facebook/docusaurus?type=ci-score" alt="CI Score"></a>
<a href="https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Ffacebook%2Fdocusaurus%2Ftree%2Fmain%2Fexamples%2Fclassic&project-name=my-docusaurus-site&repo-name=my-docusaurus-site"><img src="https://vercel.com/button" alt="Deploy with Vercel"/></a>
<a href="https://app.netlify.com/start/deploy?repository=https://github.com/slorber/docusaurus-starter"><img src="https://www.netlify.com/img/deploy/button.svg" alt="Deploy to Netlify"></a>
</p>
> **We are working hard on Docusaurus v2. If you are new to Docusaurus, try using the new version instead of v1. See the [Docusaurus v2 website](https://docusaurus.io/) for more details.**

View File

@ -5,37 +5,44 @@
* LICENSE file in the root directory of this source tree.
*/
import util from 'util';
import globCb from 'glob';
import fsCb from 'fs';
const glob = util.promisify(globCb);
const readFile = util.promisify(fsCb.readFile);
import {Globby} from '@docusaurus/utils';
import fs from 'fs-extra';
type PackageJsonFile = {
file: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
content: any;
content: {
name?: string;
private?: boolean;
version?: string;
repository?: {
type?: string;
url?: string;
directory?: string;
};
publishConfig?: {
access?: string;
};
};
};
async function getPackagesJsonFiles(): Promise<PackageJsonFile[]> {
const files = await glob('packages/*/package.json');
const files = await Globby('packages/*/package.json');
return Promise.all(
files.map(async (file) => ({
file,
content: JSON.parse(await readFile(file, 'utf8')),
content: JSON.parse(await fs.readFile(file, 'utf8')),
})),
);
}
describe('packages', () => {
test('should be found', async () => {
it('are found', async () => {
const packageJsonFiles = await getPackagesJsonFiles();
expect(packageJsonFiles.length).toBeGreaterThan(0);
});
test('should contain repository and directory for every package', async () => {
it('contain repository and directory', async () => {
const packageJsonFiles = await getPackagesJsonFiles();
packageJsonFiles
@ -51,20 +58,22 @@ describe('packages', () => {
/*
If a package starts with @, if won't be published to public npm registry
without an additional publishConfig.acces: "public" config
without an additional publishConfig.access: "public" config
This will make you publish an incomplete list of Docusaurus packages
when trying to release with lerna-publish
*/
test('should have publishConfig.access: "public" when name starts with @', async () => {
it('have publishConfig.access: "public" when name starts with @', async () => {
const packageJsonFiles = await getPackagesJsonFiles();
packageJsonFiles
.filter((packageJsonFile) => packageJsonFile.content.name.startsWith('@'))
.forEach((packageJsonFile) => {
if (packageJsonFile) {
// Unfortunately jest custom message do not exist in loops, so using an exception instead to show failing package file
// Unfortunately jest custom message do not exist in loops,
// so using an exception instead to show failing package file
// (see https://github.com/facebook/jest/issues/3293)
// expect(packageJsonFile.content.publishConfig?.access).toEqual('public');
// expect(packageJsonFile.content.publishConfig?.access)
// .toEqual('public');
if (packageJsonFile.content.publishConfig?.access !== 'public') {
throw new Error(
`Package ${packageJsonFile.file} does not have publishConfig.access: 'public'`,

View File

@ -10,7 +10,11 @@ import type {HandlerEvent, HandlerResponse} from '@netlify/functions';
const CookieName = 'DocusaurusPlaygroundName';
const PlaygroundConfigs = {
codesandbox: 'https://codesandbox.io/s/docusaurus',
// Do not use this one, see
// https://github.com/codesandbox/codesandbox-client/issues/5683#issuecomment-1023252459
// codesandbox: 'https://codesandbox.io/s/docusaurus',
codesandbox:
'https://codesandbox.io/s/github/facebook/docusaurus/tree/main/examples/classic',
// stackblitz: 'https://stackblitz.com/fork/docusaurus', // not updated
// stackblitz: 'https://stackblitz.com/github/facebook/docusaurus/tree/main/examples/classic', // slow to load
@ -22,9 +26,11 @@ const PlaygroundDocumentationUrl = 'https://docusaurus.io/docs/playground';
export type PlaygroundName = keyof typeof PlaygroundConfigs;
function isValidPlaygroundName(
playgroundName: string,
playgroundName: string | undefined,
): playgroundName is PlaygroundName {
return Object.keys(PlaygroundConfigs).includes(playgroundName);
return (
!!playgroundName && Object.keys(PlaygroundConfigs).includes(playgroundName)
);
}
export function createPlaygroundDocumentationResponse(): HandlerResponse {
@ -50,10 +56,10 @@ export function createPlaygroundResponse(
}
// Inspired by https://stackoverflow.com/a/3409200/82609
function parseCookieString(cookieString: string): Record<string, string> {
const result: Record<string, string> = {};
function parseCookieString(cookieString: string): {[key: string]: string} {
const result: {[key: string]: string} = {};
cookieString.split(';').forEach((cookie) => {
const [name, value] = cookie.split('=');
const [name, value] = cookie.split('=') as [string, string];
result[name.trim()] = decodeURI(value);
});
return result;
@ -62,19 +68,16 @@ function parseCookieString(cookieString: string): Record<string, string> {
export function readPlaygroundName(
event: HandlerEvent,
): PlaygroundName | undefined {
const parsedCookie: Record<string, string> = event.headers.cookie
const parsedCookie: {[key: string]: string} = event.headers.cookie
? parseCookieString(event.headers.cookie)
: {};
const playgroundName: string | undefined = parsedCookie[CookieName];
if (playgroundName) {
if (isValidPlaygroundName(playgroundName)) {
return playgroundName;
} else {
console.error(
`playgroundName found in cookie was invalid: ${playgroundName}`,
);
}
if (!isValidPlaygroundName(playgroundName)) {
console.error(
`playgroundName found in cookie was invalid: ${playgroundName}`,
);
return undefined;
}
return undefined;
return playgroundName;
}

View File

@ -9,6 +9,6 @@ import type {Handler} from '@netlify/functions';
import {createPlaygroundResponse} from '../functionUtils/playgroundUtils';
export const handler: Handler = async function (_event, _context) {
export const handler: Handler = async function handler() {
return createPlaygroundResponse('codesandbox');
};

View File

@ -13,7 +13,7 @@ import {
createPlaygroundDocumentationResponse,
} from '../functionUtils/playgroundUtils';
export const handler: Handler = async (event, _context) => {
export const handler: Handler = async (event) => {
const playgroundName = readPlaygroundName(event);
return playgroundName
? createPlaygroundResponse(playgroundName)

View File

@ -9,6 +9,6 @@ import type {Handler} from '@netlify/functions';
import {createPlaygroundResponse} from '../functionUtils/playgroundUtils';
export const handler: Handler = async function (_event, _context) {
export const handler: Handler = async function handler() {
return createPlaygroundResponse('stackblitz');
};

View File

@ -1,14 +1,14 @@
{
"name": "new.docusaurus.io",
"version": "2.0.0-beta.14",
"version": "2.0.0-beta.18",
"private": true,
"scripts": {
"start": "netlify dev"
},
"dependencies": {
"@netlify/functions": "^0.10.0"
"@netlify/functions": "^1.0.0"
},
"devDependencies": {
"netlify-cli": "^8.0.5"
"netlify-cli": "^9.13.6"
}
}

View File

@ -10,7 +10,7 @@ Get access from the Docusaurus npm admins (@yangshun/@JoelMarcey).
You need publish access to **the main Docusaurus repository** (not a fork).
## NPM
## npm
Publishing will only work if you are logged into npm with an account with publishing rights to the package.
@ -78,7 +78,7 @@ The `tag:` label prefix is for PRs only. Other labels are not used by the change
Generate a GitHub auth token by going to https://github.com/settings/tokens (the only permission needed is `public_repo`). Save the token somewhere for future reference.
Fetch the tags from Github (lerna-changelog looks for commits since last tag by default):
Fetch the tags from GitHub (lerna-changelog looks for commits since last tag by default):
```sh
git fetch --tags
@ -118,7 +118,7 @@ You should still be on your local branch `<your_username>/<version_to_release>`
Make a commit/push, create a pull request with the changes.
Example PR: [#3114](https://github.com/facebook/docusaurus/pull/5098), using title such as `chore(v2): prepare v2.0.0-beta.0 release`
Example PR: [#3114](https://github.com/facebook/docusaurus/pull/5098), using title such as `chore: prepare v2.0.0-beta.0 release`
**Don't merge it yet**, but wait for the CI checks to complete.
@ -163,7 +163,7 @@ npm access ls-packages
</pre>
</details>
It can happen that some accesses are not granted, as an admin might add you to the @docusaurus NPM organization, but you don't have access to the packages that are not in that organization.
It can happen that some accesses are not granted, as an admin might add you to the @docusaurus npm organization, but you don't have access to the packages that are not in that organization.
Please **double-check your permissions on these packages**, otherwise you'll publish a half-release and will have to release a new version.
@ -187,6 +187,8 @@ This command does a few things:
You should receive many emails notifying you that a new version of the packages has been published.
If above command fail (network issue or whatever), you can try to recover with `yarn lerna publish from-package`: it will try to publish the packages that are missing on npm.
Now that the release is done, **merge the pull request**.
### 7. Create a release on GitHub

View File

@ -5,8 +5,6 @@
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable import/no-extraneous-dependencies */
import fs from 'fs-extra';
import shell from 'shelljs';
@ -26,16 +24,16 @@ async function generateTemplateExample(template) {
`generating ${template} template for codesandbox in the examples folder...`,
);
// run the docusaurus script to bootstrap the template in the examples folder
// run the docusaurus script to create the template in the examples folder
const command = template.endsWith('-typescript')
? template.replace('-typescript', ' -- --typescript')
: template;
shell.exec(
// /!\ we use the published init script on purpose,
// because using the local init script is too early and could generate upcoming/unavailable config options
// remember CodeSandbox templates will use the published version, not the repo version
// because using the local init script is too early and could generate
// upcoming/unavailable config options. Remember CodeSandbox templates
// will use the published version, not the repo version
`npm init docusaurus@latest examples/${template} ${command}`,
// `node ./packages/docusaurus-init/bin/index.js init examples/${template} ${template}`,
);
// read the content of the package.json
@ -49,10 +47,10 @@ async function generateTemplateExample(template) {
// these example projects are not meant to be published to npm
templatePackageJson.private = true;
// make sure package.json name is not "examples-classic"
// the package.json name appear in CodeSandbox UI so let's display a good name!
// unfortunately we can't use uppercase or spaces
// see also https://github.com/codesandbox/codesandbox-client/pull/5136#issuecomment-763521662
// Make sure package.json name is not "examples-classic". The package.json
// name appears in CodeSandbox UI so let's display a good name!
// Unfortunately we can't use uppercase or spaces... See also
// https://github.com/codesandbox/codesandbox-client/pull/5136#issuecomment-763521662
templatePackageJson.name =
template === 'classic' ? 'docusaurus' : `docusaurus-${template}`;
templatePackageJson.description =
@ -92,18 +90,19 @@ async function generateTemplateExample(template) {
);
console.log(`Generated example for template ${template}`);
} catch (error) {
} catch (err) {
console.error(`Failed to generated example for template ${template}`);
throw error;
throw err;
}
}
/*
Starters are repositories/branches that only contains a newly initialized Docusaurus site
Those are useful for users to inspect (may be more convenient than "examples/classic)
Also some tools like Netlify deploy button currently require using the main branch of a dedicated repo
See https://github.com/jamstack/jamstack.org/pull/609
Button visible here: https://jamstack.org/generators/
/**
* Starters are repositories/branches that only contains a newly initialized
* Docusaurus site. Those are useful for users to inspect (may be more
* convenient than "examples/classic) Also some tools like Netlify deploy button
* currently require using the main branch of a dedicated repo.
* See https://github.com/jamstack/jamstack.org/pull/609
* Button visible here: https://jamstack.org/generators/
*/
function updateStarters() {
function forcePushGitSubtree({subfolder, remote, remoteBranch}) {
@ -114,12 +113,12 @@ function updateStarters() {
console.log(`forcePushGitSubtree command: ${command}`);
shell.exec(command);
console.log('forcePushGitSubtree success!');
} catch (e) {
} catch (err) {
console.error(
`Can't force push to git subtree with command '${command}'`,
);
console.error(`If it's a permission problem, ask @slorber`);
console.error(e);
console.error(err);
}
console.log('');
}
@ -181,7 +180,6 @@ const templates = (
await fs.readdir('./packages/create-docusaurus/templates')
).filter((name) => !excludes.includes(name));
console.log(`Will generate examples for templates: ${templates.join(',')}`);
// eslint-disable-next-line no-restricted-syntax
for (const template of templates) {
await generateTemplateExample(template);
}

View File

@ -5,13 +5,12 @@
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable import/no-extraneous-dependencies */
import sharp from 'sharp';
import fs from 'fs-extra';
import path from 'path';
import imageSize from 'image-size';
import {fileURLToPath} from 'url';
import logger from '@docusaurus/logger';
const allImages = (
await fs.readdir(new URL('../../website/src/data/showcase', import.meta.url))
@ -27,10 +26,11 @@ await Promise.all(
);
const {width, height} = imageSize(imgPath);
if (width === 640 && height === 320) {
// Do not emit if no resized. Important because we
// can't guarantee idempotency during resize -> optimization
// Do not emit if not resized. Important because we can't guarantee
// idempotency during resize -> optimization
return;
}
logger.info`Resized path=${imgPath}: Before number=${width}×number=${height}`;
const data = await sharp(imgPath)
.resize(640, 320, {fit: 'cover', position: 'top'})
.png()
@ -39,7 +39,8 @@ await Promise.all(
}),
);
// You should also run optimizt `find website/src/data/showcase -type f -name '*.png'`.
// This is not included here because @funboxteam/optimizt doesn't seem to play well with M1
// so I had to run this in a Rosetta terminal.
// You should also run
// optimizt `find website/src/data/showcase -type f -name '*.png'`.
// This is not included here because @funboxteam/optimizt doesn't seem to play
// well with M1 so I had to run this in a Rosetta terminal.
// TODO integrate this as part of the script

View File

@ -12,16 +12,16 @@ NEW_VERSION="$(node -p "require('./packages/docusaurus/package.json').version").
CONTAINER_NAME="verdaccio"
EXTRA_OPTS=""
usage() { echo "Usage: $0 [-n] [-s]" 1>&2; exit 1; }
usage() { echo "Usage: $0 [-s] [-t]" 1>&2; exit 1; }
while getopts ":ns" o; do
while getopts ":st" o; do
case "${o}" in
n)
EXTRA_OPTS="${EXTRA_OPTS} --use-npm"
;;
s)
EXTRA_OPTS="${EXTRA_OPTS} --skip-install"
;;
t)
EXTRA_OPTS="${EXTRA_OPTS} --typescript"
;;
*)
usage
;;
@ -55,7 +55,7 @@ cd ..
npm_config_registry="$CUSTOM_REGISTRY_URL" npx create-docusaurus@"$NEW_VERSION" test-website classic $EXTRA_OPTS
# Stop Docker container
if [[ -z "${KEEP_CONTAINER:-}" ]] && ( $(docker container inspect "$CONTAINER_NAME" > /dev/null 2>&1) ); then
if [[ -z "${KEEP_CONTAINER:-true}" ]] && ( $(docker container inspect "$CONTAINER_NAME" > /dev/null 2>&1) ); then
# Remove Docker container
docker container stop $CONTAINER_NAME > /dev/null
fi

View File

@ -17,7 +17,7 @@ yarn start
### VS Code
Use the following code in VSCode to enable breakpoints. Please ensure you have a later version of node for non-legacy debugging.
Use the following code in VS Code to enable breakpoints. Please ensure you have a later version of node for non-legacy debugging.
```json
{

View File

@ -1,27 +0,0 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
module.exports = {
presets: [
[
'@babel/env',
{
targets: {
node: 'current',
},
},
],
'@babel/react',
'@babel/preset-typescript',
],
plugins: [
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-proposal-nullish-coalescing-operator',
'@babel/plugin-proposal-optional-chaining',
],
};

View File

@ -1,4 +1,4 @@
{
"installDependencies": true,
"startCommand": "npm start"
}
}

View File

@ -12,24 +12,36 @@ Get started by **creating a new site**.
Or **try Docusaurus immediately** with **[docusaurus.new](https://docusaurus.new)**.
### What you'll need
- [Node.js](https://nodejs.org/en/download/) version 14 or above:
- When installing Node.js, you are recommended to check all checkboxes related to dependencies.
## Generate a new site
Generate a new Docusaurus site using the **classic template**:
Generate a new Docusaurus site using the **classic template**.
The classic template will automatically be added to your project after you run the command:
```bash
npm init docusaurus@latest my-website classic
```
You can type this command into Command Prompt, Powershell, Terminal, or any other integrated terminal of your code editor.
The command also installs all necessary dependencies you need to run Docusaurus.
## Start your site
Run the development server:
```bash
cd my-website
npx docusaurus start
npm run start
```
Your site starts at `http://localhost:3000`.
The `cd` command changes the directory you're working with. In order to work with your newly created Docusaurus site, you'll need to navigate the terminal there.
Open `docs/intro.md` and edit some lines: the site **reloads automatically** and displays your changes.
The `npm run start` command builds your website locally and serves it through a development server, ready for you to view at http://localhost:3000/.
Open `docs/intro.md` (this page) and edit some lines: the site **reloads automatically** and displays your changes.

View File

@ -41,14 +41,14 @@ This is my **first Docusaurus document**!
It is also possible to create your sidebar explicitly in `sidebars.js`:
```diff title="sidebars.js"
```js title="sidebars.js"
module.exports = {
tutorialSidebar: [
{
type: 'category',
label: 'Tutorial',
- items: [...],
+ items: ['hello'],
// highlight-next-line
items: ['hello'],
},
],
};

View File

@ -16,18 +16,18 @@
"dev": "docusaurus start"
},
"dependencies": {
"@docusaurus/core": "2.0.0-beta.14",
"@docusaurus/preset-classic": "2.0.0-beta.14",
"@mdx-js/react": "^1.6.21",
"@docusaurus/core": "2.0.0-beta.18",
"@docusaurus/preset-classic": "2.0.0-beta.18",
"@mdx-js/react": "^1.6.22",
"clsx": "^1.1.1",
"prism-react-renderer": "^1.2.1",
"react": "^17.0.1",
"react-dom": "^17.0.1"
"prism-react-renderer": "^1.3.1",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "2.0.0-beta.14",
"@tsconfig/docusaurus": "^1.0.4",
"typescript": "^4.5.2"
"@docusaurus/module-type-aliases": "2.0.0-beta.18",
"@tsconfig/docusaurus": "^1.0.5",
"typescript": "^4.6.3"
},
"browserslist": {
"production": [
@ -42,4 +42,4 @@
]
},
"description": "Docusaurus example project (classic-typescript template)"
}
}

View File

@ -7,4 +7,4 @@
"container": {
"node": "14"
}
}
}

View File

@ -1,18 +1,17 @@
import useBaseUrl from '@docusaurus/useBaseUrl';
import React from 'react';
import clsx from 'clsx';
import styles from './HomepageFeatures.module.css';
import styles from './styles.module.css';
type FeatureItem = {
title: string;
image: string;
Svg: React.ComponentType<React.ComponentProps<'svg'>>;
description: JSX.Element;
};
const FeatureList: FeatureItem[] = [
{
title: 'Easy to Use',
image: '/img/undraw_docusaurus_mountain.svg',
Svg: require('@site/static/img/undraw_docusaurus_mountain.svg').default,
description: (
<>
Docusaurus was designed from the ground up to be easily installed and
@ -22,7 +21,7 @@ const FeatureList: FeatureItem[] = [
},
{
title: 'Focus on What Matters',
image: '/img/undraw_docusaurus_tree.svg',
Svg: require('@site/static/img/undraw_docusaurus_tree.svg').default,
description: (
<>
Docusaurus lets you focus on your docs, and we&apos;ll do the chores. Go
@ -32,7 +31,7 @@ const FeatureList: FeatureItem[] = [
},
{
title: 'Powered by React',
image: '/img/undraw_docusaurus_react.svg',
Svg: require('@site/static/img/undraw_docusaurus_react.svg').default,
description: (
<>
Extend or customize your website layout by reusing React. Docusaurus can
@ -42,15 +41,11 @@ const FeatureList: FeatureItem[] = [
},
];
function Feature({title, image, description}: FeatureItem) {
function Feature({title, Svg, description}: FeatureItem) {
return (
<div className={clsx('col col--4')}>
<div className="text--center">
<img
className={styles.featureSvg}
alt={title}
src={useBaseUrl(image)}
/>
<Svg className={styles.featureSvg} role="img" />
</div>
<div className="text--center padding-horiz--md">
<h3>{title}</h3>

View File

@ -6,16 +6,27 @@
/* You can override the default Infima variables here. */
:root {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: rgb(33, 175, 144);
--ifm-color-primary-darker: rgb(31, 165, 136);
--ifm-color-primary-darkest: rgb(26, 136, 112);
--ifm-color-primary-light: rgb(70, 203, 174);
--ifm-color-primary-lighter: rgb(102, 212, 189);
--ifm-color-primary-lightest: rgb(146, 224, 208);
--ifm-color-primary: #2e8555;
--ifm-color-primary-dark: #29784c;
--ifm-color-primary-darker: #277148;
--ifm-color-primary-darkest: #205d3b;
--ifm-color-primary-light: #33925d;
--ifm-color-primary-lighter: #359962;
--ifm-color-primary-lightest: #3cad6e;
--ifm-code-font-size: 95%;
}
/* For readability concerns, you should choose a lighter palette in dark mode. */
[data-theme='dark'] {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: #21af90;
--ifm-color-primary-darker: #1fa588;
--ifm-color-primary-darkest: #1a8870;
--ifm-color-primary-light: #29d5b0;
--ifm-color-primary-lighter: #32d8b4;
--ifm-color-primary-lightest: #4fddbf;
}
.docusaurus-highlight-code-line {
background-color: rgba(0, 0, 0, 0.1);
display: block;
@ -23,6 +34,6 @@
padding: 0 var(--ifm-pre-padding);
}
html[data-theme='dark'] .docusaurus-highlight-code-line {
[data-theme='dark'] .docusaurus-highlight-code-line {
background-color: rgba(0, 0, 0, 0.3);
}

View File

@ -10,7 +10,7 @@
overflow: hidden;
}
@media screen and (max-width: 966px) {
@media screen and (max-width: 996px) {
.heroBanner {
padding: 2rem;
}

View File

@ -4,7 +4,7 @@ import Layout from '@theme/Layout';
import Link from '@docusaurus/Link';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import styles from './index.module.css';
import HomepageFeatures from '../components/HomepageFeatures';
import HomepageFeatures from '@site/src/components/HomepageFeatures';
function HomepageHeader() {
const {siteConfig} = useDocusaurusContext();

View File

@ -1,4 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1088" height="687.962" viewBox="0 0 1088 687.962">
<title>Easy to Use</title>
<g id="Group_12" data-name="Group 12" transform="translate(-57 -56)">
<g id="Group_11" data-name="Group 11" transform="translate(57 56)">
<path id="Path_83" data-name="Path 83" d="M1017.81,560.461c-5.27,45.15-16.22,81.4-31.25,110.31-20,38.52-54.21,54.04-84.77,70.28a193.275,193.275,0,0,1-27.46,11.94c-55.61,19.3-117.85,14.18-166.74,3.99a657.282,657.282,0,0,0-104.09-13.16q-14.97-.675-29.97-.67c-15.42.02-293.07,5.29-360.67-131.57-16.69-33.76-28.13-75-32.24-125.27-11.63-142.12,52.29-235.46,134.74-296.47,155.97-115.41,369.76-110.57,523.43,7.88C941.15,276.621,1036.99,396.031,1017.81,560.461Z" transform="translate(-56 -106.019)" fill="#3f3d56"/>

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 31 KiB

View File

@ -1,4 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1041.277" height="554.141" viewBox="0 0 1041.277 554.141">
<title>Powered by React</title>
<g id="Group_24" data-name="Group 24" transform="translate(-440 -263)">
<g id="Group_23" data-name="Group 23" transform="translate(439.989 262.965)">
<path id="Path_299" data-name="Path 299" d="M1040.82,611.12q-1.74,3.75-3.47,7.4-2.7,5.67-5.33,11.12c-.78,1.61-1.56,3.19-2.32,4.77-8.6,17.57-16.63,33.11-23.45,45.89A73.21,73.21,0,0,1,942.44,719l-151.65,1.65h-1.6l-13,.14-11.12.12-34.1.37h-1.38l-17.36.19h-.53l-107,1.16-95.51,1-11.11.12-69,.75H429l-44.75.48h-.48l-141.5,1.53-42.33.46a87.991,87.991,0,0,1-10.79-.54h0c-1.22-.14-2.44-.3-3.65-.49a87.38,87.38,0,0,1-51.29-27.54C116,678.37,102.75,655,93.85,629.64q-1.93-5.49-3.6-11.12C59.44,514.37,97,380,164.6,290.08q4.25-5.64,8.64-11l.07-.08c20.79-25.52,44.1-46.84,68.93-62,44-26.91,92.75-34.49,140.7-11.9,40.57,19.12,78.45,28.11,115.17,30.55,3.71.24,7.42.42,11.11.53,84.23,2.65,163.17-27.7,255.87-47.29,3.69-.78,7.39-1.55,11.12-2.28,66.13-13.16,139.49-20.1,226.73-5.51a189.089,189.089,0,0,1,26.76,6.4q5.77,1.86,11.12,4c41.64,16.94,64.35,48.24,74,87.46q1.37,5.46,2.37,11.11C1134.3,384.41,1084.19,518.23,1040.82,611.12Z" transform="translate(-79.34 -172.91)" fill="#f2f2f2"/>

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 35 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
{
"installDependencies": true,
"startCommand": "npm start"
}
}

View File

@ -12,24 +12,36 @@ Get started by **creating a new site**.
Or **try Docusaurus immediately** with **[docusaurus.new](https://docusaurus.new)**.
### What you'll need
- [Node.js](https://nodejs.org/en/download/) version 14 or above:
- When installing Node.js, you are recommended to check all checkboxes related to dependencies.
## Generate a new site
Generate a new Docusaurus site using the **classic template**:
Generate a new Docusaurus site using the **classic template**.
The classic template will automatically be added to your project after you run the command:
```bash
npm init docusaurus@latest my-website classic
```
You can type this command into Command Prompt, Powershell, Terminal, or any other integrated terminal of your code editor.
The command also installs all necessary dependencies you need to run Docusaurus.
## Start your site
Run the development server:
```bash
cd my-website
npx docusaurus start
npm run start
```
Your site starts at `http://localhost:3000`.
The `cd` command changes the directory you're working with. In order to work with your newly created Docusaurus site, you'll need to navigate the terminal there.
Open `docs/intro.md` and edit some lines: the site **reloads automatically** and displays your changes.
The `npm run start` command builds your website locally and serves it through a development server, ready for you to view at http://localhost:3000/.
Open `docs/intro.md` (this page) and edit some lines: the site **reloads automatically** and displays your changes.

View File

@ -41,14 +41,14 @@ This is my **first Docusaurus document**!
It is also possible to create your sidebar explicitly in `sidebars.js`:
```diff title="sidebars.js"
```js title="sidebars.js"
module.exports = {
tutorialSidebar: [
{
type: 'category',
label: 'Tutorial',
- items: [...],
+ items: ['hello'],
// highlight-next-line
items: ['hello'],
},
],
};

View File

@ -15,13 +15,13 @@
"dev": "docusaurus start"
},
"dependencies": {
"@docusaurus/core": "2.0.0-beta.14",
"@docusaurus/preset-classic": "2.0.0-beta.14",
"@mdx-js/react": "^1.6.21",
"@docusaurus/core": "2.0.0-beta.18",
"@docusaurus/preset-classic": "2.0.0-beta.18",
"@mdx-js/react": "^1.6.22",
"clsx": "^1.1.1",
"prism-react-renderer": "^1.2.1",
"react": "^17.0.1",
"react-dom": "^17.0.1"
"prism-react-renderer": "^1.3.1",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"browserslist": {
"production": [
@ -36,4 +36,4 @@
]
},
"description": "Docusaurus example project"
}
}

View File

@ -7,4 +7,4 @@
"container": {
"node": "14"
}
}
}

View File

@ -1,11 +1,11 @@
import React from 'react';
import clsx from 'clsx';
import styles from './HomepageFeatures.module.css';
import styles from './styles.module.css';
const FeatureList = [
{
title: 'Easy to Use',
Svg: require('../../static/img/undraw_docusaurus_mountain.svg').default,
Svg: require('@site/static/img/undraw_docusaurus_mountain.svg').default,
description: (
<>
Docusaurus was designed from the ground up to be easily installed and
@ -15,7 +15,7 @@ const FeatureList = [
},
{
title: 'Focus on What Matters',
Svg: require('../../static/img/undraw_docusaurus_tree.svg').default,
Svg: require('@site/static/img/undraw_docusaurus_tree.svg').default,
description: (
<>
Docusaurus lets you focus on your docs, and we&apos;ll do the chores. Go
@ -25,7 +25,7 @@ const FeatureList = [
},
{
title: 'Powered by React',
Svg: require('../../static/img/undraw_docusaurus_react.svg').default,
Svg: require('@site/static/img/undraw_docusaurus_react.svg').default,
description: (
<>
Extend or customize your website layout by reusing React. Docusaurus can
@ -39,7 +39,7 @@ function Feature({Svg, title, description}) {
return (
<div className={clsx('col col--4')}>
<div className="text--center">
<Svg className={styles.featureSvg} alt={title} />
<Svg className={styles.featureSvg} role="img" />
</div>
<div className="text--center padding-horiz--md">
<h3>{title}</h3>

View File

@ -6,16 +6,27 @@
/* You can override the default Infima variables here. */
:root {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: rgb(33, 175, 144);
--ifm-color-primary-darker: rgb(31, 165, 136);
--ifm-color-primary-darkest: rgb(26, 136, 112);
--ifm-color-primary-light: rgb(70, 203, 174);
--ifm-color-primary-lighter: rgb(102, 212, 189);
--ifm-color-primary-lightest: rgb(146, 224, 208);
--ifm-color-primary: #2e8555;
--ifm-color-primary-dark: #29784c;
--ifm-color-primary-darker: #277148;
--ifm-color-primary-darkest: #205d3b;
--ifm-color-primary-light: #33925d;
--ifm-color-primary-lighter: #359962;
--ifm-color-primary-lightest: #3cad6e;
--ifm-code-font-size: 95%;
}
/* For readability concerns, you should choose a lighter palette in dark mode. */
[data-theme='dark'] {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: #21af90;
--ifm-color-primary-darker: #1fa588;
--ifm-color-primary-darkest: #1a8870;
--ifm-color-primary-light: #29d5b0;
--ifm-color-primary-lighter: #32d8b4;
--ifm-color-primary-lightest: #4fddbf;
}
.docusaurus-highlight-code-line {
background-color: rgba(0, 0, 0, 0.1);
display: block;
@ -23,6 +34,6 @@
padding: 0 var(--ifm-pre-padding);
}
html[data-theme='dark'] .docusaurus-highlight-code-line {
[data-theme='dark'] .docusaurus-highlight-code-line {
background-color: rgba(0, 0, 0, 0.3);
}

View File

@ -4,7 +4,7 @@ import Layout from '@theme/Layout';
import Link from '@docusaurus/Link';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import styles from './index.module.css';
import HomepageFeatures from '../components/HomepageFeatures';
import HomepageFeatures from '@site/src/components/HomepageFeatures';
function HomepageHeader() {
const {siteConfig} = useDocusaurusContext();

View File

@ -10,7 +10,7 @@
overflow: hidden;
}
@media screen and (max-width: 966px) {
@media screen and (max-width: 996px) {
.heroBanner {
padding: 2rem;
}

View File

@ -1,4 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1088" height="687.962" viewBox="0 0 1088 687.962">
<title>Easy to Use</title>
<g id="Group_12" data-name="Group 12" transform="translate(-57 -56)">
<g id="Group_11" data-name="Group 11" transform="translate(57 56)">
<path id="Path_83" data-name="Path 83" d="M1017.81,560.461c-5.27,45.15-16.22,81.4-31.25,110.31-20,38.52-54.21,54.04-84.77,70.28a193.275,193.275,0,0,1-27.46,11.94c-55.61,19.3-117.85,14.18-166.74,3.99a657.282,657.282,0,0,0-104.09-13.16q-14.97-.675-29.97-.67c-15.42.02-293.07,5.29-360.67-131.57-16.69-33.76-28.13-75-32.24-125.27-11.63-142.12,52.29-235.46,134.74-296.47,155.97-115.41,369.76-110.57,523.43,7.88C941.15,276.621,1036.99,396.031,1017.81,560.461Z" transform="translate(-56 -106.019)" fill="#3f3d56"/>

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 31 KiB

View File

@ -1,4 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1041.277" height="554.141" viewBox="0 0 1041.277 554.141">
<title>Powered by React</title>
<g id="Group_24" data-name="Group 24" transform="translate(-440 -263)">
<g id="Group_23" data-name="Group 23" transform="translate(439.989 262.965)">
<path id="Path_299" data-name="Path 299" d="M1040.82,611.12q-1.74,3.75-3.47,7.4-2.7,5.67-5.33,11.12c-.78,1.61-1.56,3.19-2.32,4.77-8.6,17.57-16.63,33.11-23.45,45.89A73.21,73.21,0,0,1,942.44,719l-151.65,1.65h-1.6l-13,.14-11.12.12-34.1.37h-1.38l-17.36.19h-.53l-107,1.16-95.51,1-11.11.12-69,.75H429l-44.75.48h-.48l-141.5,1.53-42.33.46a87.991,87.991,0,0,1-10.79-.54h0c-1.22-.14-2.44-.3-3.65-.49a87.38,87.38,0,0,1-51.29-27.54C116,678.37,102.75,655,93.85,629.64q-1.93-5.49-3.6-11.12C59.44,514.37,97,380,164.6,290.08q4.25-5.64,8.64-11l.07-.08c20.79-25.52,44.1-46.84,68.93-62,44-26.91,92.75-34.49,140.7-11.9,40.57,19.12,78.45,28.11,115.17,30.55,3.71.24,7.42.42,11.11.53,84.23,2.65,163.17-27.7,255.87-47.29,3.69-.78,7.39-1.55,11.12-2.28,66.13-13.16,139.49-20.1,226.73-5.51a189.089,189.089,0,0,1,26.76,6.4q5.77,1.86,11.12,4c41.64,16.94,64.35,48.24,74,87.46q1.37,5.46,2.37,11.11C1134.3,384.41,1084.19,518.23,1040.82,611.12Z" transform="translate(-79.34 -172.91)" fill="#f2f2f2"/>

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 35 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
{
"installDependencies": true,
"startCommand": "npm start"
}
}

View File

@ -12,24 +12,36 @@ Get started by **creating a new site**.
Or **try Docusaurus immediately** with **[docusaurus.new](https://docusaurus.new)**.
### What you'll need
- [Node.js](https://nodejs.org/en/download/) version 14 or above:
- When installing Node.js, you are recommended to check all checkboxes related to dependencies.
## Generate a new site
Generate a new Docusaurus site using the **classic template**:
Generate a new Docusaurus site using the **classic template**.
The classic template will automatically be added to your project after you run the command:
```bash
npm init docusaurus@latest my-website classic
```
You can type this command into Command Prompt, Powershell, Terminal, or any other integrated terminal of your code editor.
The command also installs all necessary dependencies you need to run Docusaurus.
## Start your site
Run the development server:
```bash
cd my-website
npx docusaurus start
npm run start
```
Your site starts at `http://localhost:3000`.
The `cd` command changes the directory you're working with. In order to work with your newly created Docusaurus site, you'll need to navigate the terminal there.
Open `docs/intro.md` and edit some lines: the site **reloads automatically** and displays your changes.
The `npm run start` command builds your website locally and serves it through a development server, ready for you to view at http://localhost:3000/.
Open `docs/intro.md` (this page) and edit some lines: the site **reloads automatically** and displays your changes.

View File

@ -41,14 +41,14 @@ This is my **first Docusaurus document**!
It is also possible to create your sidebar explicitly in `sidebars.js`:
```diff title="sidebars.js"
```js title="sidebars.js"
module.exports = {
tutorialSidebar: [
{
type: 'category',
label: 'Tutorial',
- items: [...],
+ items: ['hello'],
// highlight-next-line
items: ['hello'],
},
],
};

View File

@ -19,25 +19,25 @@
"dev": "docusaurus start"
},
"dependencies": {
"@docusaurus/core": "2.0.0-beta.14",
"@docusaurus/preset-classic": "2.0.0-beta.14",
"@mdx-js/react": "^1.6.21",
"@docusaurus/core": "2.0.0-beta.18",
"@docusaurus/preset-classic": "2.0.0-beta.18",
"@mdx-js/react": "^1.6.22",
"clsx": "^1.1.1",
"react": "^17.0.1",
"react-dom": "^17.0.1"
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"@babel/eslint-parser": "^7.16.3",
"eslint": "^8.2.0",
"eslint-config-airbnb": "^19.0.0",
"eslint-config-prettier": "^8.3.0",
"@babel/eslint-parser": "^7.17.0",
"eslint": "^8.11.0",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-header": "^3.1.1",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-import": "^2.25.4",
"eslint-plugin-jsx-a11y": "^6.5.1",
"eslint-plugin-react": "^7.27.0",
"eslint-plugin-react": "^7.29.4",
"eslint-plugin-react-hooks": "^4.3.0",
"prettier": "^2.5.1",
"stylelint": "^13.2.1"
"prettier": "^2.6.0",
"stylelint": "^14.6.0"
},
"browserslist": {
"production": [

View File

@ -7,4 +7,4 @@
"container": {
"node": "14"
}
}
}

View File

@ -15,16 +15,27 @@
/* You can override the default Infima variables here. */
:root {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: rgb(33, 175, 144);
--ifm-color-primary-darker: rgb(31, 165, 136);
--ifm-color-primary-darkest: rgb(26, 136, 112);
--ifm-color-primary-light: rgb(70, 203, 174);
--ifm-color-primary-lighter: rgb(102, 212, 189);
--ifm-color-primary-lightest: rgb(146, 224, 208);
--ifm-color-primary: #2e8555;
--ifm-color-primary-dark: #29784c;
--ifm-color-primary-darker: #277148;
--ifm-color-primary-darkest: #205d3b;
--ifm-color-primary-light: #33925d;
--ifm-color-primary-lighter: #359962;
--ifm-color-primary-lightest: #3cad6e;
--ifm-code-font-size: 95%;
}
/* For readability concerns, you should choose a lighter palette in dark mode. */
[data-theme='dark'] {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: #21af90;
--ifm-color-primary-darker: #1fa588;
--ifm-color-primary-darkest: #1a8870;
--ifm-color-primary-light: #29d5b0;
--ifm-color-primary-lighter: #32d8b4;
--ifm-color-primary-lightest: #4fddbf;
}
.docusaurus-highlight-code-line {
background-color: rgb(72, 77, 91);
display: block;

View File

@ -19,7 +19,7 @@
overflow: hidden;
}
@media screen and (max-width: 966px) {
@media screen and (max-width: 996px) {
.heroBanner {
padding: 2rem;
}

View File

@ -1,4 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1088" height="687.962" viewBox="0 0 1088 687.962">
<title>Easy to Use</title>
<g id="Group_12" data-name="Group 12" transform="translate(-57 -56)">
<g id="Group_11" data-name="Group 11" transform="translate(57 56)">
<path id="Path_83" data-name="Path 83" d="M1017.81,560.461c-5.27,45.15-16.22,81.4-31.25,110.31-20,38.52-54.21,54.04-84.77,70.28a193.275,193.275,0,0,1-27.46,11.94c-55.61,19.3-117.85,14.18-166.74,3.99a657.282,657.282,0,0,0-104.09-13.16q-14.97-.675-29.97-.67c-15.42.02-293.07,5.29-360.67-131.57-16.69-33.76-28.13-75-32.24-125.27-11.63-142.12,52.29-235.46,134.74-296.47,155.97-115.41,369.76-110.57,523.43,7.88C941.15,276.621,1036.99,396.031,1017.81,560.461Z" transform="translate(-56 -106.019)" fill="#3f3d56"/>

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 31 KiB

View File

@ -1,4 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1041.277" height="554.141" viewBox="0 0 1041.277 554.141">
<title>Powered by React</title>
<g id="Group_24" data-name="Group 24" transform="translate(-440 -263)">
<g id="Group_23" data-name="Group 23" transform="translate(439.989 262.965)">
<path id="Path_299" data-name="Path 299" d="M1040.82,611.12q-1.74,3.75-3.47,7.4-2.7,5.67-5.33,11.12c-.78,1.61-1.56,3.19-2.32,4.77-8.6,17.57-16.63,33.11-23.45,45.89A73.21,73.21,0,0,1,942.44,719l-151.65,1.65h-1.6l-13,.14-11.12.12-34.1.37h-1.38l-17.36.19h-.53l-107,1.16-95.51,1-11.11.12-69,.75H429l-44.75.48h-.48l-141.5,1.53-42.33.46a87.991,87.991,0,0,1-10.79-.54h0c-1.22-.14-2.44-.3-3.65-.49a87.38,87.38,0,0,1-51.29-27.54C116,678.37,102.75,655,93.85,629.64q-1.93-5.49-3.6-11.12C59.44,514.37,97,380,164.6,290.08q4.25-5.64,8.64-11l.07-.08c20.79-25.52,44.1-46.84,68.93-62,44-26.91,92.75-34.49,140.7-11.9,40.57,19.12,78.45,28.11,115.17,30.55,3.71.24,7.42.42,11.11.53,84.23,2.65,163.17-27.7,255.87-47.29,3.69-.78,7.39-1.55,11.12-2.28,66.13-13.16,139.49-20.1,226.73-5.51a189.089,189.089,0,0,1,26.76,6.4q5.77,1.86,11.12,4c41.64,16.94,64.35,48.24,74,87.46q1.37,5.46,2.37,11.11C1134.3,384.41,1084.19,518.23,1040.82,611.12Z" transform="translate(-79.34 -172.91)" fill="#f2f2f2"/>

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 35 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

File diff suppressed because it is too large Load Diff

View File

@ -7,50 +7,69 @@
import {fileURLToPath} from 'url';
process.env.TZ = 'UTC';
const ignorePatterns = [
'/node_modules/',
'__fixtures__',
'/testUtils.ts',
'/packages/docusaurus/lib',
'/packages/docusaurus-logger/lib',
'/packages/docusaurus-utils/lib',
'/packages/docusaurus-utils-common/lib',
'/packages/docusaurus-utils-validation/lib',
'/packages/docusaurus-plugin-content-blog/lib',
'/packages/docusaurus-plugin-content-docs/lib',
'/packages/docusaurus-plugin-content-pages/lib',
'/packages/docusaurus-theme-classic/lib',
'/packages/docusaurus-theme-classic/lib-next',
'/packages/docusaurus-theme-common/lib',
'/packages/docusaurus-migrate/lib',
'/jest',
];
export default {
rootDir: fileURLToPath(new URL('.', import.meta.url)),
verbose: true,
testURL: 'http://localhost/',
testURL: 'https://docusaurus.io/',
testEnvironment: 'node',
testPathIgnorePatterns: ignorePatterns,
coveragePathIgnorePatterns: ignorePatterns,
coveragePathIgnorePatterns: [
...ignorePatterns,
// We also ignore all package entry points
'/packages/docusaurus-utils/src/index.ts',
],
transform: {
'^.+\\.[jt]sx?$': 'babel-jest',
'^.+\\.[jt]sx?$': '@swc/jest',
},
errorOnDeprecated: true,
moduleNameMapper: {
// Jest can't resolve CSS or asset imports
'^.+\\.(css|jpg|jpeg|png|svg)$': '<rootDir>/jest/emptyModule.js',
'^.+\\.(css|jpe?g|png|svg|webp)$': '<rootDir>/jest/emptyModule.ts',
// TODO we need to allow Jest to resolve core Webpack aliases automatically
'@docusaurus/(browserContext|BrowserOnly|ComponentCreator|constants|docusaurusContext|ExecutionEnvironment|Head|Interpolate|isInternalUrl|Link|Noop|renderRoutes|router|Translate|use.*)':
'@docusaurus/core/lib/client/exports/$1',
// Using src instead of lib, so we always get fresh source
'@docusaurus/(BrowserOnly|ComponentCreator|constants|ExecutionEnvironment|Head|Interpolate|isInternalUrl|Link|Noop|renderRoutes|router|Translate|use.*)':
'@docusaurus/core/src/client/exports/$1',
// TODO create dedicated testing utility for mocking contexts
// Maybe point to a fixture?
'@generated/.*': '<rootDir>/jest/emptyModule.js',
// TODO maybe use "projects" + multiple configs if we plan to add tests to another theme?
'@generated/.*': '<rootDir>/jest/emptyModule.ts',
// TODO use "projects" + multiple configs if we work on another theme?
'@theme/(.*)': '@docusaurus/theme-classic/src/theme/$1',
'@site/(.*)': 'website/$1',
// TODO why Jest can't figure node package entry points?
// Using src instead of lib, so we always get fresh source
'@docusaurus/plugin-content-docs/client':
'@docusaurus/plugin-content-docs/lib/client/index.js',
'@docusaurus/plugin-content-docs/src/client/index.ts',
'@testing-utils/(.*)': '<rootDir>/jest/utils/$1.ts',
},
globals: {
window: {
location: {href: 'https://docusaurus.io'},
},
snapshotSerializers: [
'<rootDir>/jest/snapshotPathNormalizer.ts',
'jest-serializer-react-helmet-async',
],
snapshotFormat: {
escapeString: false,
printBasicPrototype: false,
},
};

View File

@ -5,4 +5,4 @@
* LICENSE file in the root directory of this source tree.
*/
module.exports = {};
export default {};

149
jest/snapshotPathNormalizer.ts vendored Normal file
View File

@ -0,0 +1,149 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Forked from https://github.com/tribou/jest-serializer-path/blob/master/lib/index.js
// Added some project-specific handlers
import _ from 'lodash';
import {escapePath} from '@docusaurus/utils';
import stripAnsi from 'strip-ansi';
import {version} from '@docusaurus/core/package.json';
import os from 'os';
import path from 'path';
import fs from 'fs';
export function print(
val: unknown,
serialize: (val: unknown) => string,
): string {
if (val instanceof Error) {
const message = normalizePaths(val.message);
const error = new Error(message);
const allKeys = [
...Object.getOwnPropertyNames(error),
...Object.keys(val),
] as (keyof Error)[];
allKeys.forEach((key) => {
error[key] = normalizePaths(val[key]) as never;
});
return serialize(error);
} else if (val && typeof val === 'object') {
const normalizedValue = _.cloneDeep(val) as {[key: string]: unknown};
Object.keys(normalizedValue).forEach((key) => {
normalizedValue[key] = normalizePaths(normalizedValue[key]);
});
return serialize(normalizedValue);
}
return serialize(normalizePaths(val));
}
export function test(val: unknown): boolean {
return (
(typeof val === 'object' &&
val &&
Object.keys(val).some((key) =>
shouldUpdate((val as {[key: string]: unknown})[key]),
)) ||
// val.message is non-enumerable in an error
(val instanceof Error && shouldUpdate(val.message)) ||
shouldUpdate(val)
);
}
/**
* Normalize paths across platforms.
* Filters must be ran on all platforms to guard against false positives
*/
function normalizePaths<T>(value: T): T {
if (typeof value !== 'string') {
return value;
}
const cwd = process.cwd();
const cwdReal = getRealPath(cwd);
const tempDir = os.tmpdir();
const tempDirReal = getRealPath(tempDir);
const homeDir = os.homedir();
const homeDirReal = getRealPath(homeDir);
const homeRelativeToTemp = path.relative(tempDir, homeDir);
const homeRelativeToTempReal = path.relative(tempDirReal, homeDir);
const homeRealRelativeToTempReal = path.relative(tempDirReal, homeDirReal);
const homeRealRelativeToTemp = path.relative(tempDir, homeDirReal);
const runner: ((val: string) => string)[] = [
(val) => (val.includes('keepAnsi') ? val : stripAnsi(val)),
// Replace process.cwd with <PROJECT_ROOT>
(val) => val.split(cwdReal).join('<PROJECT_ROOT>'),
(val) => val.split(cwd).join('<PROJECT_ROOT>'),
// Replace home directory with <TEMP_DIR>
(val) => val.split(tempDirReal).join('<TEMP_DIR>'),
(val) => val.split(tempDir).join('<TEMP_DIR>'),
// Replace home directory with <HOME_DIR>
(val) => val.split(homeDirReal).join('<HOME_DIR>'),
(val) => val.split(homeDir).join('<HOME_DIR>'),
// handle HOME_DIR nested inside TEMP_DIR
(val) =>
val
.split(`<TEMP_DIR>${path.sep + homeRelativeToTemp}`)
.join('<HOME_DIR>'),
(val) =>
val
.split(`<TEMP_DIR>${path.sep + homeRelativeToTempReal}`)
.join('<HOME_DIR>'), // untested
(val) =>
val
.split(`<TEMP_DIR>${path.sep + homeRealRelativeToTempReal}`)
.join('<HOME_DIR>'),
(val) =>
val
.split(`<TEMP_DIR>${path.sep + homeRealRelativeToTemp}`)
.join('<HOME_DIR>'), // untested
// Replace the Docusaurus version with a stub
(val) => val.split(version).join('<CURRENT_VERSION>'),
// In case the CWD is escaped
(val) => val.split(escapePath(cwd)).join('<PROJECT_ROOT>'),
// Remove win32 drive letters, C:\ -> \
(val) => val.replace(/[a-zA-Z]:\\/g, '\\'),
// Remove duplicate backslashes created from escapePath
(val) => val.replace(/\\\\/g, '\\'),
// Convert win32 backslash's to forward slashes, \ -> /;
// ignore some that look like escape sequences.
(val) => val.replace(/\\(?!")/g, '/'),
];
let result = value as string;
runner.forEach((current) => {
result = current(result);
});
return result as T & string;
}
function shouldUpdate(value: unknown) {
// return true if value is different from normalized value
return typeof value === 'string' && normalizePaths(value) !== value;
}
function getRealPath(pathname: string) {
try {
// eslint-disable-next-line no-restricted-properties
const realPath = fs.realpathSync(pathname);
return realPath;
} catch (error) {
return pathname;
}
}

63
jest/utils/git.ts vendored Normal file
View File

@ -0,0 +1,63 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import fs from 'fs-extra';
import os from 'os';
import path from 'path';
import shell from 'shelljs';
class Git {
constructor(private dir: string) {
const res = shell.exec('git init', {cwd: dir, silent: true});
if (res.code !== 0) {
throw new Error(`git init exited with code ${res.code}.
stderr: ${res.stderr}
stdout: ${res.stdout}`);
}
// Doesn't matter currently
shell.exec('git config user.email "test@jc-verse.com"', {
cwd: dir,
silent: true,
});
shell.exec('git config user.name "Test"', {cwd: dir, silent: true});
shell.exec('git commit --allow-empty -m "First commit"', {
cwd: dir,
silent: true,
});
}
commit(msg: string, date: string, author: string): void {
const addRes = shell.exec('git add .', {cwd: this.dir, silent: true});
const commitRes = shell.exec(
`git commit -m "${msg}" --date "${date}T00:00:00Z" --author "${author}"`,
{
cwd: this.dir,
env: {GIT_COMMITTER_DATE: `${date}T00:00:00Z`},
silent: true,
},
);
if (addRes.code !== 0) {
throw new Error(`git add exited with code ${addRes.code}.
stderr: ${addRes.stderr}
stdout: ${addRes.stdout}`);
}
if (commitRes.code !== 0) {
throw new Error(`git commit exited with code ${commitRes.code}.
stderr: ${commitRes.stderr}
stdout: ${commitRes.stdout}`);
}
}
}
// This function is sync so the same mock repo can be shared across tests
export function createTempRepo(): {repoDir: string; git: Git} {
const repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'git-test-repo'));
const git = new Git(repoDir);
return {repoDir, git};
}

View File

@ -1,5 +1,5 @@
{
"version": "2.0.0-beta.14",
"version": "2.0.0-beta.18",
"npmClient": "yarn",
"useWorkspaces": true,
"changelog": {

View File

@ -23,7 +23,9 @@
"build:website": "yarn workspace website build",
"build:website:baseUrl": "yarn workspace website build:baseUrl",
"build:website:blogOnly": "yarn workspace website build:blogOnly",
"build:website:deployPreview": "cross-env NETLIFY=true CONTEXT='deploy-preview' yarn workspace website build",
"build:website:deployPreview:testWrap": "yarn workspace website test:swizzle:wrap:ts",
"build:website:deployPreview:build": "cross-env NETLIFY=true CONTEXT='deploy-preview' yarn workspace website build",
"build:website:deployPreview": "yarn build:website:deployPreview:testWrap && yarn build:website:deployPreview:build",
"build:website:fast": "yarn workspace website build:fast",
"build:website:en": "yarn workspace website build --locale en",
"clear:website": "yarn workspace website clear",
@ -50,7 +52,7 @@
"lint:spelling": "cspell \"**\" --no-progress",
"lint:style": "stylelint \"**/*.css\"",
"lerna": "lerna",
"test": "cross-env TZ=UTC jest",
"test": "jest",
"test:build:website": "./admin/scripts/test-release.sh",
"watch": "yarn lerna run --parallel watch",
"clear": "(yarn workspace website clear || echo 'Failure while running docusaurus clear') && yarn lerna exec --ignore docusaurus yarn rimraf lib lib-next",
@ -58,72 +60,59 @@
"lock:update": "npx yarn-deduplicate"
},
"devDependencies": {
"@babel/cli": "^7.16.0",
"@babel/core": "^7.16.0",
"@babel/eslint-parser": "^7.16.3",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.16.0",
"@babel/plugin-proposal-optional-chaining": "^7.16.0",
"@babel/plugin-transform-modules-commonjs": "^7.16.0",
"@babel/preset-typescript": "^7.16.0",
"@crowdin/cli": "^3.7.1",
"@types/fs-extra": "^9.0.6",
"@types/jest": "^26.0.20",
"@types/lodash": "^4.14.168",
"@types/node": "^17.0.8",
"@types/prompts": "^2.0.9",
"@types/react": "^17.0.2",
"@types/react-dev-utils": "^9.0.1",
"@babel/cli": "^7.17.6",
"@babel/core": "^7.17.8",
"@babel/preset-typescript": "^7.16.7",
"@crowdin/cli": "^3.7.8",
"@swc/core": "^1.2.162",
"@swc/jest": "^0.2.20",
"@testing-library/react-hooks": "^7.0.2",
"@types/fs-extra": "^9.0.13",
"@types/jest": "^27.4.1",
"@types/lodash": "^4.14.181",
"@types/node": "^17.0.23",
"@types/prompts": "^2.0.14",
"@types/react": "^17.0.43",
"@types/react-dev-utils": "^9.0.10",
"@types/react-test-renderer": "^17.0.1",
"@types/semver": "^7.1.0",
"@types/shelljs": "^0.8.6",
"@typescript-eslint/eslint-plugin": "^5.8.1",
"@typescript-eslint/parser": "^5.8.1",
"@types/semver": "^7.3.9",
"@types/shelljs": "^0.8.11",
"@typescript-eslint/eslint-plugin": "^5.17.0",
"@typescript-eslint/parser": "^5.17.0",
"concurrently": "^7.0.0",
"cross-env": "^7.0.3",
"cspell": "^5.16.0",
"eslint": "^8.2.0",
"eslint-config-airbnb": "^19.0.0",
"eslint-config-prettier": "^8.3.0",
"cspell": "^5.19.5",
"eslint": "^8.12.0",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-header": "^3.1.1",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-jest": "^25.7.0",
"eslint-plugin-import": "^2.25.4",
"eslint-plugin-jest": "^26.1.3",
"eslint-plugin-jsx-a11y": "^6.5.1",
"eslint-plugin-react": "^7.27.0",
"eslint-plugin-react-hooks": "^4.3.0",
"glob": "^7.1.6",
"eslint-plugin-react": "^7.29.4",
"eslint-plugin-react-hooks": "^4.4.0",
"eslint-plugin-regexp": "^1.6.0",
"husky": "^7.0.4",
"image-size": "^1.0.1",
"jest": "^26.6.3",
"jest": "^27.5.1",
"jest-serializer-react-helmet-async": "^1.0.21",
"lerna": "^4.0.0",
"lerna-changelog": "^1.0.1",
"lint-staged": "^12.1.7",
"netlify-cli": "^8.0.5",
"nodemon": "^2.0.13",
"prettier": "^2.5.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"lerna-changelog": "^2.2.0",
"lint-staged": "^12.3.7",
"netlify-cli": "^9.13.6",
"nodemon": "^2.0.15",
"prettier": "^2.6.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-test-renderer": "^17.0.2",
"remark-parse": "^8.0.2",
"rimraf": "^3.0.2",
"sharp": "^0.29.1",
"stylelint": "^14.3.0",
"sharp": "^0.30.3",
"strip-ansi": "^6.0.1",
"stylelint": "^14.6.1",
"stylelint-config-prettier": "^9.0.3",
"stylelint-config-standard": "^24.0.0",
"tslib": "^2.3.1",
"typescript": "^4.5.2"
},
"lint-staged": {
"*.{js,jsx,ts,tsx,mjs}": [
"eslint --fix"
],
"*.css": [
"stylelint --allow-empty-input --fix"
],
"*": [
"prettier --ignore-unknown --write",
"cspell --no-must-find-files --no-progress"
]
},
"engines": {
"node": ">=14"
"stylelint-config-standard": "^25.0.0",
"typescript": "^4.6.3",
"unified": "^9.2.2"
}
}

View File

@ -8,12 +8,14 @@
// @ts-check
const logger = require('@docusaurus/logger').default;
const semver = require('semver');
const path = require('path');
const program = require('commander');
const {default: init} = require('../lib');
const requiredVersion = require('../package.json').engines.node;
import logger from '@docusaurus/logger';
import semver from 'semver';
import path from 'path';
import {program} from 'commander';
import {createRequire} from 'module';
const packageJson = createRequire(import.meta.url)('../package.json');
const requiredVersion = packageJson.engines.node;
if (!semver.satisfies(process.version, requiredVersion)) {
logger.error('Minimum Node.js version not met :(');
@ -21,46 +23,54 @@ if (!semver.satisfies(process.version, requiredVersion)) {
process.exit(1);
}
function wrapCommand(fn) {
return (...args) =>
fn(...args).catch((err) => {
logger.error(err.stack);
process.exitCode = 1;
});
}
program.version(packageJson.version);
program
.version(require('../package.json').version)
.usage('<command> [options]');
program
.command('init [siteName] [template] [rootDir]', {isDefault: true})
.option('--use-npm')
.option('--skip-install')
.option('--typescript')
.arguments('[siteName] [template] [rootDir]')
.option(
'-p, --package-manager <manager>',
'The package manager used to install dependencies. One of yarn, npm, and pnpm.',
)
.option(
'-s, --skip-install',
'Do not run package manager immediately after scaffolding',
)
.option('-t, --typescript', 'Use the TypeScript template variant')
.option(
'-g, --git-strategy <strategy>',
`Only used if the template is a git repository.
\`deep\`: preserve full history
\`shallow\`: clone with --depth=1
\`copy\`: do a shallow clone, but do not create a git repo
\`custom\`: enter your custom git clone command. We will prompt you for it.`,
)
.description('Initialize website.')
.action(
(
siteName,
template,
rootDir = '.',
{useNpm, skipInstall, typescript} = {},
{packageManager, skipInstall, typescript, gitStrategy} = {},
) => {
wrapCommand(init)(path.resolve(rootDir), siteName, template, {
useNpm,
skipInstall,
typescript,
// See https://github.com/facebook/docusaurus/pull/6860
import('../lib/index.js').then(({default: init}) => {
init(path.resolve(rootDir), siteName, template, {
packageManager,
skipInstall,
typescript,
gitStrategy,
});
});
},
);
program.arguments('<command>').action((cmd) => {
program.outputHelp();
logger.error`Unknown command code=${cmd}.`;
});
program.parse(process.argv);
if (!process.argv.slice(1).length) {
program.outputHelp();
}
process.on('unhandledRejection', (err) => {
logger.error(err);
process.exit(1);
});

View File

@ -1,7 +1,8 @@
{
"name": "create-docusaurus",
"version": "2.0.0-beta.14",
"version": "2.0.0-beta.18",
"description": "Create Docusaurus apps easily.",
"type": "module",
"repository": {
"type": "git",
"url": "https://github.com/facebook/docusaurus.git",
@ -12,8 +13,8 @@
},
"scripts": {
"create-docusaurus": "create-docusaurus",
"build": "tsc",
"watch": "tsc --watch"
"build": "tsc -p tsconfig.build.json",
"watch": "tsc -p tsconfig.build.json --watch"
},
"bin": "bin/index.js",
"publishConfig": {
@ -21,20 +22,20 @@
},
"license": "MIT",
"dependencies": {
"@docusaurus/logger": "2.0.0-beta.14",
"@docusaurus/logger": "2.0.0-beta.18",
"commander": "^5.1.0",
"fs-extra": "^10.0.0",
"lodash": "^4.17.20",
"prompts": "^2.4.1",
"semver": "^7.3.4",
"shelljs": "^0.8.4",
"supports-color": "^8.1.1",
"fs-extra": "^10.0.1",
"lodash": "^4.17.21",
"prompts": "^2.4.2",
"semver": "^7.3.5",
"shelljs": "^0.8.5",
"supports-color": "^9.2.2",
"tslib": "^2.3.1"
},
"engines": {
"node": ">=14"
},
"devDependencies": {
"@types/supports-color": "^8.1.1"
},
"engines": {
"node": ">=14"
}
}

View File

@ -7,30 +7,102 @@
import logger from '@docusaurus/logger';
import fs from 'fs-extra';
import {execSync} from 'child_process';
import prompts, {type Choice} from 'prompts';
import path from 'path';
import shell from 'shelljs';
import {kebabCase, sortBy} from 'lodash';
import _ from 'lodash';
import supportsColor from 'supports-color';
import {fileURLToPath} from 'url';
const RecommendedTemplate = 'classic';
const TypeScriptTemplateSuffix = '-typescript';
function hasYarn() {
try {
execSync('yarnpkg --version', {stdio: 'ignore'});
return true;
} catch (e) {
return false;
// Only used in the rare, rare case of running globally installed create +
// using --skip-install. We need a default name to show the tip text
const DefaultPackageManager = 'npm';
const SupportedPackageManagers = {
npm: 'package-lock.json',
yarn: 'yarn.lock',
pnpm: 'pnpm-lock.yaml',
};
type SupportedPackageManager = keyof typeof SupportedPackageManagers;
const PackageManagersList = Object.keys(
SupportedPackageManagers,
) as SupportedPackageManager[];
async function findPackageManagerFromLockFile(): Promise<
SupportedPackageManager | undefined
> {
for (const packageManager of PackageManagersList) {
const lockFilePath = path.resolve(SupportedPackageManagers[packageManager]);
if (await fs.pathExists(lockFilePath)) {
return packageManager;
}
}
return undefined;
}
function findPackageManagerFromUserAgent():
| SupportedPackageManager
| undefined {
return PackageManagersList.find((packageManager) =>
process.env.npm_config_user_agent?.startsWith(packageManager),
);
}
async function askForPackageManagerChoice(): Promise<SupportedPackageManager> {
const hasYarn = shell.exec('yarn --version', {silent: true}).code === 0;
const hasPnpm = shell.exec('pnpm --version', {silent: true}).code === 0;
if (!hasYarn && !hasPnpm) {
return 'npm';
}
const choices = ['npm', hasYarn && 'yarn', hasPnpm && 'pnpm']
.filter((p): p is string => Boolean(p))
.map((p) => ({title: p, value: p}));
return (
await prompts({
type: 'select',
name: 'packageManager',
message: 'Select a package manager...',
choices,
})
).packageManager;
}
async function getPackageManager(
packageManagerChoice: SupportedPackageManager | undefined,
skipInstall: boolean = false,
): Promise<SupportedPackageManager> {
if (
packageManagerChoice &&
!PackageManagersList.includes(packageManagerChoice)
) {
throw new Error(
`Invalid package manager choice ${packageManagerChoice}. Must be one of ${PackageManagersList.join(
', ',
)}`,
);
}
return (
packageManagerChoice ??
(await findPackageManagerFromLockFile()) ??
findPackageManagerFromUserAgent() ??
// This only happens if the user has a global installation in PATH
(skipInstall ? DefaultPackageManager : askForPackageManagerChoice())
);
}
function isValidGitRepoUrl(gitRepoUrl: string) {
return ['https://', 'git@'].some((item) => gitRepoUrl.startsWith(item));
}
async function updatePkg(pkgPath: string, obj: Record<string, unknown>) {
async function updatePkg(pkgPath: string, obj: {[key: string]: unknown}) {
const content = await fs.readFile(pkgPath, 'utf-8');
const pkg = JSON.parse(content);
const newPkg = Object.assign(pkg, obj);
@ -38,19 +110,17 @@ async function updatePkg(pkgPath: string, obj: Record<string, unknown>) {
await fs.outputFile(pkgPath, `${JSON.stringify(newPkg, null, 2)}\n`);
}
function readTemplates(templatesDir: string) {
const templates = fs
.readdirSync(templatesDir)
.filter(
(d) =>
!d.startsWith('.') &&
!d.startsWith('README') &&
!d.endsWith(TypeScriptTemplateSuffix) &&
d !== 'shared',
);
async function readTemplates(templatesDir: string) {
const templates = (await fs.readdir(templatesDir)).filter(
(d) =>
!d.startsWith('.') &&
!d.startsWith('README') &&
!d.endsWith(TypeScriptTemplateSuffix) &&
d !== 'shared',
);
// Classic should be first in list!
return sortBy(templates, (t) => t !== RecommendedTemplate);
return _.sortBy(templates, (t) => t !== RecommendedTemplate);
}
function createTemplateChoices(templates: string[]) {
@ -79,44 +149,67 @@ async function copyTemplate(
template: string,
dest: string,
) {
await fs.copy(path.resolve(templatesDir, 'shared'), dest);
await fs.copy(path.join(templatesDir, 'shared'), dest);
// TypeScript variants will copy duplicate resources like CSS & config from base template
// TypeScript variants will copy duplicate resources like CSS & config from
// base template
const tsBaseTemplate = getTypeScriptBaseTemplate(template);
if (tsBaseTemplate) {
const tsBaseTemplatePath = path.resolve(templatesDir, tsBaseTemplate);
await fs.copy(tsBaseTemplatePath, dest, {
filter: (filePath) =>
fs.statSync(filePath).isDirectory() ||
filter: async (filePath) =>
(await fs.stat(filePath)).isDirectory() ||
path.extname(filePath) === '.css' ||
path.basename(filePath) === 'docusaurus.config.js',
});
}
await fs.copy(path.resolve(templatesDir, template), dest, {
// Symlinks don't exist in published NPM packages anymore, so this is only to prevent errors during local testing
filter: (filePath) => !fs.lstatSync(filePath).isSymbolicLink(),
// Symlinks don't exist in published npm packages anymore, so this is only
// to prevent errors during local testing
filter: async (filePath) => !(await fs.lstat(filePath)).isSymbolicLink(),
});
}
const gitStrategies = ['deep', 'shallow', 'copy', 'custom'] as const;
async function getGitCommand(gitStrategy: typeof gitStrategies[number]) {
switch (gitStrategy) {
case 'shallow':
case 'copy':
return 'git clone --recursive --depth 1';
case 'custom': {
const {command} = await prompts({
type: 'text',
name: 'command',
message:
'Write your own git clone command. The repository URL and destination directory will be supplied. E.g. "git clone --depth 10"',
});
return command;
}
case 'deep':
default:
return 'git clone';
}
}
export default async function init(
rootDir: string,
siteName?: string,
reqTemplate?: string,
cliOptions: Partial<{
useNpm: boolean;
packageManager: SupportedPackageManager;
skipInstall: boolean;
typescript: boolean;
gitStrategy: typeof gitStrategies[number];
}> = {},
): Promise<void> {
const useYarn = cliOptions.useNpm ? false : hasYarn();
const templatesDir = path.resolve(__dirname, '../templates');
const templates = readTemplates(templatesDir);
const templatesDir = fileURLToPath(new URL('../templates', import.meta.url));
const templates = await readTemplates(templatesDir);
const hasTS = (templateName: string) =>
fs.pathExistsSync(
path.resolve(templatesDir, `${templateName}${TypeScriptTemplateSuffix}`),
fs.pathExists(
path.join(templatesDir, `${templateName}${TypeScriptTemplateSuffix}`),
);
let name = siteName;
// Prompt if siteName is not passed from CLI.
@ -136,7 +229,7 @@ export default async function init(
}
const dest = path.resolve(rootDir, name);
if (fs.existsSync(dest)) {
if (await fs.pathExists(dest)) {
logger.error`Directory already exists at path=${dest}!`;
process.exit(1);
}
@ -152,7 +245,7 @@ export default async function init(
choices: createTemplateChoices(templates),
});
template = templatePrompt.template;
if (template && !useTS && hasTS(template)) {
if (template && !useTS && (await hasTS(template))) {
const tsPrompt = await prompts({
type: 'confirm',
name: 'useTS',
@ -164,6 +257,8 @@ export default async function init(
}
}
let gitStrategy = cliOptions.gitStrategy ?? 'deep';
// If user choose Git repository, we'll prompt for the url.
if (template === 'Git repository') {
const repoPrompt = await prompts({
@ -176,17 +271,31 @@ export default async function init(
return logger.red('Invalid repository URL');
},
message: logger.interpolate`Enter a repository URL from GitHub, Bitbucket, GitLab, or any other public repo.
(e.g: path=${'https://github.com/ownerName/repoName.git'})`,
(e.g: url=${'https://github.com/ownerName/repoName.git'})`,
});
({gitStrategy} = await prompts({
type: 'select',
name: 'gitStrategy',
message: 'How should we clone this repo?',
choices: [
{title: 'Deep clone: preserve full history', value: 'deep'},
{title: 'Shallow clone: clone with --depth=1', value: 'shallow'},
{
title: 'Copy: do a shallow clone, but do not create a git repo',
value: 'copy',
},
{title: 'Custom: enter your custom git clone command', value: 'custom'},
],
}));
template = repoPrompt.gitRepoUrl;
} else if (template === 'Local template') {
const dirPrompt = await prompts({
type: 'text',
name: 'templateDir',
validate: (dir?: string) => {
validate: async (dir?: string) => {
if (dir) {
const fullDir = path.resolve(process.cwd(), dir);
if (fs.existsSync(fullDir)) {
const fullDir = path.resolve(dir);
if (await fs.pathExists(fullDir)) {
return true;
}
return logger.red(
@ -209,19 +318,26 @@ export default async function init(
logger.info('Creating new Docusaurus project...');
if (isValidGitRepoUrl(template)) {
logger.info`Cloning Git template path=${template}...`;
if (
shell.exec(`git clone --recursive ${template} ${dest}`, {silent: true})
.code !== 0
) {
logger.info`Cloning Git template url=${template}...`;
if (!gitStrategies.includes(gitStrategy)) {
logger.error`Invalid git strategy: name=${gitStrategy}. Value must be one of ${gitStrategies.join(
', ',
)}.`;
process.exit(1);
}
const command = await getGitCommand(gitStrategy);
if (shell.exec(`${command} ${template} ${dest}`).code !== 0) {
logger.error`Cloning Git template name=${template} failed!`;
process.exit(1);
}
if (gitStrategy === 'copy') {
await fs.remove(path.join(dest, '.git'));
}
} else if (templates.includes(template)) {
// Docusaurus templates.
if (useTS) {
if (!hasTS(template)) {
logger.error`Template name=${template} doesn't provide the Typescript variant.`;
if (!(await hasTS(template))) {
logger.error`Template name=${template} doesn't provide the TypeScript variant.`;
process.exit(1);
}
template = `${template}${TypeScriptTemplateSuffix}`;
@ -232,8 +348,8 @@ export default async function init(
logger.error`Copying Docusaurus template name=${template} failed!`;
throw err;
}
} else if (fs.existsSync(path.resolve(process.cwd(), template))) {
const templateDir = path.resolve(process.cwd(), template);
} else if (await fs.pathExists(path.resolve(template))) {
const templateDir = path.resolve(template);
try {
await fs.copy(templateDir, dest);
} catch (err) {
@ -248,7 +364,7 @@ export default async function init(
// Update package.json info.
try {
await updatePkg(path.join(dest, 'package.json'), {
name: kebabCase(name),
name: _.kebabCase(name),
version: '0.0.0',
private: true,
});
@ -259,29 +375,36 @@ export default async function init(
// We need to rename the gitignore file to .gitignore
if (
!fs.pathExistsSync(path.join(dest, '.gitignore')) &&
fs.pathExistsSync(path.join(dest, 'gitignore'))
!(await fs.pathExists(path.join(dest, '.gitignore'))) &&
(await fs.pathExists(path.join(dest, 'gitignore')))
) {
await fs.move(path.join(dest, 'gitignore'), path.join(dest, '.gitignore'));
}
if (fs.pathExistsSync(path.join(dest, 'gitignore'))) {
fs.removeSync(path.join(dest, 'gitignore'));
if (await fs.pathExists(path.join(dest, 'gitignore'))) {
await fs.remove(path.join(dest, 'gitignore'));
}
const pkgManager = useYarn ? 'yarn' : 'npm';
// Display the most elegant way to cd.
const cdpath = path.relative('.', dest);
const pkgManager = await getPackageManager(
cliOptions.packageManager,
cliOptions.skipInstall,
);
if (!cliOptions.skipInstall) {
shell.cd(dest);
logger.info`Installing dependencies with name=${pkgManager}...`;
if (
shell.exec(useYarn ? 'yarn' : 'npm install --color always', {
env: {
...process.env,
// Force coloring the output, since the command is invoked by shelljs, which is not the interactive shell
...(supportsColor.stdout ? {FORCE_COLOR: '1'} : {}),
shell.exec(
pkgManager === 'yarn' ? 'yarn' : `${pkgManager} install --color always`,
{
env: {
...process.env,
// Force coloring the output, since the command is invoked,
// by shelljs which is not the interactive shell
...(supportsColor.stdout ? {FORCE_COLOR: '1'} : {}),
},
},
}).code !== 0
).code !== 0
) {
logger.error('Dependency installation failed.');
logger.info`The site directory has already been created, and you can retry by typing:
@ -292,16 +415,17 @@ export default async function init(
}
}
logger.success`Created path=${cdpath}.`;
const useNpm = pkgManager === 'npm';
logger.success`Created name=${cdpath}.`;
logger.info`Inside that directory, you can run several commands:
code=${`${pkgManager} start`}
Starts the development server.
code=${`${pkgManager} ${useYarn ? '' : 'run '}build`}
code=${`${pkgManager} ${useNpm ? 'run ' : ''}build`}
Bundles your website into static files for production.
code=${`${pkgManager} ${useYarn ? '' : 'run '}serve`}
code=${`${pkgManager} ${useNpm ? 'run ' : ''}serve`}
Serves the built website locally.
code=${`${pkgManager} deploy`}

View File

@ -1,6 +1,6 @@
{
"name": "docusaurus-2-classic-typescript-template",
"version": "2.0.0-beta.14",
"version": "2.0.0-beta.18",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
@ -15,18 +15,18 @@
"typecheck": "tsc"
},
"dependencies": {
"@docusaurus/core": "2.0.0-beta.14",
"@docusaurus/preset-classic": "2.0.0-beta.14",
"@mdx-js/react": "^1.6.21",
"@docusaurus/core": "2.0.0-beta.18",
"@docusaurus/preset-classic": "2.0.0-beta.18",
"@mdx-js/react": "^1.6.22",
"clsx": "^1.1.1",
"prism-react-renderer": "^1.2.1",
"react": "^17.0.1",
"react-dom": "^17.0.1"
"prism-react-renderer": "^1.3.1",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "2.0.0-beta.14",
"@tsconfig/docusaurus": "^1.0.4",
"typescript": "^4.5.2"
"@docusaurus/module-type-aliases": "2.0.0-beta.18",
"@tsconfig/docusaurus": "^1.0.5",
"typescript": "^4.6.3"
},
"browserslist": {
"production": [

View File

@ -1 +0,0 @@
../../../classic/src/components/HomepageFeatures.module.css

View File

@ -1,18 +1,17 @@
import useBaseUrl from '@docusaurus/useBaseUrl';
import React from 'react';
import clsx from 'clsx';
import styles from './HomepageFeatures.module.css';
import styles from './styles.module.css';
type FeatureItem = {
title: string;
image: string;
Svg: React.ComponentType<React.ComponentProps<'svg'>>;
description: JSX.Element;
};
const FeatureList: FeatureItem[] = [
{
title: 'Easy to Use',
image: '/img/undraw_docusaurus_mountain.svg',
Svg: require('@site/static/img/undraw_docusaurus_mountain.svg').default,
description: (
<>
Docusaurus was designed from the ground up to be easily installed and
@ -22,7 +21,7 @@ const FeatureList: FeatureItem[] = [
},
{
title: 'Focus on What Matters',
image: '/img/undraw_docusaurus_tree.svg',
Svg: require('@site/static/img/undraw_docusaurus_tree.svg').default,
description: (
<>
Docusaurus lets you focus on your docs, and we&apos;ll do the chores. Go
@ -32,7 +31,7 @@ const FeatureList: FeatureItem[] = [
},
{
title: 'Powered by React',
image: '/img/undraw_docusaurus_react.svg',
Svg: require('@site/static/img/undraw_docusaurus_react.svg').default,
description: (
<>
Extend or customize your website layout by reusing React. Docusaurus can
@ -42,15 +41,11 @@ const FeatureList: FeatureItem[] = [
},
];
function Feature({title, image, description}: FeatureItem) {
function Feature({title, Svg, description}: FeatureItem) {
return (
<div className={clsx('col col--4')}>
<div className="text--center">
<img
className={styles.featureSvg}
alt={title}
src={useBaseUrl(image)}
/>
<Svg className={styles.featureSvg} role="img" />
</div>
<div className="text--center padding-horiz--md">
<h3>{title}</h3>

View File

@ -0,0 +1 @@
../../../../classic/src/components/HomepageFeatures/styles.module.css

View File

@ -4,7 +4,7 @@ import Layout from '@theme/Layout';
import Link from '@docusaurus/Link';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import styles from './index.module.css';
import HomepageFeatures from '../components/HomepageFeatures';
import HomepageFeatures from '@site/src/components/HomepageFeatures';
function HomepageHeader() {
const {siteConfig} = useDocusaurusContext();

View File

@ -13,6 +13,9 @@ const config = {
onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'warn',
favicon: 'img/favicon.ico',
// GitHub pages deployment config.
// If you aren't using GitHub pages, you don't need these.
organizationName: 'facebook', // Usually your GitHub org/user name.
projectName: 'docusaurus', // Usually your repo name.
@ -24,11 +27,14 @@ const config = {
docs: {
sidebarPath: require.resolve('./sidebars.js'),
// Please change this to your repo.
editUrl: 'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/',
// Remove this to remove the "edit this page" links.
editUrl:
'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/',
},
blog: {
showReadingTime: true,
// Please change this to your repo.
// Remove this to remove the "edit this page" links.
editUrl:
'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/',
},

View File

@ -1,6 +1,6 @@
{
"name": "docusaurus-2-classic-template",
"version": "2.0.0-beta.14",
"version": "2.0.0-beta.18",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
@ -14,13 +14,16 @@
"write-heading-ids": "docusaurus write-heading-ids"
},
"dependencies": {
"@docusaurus/core": "2.0.0-beta.14",
"@docusaurus/preset-classic": "2.0.0-beta.14",
"@mdx-js/react": "^1.6.21",
"@docusaurus/core": "2.0.0-beta.18",
"@docusaurus/preset-classic": "2.0.0-beta.18",
"@mdx-js/react": "^1.6.22",
"clsx": "^1.1.1",
"prism-react-renderer": "^1.2.1",
"react": "^17.0.1",
"react-dom": "^17.0.1"
"prism-react-renderer": "^1.3.1",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "2.0.0-beta.18"
},
"browserslist": {
"production": [

View File

@ -1,11 +1,11 @@
import React from 'react';
import clsx from 'clsx';
import styles from './HomepageFeatures.module.css';
import styles from './styles.module.css';
const FeatureList = [
{
title: 'Easy to Use',
Svg: require('../../static/img/undraw_docusaurus_mountain.svg').default,
Svg: require('@site/static/img/undraw_docusaurus_mountain.svg').default,
description: (
<>
Docusaurus was designed from the ground up to be easily installed and
@ -15,7 +15,7 @@ const FeatureList = [
},
{
title: 'Focus on What Matters',
Svg: require('../../static/img/undraw_docusaurus_tree.svg').default,
Svg: require('@site/static/img/undraw_docusaurus_tree.svg').default,
description: (
<>
Docusaurus lets you focus on your docs, and we&apos;ll do the chores. Go
@ -25,7 +25,7 @@ const FeatureList = [
},
{
title: 'Powered by React',
Svg: require('../../static/img/undraw_docusaurus_react.svg').default,
Svg: require('@site/static/img/undraw_docusaurus_react.svg').default,
description: (
<>
Extend or customize your website layout by reusing React. Docusaurus can
@ -39,7 +39,7 @@ function Feature({Svg, title, description}) {
return (
<div className={clsx('col col--4')}>
<div className="text--center">
<Svg className={styles.featureSvg} alt={title} />
<Svg className={styles.featureSvg} role="img" />
</div>
<div className="text--center padding-horiz--md">
<h3>{title}</h3>

View File

@ -17,7 +17,7 @@
}
/* For readability concerns, you should choose a lighter palette in dark mode. */
html[data-theme='dark'] {
[data-theme='dark'] {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: #21af90;
--ifm-color-primary-darker: #1fa588;
@ -34,6 +34,6 @@ html[data-theme='dark'] {
padding: 0 var(--ifm-pre-padding);
}
html[data-theme='dark'] .docusaurus-highlight-code-line {
[data-theme='dark'] .docusaurus-highlight-code-line {
background-color: rgba(0, 0, 0, 0.3);
}

View File

@ -4,7 +4,7 @@ import Layout from '@theme/Layout';
import Link from '@docusaurus/Link';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import styles from './index.module.css';
import HomepageFeatures from '../components/HomepageFeatures';
import HomepageFeatures from '@site/src/components/HomepageFeatures';
function HomepageHeader() {
const {siteConfig} = useDocusaurusContext();

View File

@ -10,7 +10,7 @@
overflow: hidden;
}
@media screen and (max-width: 966px) {
@media screen and (max-width: 996px) {
.heroBanner {
padding: 2rem;
}

View File

@ -18,6 +18,9 @@ const config = {
onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'warn',
favicon: 'img/favicon.ico',
// GitHub pages deployment config.
// If you aren't using GitHub pages, you don't need these.
organizationName: 'facebook', // Usually your GitHub org/user name.
projectName: 'docusaurus', // Usually your repo name.
@ -29,12 +32,14 @@ const config = {
docs: {
sidebarPath: require.resolve('./sidebars.js'),
// Please change this to your repo.
// Remove this to remove the "edit this page" links.
editUrl:
'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/',
},
blog: {
showReadingTime: true,
// Please change this to your repo.
// Remove this to remove the "edit this page" links.
editUrl:
'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/',
},

Some files were not shown because too many files have changed in this diff Show More