Skip to content

Commit

Permalink
chore(docs): try another way for runnable scss module demos
Browse files Browse the repository at this point in the history
  • Loading branch information
mlaursen committed Nov 11, 2023
1 parent e86d030 commit 128fad6
Show file tree
Hide file tree
Showing 9 changed files with 132 additions and 43 deletions.
8 changes: 8 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ jobs:
- run: pnpm build --filter="./packages/*"
- run: pnpm lint
- run: pnpm typecheck

# # Check if there are uncommitted generated changes
# - run: pnpm --filter docs api-pages
# - run: pnpm --filter docs mdx-pages
# - run: pnpm --filter docs scss-lookup
# - run: pnpm --filter docs prism-themes
# - run: git diff --quiet

- run: pnpm test -- -- --coverage
- run: npx codecov -t ${{ secrets.CODECOV_TOKEN }}

Expand Down
4 changes: 2 additions & 2 deletions apps/docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
"clean": "rm -rf .turbo .next node_modules",
"next-dev": "next dev",
"next-build": "next build",
"dev": "npm-run-all create-env api-docs watch",
"build": "npm-run-all create-env api-docs mdx-pages scss-lookup next-build",
"dev": "npm-run-all create-env watch",
"build": "npm-run-all create-env next-build",
"start": "next start"
},
"engines": {
Expand Down
6 changes: 6 additions & 0 deletions apps/docs/scripts/codeCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { type FakeScssModule } from "../src/utils/fakeScssModules.js";

/**
* Mutable cache
*/
export const scssModulesCache = new Map<string, FakeScssModule>();
34 changes: 31 additions & 3 deletions apps/docs/scripts/createMarkdownPages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@ import { watch } from "chokidar";
import { glob } from "glob";
import { existsSync } from "node:fs";
import { join, parse, type ParsedPath } from "node:path";
import { scssModulesCache } from "./codeCache.js";
import { createDemoMdx } from "./utils/createDemoMdx.js";
import { createMdxPage } from "./utils/createMdxPage.js";
import {
createScssModuleFile,
updateScssModule,
} from "./utils/createScssModules.js";
import { getScriptFlags } from "./utils/getScriptFlags.js";
import { log } from "./utils/log.js";

Expand All @@ -18,8 +23,14 @@ const { isWatch } = getScriptFlags();
async function createAll(): Promise<void> {
await Promise.all([
...readmes.map((markdownPath) => createMdxPage(markdownPath)),
...mdxDemos.map(async (demoPath) => createDemoMdx(demoPath, false)),
...mdxDemos.map((demoPath) =>
createDemoMdx({
demoPath,
isLogged: false,
})
),
]);
await createScssModuleFile();
}

await log(createAll(), "Compiling mdx and demos", "Compiled");
Expand All @@ -29,7 +40,10 @@ const isProbablyDemoRelatedFile = (
demosPath: string
): boolean => {
const { base, ext } = parsed;
if (["page.tsx", "toc.ts"].includes(base) || [".mdx", ".md"].includes(ext)) {
if (
["page.tsx", "toc.ts"].includes(base) ||
[".mdx", ".md", ".scss"].includes(ext)
) {
return false;
}

Expand All @@ -50,7 +64,10 @@ if (isWatch) {
try {
if (isMdxDemos || isProbablyDemoRelatedFile(parsed, maybeDemos)) {
await log(
createDemoMdx(isMdxDemos ? path : maybeDemos, true),
createDemoMdx({
demoPath: isMdxDemos ? path : maybeDemos,
isLogged: true,
}),
`Compiling demos for ${path}`,
"Compiled demos"
);
Expand All @@ -60,11 +77,22 @@ if (isWatch) {
`Compiling markdown for ${path}`,
"Compiled markdown"
);
} else if (parsed.ext === ".scss") {
await log(
updateScssModule(path),
"Updating fake scss modules",
"Updated fake scss modules"
);
}
} catch (e) {
console.error(e);
}
});
watcher.on("unlink", async (path) => {
if (path.endsWith(".module.scss")) {
scssModulesCache.delete(path);
}
});
watcher.on("ready", () => {
console.log(" ✓ Watching for markdown changes ... ");
});
Expand Down
17 changes: 10 additions & 7 deletions apps/docs/scripts/utils/createDemoMarkdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async function insertImportedCode(options: FixOptions): Promise<void> {

const demoFilePath = join(directory, importName);
const { styles, demoCode } = await log(
getDemoCode(demoFilePath, directory),
getDemoCode({ directory, demoFilePath }),
"",
isLogged ? `Compiled ${demoFilePath}` : ""
);
Expand All @@ -51,9 +51,6 @@ async function insertImportedCode(options: FixOptions): Promise<void> {
phone && "phone",
fileName && `fileName="${fileName}"`,
styles.length > 0 && `styles="${styles.join(",")}"`,
process.env.NODE_ENV !== "production" &&
styles.length &&
`hotReload="${Date.now()}"`,
]
.filter(Boolean)
.join(" ");
Expand Down Expand Up @@ -112,11 +109,17 @@ const parseOptions = (line: string): ParsedOptions => {
};
};

interface CreateDemoMarkdownOptions {
path: string;
outPath: string;
isLogged: boolean;
}

export async function createDemoMarkdown(
path: string,
outPath: string,
isLogged: boolean
options: CreateDemoMarkdownOptions
): Promise<void> {
const { path, outPath, isLogged } = options;

const directory = dirname(path);
const raw = await readFile(path, "utf8");

Expand Down
17 changes: 12 additions & 5 deletions apps/docs/scripts/utils/createDemoMdx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,19 @@ import { createMdxPage } from "./createMdxPage.js";

const DEMO_PAGE_MDX = "demo-page.mdx";

export async function createDemoMdx(
demoPath: string,
isLogged: boolean
): Promise<void> {
interface Options {
demoPath: string;
isLogged: boolean;
}

export async function createDemoMdx(options: Options): Promise<void> {
const { demoPath, isLogged } = options;
const demoPageMdxPath = demoPath.replace(parse(demoPath).base, DEMO_PAGE_MDX);

await createDemoMarkdown(demoPath, demoPageMdxPath, isLogged);
await createDemoMarkdown({
path: demoPath,
outPath: demoPageMdxPath,
isLogged,
});
await createMdxPage(demoPath, DEMO_PAGE_MDX);
}
42 changes: 42 additions & 0 deletions apps/docs/scripts/utils/createScssModules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { readFile, writeFile } from "node:fs/promises";
import { basename } from "node:path";
import { compileScssModule } from "../../src/utils/compileScssModule.js";
import { format } from "../../src/utils/format.js";
import { scssModulesCache } from "../codeCache.js";
import { GENERATED_FILE_BANNER } from "../constants.js";

const SCSS_MODULES_PATH = "src/constants/scssModulesLookup.ts";

export async function createScssModule(scssModulePath: string): Promise<void> {
const scss = await readFile(scssModulePath, "utf8");
const fileName = basename(scssModulePath);
const baseName = fileName.replace(".module.scss", "");
const css = await compileScssModule({
scss,
baseName,
});

scssModulesCache.set(scssModulePath, {
css,
scss,
baseName,
fileName,
});
}

export async function createScssModuleFile(): Promise<void> {
const contents = await format(`${GENERATED_FILE_BANNER}
import "server-only";
import { type FakeScssModule } from "../utils/fakeScssModules.js";
export const SCSS_MODULES: Record<string, FakeScssModule> =
${JSON.stringify(Object.fromEntries(scssModulesCache.entries()))};
`);

await writeFile(SCSS_MODULES_PATH, contents);
}

export async function updateScssModule(scssModulePath: string): Promise<void> {
await createScssModule(scssModulePath);
await createScssModuleFile();
}
14 changes: 12 additions & 2 deletions apps/docs/scripts/utils/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
type SourceFile,
} from "ts-morph";
import { format } from "../../src/utils/format.js";
import { createScssModule } from "./createScssModules.js";

const getImportName = (imp: ImportDeclaration): string =>
imp
Expand Down Expand Up @@ -71,10 +72,16 @@ interface DemoCode {
demoCode: string;
}

interface DemoCodeOptions {
directory: string;
demoFilePath: string;
}

export const getDemoCode = async (
demoFilePath: string,
directory: string
options: DemoCodeOptions
): Promise<DemoCode> => {
const { directory, demoFilePath } = options;

const project = new Project({
tsConfigFilePath: "./tsconfig.json",
skipAddingFilesFromTsConfig: true,
Expand Down Expand Up @@ -107,6 +114,9 @@ export const getDemoCode = async (

imp.remove();
});
await Promise.all(
styles.map(async (scssModulePath) => createScssModule(scssModulePath))
);

const demoCode = await format(demo.getFullText());

Expand Down
33 changes: 9 additions & 24 deletions apps/docs/src/utils/parseCodeBlock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@ import { type RunnableCodeAndPreviewOptions } from "@/components/DangerouslyRunC
import { type RunnableCodePreviewOptions } from "@/components/DangerouslyRunCode/RunnableCodePreviewContainer.jsx";
import { type PackageManagerCodeBlockProps } from "@/components/PackageManagerCodeBlock.js";
import { type HighlightedTypescriptCode } from "@/components/TypescriptCode.js";
import { compileScssModule } from "@/utils/compileScssModule.js";
import { SCSS_MODULES } from "@/constants/scssModulesLookup.js";
import { convertTsToJs } from "@/utils/convertTsToJs.js";
import { highlightCode } from "@/utils/highlightCode.js";
import { readFile } from "node:fs/promises";
import { basename } from "node:path";
import "server-only";
import { type FakeScssModule } from "./fakeScssModules.js";

Expand Down Expand Up @@ -86,9 +84,6 @@ export async function parseCodeBlock(
case "styles":
scssModulesPaths = value.split(",");
break;
case "hotReload":
// this is used to force hot reloading when scss modules exist
break;
default:
throw new Error(`Unsupported code property: ${name}`);
}
Expand Down Expand Up @@ -132,24 +127,14 @@ export async function parseCodeBlock(

let scssModules: FakeScssModule[] | undefined;
if (scssModulesPaths) {
scssModules = await Promise.all(
scssModulesPaths.map<Promise<FakeScssModule>>(async (scssModulePath) => {
const fileName = basename(scssModulePath);
const baseName = fileName.replace(".module.scss", "");
const scss = await readFile(scssModulePath, "utf8");
const css = await compileScssModule({
scss,
baseName,
});

return {
css,
scss,
baseName,
fileName,
};
})
);
scssModules = scssModulesPaths.map((scssModulesPath) => {
const fakeScssModule = SCSS_MODULES[scssModulesPath];
if (!fakeScssModule) {
throw new Error(`Missing fake scss module for: "${scssModulesPath}"`);
}

return fakeScssModule;
});
}

return {
Expand Down

0 comments on commit 128fad6

Please sign in to comment.