docs(core): fix preview images and refactored out WORKSPACE_ROOT environment variable (#6311)

This commit is contained in:
Jack Hsu 2021-07-09 00:19:02 -04:00 committed by GitHub
parent 9bbfbddabf
commit 63d9c578a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 143 additions and 79 deletions

View File

@ -1,24 +1,8 @@
import { DocumentsApi } from './documents.api';
import type { DocumentMetadata } from './documents.models';
import { join } from 'path';
import fs from 'fs';
const archiveRootPath = join(
process.env.WORKSPACE_ROOT,
'nx-dev/nx-dev/public/documentation'
);
const documentsCache = new Map<string, DocumentMetadata[]>([
['latest', readJsonFile(join(archiveRootPath, 'latest', 'map.json'))],
['previous', readJsonFile(join(archiveRootPath, 'previous', 'map.json'))],
]);
const versionsData = readJsonFile(join(archiveRootPath, 'versions.json'));
function readJsonFile(f) {
return JSON.parse(fs.readFileSync(f).toString());
}
import { createDocumentApiOptions } from './test-utils';
describe('DocumentsApi', () => {
const api = new DocumentsApi(versionsData, documentsCache);
const api = new DocumentsApi(createDocumentApiOptions());
describe('getDocument', () => {
it('should retrieve documents that exist', () => {

View File

@ -1,11 +1,7 @@
import { readFileSync } from 'fs';
import { join, relative } from 'path';
import matter from 'gray-matter';
import {
archiveRootPath,
extractTitle,
previewRootPath,
} from './documents.utils';
import { extractTitle } from './documents.utils';
import {
DocumentData,
DocumentMetadata,
@ -24,16 +20,20 @@ export const flavorList: {
export class DocumentsApi {
constructor(
private readonly versions: VersionMetadata[],
private readonly documentsMap: Map<string, DocumentMetadata[]>
private readonly options: {
previewRoot: string;
archiveRoot: string;
versions: VersionMetadata[];
documentsMap: Map<string, DocumentMetadata[]>;
}
) {}
getDefaultVersion(): VersionMetadata {
return this.versions.find((v) => v.default);
return this.options.versions.find((v) => v.default);
}
getVersions(): VersionMetadata[] {
return this.versions;
return this.options.versions;
}
getDocument(
@ -52,7 +52,9 @@ export class DocumentsApi {
return {
filePath: relative(
versionId === 'preview' ? previewRootPath : archiveRootPath,
versionId === 'preview'
? this.options.previewRoot
: this.options.archiveRoot,
docPath
),
data: file.data,
@ -62,7 +64,7 @@ export class DocumentsApi {
}
getDocuments(version: string) {
const docs = this.documentsMap.get(version);
const docs = this.options.documentsMap.get(version);
if (docs) {
return docs;
} else {
@ -106,13 +108,13 @@ export class DocumentsApi {
getDocumentsRoot(version: string): string {
if (version === 'preview') {
return previewRootPath;
return this.options.previewRoot;
}
if (version === 'latest' || version === 'previous') {
return join(
archiveRootPath,
this.versions.find((x) => x.id === version).path
this.options.archiveRoot,
this.options.versions.find((x) => x.id === version).path
);
}

View File

@ -1,11 +1,3 @@
import { join } from 'path';
export const archiveRootPath = join(
process.env.WORKSPACE_ROOT,
'nx-dev/nx-dev/public/documentation'
);
export const previewRootPath = join(process.env.WORKSPACE_ROOT, 'docs');
export function extractTitle(markdownContent: string): string | null {
return (
/^\s*#\s+(?<title>.+)[\n.]+/.exec(markdownContent)?.groups.title ?? null

View File

@ -1,27 +1,9 @@
import { MenuApi } from './menu.api';
import {
DocumentMetadata,
DocumentsApi,
} from '@nrwl/nx-dev/data-access-documents';
import { join } from 'path';
import * as fs from 'fs';
const archiveRootPath = join(
process.env.WORKSPACE_ROOT,
'nx-dev/nx-dev/public/documentation'
);
const documentsCache = new Map<string, DocumentMetadata[]>([
['latest', readJsonFile(join(archiveRootPath, 'latest', 'map.json'))],
['previous', readJsonFile(join(archiveRootPath, 'previous', 'map.json'))],
]);
const versionsData = readJsonFile(join(archiveRootPath, 'versions.json'));
function readJsonFile(f) {
return JSON.parse(fs.readFileSync(f).toString());
}
import { DocumentsApi } from '@nrwl/nx-dev/data-access-documents';
import { createDocumentApiOptions } from './test-utils';
describe('MenuApi', () => {
const docsApi = new DocumentsApi(versionsData, documentsCache);
const docsApi = new DocumentsApi(createDocumentApiOptions());
const api = new MenuApi(docsApi);
describe('getMenu', () => {

View File

@ -0,0 +1,42 @@
import { join } from 'path';
import { DocumentMetadata } from '@nrwl/nx-dev/data-access-documents';
import fs from 'fs';
function readJsonFile(f) {
return JSON.parse(fs.readFileSync(f).toString());
}
export function createDocumentApiOptions() {
return {
versions: readJsonFile(
join(
join(__dirname, '../../../nx-dev/public/documentation'),
'versions.json'
)
),
documentsMap: new Map<string, DocumentMetadata[]>([
[
'latest',
readJsonFile(
join(
join(__dirname, '../../../nx-dev/public/documentation'),
'latest',
'map.json'
)
),
],
[
'previous',
readJsonFile(
join(
join(__dirname, '../../../nx-dev/public/documentation'),
'previous',
'map.json'
)
),
],
]),
previewRoot: join(__dirname, '../../../../docs'),
archiveRoot: join(__dirname, '../../../nx-dev/public/documentation'),
};
}

View File

@ -1 +0,0 @@
process.env.WORKSPACE_ROOT = process.cwd();

View File

@ -1,6 +1,7 @@
import React from 'react';
import ReactMarkdown from 'react-markdown';
import autolinkHeadings from 'rehype-autolink-headings';
import Image from 'next/image';
import gfm from 'remark-gfm';
import slug from 'rehype-slug';
import { DocumentData } from '@nrwl/nx-dev/data-access-documents';
@ -19,7 +20,11 @@ export interface ContentProps {
interface ComponentsConfig {
readonly code: { callback: (command: string) => void };
}
const components: any = (config: ComponentsConfig) => ({
p({ children }) {
return <>{children}</>;
},
code({ node, inline, className, children, ...props }) {
const language = /language-(\w+)/.exec(className || '')?.[1];
return !inline && language ? (
@ -80,6 +85,7 @@ export function Content(props: ContentProps) {
</div>
);
}
function createAnchorContent(node) {
node.properties.className = ['group'];
return {

View File

@ -11,7 +11,7 @@ export function transformImagePath({
}): (src: string) => string {
return (src) => {
if (/\.(gif|jpe?g|tiff?|png|webp|bmp)$/i.test(src)) {
if (version === 'preview') {
if (!process.env.VERCEL && version === 'preview') {
src = `/api/preview-asset?uri=${encodeURIComponent(
src
)}&document=${encodeURIComponent(document.filePath)}`;

View File

@ -1,3 +1,4 @@
import { join } from 'path';
import {
DocumentMetadata,
DocumentsApi,
@ -37,8 +38,14 @@ export function loadVersionsData(): VersionMetadata[] {
return versions;
}
export const documentsApi = new DocumentsApi(
loadVersionsData(),
loadDocumentsData()
);
export const documentsApi = new DocumentsApi({
previewRoot: join(process.env.NX_WORKSPACE_ROOT, 'docs'),
archiveRoot: join(
process.env.NX_WORKSPACE_ROOT,
'nx-dev/nx-dev/public/documentation'
),
documentsMap: loadDocumentsData(),
versions: loadVersionsData(),
});
export const menuApi = new MenuApi(documentsApi);

View File

@ -1,10 +1,10 @@
const { join } = require('path');
// nx-ignore-next-line
const withNx = require('@nrwl/next/plugins/with-nx');
module.exports = withNx({
// For both client and server
env: {
WORKSPACE_ROOT: join(__dirname, '../..'),
VERCEL: process.env.VERCEL,
},
async redirects() {
// TODO(jack): Remove in Nx 13

View File

@ -1,10 +1,12 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { join } from 'path';
import * as send from 'send';
// Repeated here since `data-access-documents` isn't available at runtime.
const previewRootPath = join(process.env.WORKSPACE_ROOT, 'docs');
// nx-ignore-next-line
import { appRootPath } from '@nrwl/tao/src/utils/app-root';
// This is only guaranteed during local dev since Vercel will not contain the entire workspace during runtime
const previewRootPath = join(appRootPath, 'docs');
export default function (req: NextApiRequest, res: NextApiResponse) {
return new Promise<void>((resolve) => {

View File

@ -4,6 +4,52 @@
"projectType": "application",
"targets": {
"build": {
"dependsOn": [
{
"target": "build-base",
"projects": "self"
},
{
"target": "copy-preview",
"projects": "self"
},
{
"target": "sitemap",
"projects": "self"
}
],
"executor": "@nrwl/workspace:run-commands",
"options": {
"command": "echo Build complete!"
}
},
"sitemap": {
"dependsOn": [
{
"target": "copy-preview",
"projects": "self"
}
],
"executor": "@nrwl/workspace:run-commands",
"outputs": ["dist/nx-dev/nx-dev/public"],
"options": {
"command": "npx next-sitemap --config ./nx-dev/nx-dev/next-sitemap.js"
}
},
"copy-preview": {
"dependsOn": [
{
"target": "build-base",
"projects": "self"
}
],
"executor": "@nrwl/workspace:run-commands",
"outputs": ["dist/nx-dev/nx-dev/public"],
"options": {
"command": "rm -rf dist/nx-dev/nx-dev/public/documentation/preview && cp -r docs dist/nx-dev/nx-dev/public/documentation/preview"
}
},
"build-base": {
"dependsOn": [
{
"target": "build",
@ -52,12 +98,6 @@
"jestConfig": "nx-dev/nx-dev/jest.config.js",
"passWithNoTests": true
}
},
"sitemap": {
"executor": "@nrwl/workspace:run-commands",
"options": {
"command": "./node_modules/.bin/next-sitemap --config ./nx-dev/nx-dev/next-sitemap.js"
}
}
},
"tags": ["scope:nx-dev", "type:app"],

10
nx.json
View File

@ -14,7 +14,15 @@
"runner": "@nrwl/nx-cloud",
"options": {
"accessToken": "YzVhYjFiNzAtYTYxZS00OWM3LTlkOGYtZjRmOGRlNDY4MTJhfHJlYWQtd3JpdGU=",
"cacheableOperations": ["build", "build-base", "test", "lint", "e2e"],
"cacheableOperations": [
"build",
"build-base",
"test",
"lint",
"e2e",
"copy-preview",
"sitemap"
],
"canTrackAnalytics": false,
"showUsageWarnings": true,
"runtimeCacheInputs": [