-
Notifications
You must be signed in to change notification settings - Fork 56
feat: add support --download flag to downloading and localizing 3D models from JLCPCB #2471
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
techmannih
wants to merge
2
commits into
tscircuit:main
Choose a base branch
from
techmannih:down
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,19 +2,103 @@ import { fetchEasyEDAComponent, convertRawEasyToTsx } from "easyeda/browser" | |
| import fs from "node:fs/promises" | ||
| import path from "node:path" | ||
|
|
||
| export interface ImportOptions { | ||
| download?: boolean | ||
| projectDir?: string | ||
| } | ||
|
|
||
| /** | ||
| * Imports a component from JLCPCB/EasyEDA, optionally downloading its 3D model. | ||
| */ | ||
| export const importComponentFromJlcpcb = async ( | ||
| jlcpcbPartNumber: string, | ||
| projectDir: string = process.cwd(), | ||
| options: ImportOptions | string = {}, | ||
| ) => { | ||
| const projectDir = | ||
| typeof options === "string" ? options : options.projectDir || process.cwd() | ||
| const shouldDownload = | ||
| typeof options === "object" ? Boolean(options.download) : false | ||
|
|
||
| const component = await fetchEasyEDAComponent(jlcpcbPartNumber) | ||
| const tsx = await convertRawEasyToTsx(component) | ||
| const fileName = tsx.match(/export const (\w+) = .*/)?.[1] | ||
| let tsxContent = await convertRawEasyToTsx(component) | ||
|
|
||
| const componentNameMatch = tsxContent.match(/export const (\w+) = .*/) | ||
| const fileName = componentNameMatch?.[1] | ||
| if (!fileName) { | ||
| throw new Error("Could not determine file name of converted component") | ||
| } | ||
|
|
||
| const importsDir = path.join(projectDir, "imports") | ||
| await fs.mkdir(importsDir, { recursive: true }) | ||
| const filePath = path.join(importsDir, `${fileName}.tsx`) | ||
| await fs.writeFile(filePath, tsx) | ||
| const componentDir = path.join(importsDir, fileName) | ||
| await fs.mkdir(componentDir, { recursive: true }) | ||
|
|
||
| if (shouldDownload) { | ||
| tsxContent = await downloadAndLocalize3dModel({ | ||
| tsxContent, | ||
| jlcpcbPartNumber, | ||
| componentDir, | ||
| }) | ||
| } | ||
|
|
||
| const filePath = path.join(componentDir, "index.tsx") | ||
| await fs.writeFile(filePath, tsxContent) | ||
|
|
||
| return { filePath } | ||
| } | ||
|
|
||
| /** | ||
| * Downloads the 3D model referenced in the TSX and updates the TSX to use a local path. | ||
| */ | ||
| async function downloadAndLocalize3dModel(params: { | ||
| tsxContent: string | ||
| jlcpcbPartNumber: string | ||
| componentDir: string | ||
| }): Promise<string> { | ||
| const { tsxContent, jlcpcbPartNumber, componentDir } = params | ||
|
|
||
| const objUrlMatch = tsxContent.match(/objUrl: "(https?:\/\/[^"]+)"/) | ||
| const modelUrlMatch = tsxContent.match(/modelUrl: "(https?:\/\/[^"]+)"/) | ||
| const remoteUrlMatch = objUrlMatch || modelUrlMatch | ||
|
|
||
| if (!remoteUrlMatch) { | ||
| return tsxContent | ||
| } | ||
|
|
||
| const remoteUrl = remoteUrlMatch[1] | ||
|
|
||
| try { | ||
| const response = await fetch(remoteUrl) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ig you should be using |
||
| if (!response.ok) { | ||
| console.warn(`Failed to download 3D model from ${remoteUrl}`) | ||
| return tsxContent | ||
| } | ||
|
|
||
| const contentDisposition = response.headers.get("content-disposition") | ||
| let modelFileName = `${jlcpcbPartNumber}.obj` | ||
|
|
||
| if (contentDisposition) { | ||
| // Robust extraction of filename from content-disposition | ||
| const filenameMatch = contentDisposition.match( | ||
| /filename\*?=['"]?([^;'"\n]*)['"]?/i, | ||
| ) | ||
| if (filenameMatch?.[1]) { | ||
| modelFileName = path.basename(filenameMatch[1]) | ||
| } | ||
| } | ||
|
|
||
| const modelFilePath = path.join(componentDir, modelFileName) | ||
| const arrayBuffer = await response.arrayBuffer() | ||
| await fs.writeFile(modelFilePath, Buffer.from(arrayBuffer)) | ||
|
|
||
| // Update TSX to use relative path (safer string replacement) | ||
| const localModelPath = `./${modelFileName}` | ||
| const urlPattern = objUrlMatch ? "objUrl" : "modelUrl" | ||
| const oldUrlLine = remoteUrlMatch[0] | ||
| const newUrlLine = `${urlPattern}: "${localModelPath}"` | ||
|
|
||
| return tsxContent.replace(oldUrlLine, newUrlLine) | ||
| } catch (error) { | ||
| console.error("Error downloading 3D model:", error) | ||
| return tsxContent | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unclear naming here, rename part and partId
partNumber is fine. lcscId is better than partId and used elsewhere