@jlcpcb/cli 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jlcpcb/cli",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "CLI for JLC/EasyEDA component sourcing and KiCad library management",
@@ -20,6 +20,7 @@
20
20
  "scripts": {
21
21
  "build": "bun build ./src/index.ts --outdir ./dist --target node && mkdir -p ./dist/assets && cp ../core/dist/assets/search.html ./dist/assets/",
22
22
  "dev": "bun --watch ./src/index.ts",
23
+ "lint": "eslint src --ext .ts,.tsx",
23
24
  "typecheck": "tsc --noEmit",
24
25
  "test": "bun test",
25
26
  "clean": "rm -rf dist"
@@ -44,7 +45,9 @@
44
45
  "ink-select-input": "6.2.0",
45
46
  "@jlcpcb/core": "workspace:*",
46
47
  "open": "11.0.0",
47
- "react-devtools-core": "7.0.1"
48
+ "react": "^19.0.0",
49
+ "react-devtools-core": "7.0.1",
50
+ "string-width": "^8.2.0"
48
51
  },
49
52
  "devDependencies": {
50
53
  "@types/node": "^20.0.0",
package/src/app/App.tsx CHANGED
@@ -80,9 +80,10 @@ export function App<T extends ScreenName>({ initialScreen, initialParams }: AppP
80
80
  );
81
81
  }
82
82
 
83
- export function renderApp<T extends ScreenName>(
83
+ export async function renderApp<T extends ScreenName>(
84
84
  initialScreen: T,
85
85
  initialParams: ScreenParams[T]
86
- ): void {
87
- render(<App initialScreen={initialScreen} initialParams={initialParams} />);
86
+ ): Promise<void> {
87
+ const instance = render(<App initialScreen={initialScreen} initialParams={initialParams} />);
88
+ await instance.waitUntilExit();
88
89
  }
@@ -142,8 +142,8 @@ export function DetailView({ component, terminalWidth, isInstalled, installedInf
142
142
 
143
143
  // Footer text based on installation status
144
144
  const footerText = isInstalled
145
- ? 'S SymbolF FootprintM 3D Model • R Regenerate • D Datasheet • Esc Back'
146
- : 'Enter Install • D Datasheet • Esc Back';
145
+ ? 'R RegenerateD DeleteO Datasheet • Esc Back'
146
+ : 'Enter Install • O Datasheet • Esc Back';
147
147
 
148
148
  return (
149
149
  <Box flexDirection="column" width="100%">
@@ -2,6 +2,11 @@ import React from 'react';
2
2
  import { Box, Text } from 'ink';
3
3
  import type { ComponentSearchResult } from '@jlcpcb/core';
4
4
  import { Divider } from './Divider.js';
5
+ import {
6
+ formatListHeader,
7
+ formatListRow,
8
+ getListViewColumnWidths,
9
+ } from './list-view-format.js';
5
10
 
6
11
  interface ListViewProps {
7
12
  results: ComponentSearchResult[];
@@ -10,72 +15,47 @@ interface ListViewProps {
10
15
  terminalWidth: number;
11
16
  }
12
17
 
13
- function formatStock(stock: number): string {
14
- if (stock < 1000) return String(stock);
15
- return '>1k';
16
- }
17
-
18
- function truncate(str: string, len: number): string {
19
- if (!str) return '';
20
- return str.length > len ? str.slice(0, len - 1) + '…' : str;
21
- }
22
-
23
18
  export function ListView({
24
19
  results,
25
20
  selectedIndex,
26
21
  isFiltered,
27
22
  terminalWidth,
28
23
  }: ListViewProps) {
29
- // Calculate column widths based on terminal width
30
- const minWidth = 80;
31
- const availableWidth = Math.max(terminalWidth - 4, minWidth);
32
-
33
- // Fixed columns: MFR.Part(18), Package(10), Stock(6), Price(8), Library(10) + spacing
34
- const mfrPartWidth = 18;
35
- const pkgWidth = 10;
36
- const stockWidth = 6;
37
- const priceWidth = 8;
38
- const libraryWidth = 10;
39
- const fixedWidth = mfrPartWidth + pkgWidth + stockWidth + priceWidth + libraryWidth + 4; // +4 for spacing
40
-
41
- // Description gets all remaining space
42
- const descWidth = Math.max(availableWidth - fixedWidth, 15);
24
+ const widths = getListViewColumnWidths(terminalWidth);
43
25
 
44
26
  return (
45
27
  <Box flexDirection="column">
46
28
  <Box marginBottom={1}>
47
- <Text bold dimColor>
48
- {' '}
49
- {'MFR.Part'.padEnd(mfrPartWidth)}
50
- {'Description'.padEnd(descWidth)}
51
- {'Package'.padEnd(pkgWidth)}
52
- {'Stock'.padStart(stockWidth)}
53
- {'Price'.padStart(priceWidth)}
54
- {' Library'}
55
- </Text>
29
+ <Text bold dimColor>{formatListHeader(widths)}</Text>
56
30
  </Box>
57
31
  {results.map((r, i) => {
58
32
  const isSelected = i === selectedIndex;
59
- const mfrPart = truncate(r.name || '', mfrPartWidth - 1).padEnd(mfrPartWidth);
60
- const desc = truncate(r.description || '', descWidth - 1).padEnd(descWidth);
61
- const pkg = truncate(r.package || '', pkgWidth - 1).padEnd(pkgWidth);
62
- const stock = formatStock(r.stock || 0).padStart(stockWidth);
63
- const price = r.price ? `$${r.price.toFixed(2)}`.padStart(priceWidth) : ' N/A';
64
- const library = r.libraryType === 'basic' ? 'Basic' : 'Extended';
65
- const libraryColor = r.libraryType === 'basic' ? 'green' : 'yellow';
33
+ const row = formatListRow(r, widths);
66
34
 
67
35
  return (
68
36
  <Box key={r.lcscId}>
69
37
  <Text color="cyan">{isSelected ? '▶' : ' '}</Text>
70
- <Text inverse={isSelected}>
71
- <Text color="cyan">{mfrPart}</Text>
72
- <Text dimColor>{desc}</Text>
73
- {pkg}
74
- {stock}
75
- {price}
76
- {' '}
77
- <Text color={libraryColor}>{library}</Text>
78
- </Text>
38
+ {isSelected ? (
39
+ <Text inverse>
40
+ {row.mfrPart}
41
+ {row.desc}
42
+ {row.pkg}
43
+ {row.stock}
44
+ {row.price}
45
+ {' '}
46
+ {row.library}
47
+ </Text>
48
+ ) : (
49
+ <Text>
50
+ <Text color="cyan">{row.mfrPart}</Text>
51
+ <Text dimColor>{row.desc}</Text>
52
+ {row.pkg}
53
+ {row.stock}
54
+ {row.price}
55
+ {' '}
56
+ <Text color={row.libraryColor}>{row.library}</Text>
57
+ </Text>
58
+ )}
79
59
  </Box>
80
60
  );
81
61
  })}
@@ -0,0 +1,58 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+
3
+ import type { InstalledComponent } from '@jlcpcb/core';
4
+
5
+ import {
6
+ formatLibraryHeader,
7
+ formatLibraryRow,
8
+ getLibraryTableWidths,
9
+ } from './library-table-format.js';
10
+ import { measureTextWidth } from './table-text.js';
11
+
12
+ function createInstalledComponent(
13
+ overrides: Partial<InstalledComponent>
14
+ ): InstalledComponent {
15
+ return {
16
+ lcscId: 'C123',
17
+ name: 'LM2940CT-5.0/NOPB',
18
+ category: 'Power',
19
+ symbolRef: 'JLC-MCP:LM2940CT-5.0/NOPB',
20
+ footprintRef: 'JLC-MCP:TO-220',
21
+ library: 'JLC-MCP',
22
+ has3dModel: true,
23
+ ...overrides,
24
+ };
25
+ }
26
+
27
+ describe('library-table-format', () => {
28
+ it('formats header and rows to deterministic widths', () => {
29
+ const widths = getLibraryTableWidths(120);
30
+ const header = formatLibraryHeader(widths);
31
+ const with3d = formatLibraryRow(
32
+ createInstalledComponent({ has3dModel: true }),
33
+ '宽字符 description',
34
+ widths
35
+ );
36
+ const without3d = formatLibraryRow(
37
+ createInstalledComponent({ has3dModel: false, footprintRef: undefined }),
38
+ 'plain description',
39
+ widths
40
+ );
41
+
42
+ const render = (row: ReturnType<typeof formatLibraryRow>) =>
43
+ ' ' +
44
+ row.name +
45
+ row.category +
46
+ row.description +
47
+ row.sym +
48
+ row.fp +
49
+ row.model;
50
+
51
+ expect(measureTextWidth(header)).toBe(measureTextWidth(render(with3d)));
52
+ expect(measureTextWidth(render(with3d))).toBe(
53
+ measureTextWidth(render(without3d))
54
+ );
55
+ expect(measureTextWidth(with3d.model)).toBe(widths.modelWidth);
56
+ expect(measureTextWidth(without3d.fp)).toBe(widths.fpWidth);
57
+ });
58
+ });
@@ -0,0 +1,87 @@
1
+ import type { InstalledComponent } from '@jlcpcb/core';
2
+
3
+ import {
4
+ padEndToWidth,
5
+ truncateToWidth,
6
+ } from './table-text.js';
7
+
8
+ export interface LibraryTableWidths {
9
+ nameWidth: number;
10
+ categoryWidth: number;
11
+ descWidth: number;
12
+ symWidth: number;
13
+ fpWidth: number;
14
+ modelWidth: number;
15
+ }
16
+
17
+ export function getLibraryTableWidths(terminalWidth: number): LibraryTableWidths {
18
+ const nameWidth = 20;
19
+ const categoryWidth = 12;
20
+ const symWidth = 5;
21
+ const fpWidth = 5;
22
+ const modelWidth = 5;
23
+ const descWidth = Math.max(
24
+ terminalWidth - 2 - nameWidth - categoryWidth - symWidth - fpWidth - modelWidth,
25
+ 15
26
+ );
27
+
28
+ return {
29
+ nameWidth,
30
+ categoryWidth,
31
+ descWidth,
32
+ symWidth,
33
+ fpWidth,
34
+ modelWidth,
35
+ };
36
+ }
37
+
38
+ export function formatLibraryHeader(widths: LibraryTableWidths): string {
39
+ return (
40
+ ' ' +
41
+ padEndToWidth('Name', widths.nameWidth) +
42
+ padEndToWidth('Category', widths.categoryWidth) +
43
+ padEndToWidth('Description', widths.descWidth) +
44
+ padEndToWidth('Sym', widths.symWidth) +
45
+ padEndToWidth('FP', widths.fpWidth) +
46
+ padEndToWidth('3D', widths.modelWidth)
47
+ );
48
+ }
49
+
50
+ export function formatLibraryRow(
51
+ item: InstalledComponent,
52
+ description: string,
53
+ widths: LibraryTableWidths
54
+ ): {
55
+ name: string;
56
+ category: string;
57
+ description: string;
58
+ sym: string;
59
+ fp: string;
60
+ model: string;
61
+ fpColor: 'red' | 'cyan' | 'green';
62
+ modelColor: 'red' | 'green';
63
+ } {
64
+ const isStandardFp =
65
+ item.footprintRef && !item.footprintRef.startsWith('JLC-MCP:');
66
+ const fpLabel = !item.footprintRef ? 'N' : isStandardFp ? 'S' : 'Y';
67
+
68
+ return {
69
+ name: padEndToWidth(
70
+ truncateToWidth(item.name, widths.nameWidth - 1),
71
+ widths.nameWidth
72
+ ),
73
+ category: padEndToWidth(
74
+ truncateToWidth(item.category, widths.categoryWidth - 1),
75
+ widths.categoryWidth
76
+ ),
77
+ description: padEndToWidth(
78
+ truncateToWidth(description, widths.descWidth - 1),
79
+ widths.descWidth
80
+ ),
81
+ sym: padEndToWidth('Y', widths.symWidth),
82
+ fp: padEndToWidth(fpLabel, widths.fpWidth),
83
+ model: padEndToWidth(item.has3dModel ? 'Y' : 'N', widths.modelWidth),
84
+ fpColor: !item.footprintRef ? 'red' : isStandardFp ? 'cyan' : 'green',
85
+ modelColor: item.has3dModel ? 'green' : 'red',
86
+ };
87
+ }
@@ -0,0 +1,60 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+
3
+ import type { ComponentSearchResult } from '@jlcpcb/core';
4
+
5
+ import {
6
+ formatListHeader,
7
+ formatListRow,
8
+ getListViewColumnWidths,
9
+ } from './list-view-format.js';
10
+ import { measureTextWidth } from './table-text.js';
11
+
12
+ function createResult(
13
+ overrides: Partial<ComponentSearchResult>
14
+ ): ComponentSearchResult {
15
+ return {
16
+ lcscId: 'C123',
17
+ name: 'LM2940CT-5.0/NOPB',
18
+ description:
19
+ '1 150uVrms 1A 26V 30mA 500mV@(1A) 5V 72dB@(120Hz) Fixed Positive Under Voltage Lockout',
20
+ package: 'TO-220',
21
+ manufacturer: 'TI',
22
+ stock: 28,
23
+ price: 1.01,
24
+ libraryType: 'extended',
25
+ ...overrides,
26
+ };
27
+ }
28
+
29
+ describe('list-view-format', () => {
30
+ it('formats header and rows to deterministic widths', () => {
31
+ const widths = getListViewColumnWidths(120);
32
+ const header = formatListHeader(widths);
33
+ const extendedRow = formatListRow(createResult({ libraryType: 'extended' }), widths);
34
+ const basicRow = formatListRow(createResult({ libraryType: 'basic' }), widths);
35
+
36
+ const render = (row: ReturnType<typeof formatListRow>) =>
37
+ ' ' + row.mfrPart + row.desc + row.pkg + row.stock + row.price + ' ' + row.library;
38
+
39
+ expect(measureTextWidth(header)).toBe(measureTextWidth(render(extendedRow)));
40
+ expect(measureTextWidth(render(extendedRow))).toBe(
41
+ measureTextWidth(render(basicRow))
42
+ );
43
+ expect(measureTextWidth(extendedRow.library)).toBe(widths.libraryWidth);
44
+ expect(measureTextWidth(basicRow.library)).toBe(widths.libraryWidth);
45
+ });
46
+
47
+ it('truncates and pads by display width for wide characters', () => {
48
+ const widths = getListViewColumnWidths(60);
49
+ const row = formatListRow(
50
+ createResult({
51
+ name: '电源模块-REGULATOR',
52
+ description: '宽字符 mixed description',
53
+ }),
54
+ widths
55
+ );
56
+
57
+ expect(measureTextWidth(row.mfrPart)).toBe(widths.mfrPartWidth);
58
+ expect(measureTextWidth(row.desc)).toBe(widths.descWidth);
59
+ });
60
+ });
@@ -0,0 +1,97 @@
1
+ import type { ComponentSearchResult } from '@jlcpcb/core';
2
+ import {
3
+ padEndToWidth,
4
+ padStartToWidth,
5
+ truncateToWidth,
6
+ } from './table-text.js';
7
+
8
+ export interface ListViewColumnWidths {
9
+ mfrPartWidth: number;
10
+ descWidth: number;
11
+ pkgWidth: number;
12
+ stockWidth: number;
13
+ priceWidth: number;
14
+ libraryWidth: number;
15
+ }
16
+
17
+ export function formatStock(stock: number): string {
18
+ if (stock < 1000) return String(stock);
19
+ return '>1k';
20
+ }
21
+
22
+ export function truncate(str: string, len: number): string {
23
+ return truncateToWidth(str, len);
24
+ }
25
+
26
+ export function getListViewColumnWidths(terminalWidth: number): ListViewColumnWidths {
27
+ const minWidth = 80;
28
+ const availableWidth = Math.max(terminalWidth - 4, minWidth);
29
+
30
+ const mfrPartWidth = 18;
31
+ const pkgWidth = 10;
32
+ const stockWidth = 6;
33
+ const priceWidth = 8;
34
+ const libraryWidth = 10;
35
+ const fixedWidth =
36
+ mfrPartWidth + pkgWidth + stockWidth + priceWidth + libraryWidth + 4;
37
+
38
+ return {
39
+ mfrPartWidth,
40
+ descWidth: Math.max(availableWidth - fixedWidth, 15),
41
+ pkgWidth,
42
+ stockWidth,
43
+ priceWidth,
44
+ libraryWidth,
45
+ };
46
+ }
47
+
48
+ export function formatListHeader(widths: ListViewColumnWidths): string {
49
+ return (
50
+ ' ' +
51
+ padEndToWidth('MFR.Part', widths.mfrPartWidth) +
52
+ padEndToWidth('Description', widths.descWidth) +
53
+ padEndToWidth('Package', widths.pkgWidth) +
54
+ padStartToWidth('Stock', widths.stockWidth) +
55
+ padStartToWidth('Price', widths.priceWidth) +
56
+ ' ' +
57
+ padEndToWidth('Library', widths.libraryWidth)
58
+ );
59
+ }
60
+
61
+ export function formatListRow(
62
+ result: ComponentSearchResult,
63
+ widths: ListViewColumnWidths
64
+ ): {
65
+ mfrPart: string;
66
+ desc: string;
67
+ pkg: string;
68
+ stock: string;
69
+ price: string;
70
+ library: string;
71
+ libraryLabel: string;
72
+ libraryColor: 'green' | 'yellow';
73
+ } {
74
+ const libraryLabel = result.libraryType === 'basic' ? 'Basic' : 'Extended';
75
+
76
+ return {
77
+ mfrPart: padEndToWidth(
78
+ truncate(result.name || '', widths.mfrPartWidth - 1),
79
+ widths.mfrPartWidth
80
+ ),
81
+ desc: padEndToWidth(
82
+ truncate(result.description || '', widths.descWidth - 1),
83
+ widths.descWidth
84
+ ),
85
+ pkg: padEndToWidth(
86
+ truncate(result.package || '', widths.pkgWidth - 1),
87
+ widths.pkgWidth
88
+ ),
89
+ stock: padStartToWidth(formatStock(result.stock || 0), widths.stockWidth),
90
+ price: result.price
91
+ ? padStartToWidth(`$${result.price.toFixed(2)}`, widths.priceWidth)
92
+ : padStartToWidth('N/A', widths.priceWidth),
93
+ library: padEndToWidth(libraryLabel, widths.libraryWidth),
94
+ libraryLabel,
95
+ libraryColor: result.libraryType === 'basic' ? 'green' : 'yellow',
96
+ };
97
+ }
@@ -0,0 +1,59 @@
1
+ import stringWidth from 'string-width';
2
+
3
+ const segmenter =
4
+ typeof Intl !== 'undefined' && 'Segmenter' in Intl
5
+ ? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
6
+ : null;
7
+
8
+ function getGraphemes(value: string): string[] {
9
+ if (!segmenter) {
10
+ return Array.from(value);
11
+ }
12
+
13
+ return Array.from(segmenter.segment(value), ({ segment }) => segment);
14
+ }
15
+
16
+ export function measureTextWidth(value: string): number {
17
+ return stringWidth(value);
18
+ }
19
+
20
+ export function padEndToWidth(value: string, width: number): string {
21
+ const padding = Math.max(width - measureTextWidth(value), 0);
22
+ return value + ' '.repeat(padding);
23
+ }
24
+
25
+ export function padStartToWidth(value: string, width: number): string {
26
+ const padding = Math.max(width - measureTextWidth(value), 0);
27
+ return ' '.repeat(padding) + value;
28
+ }
29
+
30
+ export function truncateToWidth(value: string, width: number): string {
31
+ if (!value || width <= 0) {
32
+ return '';
33
+ }
34
+
35
+ if (measureTextWidth(value) <= width) {
36
+ return value;
37
+ }
38
+
39
+ const ellipsis = '…';
40
+ const ellipsisWidth = measureTextWidth(ellipsis);
41
+ if (width <= ellipsisWidth) {
42
+ return ellipsis;
43
+ }
44
+
45
+ let output = '';
46
+ let currentWidth = 0;
47
+ const targetWidth = width - ellipsisWidth;
48
+
49
+ for (const grapheme of getGraphemes(value)) {
50
+ const graphemeWidth = measureTextWidth(grapheme);
51
+ if (currentWidth + graphemeWidth > targetWidth) {
52
+ break;
53
+ }
54
+ output += grapheme;
55
+ currentWidth += graphemeWidth;
56
+ }
57
+
58
+ return output + ellipsis;
59
+ }
@@ -83,5 +83,9 @@ export function useNavigation(): NavigationContextValue {
83
83
 
84
84
  export function useCurrentScreen(): HistoryEntry {
85
85
  const { history, currentIndex } = useNavigation();
86
- return history[currentIndex];
86
+ const entry = history[currentIndex];
87
+ if (!entry) {
88
+ throw new Error(`Invalid navigation state: currentIndex=${currentIndex}, history.length=${history.length}`);
89
+ }
90
+ return entry;
87
91
  }
@@ -73,38 +73,14 @@ export function InfoScreen() {
73
73
  const datasheetUrl = component && ('datasheetPdf' in component ? component.datasheetPdf : 'datasheet' in component ? component.datasheet : undefined);
74
74
 
75
75
  const [isRegenerating, setIsRegenerating] = useState(false);
76
+ const [isDeleting, setIsDeleting] = useState(false);
76
77
  const [regenerateMessage, setRegenerateMessage] = useState<string | null>(null);
77
78
 
78
79
  useInput((input, key) => {
79
- if (isLoading || !component || isCheckingLibrary || isRegenerating) return;
80
+ if (isLoading || !component || isCheckingLibrary || isRegenerating || isDeleting) return;
80
81
 
81
82
  const lowerInput = input.toLowerCase();
82
83
 
83
- // S - Open Symbol in KiCad
84
- if (lowerInput === 's' && installedInfo && libraryStatus) {
85
- const symbolPath = `${libraryStatus.paths.symbolsDir}/JLC-MCP-${installedInfo.category}.kicad_sym`;
86
- open(symbolPath);
87
- return;
88
- }
89
-
90
- // F - Open Footprint in KiCad
91
- if (lowerInput === 'f' && installedInfo && libraryStatus) {
92
- if (installedInfo.footprintRef?.startsWith('JLC-MCP:')) {
93
- const fpName = installedInfo.footprintRef.split(':')[1];
94
- const footprintPath = `${libraryStatus.paths.footprintsDir}/JLC-MCP.pretty/${fpName}.kicad_mod`;
95
- open(footprintPath);
96
- }
97
- // Standard KiCad footprints can't be opened directly
98
- return;
99
- }
100
-
101
- // M - Open 3D Model
102
- if (lowerInput === 'm' && installedInfo && libraryStatus && installedInfo.has3dModel) {
103
- const modelPath = `${libraryStatus.paths.models3dDir}/${installedInfo.name}.step`;
104
- open(modelPath);
105
- return;
106
- }
107
-
108
84
  // R - Regenerate symbol and footprint
109
85
  if (lowerInput === 'r' && installedInfo) {
110
86
  setIsRegenerating(true);
@@ -124,8 +100,27 @@ export function InfoScreen() {
124
100
  return;
125
101
  }
126
102
 
127
- // D - Open Datasheet
128
- if (lowerInput === 'd' && datasheetUrl) {
103
+ // D - Delete component
104
+ if (lowerInput === 'd' && installedInfo) {
105
+ setIsDeleting(true);
106
+ setRegenerateMessage('Deleting component...');
107
+
108
+ libraryService.remove(installedInfo.lcscId)
109
+ .then(() => {
110
+ setRegenerateMessage('✓ Component deleted');
111
+ setInstalledInfo(null);
112
+ setTimeout(() => setRegenerateMessage(null), 2000);
113
+ })
114
+ .catch((err) => {
115
+ setRegenerateMessage(`✗ Delete failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
116
+ setTimeout(() => setRegenerateMessage(null), 3000);
117
+ })
118
+ .finally(() => setIsDeleting(false));
119
+ return;
120
+ }
121
+
122
+ // O - Open Datasheet
123
+ if (lowerInput === 'o' && datasheetUrl) {
129
124
  open(datasheetUrl);
130
125
  return;
131
126
  }