Skip to content

Commit

Permalink
Feat(cosmos): add react-cosmos
Browse files Browse the repository at this point in the history
  • Loading branch information
noahehall committed Jun 10, 2023
1 parent 4468b48 commit aaa097f
Show file tree
Hide file tree
Showing 8 changed files with 195 additions and 11 deletions.
Binary file modified bun.lockb
Binary file not shown.
118 changes: 118 additions & 0 deletions cosmos.bunserver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { rm, stat } from "node:fs/promises";
import type { ServeOptions } from "bun";
import * as path from "path";

import cosmosConfig from "./cosmos.config.json";

const PROJECT_ROOT = import.meta.dir;
const BUILD_DIR = path.resolve(PROJECT_ROOT, "build");

const waitForCosmosImports = async () => {
const fpath = `${PROJECT_ROOT}/cosmos.imports.ts`;
try {
const cosmosImports = await stat(fpath);
if (!cosmosImports.isFile()) {
throw new Error(`
file doesnt exist yet
`);
}
} catch {
return new Promise((resolve) => {
setTimeout(() => resolve(waitForCosmosImports()), 1000);
});
}
};

const buildApp = async () =>
rm(BUILD_DIR, { force: true, recursive: true }).then(() =>
Bun.build({
entrypoints: ["./cosmos.entrypoint.tsx"],
target: "browser",
outdir: "build",
})
.then((output) => output)
.catch((e) => {
console.info("\n\n error in build", e);
})
);

await waitForCosmosImports();
await buildApp().then((output) => {
if (output.success)
console.info(
`app built: ${output.success}; ${output.outputs.length} files `
);
else {
for (const message of output.logs) {
// Bun will pretty print the message object
console.error(message);
}
throw new Error(`build failed`);
}
});

const returnIndex = () => {
const index = `
<!DOCTYPE html>
<html lang="en">
<body>
<script src="${BUILD_DIR}/cosmos.entrypoint.js" type="module">
</script>
</body>
</html>
`;

return new Response(index, {
headers: {
"Content-Type": "text/html",
"Access-Control-Allow-Origin": "*",
},
});
};

async function serveFromDir(config: {
directory?: string;
path: string;
}): Promise<Response | null> {
const filepath = path.join(config.directory || "", config.path);

try {
const fd = await stat(filepath);
if (fd && fd.isFile()) {
return new Response(Bun.file(filepath), {
headers: { "Access-Control-Allow-Origin": "*" },
});
}
} catch (err) {}

return null;
}
export default {
port: cosmosConfig.rendererUrl.split(":").pop(),
hostname: "0.0.0.0",
async fetch(req) {
const reqPath = new URL(req.url).pathname;
console.log(req.method, reqPath);

if (reqPath === "/") return returnIndex();
else {
const filepath = req.url.replace(cosmosConfig.rendererUrl, "");

const exactResponse = await serveFromDir({ path: filepath });
if (exactResponse) return exactResponse;

const buildResponse = await serveFromDir({
directory: BUILD_DIR,
path: filepath,
});
if (buildResponse) return buildResponse;

return new Response("File not found", {
status: 404,
});
}
},
} satisfies ServeOptions;

// watch imports
await import("./cosmos.imports.ts").catch((e) => e);
4 changes: 4 additions & 0 deletions cosmos.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"port": 5000,
"rendererUrl": "http://0.0.0.0:5050"
}
4 changes: 4 additions & 0 deletions cosmos.entrypoint.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { mountDomRenderer } from "react-cosmos-dom";
import * as mountArgs from "./cosmos.imports";

mountDomRenderer(mountArgs);
23 changes: 23 additions & 0 deletions cosmos.imports.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// This file is automatically generated by Cosmos. Add it to .gitignore and
// only edit if you know what you're doing.

import { RendererConfig, UserModuleWrappers } from 'react-cosmos-core';

import * as fixture0 from './src/fixtures/example.fixture';

export const rendererConfig: RendererConfig = {
"playgroundUrl": "http://localhost:5000",
"rendererUrl": "http://0.0.0.0:5050"
};

const fixtures = {
'src/fixtures/example.fixture.tsx': { module: fixture0 }
};

const decorators = {};

export const moduleWrappers: UserModuleWrappers = {
lazy: false,
fixtures,
decorators
};
10 changes: 8 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
"main": "dist/index.js",
"module": "src/index.ts",
"scripts": {
"cosmos": "bun run cosmos:start & bun run cosmos:bun",
"cosmos:bun": "bun --watch cosmos.bunserver.ts",
"cosmos:start": "cosmos --expose-imports",
"barrels": "bunx barrelsby --config ./barrels.json",
"build": "rm -rf ./dist/* && bun build src/index.ts --outdir ./dist",
"lint": "bunx eslint src --fix --resolve-plugins-relative-to .",
Expand All @@ -20,14 +23,17 @@
"react": "^18.2"
},
"devDependencies": {
"@types/react": "18.2.7",
"react-cosmos-core": "^6.0.0-alpha.0",
"react-cosmos-dom": "next",
"react-cosmos": "next",
"@types/react": "18.2.9",
"barrels": "1.6.6",
"bun-types": "canary",
"eslint-config-prettier": "8.8.0",
"eslint-config-react-app": "7.0.1",
"eslint-plugin-jsx-a11y": "6.7.1",
"eslint-plugin-react": "7.32.2",
"eslint": "8.41.0",
"eslint": "8.42.0",
"framer-motion": "10.12.16",
"npm-check-updates": "16.10.12",
"prettier": "2.8.8",
Expand Down
37 changes: 37 additions & 0 deletions src/fixtures/example.fixture.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { ReactFP, FPContainer, FPItem } from "src/index";

export default function App() {
return (
<ReactFP>
<FPContainer>
<FPItem
style={{
backgroundColor: "lime",
height: "80vh", // defaults to 100vh
padding: "1em",
}}
>
1
</FPItem>

<FPItem
style={{
backgroundColor: "coral",
padding: "1em",
}}
>
2
</FPItem>

<FPItem
style={{
backgroundColor: "firebrick",
padding: "1em",
}}
>
3
</FPItem>
</FPContainer>
</ReactFP>
);
}
10 changes: 1 addition & 9 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,11 @@
"**/node_modules",
"**/.git",
"**/build",
"**/.turbo",
"**/dist",
"**/lib"
]
},
"exclude": [
"**/node_modules",
"**/.git",
"**/build",
"**/.turbo",
"**/dist",
"**/lib"
],
"exclude": ["**/node_modules", "**/.git", "**/build", "**/dist", "**/lib"],
"compilerOptions": {
"allowImportingTsExtensions": true,
"allowJs": true,
Expand Down

0 comments on commit aaa097f

Please sign in to comment.