Skip to content
This repository has been archived by the owner on Jan 2, 2025. It is now read-only.

Commit

Permalink
Fix package name in file menu (#64)
Browse files Browse the repository at this point in the history
* initial setup and formatting

* add package_info table and routes

* implement package name fix

* Update dev-server-api/routes/api/package_info/get.ts

Co-authored-by: Severin Ibarluzea <[email protected]>

* Update dev-server-api/routes/api/package_info/create.ts

Co-authored-by: Severin Ibarluzea <[email protected]>

---------

Co-authored-by: Severin Ibarluzea <[email protected]>
  • Loading branch information
Slaviiiii and seveibar authored Jul 5, 2024
1 parent 6927c39 commit fb48ab8
Show file tree
Hide file tree
Showing 12 changed files with 142 additions and 37 deletions.
Binary file modified dev-server-api/bun.lockb
Binary file not shown.
28 changes: 28 additions & 0 deletions dev-server-api/routes/api/package_info/create.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { withWinterSpec } from "src/with-winter-spec"
import { z } from "zod"

export default withWinterSpec({
methods: ["POST"],
jsonBody: z.object({
package_name: z.string()
}),
jsonResponse: z.object({
package_info: z.object({
name: z.string()
})
}),
auth: "none",
})(async (req, ctx) => {
const package_name = req.jsonBody.package_name
const package_info = await ctx.db
.insertInto("package_info")
.values({
name: package_name
})
.returningAll()
.executeTakeFirstOrThrow()

return ctx.json({
package_info
})
})
18 changes: 18 additions & 0 deletions dev-server-api/routes/api/package_info/get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { export_package_info } from "src/lib/zod/export_package_info"
import { withWinterSpec } from "src/with-winter-spec"
import { z } from "zod"

export default withWinterSpec({
methods: ["GET"],
jsonResponse: z.object({
package_info: export_package_info
}),
auth: "none",
})(async (req, ctx) => {
const package_info = await ctx.db
.selectFrom("package_info")
.select("name")
.executeTakeFirstOrThrow()

return ctx.json({ package_info })
})
5 changes: 5 additions & 0 deletions dev-server-api/src/db/create-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ import type { DbClient } from "./get-db"

export const createSchema = async (db: DbClient) => {
console.log("Creating schema...")
await db.schema
.createTable("package_info")
.addColumn("name", "text", (col) => col.notNull())
.execute()

await db.schema
.createTable("dev_package_example")
.addColumn("dev_package_example_id", "integer", (col) =>
Expand Down
22 changes: 15 additions & 7 deletions dev-server-api/src/db/get-db.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { Kysely, sql, type Generated, SqliteDialect } from "kysely"
import { createSchema } from "./create-schema"
import { mkdirSync } from "fs"
import { Kysely, SqliteDialect, sql, type Generated } from "kysely"
import * as Path from "path"
import { createSchema } from "./create-schema"

export interface PackageInfo {
name: string
}

export interface DevPackageExample {
dev_package_example_id: Generated<number>
Expand Down Expand Up @@ -40,6 +44,7 @@ interface KyselyDatabaseSchema {
dev_package_example: DevPackageExample
export_request: ExportRequest
export_file: ExportFile
package_info: PackageInfo
}

export type DbClient = Kysely<KyselyDatabaseSchema>
Expand Down Expand Up @@ -72,7 +77,7 @@ export const getDb = async (): Promise<Kysely<KyselyDatabaseSchema>> => {
create: true,
}),
})
} catch (e) {}
} catch (e) { }
}

if (!dialect) {
Expand All @@ -82,7 +87,7 @@ export const getDb = async (): Promise<Kysely<KyselyDatabaseSchema>> => {
dialect = new SqliteDialect({
database: new BetterSqlite3.default(devServerDbPath),
})
} catch (e) {}
} catch (e) { }
}

if (!dialect) {
Expand All @@ -98,12 +103,15 @@ export const getDb = async (): Promise<Kysely<KyselyDatabaseSchema>> => {
const schemaExistsResult = await sql`
SELECT name
FROM sqlite_master
WHERE type='table' AND name='dev_package_example'
WHERE type='table' AND name IN ('dev_package_example', 'export_request', 'export_file', 'package_info')
`.execute(db)

if (schemaExistsResult.rows.length === 0) {
// Check if the number of existing tables matches the number of required tables
if (schemaExistsResult.rows.length < 4) {
await createSchema(db)
}

globalDb = db

return db
}
}
5 changes: 5 additions & 0 deletions dev-server-api/src/lib/zod/export_package_info.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { z } from "zod"

export const export_package_info = z.object({
name: z.string()
})
Binary file modified dev-server-frontend/bun.lockb
Binary file not shown.
3 changes: 2 additions & 1 deletion dev-server-frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"scripts": {
"dev": "vite",
"start": "npm run dev",
"build": "tsc && vite build --base /preview && rm -f dist/bundle* && make-vfs --dir dist --outfile ./dist/bundle.ts",
"build": "tsc && vite build --base /preview && rimraf dist/bundle.ts && make-vfs --dir dist --outfile ./dist/bundle.ts",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 10",
"preview": "vite preview",
"update-deps": "bun add @tscircuit/pcb-viewer@latest @tscircuit/builder@latest @tscircuit/schematic-viewer@latest @tscircuit/3d-viewer@latest"
Expand Down Expand Up @@ -45,6 +45,7 @@
"react-error-boundary": "^4.0.13",
"react-hot-toast": "^2.4.1",
"react-query": "^3.39.3",
"rimraf": "^5.0.7",
"tailwind-merge": "^2.2.1",
"tailwindcss-animate": "^1.0.7",
"zod": "^3.22.4",
Expand Down
16 changes: 8 additions & 8 deletions dev-server-frontend/src/ExampleContentView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ export const ExampleContentView = () => {
"relative",
`h-[${editorHeight}px]`,
viewMode === "split" &&
splitMode === "horizontal" &&
"grid grid-cols-2",
splitMode === "horizontal" &&
"grid grid-cols-2",
viewMode === "split" && splitMode === "vertical" && "grid grid-rows-2",
)}
>
Expand Down Expand Up @@ -141,28 +141,28 @@ export const ExampleContentView = () => {
)}
{pkg?.error && viewMode !== "soup" && (
<div className="absolute top-0 w-full">
<div className="bg-red-50 shadow-lg p-4 m-16 border-red-200 border rounded-lg whitespace-pre">
<div className="p-4 m-16 whitespace-pre border border-red-200 rounded-lg shadow-lg bg-red-50">
{pkg?.error}
</div>
</div>
)}
{notFound && (
<div className="absolute top-0 w-full flex justify-center">
<div className="absolute top-0 flex justify-center w-full">
<div className="bg-yellow-50 shadow-lg p-4 m-16 border-yellow-200 border rounded-lg whitespace-pre max-w-[400px]">
Select an example from the menu above
</div>
</div>
)}
{isLoading && !isError && (
<div className="absolute top-0 w-full flex justify-center">
<div className="bg-gray-50 shadow-lg p-4 m-16 border-gray-200 border rounded-lg whitespace-pre">
<div className="absolute top-0 flex justify-center w-full">
<div className="p-4 m-16 whitespace-pre border border-gray-200 rounded-lg shadow-lg bg-gray-50">
Loading...
</div>
</div>
)}
{pkg && pkg.is_loading && (
<div className="absolute top-0 right-0 bg-white p-4 py-2 m-4 rounded-md flex items-center z-10 shadow-lg border border-gray-200">
<div className="border-2 border-blue-400 border-t-transparent rounded-full w-4 h-4 animate-spin mr-2"></div>
<div className="absolute top-0 right-0 z-10 flex items-center p-4 py-2 m-4 bg-white border border-gray-200 rounded-md shadow-lg">
<div className="w-4 h-4 mr-2 border-2 border-blue-400 rounded-full border-t-transparent animate-spin"></div>
Rebuilding...
</div>
)}
Expand Down
33 changes: 26 additions & 7 deletions dev-server-frontend/src/HeaderMenu.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
import axios from "axios"
import { useState } from "react"
import toast from "react-hot-toast"
import { useQuery } from "react-query"
import {
Menubar,
MenubarCheckboxItem,
MenubarContent,
MenubarItem,
MenubarMenu,
MenubarRadioGroup,
MenubarRadioItem,
MenubarCheckboxItem,
MenubarSeparator,
MenubarSub,
MenubarSubContent,
MenubarSubTrigger,
MenubarTrigger,
} from "src/components/ui/menubar"
import toast from "react-hot-toast"
import { useGlobalStore } from "./hooks/use-global-store"
import frontendPackageJson from "../package.json"
import cliPackageJson from "../../package.json"
import { useGerberExportDialog } from "./components/dialogs/gerber-export-dialog"
import frontendPackageJson from "../package.json"
import { useGenericExportDialog } from "./components/dialogs/generic-export-dialog"
import { useGerberExportDialog } from "./components/dialogs/gerber-export-dialog"
import { useGlobalStore } from "./hooks/use-global-store"

export const HeaderMenu = () => {
const [viewMode, setViewMode] = useGlobalStore((s) => [
Expand All @@ -29,6 +31,23 @@ export const HeaderMenu = () => {
s.split_mode,
s.setSplitMode,
])

const {
data,
isLoading,
} = useQuery(
["package_info"],
async () =>
axios
.get(`/api/package_info/get`),
{
refetchOnWindowFocus: true,
retry: false,
},
)

const name = data?.data.package_info.name

const [inDebugMode, setInDebugMode] = useState(false)
const gerberExportDialog = useGerberExportDialog()
const pnpExportDialog = useGenericExportDialog({
Expand Down Expand Up @@ -65,7 +84,7 @@ export const HeaderMenu = () => {
<MenubarMenu>
<MenubarTrigger>File</MenubarTrigger>
<MenubarContent className="z-[200]">
<MenubarItem disabled>seveibar/[email protected]</MenubarItem>
<MenubarItem disabled>{name}</MenubarItem>
<MenubarSeparator />
<MenubarItem
onSelect={() => {
Expand Down Expand Up @@ -150,7 +169,7 @@ export const HeaderMenu = () => {
<MenubarMenu>
<MenubarTrigger>Package</MenubarTrigger>
<MenubarContent className="z-[200]">
<MenubarItem disabled>seveibar/[email protected]</MenubarItem>
<MenubarItem disabled>{name}</MenubarItem>
<MenubarSeparator />
<MenubarCheckboxItem
checked
Expand Down
11 changes: 9 additions & 2 deletions lib/cmd-fns/dev/dev-server-request-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,20 @@ import frontendVfs from "../../../dev-server-frontend/dist/bundle"
import EdgeRuntimePrimitives from "@edge-runtime/primitives"
import mime from "mime-types"

/**
* Handles all requests to :3020, then proxies...
*
* /api/* : to the api server
* /* : to the static frontend bundle inside dev-server-frontend
*
*/
export const devServerRequestHandler = async (bunReq: Request) => {
const url = new URL(bunReq.url)
const requestType = url.pathname.startsWith("/api")
? "api"
: url.pathname.startsWith("/preview")
? "preview"
: "other"
? "preview"
: "other"

if (requestType === "api") {
// We have to shim Bun's Request until they fix the issue where
Expand Down
38 changes: 26 additions & 12 deletions lib/cmd-fns/dev/index.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import { AppContext } from "../../util/app-context"
import { z } from "zod"
import $ from "dax-sh"
import fs from 'fs'
import { unlink } from "fs/promises"
import kleur from "kleur"
import prompts from "prompts"
import open from "open"
import { startDevServer } from "./start-dev-server"
import { getDevServerAxios } from "./get-dev-server-axios"
import { uploadExamplesFromDirectory } from "./upload-examples-from-directory"
import { unlink } from "fs/promises"
import * as Path from "path"
import { startFsWatcher } from "./start-fs-watcher"
import prompts from "prompts"
import { z } from "zod"
import { AppContext } from "../../util/app-context"
import { initCmd } from "../init"
import { createOrModifyNpmrc } from "../init/create-or-modify-npmrc"
import { checkIfInitialized } from "./check-if-initialized"
import { initCmd } from "../init"
import { startExportRequestWatcher } from "./start-export-request-watcher"
import $ from "dax-sh"
import { getDevServerAxios } from "./get-dev-server-axios"
import { startDevServer } from "./start-dev-server"
import { startEditEventWatcher } from "./start-edit-event-watcher"
import { startExportRequestWatcher } from "./start-export-request-watcher"
import { startFsWatcher } from "./start-fs-watcher"
import { uploadExamplesFromDirectory } from "./upload-examples-from-directory"

export const devCmd = async (ctx: AppContext, args: any) => {
const params = z
Expand Down Expand Up @@ -57,7 +58,7 @@ export const devCmd = async (ctx: AppContext, args: any) => {
// TODO

// Delete old .tscircuit/dev-server.sqlite
unlink(Path.join(cwd, ".tscircuit/dev-server.sqlite")).catch(() => {})
unlink(Path.join(cwd, ".tscircuit/dev-server.sqlite")).catch(() => { })

console.log(
kleur.green(
Expand All @@ -71,6 +72,19 @@ export const devCmd = async (ctx: AppContext, args: any) => {

// Reset the database, allows migration to re-run
await devServerAxios.post("/api/dev_server/reset")
.catch(e => {
console.log("Failed to reset database, continuing anyway...")
})

// Add package name to the package_info table
const packageJsonPath = Path.resolve(cwd, 'package.json')
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))
const packageName = packageJson.name

console.log(`Adding package info...`)
await devServerAxios.post("/api/package_info/create", {
package_name: packageName
}, ctx)

// Soupify all examples
console.log(`Loading examples...`)
Expand Down

0 comments on commit fb48ab8

Please sign in to comment.