# Schematic editor — library for developers

Electrical schematics on top of diagram-editor: components with designators and values, nets, buses, power, ERC, bill of materials, GOST and ISO frames, SPICE and KiCad netlists, KiCad import and export, simulation.

## Installation

```sh
npm install @openlibsdev/schematic-editor
```

```js
import SchematicEditor from "https://cdn.jsdelivr.net/npm/@openlibsdev/schematic-editor@1.0.0/+esm";
```

## Usage

```js
import SchematicEditor from "@openlibsdev/schematic-editor";

const p = SchematicEditor.createProject(), d = p.pages[0].diagram;
const r = SchematicEditor.addComponent(p, d, "elResistor", 40, 40);   // r.ref === "R1"
SchematicEditor.renumber(p, "gost");
console.log(SchematicEditor.nets(p).nets.length);   // nets with their pins
console.log(SchematicEditor.erc(p));                 // [{ level, code, page, ids, ... }]
const spice = SchematicEditor.spiceNetlist(p);
```

## API

### `SchematicEditor.createProject()`

Creates a schematic project.

### `SchematicEditor.addComponent(x, d, type, px, py, props)`

Adds a component with the next designator and a default value.

### `SchematicEditor.addEdge(d, from, to, props)`

Connects pins with a wire.

### `SchematicEditor.renumber(x, style)`

Renumbers designators by position (GOST or IEC style).

### `SchematicEditor.nets(x)`

Electrical nets of the schematic: {nets: [{name, pins, wires, labels, power}], byEdge, byPin}.

### `SchematicEditor.erc(x)`

Electrical rules check: a list of problems.

### `SchematicEditor.bomGrouped(x)`

Bill of materials grouped by value.

### `SchematicEditor.pe3Rows(x, opts)`

Rows of the GOST list of elements (PE3).

### `SchematicEditor.spiceNetlist(x, opts)`

SPICE netlist.

### `SchematicEditor.kicadNetlist(x, opts)`

KiCad netlist.

### `SchematicEditor.kicadSchematic(x, opts)`

Schematic in KiCad .kicad_sch format.

### `SchematicEditor.kicadImport(input, opts)`

Opens a KiCad schematic.

### `SchematicEditor.simNetlist(x, analysis)`

Netlist for the built-in simulator.

### `SchematicEditor.logicModel(x)`

Model for logic simulation.

### `SchematicEditor.toSVG(d, opts)`

Schematic as SVG.

### `SchematicEditor.toBlob(d, format, opts)`

Schematic as a file.

### `SchematicEditor.serialize(x)`

Project → JSON.

### `SchematicEditor.parse(data)`

JSON → project.

### `SchematicEditor.PARTS`

Component library.

### `SchematicEditor.ALIGNS`

Text alignments: left, center, right.

### `SchematicEditor.APP`

Name, version and release date of the library: {name, version, created}.

### `SchematicEditor.ARROWS`

Line end markers: arrows, triangles, diamonds, circle and the ER crow's-foot ends.

### `SchematicEditor.BAND`

Height of a container's title band, in pixels.

### `SchematicEditor.DASHES`

Line styles: solid, dashed, dotted (as dash patterns).

### `SchematicEditor.DEFAULT_VALUES`

Value a new component starts with, by type (10 kΩ, 100 nF, …).

### `SchematicEditor.DOTS`

Junction dot modes of a line: auto, on, off.

### `SchematicEditor.EDGE_DEFAULTS`

Default properties of a new line: ends, kind, arrows, color, width, style, text.

### `SchematicEditor.FIELDS`

Standard component fields: Footprint, Datasheet, Manufacturer, MPN (they go into the parts list and the KiCad netlist).

### `SchematicEditor.FORMATS`

Export formats and their MIME types.

### `SchematicEditor.FRAMES`

Drawing frames: none, GOST, ISO.

### `SchematicEditor.GATES`

Logic gates and parts for the logic simulation, with their function and pins.

### `SchematicEditor.IMAGE_LIMIT`

Largest picture kept in a diagram, in bytes of its data URL (3 MB).

### `SchematicEditor.KICAD`

KiCad library symbol and pin order of each component type, for the KiCad netlist and schematic.

### `SchematicEditor.LABELS`

Net label types: local (joins wires of its page) and global (of every page).

### `SchematicEditor.LINE_KINDS`

Line kinds: straight, elbow (right angles), curved.

### `SchematicEditor.MIN_SIZE`

Smallest width and height of a shape, in pixels.

### `SchematicEditor.MM`

Pixels per millimetre on a sheet (4).

### `SchematicEditor.NODE_DEFAULTS`

Default properties of a new shape: text, fill, opacity, border, font, alignment.

### `SchematicEditor.PAGE_DEFAULTS`

Default page settings: background, transparency, grid, snapping, grid size, margin, junction dots.

### `SchematicEditor.PIN_SIDES`

Sides a pin of an own symbol can be on: left, right, top, bottom.

### `SchematicEditor.PIN_TYPES`

Electrical pin types: passive, input, output, bidirectional, power in, power out, not connected.

### `SchematicEditor.POWER`

Power symbols and the net name each one gives: VCC, VDD, GND, GNDA, Earth.

### `SchematicEditor.PREFIX`

Designator prefix of each component type in the IEC and GOST styles (R, C, VD, …).

### `SchematicEditor.SHAPES`

Shape types.

### `SchematicEditor.SHAPE_SETS`

Symbols by set as the editor offers them: electrical, logic, instruments, nets (labels, power, ground), parts, own symbols.

### `SchematicEditor.SHEETS`

Paper sizes in millimetres: A4, A3, A2, A1.

### `SchematicEditor.SIDES`

Sides a line can attach to: auto, top, right, bottom, left.

### `SchematicEditor.SIM_MODELS`

SPICE models of the simulator's standard parts (diodes, transistors, op-amp, LM317).

### `SchematicEditor.SOURCE_TYPES`

Component types that are sources in the simulation: battery, DC, AC, current source, function generator.

### `SchematicEditor.SPICE`

SPICE element letter, pin order and model of each component type.

### `SchematicEditor.STYLES`

Designation styles: iec, gost.

### `SchematicEditor.TB_FIELDS`

Fields of the title block: title, document name and number, organisation, signatures, date, scale, …

### `SchematicEditor.TEMPLATES`

Ready circuits: LED with a switch, transistor switch, half adder, amplifiers, power supply, RC filter, multivibrator, rectifier, latch, relay driver, ATtiny blink and more.

### `SchematicEditor.addBend(d, e, x, y)`

Adds a bend where the line passes near a point; returns its index, or -1.

### `SchematicEditor.addNode(d, type, x, y, props)`

Adds a shape at a point.

### `SchematicEditor.addPowerUnit(x, d, n)`

Places the power unit of a multi-unit part next to the node when it is not placed yet; returns it.

### `SchematicEditor.addSymbol(x, def)`

Adds an own symbol definition to the project; returns its type.

### `SchematicEditor.align(d, ids, how)`

Aligns items.

### `SchematicEditor.anchor(n, side)`

Point in the middle of a side of a shape's outline (taking rotation into account).

### `SchematicEditor.assignRef(x, n, style)`

Gives a component a designator (and a default value when it has none).

### `SchematicEditor.bounds(d, ids)`

Box around the given items (or all of them); null for an empty diagram.

### `SchematicEditor.busMembers(name)`

Signals a bus name stands for: "D[0..7]" → D0…D7, "{SDA SCL}" → SDA, SCL; null when it is not a bus name.

### `SchematicEditor.buses(x)`

Buses of a project: [{page, edge, name, members, used}].

### `SchematicEditor.clone(d)`

Deep copy of a diagram.

### `SchematicEditor.components(x)`

Components of a project, one row per designator, sorted (R1, R2, R10).

### `SchematicEditor.contents(d, c)`

Shapes lying inside a container.

### `SchematicEditor.createDiagram()`

Creates an empty diagram.

### `SchematicEditor.cssFont(it)`

CSS font string of an item (style, weight, size, family).

### `SchematicEditor.decorationBox(d)`

Box of the page decoration (for example a drawing frame) set with setDecorations, or null.

### `SchematicEditor.dipPins(n)`

Pins of a DIP package: 1…n/2 down the left side, the rest up the right side.

### `SchematicEditor.distToSegment(p, a, b)`

Distance from a point to a line segment.

### `SchematicEditor.distribute(d, ids, axis)`

Spaces items evenly.

### `SchematicEditor.drawPrimitives(ctx, prims)`

Draws primitives (from primitives()) on a canvas 2D context.

### `SchematicEditor.duplicate(d, ids, dx, dy)`

Copies items and pastes them shifted by (dx, dy); returns the new ids.

### `SchematicEditor.edgeAt(d, x, y, tol)`

The topmost line passing near a point, or null.

### `SchematicEditor.edgeEnds(d, e)`

Where a line really ends: [start, end], each with point, side, pin and whether it is free.

### `SchematicEditor.electricShape(W, H, o)`

Makes an electrical symbol shape from its size and drawing (lines, pins, label place), for registerShape.

### `SchematicEditor.exportBox(d, ids)`

Area to export: the given items with their outside labels, or the whole diagram with its decoration.

### `SchematicEditor.extract(d, ids)`

Copies a part of a diagram (shapes and the lines between them) as a piece to insert elsewhere.

### `SchematicEditor.fieldColumns(x)`

Columns of a parts list: the standard fields, then the own field names in use.

### `SchematicEditor.find(d, id)`

A shape or a line by its id.

### `SchematicEditor.findEdge(d, id)`

A line by its id, or null.

### `SchematicEditor.findNamedColor(text, lang)`

Finds a named color by its name in the given language ("dark blue" → #00008b).

### `SchematicEditor.findNode(d, id)`

A shape by its id, or null.

### `SchematicEditor.fitToSheet(x)`

Moves the drawing of every page into its frame's working area when it does not fit; returns how many pages moved.

### `SchematicEditor.footprintsFor(type)`

Suggested KiCad footprints for a component type.

### `SchematicEditor.gateFn(fn, ins)`

Output of a logic function for input values 0, 1, X (unknown) and Z (not driven).

### `SchematicEditor.genWave(value)`

Function generator value ("sine 1 V 1 kHz", "pulse 5 V 10 kHz 20%", or a SPICE waveform) → {spice, wave, amp, freq}.

### `SchematicEditor.group(d, ids)`

Groups items.

### `SchematicEditor.insert(d, part, dx, dy)`

Inserts a piece made by extract, shifted by (dx, dy); groups get new names. Returns the new ids.

### `SchematicEditor.isClosed(n)`

Whether a switch or contact is closed.

### `SchematicEditor.isComponent(n)`

Whether a node is a component (has a designator), not a wire, label or drawing.

### `SchematicEditor.itemsInRect(d, box)`

Ids of the shapes and lines entirely inside a rectangle.

### `SchematicEditor.junctions(d)`

Points where junction dots are drawn (T joints and crossings of three or more wires).

### `SchematicEditor.labelName(n)`

Net name of a label or power symbol.

### `SchematicEditor.labelPlace(n)`

Where the outside label of a symbol goes: below, above or to the right.

### `SchematicEditor.labelText(n)`

Text of a symbol's label: designator, value and text, one per line.

### `SchematicEditor.layoutTree(d, opts)`

Arranges shapes as a tree.

### `SchematicEditor.like(type)`

The standard type a component type is drawn and simulated as.

### `SchematicEditor.listNamedColors(lang)`

Lists the named colors with their names in the given language.

### `SchematicEditor.loadFonts(d)`

Loads the font files of every family the diagram uses, so drawing and measuring use the real fonts.

### `SchematicEditor.loadImages(d)`

Loads every picture of the diagram before drawing.

### `SchematicEditor.logicSettle(model, st)`

Settles the logic circuit at a moment: steps until nothing changes; flip-flops switch on rising clock edges.

### `SchematicEditor.logicState(model, prev)`

State of the logic simulation: outputs, clocks and time (continuing from the previous state).

### `SchematicEditor.markup(d, opts)`

The diagram as SVG elements without the <svg> around them (to put into your own SVG).

### `SchematicEditor.move(d, ids, dx, dy)`

Moves items.

### `SchematicEditor.moveSegment(d, e, k, dx, dy)`

Moves one segment of a line as it is drawn by (dx, dy).

### `SchematicEditor.namedColorTexts(lang)`

Labels of the color field in the given language (the texts of the color picker), English for a missing language.

### `SchematicEditor.nearestPin(n, x, y, toward)`

Index of the pin of a shape nearest to a point, or -1.

### `SchematicEditor.nextLabel(x)`

Name for a new net label: NET1, NET2, … (the first one not used in the project).

### `SchematicEditor.nextRef(x, prefix)`

Next free designator for a prefix in the whole project: R1, R2, …

### `SchematicEditor.nodeAt(d, x, y, pad)`

The topmost shape under a point (a container only on its title band and border).

### `SchematicEditor.normalize(d)`

Any object → a valid diagram: unknown values replaced by defaults, ids made unique, broken lines removed.

### `SchematicEditor.normalizeProject(p)`

Any object → a valid project with pages.

### `SchematicEditor.normalizeSymbol(def)`

Checks an own symbol definition and fills in what is missing.

### `SchematicEditor.order(d, ids, how)`

Changes the drawing order of shapes: front, back, forward, backward.

### `SchematicEditor.orthoThrough(a, sa, vias, b, sb)`

Right-angle polyline from one point through via points to another, leaving and entering along the given sides.

### `SchematicEditor.parseAny(data)`

A project from a file: ours (JSON) or KiCad's (.kicad_sch).

### `SchematicEditor.pe3Sheets(x, opts)`

The GOST list of elements (PE3) laid out on A4 sheets with frames.

### `SchematicEditor.pinType(type, i)`

Electrical type of a pin of a component type.

### `SchematicEditor.pins(n)`

Pins of a shape as seen (electrical and logic symbols): [{x, y, side}].

### `SchematicEditor.placeAt(x, d, type, p)`

Puts a symbol with its first pin on a point (a label on a wire splits it with a junction).

### `SchematicEditor.powerVolts(name)`

Voltage given by a power net name: "+5 V" → 5, "3V3" → 3.3; null for VCC, VDD, …

### `SchematicEditor.primitives(d, opts)`

The diagram as a list of drawing primitives (paths, texts, pictures), ready for canvas or SVG.

### `SchematicEditor.projectSymbols(x)`

Types of the own symbols defined in the project.

### `SchematicEditor.readFiles(files, opts)`

A project from chosen files: our .json, KiCad .kicad_sch (with its sheets) or a .zip of them.

### `SchematicEditor.readSim(result, built)`

Simulator result → voltages of nets and currents of parts (for an AC analysis in dB and degrees).

### `SchematicEditor.refPrefix(type, style)`

Designator prefix of a component type in a style (IEC or GOST).

### `SchematicEditor.refreshCustomSet(x)`

Updates the "own symbols" set of the editor from the project.

### `SchematicEditor.refreshRefs(x, d, ids)`

Gives pasted or duplicated components the next free designators.

### `SchematicEditor.registerShape(type, shape)`

Adds a shape type.

### `SchematicEditor.remove(d, ids)`

Removes items.

### `SchematicEditor.removeBend(e, i)`

Removes a bend of a line by its index.

### `SchematicEditor.removeSymbol(x, type)`

Removes an own symbol definition that is not used; returns whether it was removed.

### `SchematicEditor.resetBends(e)`

Removes all manual bends of a line (back to automatic routing).

### `SchematicEditor.rotate(d, ids, dir)`

Turns shapes by a quarter turn (1: clockwise, -1: counter-clockwise) around their centres.

### `SchematicEditor.route(d, e)`

Recomputes the path of a connector.

### `SchematicEditor.scalePath(d, sx, sy)`

Scales SVG path data (M L H V Q C A Z) by sx and sy.

### `SchematicEditor.setCornerJoins(on)`

Turns junction dots at wire corners on or off.

### `SchematicEditor.setDecorations(fn)`

Sets a function that draws a page decoration (for example a drawing frame and title block).

### `SchematicEditor.setFieldAll(x, type, value, name, text)`

Sets a field on every component of a type (and value); returns how many changed.

### `SchematicEditor.setProjectHook(fn)`

Sets a function called on every project being opened (to migrate or complete its data).

### `SchematicEditor.setRefText(fn)`

Sets a function that formats designators in labels.

### `SchematicEditor.setSheetProject(x, labels)`

Sets the project and the texts of the forms the drawing frame and title block are drawn with.

### `SchematicEditor.setStyle(x, style)`

Sets the designation style of the whole project: IEC or GOST.

### `SchematicEditor.setUnit(x, n, unit)`

Makes a node another unit of its package; the unit that was there takes its place.

### `SchematicEditor.sheetBox(sh)`

Box of a sheet in pixels, with its size in millimetres.

### `SchematicEditor.sheetInner(sh)`

Inner frame of a sheet in millimetres.

### `SchematicEditor.sheetOf(x)`

Sheet settings of a project: size, orientation, frame, title block fields.

### `SchematicEditor.sheetPlan(box)`

How a diagram is cut into A4 sheets at real size: orientation, columns, rows, tile size.

### `SchematicEditor.sheetSize(sh)`

Paper size of a sheet in millimetres, with its orientation.

### `SchematicEditor.sheetWorkArea(sh, first)`

Where the drawing may go on a sheet: the frame without the title block.

### `SchematicEditor.siblings(x, n)`

The other placed units of a node's package.

### `SchematicEditor.simErrors(info, errors)`

Problems the simulator reports (convergence, singular matrix, …) as codes the editor explains.

### `SchematicEditor.snap(d, v)`

Rounds a coordinate to the grid when snapping is on.

### `SchematicEditor.spiceNumber(t)`

A number in SPICE notation or with units ("10m", "1 MHz", "4.7k") → {text, value}, or null.

### `SchematicEditor.spiceValue(v)`

A component value → SPICE notation: "10 kΩ" → "10k", "1 MΩ" → "1Meg".

### `SchematicEditor.splitWire(d, edgeId, x, y)`

Splits a wire at a point with a junction; returns the junction shape, or null.

### `SchematicEditor.styleOf(x)`

Designation style of a project: "iec" or "gost".

### `SchematicEditor.symbolGeometry(d)`

Drawing of an own symbol definition: box, pins and leads.

### `SchematicEditor.symbolName(type)`

Name of a symbol type, or null.

### `SchematicEditor.symbolOf(type)`

Definition of a symbol type, or null.

### `SchematicEditor.symbolPreview(def)`

Picture of an own symbol definition as SVG, for a preview.

### `SchematicEditor.symbolUses(x, type)`

How many times a symbol type is placed in the project.

### `SchematicEditor.template(name, texts, style)`

A ready circuit by template name, with your own texts, in the IEC or GOST style.

### `SchematicEditor.textBox(n)`

Box where a shape's text is placed, with its lines and alignment.

### `SchematicEditor.textFontData`

Data for a text and font block: the font list, loading a font style, adding a font file, the block's labels in a language and the default values.

### `SchematicEditor.toCanvas(d, opts)`

Diagram as a <canvas>.

### `SchematicEditor.ungroup(d, ids)`

Ungroups the groups of the given items; returns how many shapes left a group.

### `SchematicEditor.unitOf(n)`

Unit of a node of a multi-unit part: {base, unit, units, multi}, or null.

### `SchematicEditor.unitRef(n, style)`

Designator with the unit: U1A (IEC) or DD1.1 (GOST).

### `SchematicEditor.unitTag(type, style)`

What a unit adds to the designator: "A" (IEC) or ".1" (GOST).

### `SchematicEditor.unitsOf(x, n, style)`

Units of a node's package for the editor: which are placed, alike, and whether the power unit is placed.

### `SchematicEditor.updateSymbol(x, type, def)`

Changes an own symbol definition; every placed copy takes the new drawing.

### `SchematicEditor.visualBox(n)`

Everything a shape takes in the picture: its box and an outside label.

### `SchematicEditor.wirePoint(d, x, y, tol, except)`

Point on the nearest wire within a distance, or null (a dropped wire end lands there).

### `SchematicEditor.withContents(d, ids)`

The ids plus the contents of every container among them.

### `SchematicEditor.withGroups(d, ids)`

The ids plus the other members of their groups.

### `SchematicEditor.wrapText(text, it, maxWidth)`

Splits text into lines no wider than a width (words kept whole).

## Dependencies

- @imagemagick/magick-wasm 0.0.35 (Apache-2.0)
- @imagemagick/magick-wasm 0.0.35 (Apache-2.0)
- @simonwep/pickr 1.10.2 (MIT)
- @simonwep/pickr 1.10.2 (MIT)
- chart.js 4.4.1 (MIT)
- dejavu-fonts-ttf 2.37.3 (Bitstream Vera Fonts License (free, redistributable); DejaVu changes are public domain)
- eecircuit-engine 1.9.0 (MIT)
- imagetracerjs 1.2.6 (Unlicense)
- jspdf 2.5.2 (MIT)
- jszip 3.10.1 ((MIT OR GPL-3.0-or-later))

- GitHub: https://github.com/OpenLibsDev/schematic-editor
- npm: https://www.npmjs.com/package/@openlibsdev/schematic-editor
- Open the app: https://openlibs.dev/en/app/schematic-editor/
