@biolibs/bionet-tools 0.1.4 → 0.1.6

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.
Files changed (48) hide show
  1. package/README.md +50 -0
  2. package/dist/digest-bench.d.ts +1 -1
  3. package/dist/digest-bench.d.ts.map +1 -1
  4. package/dist/digest-bench.js +16 -1
  5. package/dist/digest-bench.js.map +1 -1
  6. package/dist/index.d.ts +6 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +6 -0
  9. package/dist/index.js.map +1 -1
  10. package/dist/ligate-bench.d.ts +1 -1
  11. package/dist/ligate-bench.d.ts.map +1 -1
  12. package/dist/ligate-bench.js +12 -1
  13. package/dist/ligate-bench.js.map +1 -1
  14. package/dist/pcr-bench.d.ts +1 -1
  15. package/dist/pcr-bench.d.ts.map +1 -1
  16. package/dist/pcr-bench.js +19 -0
  17. package/dist/pcr-bench.js.map +1 -1
  18. package/dist/primer-bench.d.ts +120 -0
  19. package/dist/primer-bench.d.ts.map +1 -0
  20. package/dist/primer-bench.js +285 -0
  21. package/dist/primer-bench.js.map +1 -0
  22. package/dist/primer-design.d.ts +273 -0
  23. package/dist/primer-design.d.ts.map +1 -0
  24. package/dist/primer-design.js +273 -0
  25. package/dist/primer-design.js.map +1 -0
  26. package/dist/primer-working.d.ts +154 -0
  27. package/dist/primer-working.d.ts.map +1 -0
  28. package/dist/primer-working.js +245 -0
  29. package/dist/primer-working.js.map +1 -0
  30. package/dist/tools.d.ts +8 -4
  31. package/dist/tools.d.ts.map +1 -1
  32. package/dist/tools.js +9 -4
  33. package/dist/tools.js.map +1 -1
  34. package/dist/working.d.ts +16 -0
  35. package/dist/working.d.ts.map +1 -1
  36. package/dist/working.js +21 -0
  37. package/dist/working.js.map +1 -1
  38. package/package.json +3 -2
  39. package/src/digest-bench.tsx +13 -2
  40. package/src/index.ts +6 -0
  41. package/src/ligate-bench.tsx +11 -2
  42. package/src/pcr-bench.tsx +14 -1
  43. package/src/primer-bench.tsx +500 -0
  44. package/src/primer-design.ts +406 -0
  45. package/src/primer-working.ts +289 -0
  46. package/src/tools.tsx +14 -6
  47. package/src/working.tsx +29 -0
  48. package/tools.css +49 -2
@@ -0,0 +1,500 @@
1
+ "use client";
2
+
3
+ /**
4
+ * Designing primers, at a desk.
5
+ *
6
+ * Primers are not made at a machine. They are chosen by somebody looking at a sequence, sent off to
7
+ * be made, and arrive as tubes. So this tool has no instrument: it has a part from the lab, a
8
+ * stretch of it to amplify, and the pair that would amplify it — with every candidate that was
9
+ * weighed, what a careful person would stop at, and the working for each figure.
10
+ *
11
+ * Like the tools that do stand at a machine, it knows nothing of three dimensions. It hands a host
12
+ * the tube of the template to look at and the template as a molecule with the stretch and the pair
13
+ * marked on it, and a scene that is showing that tube draws them over it.
14
+ */
15
+ import { useEffect, useMemo, useRef, useState, type PointerEvent, type ReactNode } from "react";
16
+ import type { PartState } from "@biolibs/bionet";
17
+ import { useAct, useLab } from "@biolibs/bionet-react";
18
+ import { Glossed } from "@biolibs/glossary-react";
19
+ import { DEFAULT_DESIGN } from "@biolibs/pcr";
20
+ import { SequenceMap, type MapSpan } from "./map.js";
21
+ import { planPcr } from "./pcr.js";
22
+ import { designPair, featureStretches, primerOrder, stretchLength, type DesignedPrimer, type PrimerDesign, type Stretch } from "./primer-design.js";
23
+ import { crossWorking, gcWorking, primerTmWorking, productWorking, scoreWorking, selfWorking, tmApartWorking } from "./primer-working.js";
24
+ import { featureTone, moleculeOf, type DrawnMolecule } from "./sequence-file.js";
25
+ import { PairedBases, ShowWorking } from "./working.js";
26
+
27
+ const count = (value: number): string => value.toLocaleString("en-US");
28
+ const whole = (text: string): number | undefined => (text.trim() === "" || !Number.isFinite(Number(text)) ? undefined : Math.round(Number(text)));
29
+
30
+ /** The parts of the panel, in the order they are read, for a host that wants one of them in view. */
31
+ export type PrimerSection = "choose" | "pair" | "considered" | "working" | "order";
32
+
33
+ /** What a host is handed to draw beside the panel: where to look, and what to picture there. */
34
+ export interface PrimerDesk {
35
+ /** The tube of the template to look at, and the place it is in, if the lab has one that has been put somewhere. */
36
+ focus: { place: string; item: string } | null;
37
+ /** The template as a molecule, with the stretch and the two primers marked on it. `null` until a part is chosen. */
38
+ molecule: DrawnMolecule | null;
39
+ /** The tubes a PCR of this design would be run from, once the lab has a tube of each: the template and the two primers. */
40
+ ready: { template: string; forward: string; reverse: string } | null;
41
+ }
42
+
43
+ /**
44
+ * The template with a design drawn on it: its own features, the stretch, and a primer at each end.
45
+ *
46
+ * @param part - The template.
47
+ * @param design - The design, if there is one.
48
+ * @param names - What the two primers are called.
49
+ * @returns The molecule, as a scene draws one.
50
+ */
51
+ export function designedMolecule(part: Pick<PartState, "name" | "length" | "circular" | "features">, design: PrimerDesign | null,
52
+ names: { forward: string; reverse: string }): DrawnMolecule {
53
+ const drawn = moleculeOf(part);
54
+ if (design === null) return drawn;
55
+ // A stretch through the origin is drawn as the two pieces either side of it.
56
+ const pieces = (start: number, end: number): [number, number][] =>
57
+ (end <= part.length ? [[start, end]] : [[start, part.length], [0, end - part.length]]);
58
+ const mark = (start: number, end: number, strand: -1 | 0 | 1, tone: DrawnMolecule["features"][number]["tone"], label: string) =>
59
+ pieces(start, end).filter(([from, to]) => to > from).map(([from, to], at) => ({ start: from, end: to, strand, tone, label: at === 0 ? label : "" }));
60
+ return {
61
+ ...drawn,
62
+ features: [
63
+ ...drawn.features,
64
+ ...mark(design.stretch.start, design.stretch.start + design.length, 0, "good", `${count(design.length)} bp`),
65
+ ...mark(design.forward.start, design.forward.end, 1, featureTone("primer_bind"), names.forward),
66
+ ...mark(design.reverse.start, design.reverse.end, -1, featureTone("primer_bind"), names.reverse),
67
+ ],
68
+ };
69
+ }
70
+
71
+ /**
72
+ * A part laid out as a strip, to drag a stretch out on.
73
+ *
74
+ * What is marked on the part is drawn above the line, so that a stretch can be dragged to fit a
75
+ * feature by eye. The stretch chosen is shaded. Typing the numbers does the same thing, and is the
76
+ * only way to say a stretch that runs through a circle's origin.
77
+ *
78
+ * @param props - `part` is the part; `stretch` is what is chosen; `onStretch` is told a new one.
79
+ */
80
+ export function StretchStrip({ part, stretch, onStretch }: { part: Pick<PartState, "name" | "length" | "features">; stretch: Stretch | null; onStretch: (stretch: Stretch) => void }) {
81
+ const [width, left, axis] = [640, 12, 34];
82
+ const across = width - 2 * left;
83
+ const x = (position: number): number => left + (position / part.length) * across;
84
+ const dragging = useRef<number | null>(null);
85
+ const [drag, setDrag] = useState<[number, number] | null>(null);
86
+ const at = (event: PointerEvent<SVGSVGElement>): number => {
87
+ const box = event.currentTarget.getBoundingClientRect();
88
+ const along = ((event.clientX - box.left) / box.width) * width;
89
+ return Math.round(Math.min(Math.max((along - left) / across, 0), 1) * part.length);
90
+ };
91
+ const shown: [number, number][] = drag !== null ? [[Math.min(...drag), Math.max(...drag)]]
92
+ : stretch === null ? [] : stretch.end > stretch.start ? [[stretch.start, stretch.end]] : [[stretch.start, part.length], [0, stretch.end]];
93
+ return (
94
+ <svg className="strip" viewBox={`0 0 ${width} 52`} role="img" style={{ touchAction: "none" }}
95
+ aria-label={`${part.name} as a strip of ${count(part.length)} bases. ${stretch === null ? "No stretch is chosen." : `The stretch chosen is ${count(stretch.start + 1)} to ${count(stretch.end)}.`} Drag across it to choose another.`}
96
+ onPointerDown={(event) => { event.currentTarget.setPointerCapture(event.pointerId); dragging.current = at(event); setDrag([dragging.current, dragging.current]); }}
97
+ onPointerMove={(event) => { if (dragging.current !== null) setDrag([dragging.current, at(event)]); }}
98
+ onPointerUp={(event) => {
99
+ const from = dragging.current;
100
+ dragging.current = null;
101
+ setDrag(null);
102
+ if (from === null) return;
103
+ const [start, end] = [Math.min(from, at(event)), Math.max(from, at(event))];
104
+ // A press without a drag chooses nothing.
105
+ if (end - start >= 2) onStretch({ start, end });
106
+ }}>
107
+ {shown.map(([from, to], index) => <rect key={index} x={x(from)} y={4} width={Math.max(1, x(to) - x(from))} height={44} className="chosen" />)}
108
+ {part.features.flatMap((feature, index) => feature.parts.filter((piece) => piece.end > piece.start).map((piece, nth) => (
109
+ <rect key={`${index} ${nth}`} x={x(piece.start)} y={axis - 16} width={Math.max(1.5, x(piece.end) - x(piece.start))} height={9} rx={2} className={`feature tone-${featureTone(feature.type)}`}>
110
+ <title>{`${feature.label}, ${count(piece.start + 1)}..${count(piece.end)}`}</title>
111
+ </rect>
112
+ )))}
113
+ <line x1={left} x2={left + across} y1={axis} y2={axis} className="backbone" />
114
+ <text x={left} y={axis + 13} className="length">1</text>
115
+ <text x={left + across} y={axis + 13} textAnchor="end" className="length">{count(part.length)}</text>
116
+ {shown.length > 0 && <text x={(x(shown[0]![0]) + x(shown[0]![1])) / 2} y={axis + 13} textAnchor="middle" className="spanned">{count(shown[0]![0] + 1)}–{count(shown[0]![1])}</text>}
117
+ </svg>
118
+ );
119
+ }
120
+
121
+ /**
122
+ * The one picture that makes a pair of primers plain: the template's two strands, and a primer on
123
+ * each, at the two ends of the stretch, pointing at each other.
124
+ *
125
+ * The forward primer has the top strand's sequence, so it lies on the bottom strand and is extended
126
+ * rightwards; the reverse primer the other way about. It is not to scale along its length: the ends
127
+ * are drawn large enough to read and the middle is cut short.
128
+ *
129
+ * @param props - `design` is the design; `names` is what the primers are called.
130
+ */
131
+ export function PairPicture({ design, names }: { design: PrimerDesign; names: { forward: string; reverse: string } }) {
132
+ const [f, r] = [design.forward.chosen.report, design.reverse.chosen.report];
133
+ const says = `The template's two strands, with ${count(design.length)} bases between the ends of the stretch. ${names.forward}, ${f.length} bases, lies on the bottom strand at the left end, from base ${count(design.forward.start + 1)}, and points right. `
134
+ + `${names.reverse}, ${r.length} bases, lies on the top strand at the right end, up to base ${count(design.stretch.end)}, and points left. What lies between their far ends is copied.`;
135
+ const [from, to, top, bottom] = [90, 550, 34, 92];
136
+ const arrow = (x1: number, x2: number, y: number): string => { const back = x2 > x1 ? -8 : 8; return `M${x1},${y} L${x2},${y} M${x2 + back},${y - 5} L${x2},${y} L${x2 + back},${y + 5}`; };
137
+ return (
138
+ <svg className="pairpicture" viewBox="0 0 640 128" role="img" aria-label={says}>
139
+ <rect x={from} y={top - 12} width={to - from} height={bottom - top + 24} className="chosen" />
140
+ <line x1={20} x2={620} y1={top} y2={top} className="strand" /><line x1={20} x2={620} y1={bottom} y2={bottom} className="strand" />
141
+ <text x={14} y={top + 4} textAnchor="end" className="ends">5′</text><text x={626} y={top + 4} className="ends">3′</text>
142
+ <text x={14} y={bottom + 4} textAnchor="end" className="ends">3′</text><text x={626} y={bottom + 4} className="ends">5′</text>
143
+ <text x={320} y={top - 16} textAnchor="middle" className="ends">top strand</text><text x={320} y={bottom + 28} textAnchor="middle" className="ends">bottom strand</text>
144
+ <path d={arrow(from, from + 120, bottom - 12)} className="primer" />
145
+ <text x={from} y={bottom - 22} className="named">{names.forward} · 5′→3′ · {f.length} bases</text>
146
+ <path d={arrow(to, to - 120, top + 12)} className="primer" />
147
+ <text x={to} y={top + 32} textAnchor="end" className="named">{names.reverse} · 5′→3′ · {r.length} bases</text>
148
+ <text x={320} y={(top + bottom) / 2 + 4} textAnchor="middle" className="between">{count(design.length)} bp copied</text>
149
+ <text x={from} y={bottom + 28} textAnchor="middle" className="ends">{count(design.stretch.start + 1)}</text>
150
+ <text x={to} y={top - 16} textAnchor="middle" className="ends">{count(design.stretch.end)}</text>
151
+ </svg>
152
+ );
153
+ }
154
+
155
+ /** The candidates for one primer, as a comparison. */
156
+ function Candidates({ end, name, targetTm, onUse }: { end: DesignedPrimer; name: string; targetTm: number; onUse: (length: number | undefined) => void }) {
157
+ return (
158
+ <div className="candidates">
159
+ <h3>{name} <span className="dim">· {end.which}</span></h3>
160
+ <table>
161
+ <thead><tr><th>Bases</th><th>Tm</th><th>from {targetTm}°</th><th>GC</th><th>3′ end</th><th>Self</th><th>Score</th><th /></tr></thead>
162
+ <tbody>
163
+ {end.candidates.map((one) => {
164
+ const { report } = one;
165
+ const [chosen, best] = [one === end.chosen, one === end.best];
166
+ return (
167
+ <tr key={report.length} className={chosen ? "chosen" : undefined} aria-current={chosen ? "true" : undefined}>
168
+ <td>{report.length}</td>
169
+ <td>{report.tm.toFixed(1)}</td>
170
+ <td>{one.offTarget.toFixed(1)}</td>
171
+ <td>{(report.gc * 100).toFixed(0)}%</td>
172
+ <td className={report.gcClamp ? undefined : "look"} title={report.gcClamp ? "It ends in G or C." : "It does not end in G or C, which adds 2 to its score."}>{report.sequence.at(-1)}{report.gcClamp ? "" : " +2"}</td>
173
+ <td title={`${report.selfComplement} bases in a row pair with itself; ${report.endSelfComplement} at its 3′ end. Longest run of one base: ${report.longestRun}.`}>{report.selfComplement}/{report.endSelfComplement}</td>
174
+ <td><strong>{one.score.toFixed(2)}</strong></td>
175
+ <td className="small">
176
+ {best && <span className="good">scored best</span>}
177
+ {chosen && !best && <span>in use</span>}
178
+ {!chosen && <button type="button" className="plain" onClick={() => onUse(best ? undefined : report.length)} aria-label={`Use ${report.length} bases for the ${end.which} primer`}>use</button>}
179
+ {report.warnings.length > 0 && <span className="look" title={report.warnings.join("\n")}> · {report.warnings.length} {report.warnings.length === 1 ? "warning" : "warnings"}</span>}
180
+ </td>
181
+ </tr>
182
+ );
183
+ })}
184
+ </tbody>
185
+ </table>
186
+ <p className="small">{end.why}{end.chosen !== end.best && <> <strong>{end.chosen.report.length} bases is in use instead, by your choice.</strong></>}</p>
187
+ </div>
188
+ );
189
+ }
190
+
191
+ /**
192
+ * Designing primers.
193
+ *
194
+ * @param options - `start` says what to open on, for a tour or a link: the part by its checksum, a
195
+ * stretch or a feature of it by name, what to call the pair, and which part of the panel to have in view. `onPcr`, if given, adds a way to
196
+ * go on to a PCR once the lab has a tube of the template and of each primer, and is told which.
197
+ * @returns `panel`, the tool itself, and `desk`, what a scene beside it should look at and picture.
198
+ *
199
+ * @example
200
+ * ```tsx
201
+ * import { usePrimerBench } from "@biolibs/bionet-tools";
202
+ *
203
+ * const primers = usePrimerBench();
204
+ * // LabView is the scene package's. The room stays, with the template's tube in view and the pair drawn on its molecule.
205
+ * <LabView lab={lab} wide beside={primers.panel} {...(primers.desk.focus === null ? {} : { focus: primers.desk.focus })}
206
+ * molecule={(item) => (item === primers.desk.focus?.item ? primers.desk.molecule : null)} />
207
+ * ```
208
+ */
209
+ export function usePrimerBench({ start, onPcr }: {
210
+ /** What to show. Followed whenever it changes. */
211
+ start?: { part?: string; stretch?: Stretch; feature?: string; name?: string; section?: PrimerSection };
212
+ onPcr?: (tubes: { template: string; forward: string; reverse: string }) => void;
213
+ } = {}): { panel: ReactNode; desk: PrimerDesk } {
214
+ const lab = useLab()?.lab;
215
+ const act = useAct();
216
+ const [chosen, setChosen] = useState<string | null>(start?.part ?? null);
217
+ const [from, setFrom] = useState(start?.stretch === undefined ? "" : String(start.stretch.start + 1));
218
+ const [to, setTo] = useState(start?.stretch === undefined ? "" : String(start.stretch.end));
219
+ const [target, setTarget] = useState(String(DEFAULT_DESIGN.targetTm));
220
+ const [shortest, setShortest] = useState(String(DEFAULT_DESIGN.minLength));
221
+ const [longest, setLongest] = useState(String(DEFAULT_DESIGN.maxLength));
222
+ const [lengths, setLengths] = useState<{ forward?: number; reverse?: number }>({});
223
+ const [base, setBase] = useState(start?.name ?? "");
224
+ const [amount, setAmount] = useState("100");
225
+ const [busy, setBusy] = useState(false);
226
+ const [said, setSaid] = useState<string | null>(null);
227
+ // The lab as it stands now, for reading straight after asking it to change.
228
+ const latest = useRef(lab);
229
+ latest.current = lab;
230
+
231
+ // Templates worth designing on: anything long enough to hold a pair with something between them.
232
+ const parts = useMemo(() => (lab?.parts ?? []).filter((one) => one.length >= 2 * DEFAULT_DESIGN.minLength + 1), [lab?.parts]);
233
+ const part = parts.find((one) => one.checksum === chosen) ?? parts.find((one) => one.features.length > 0) ?? parts[0];
234
+ const offered = useMemo(() => (part === undefined ? [] : featureStretches(part)), [part]);
235
+ const choose = (stretch: Stretch): void => { setFrom(String(stretch.start + 1)); setTo(String(stretch.end)); setLengths({}); setSaid(null); };
236
+
237
+ // A host driving the tool — a tour, or a link — says what to show by changing `start`.
238
+ const asked = JSON.stringify(start ?? null);
239
+ useEffect(() => {
240
+ if (start === undefined) return;
241
+ if (start.part !== undefined) setChosen(start.part);
242
+ if (start.name !== undefined) setBase(start.name);
243
+ const held = latest.current?.parts.find((one) => one.checksum === start.part);
244
+ const named = start.feature === undefined || held === undefined ? undefined : featureStretches(held).find((one) => one.label === start.feature);
245
+ const stretch = start.stretch ?? named;
246
+ if (stretch !== undefined) choose(stretch);
247
+ }, [asked]);
248
+ // The panel is long, so a host that is talking about one part of it can ask for that part to be in view.
249
+ const shown = useRef<HTMLDivElement | null>(null);
250
+ useEffect(() => {
251
+ if (start?.section === undefined) return;
252
+ const held = setTimeout(() => shown.current?.querySelector(`[data-section="${start.section}"]`)?.scrollIntoView({ block: "start" }), 60);
253
+ return () => clearTimeout(held);
254
+ }, [asked]);
255
+
256
+ // Typed as a sequence file numbers bases: from 1, and the last one counted.
257
+ const stretch = useMemo((): Stretch | null => {
258
+ const [first, last] = [whole(from), whole(to)];
259
+ if (part === undefined || first === undefined || last === undefined) return null;
260
+ const typed = { start: first - 1, end: last };
261
+ return stretchLength(typed, part) === 0 ? null : typed;
262
+ }, [part, from, to]);
263
+ const ask = useMemo(() => ({
264
+ targetTm: whole(target) ?? DEFAULT_DESIGN.targetTm, minLength: whole(shortest) ?? DEFAULT_DESIGN.minLength, maxLength: whole(longest) ?? DEFAULT_DESIGN.maxLength,
265
+ ...(lengths.forward === undefined ? {} : { forwardLength: lengths.forward }), ...(lengths.reverse === undefined ? {} : { reverseLength: lengths.reverse }),
266
+ }), [target, shortest, longest, lengths]);
267
+ const design = useMemo(() => {
268
+ if (part === undefined || stretch === null) return null;
269
+ try { return designPair(part, stretch, ask); } catch { return null; }
270
+ }, [part, stretch, ask]);
271
+
272
+ const feature = stretch === null ? undefined : offered.find((one) => one.start === stretch.start && one.end === stretch.end);
273
+ const usual = (base.trim() || feature?.label || part?.name || "primer").slice(0, 190);
274
+ const order = design === null ? null : primerOrder(design, { base: usual });
275
+ const names = { forward: order?.parts[0].name ?? "forward", reverse: order?.parts[1].name ?? "reverse" };
276
+ // The same engine the PCR tool uses, given the pair: what a PCR with them would in fact make.
277
+ const made = useMemo(() => (part === undefined || design === null ? null
278
+ : planPcr(part, design.forward.chosen.report.sequence, design.reverse.chosen.report.sequence, { annealAtLeast: Math.min(18, design.forward.chosen.report.length, design.reverse.chosen.report.length) })), [part, design]);
279
+
280
+ const tubeOf = (sequence: string | undefined, circular: boolean): string | undefined => {
281
+ const held = lab?.parts.find((one) => one.circular === circular && one.sequence.toUpperCase() === sequence?.toUpperCase());
282
+ return held === undefined ? undefined : lab?.items.find((item) => item.part === held.checksum && !item.retired && item.amount > 0)?.item;
283
+ };
284
+ const templateTube = part === undefined ? undefined : lab?.items.filter((item) => item.part === part.checksum && !item.retired).sort((a, b) => Number(b.where !== null) - Number(a.where !== null))[0];
285
+ const [forwardTube, reverseTube] = [tubeOf(order?.parts[0].sequence, false), tubeOf(order?.parts[1].sequence, false)];
286
+ const held = order === null ? [false, false] : order.parts.map((one) => lab?.parts.some((each) => !each.circular && each.sequence.toUpperCase() === one.sequence) === true);
287
+ const ready = templateTube === undefined || templateTube.amount <= 0 || forwardTube === undefined || reverseTube === undefined ? null
288
+ : { template: templateTube.item, forward: forwardTube, reverse: reverseTube };
289
+ const desk: PrimerDesk = {
290
+ focus: templateTube === undefined || templateTube.where === null ? null : { place: templateTube.where.place, item: templateTube.item },
291
+ molecule: part === undefined ? null : designedMolecule(part, design, names),
292
+ ready,
293
+ };
294
+
295
+ /** Add the two primers as parts, and a tube of each if they have arrived. */
296
+ const add = async (arrived: boolean): Promise<void> => {
297
+ if (order === null) return;
298
+ setBusy(true);
299
+ const tubes = whole(amount);
300
+ let trouble: string | null = null;
301
+ for (const primer of order.parts) {
302
+ const answer = await act("addPart", primer);
303
+ if (!answer.ok) { trouble = answer.error; break; }
304
+ if (!arrived) continue;
305
+ // The part is known by its sequence, so the one just added is the one with these bases. The
306
+ // window hears of it a moment after the lab has it.
307
+ let found: PartState | undefined;
308
+ for (let tries = 0; tries < 40 && found === undefined; tries++) {
309
+ found = latest.current?.parts.find((one) => !one.circular && one.sequence.toUpperCase() === primer.sequence);
310
+ if (found === undefined) await new Promise((resolve) => setTimeout(resolve, 25));
311
+ }
312
+ if (found === undefined) { trouble = `${primer.name} was added, but the lab has not shown it yet, so no tube of it was added.`; break; }
313
+ const tube = await act("addItem", { part: found.checksum, amount: tubes === undefined || tubes < 0 ? 100 : tubes, unit: "µL" });
314
+ if (!tube.ok) { trouble = tube.error; break; }
315
+ }
316
+ setBusy(false);
317
+ setSaid(trouble ?? (arrived
318
+ ? `${names.forward} and ${names.reverse} are parts in the freezer now, with a tube of each, not yet put anywhere. No run was recorded, because nothing was made here: the tubes say only that they are in the lab.`
319
+ : `${names.forward} and ${names.reverse} are parts in the freezer now, with no tubes. Add a tube of each when they arrive.`));
320
+ };
321
+
322
+ // One set for the panel, so that a term is explained where it is first met and not at every mention.
323
+ const seen = new Set<string>();
324
+ const spans: MapSpan[] = part === undefined || design === null ? [] : designedMolecule({ ...part, features: [] }, design, names).features
325
+ .map((one) => ({ start: one.start, end: one.end, label: one.label, strand: one.strand }));
326
+ const stops = design?.warnings.filter((one) => one.weight === "stop").length ?? 0;
327
+
328
+ const panel = lab === null || lab === undefined ? null : (
329
+ <div className="bionet benchpanel primers" ref={shown}>
330
+ <section className="card" data-section="choose">
331
+ <div className="toolhead"><h2>Design primers</h2></div>
332
+ <p className="small"><Glossed seen={seen} text="A pair of primers marks the two ends of the stretch a PCR copies. Choose a part and the stretch of it to amplify, and the pair is designed here, in this window, from the lab's own sequence." /></p>
333
+ {part === undefined ? <p className="empty">The lab has no part long enough to design primers on. Bring one in on the Sequences tool.</p> : (
334
+ <>
335
+ <fieldset disabled={busy} className="choosing">
336
+ <label>Template
337
+ <select value={part.checksum} aria-label="Template" onChange={(event) => { setChosen(event.target.value); setFrom(""); setTo(""); setLengths({}); setSaid(null); }}>
338
+ {parts.map((one) => <option key={one.checksum} value={one.checksum}>{one.name} · {count(one.length)} bp{one.circular ? " · circular" : ""}</option>)}
339
+ </select>
340
+ </label>
341
+ <label>Amplify a feature
342
+ <select value={feature === undefined ? "" : String(offered.indexOf(feature))} aria-label="Amplify a feature" disabled={offered.length === 0}
343
+ onChange={(event) => { const picked = offered[Number(event.target.value)]; if (event.target.value !== "" && picked !== undefined) choose(picked); }}>
344
+ <option value="">{offered.length === 0 ? "Nothing is marked on this part" : "Choose a feature…"}</option>
345
+ {offered.map((one, index) => <option key={index} value={index}>{one.label} · {one.type} · {count(one.start + 1)}..{count(one.end)} · {count(one.length)} bp</option>)}
346
+ </select>
347
+ </label>
348
+ <label>From base<input type="number" min={1} max={part.length} step={1} value={from} onChange={(event) => { setFrom(event.target.value); setLengths({}); }} aria-label="From base" /></label>
349
+ <label>To base<input type="number" min={1} max={part.length} step={1} value={to} onChange={(event) => { setTo(event.target.value); setLengths({}); }} aria-label="To base" /></label>
350
+ </fieldset>
351
+ <StretchStrip part={part} stretch={stretch} onStretch={choose} />
352
+ <p className="dim small">
353
+ Drag across the strip, type the two bases, or choose a feature.
354
+ {part.circular && " On a circle, a From after the To runs the stretch through the origin."}
355
+ {stretch === null && from !== "" && to !== "" && <strong className="trouble"> That is not a stretch of this part.</strong>}
356
+ </p>
357
+ <div className="mapped">
358
+ <SequenceMap name={part.name} length={part.length} circular={part.circular} features={part.features} spans={spans} />
359
+ <fieldset disabled={busy} className="aims">
360
+ <label>Aim for<input type="number" min={40} max={80} step={1} value={target} onChange={(event) => { setTarget(event.target.value); setLengths({}); }} aria-label="Melting temperature aimed for" /> °C</label>
361
+ <label>Shortest<input type="number" min={8} max={60} step={1} value={shortest} onChange={(event) => { setShortest(event.target.value); setLengths({}); }} aria-label="Shortest primer" /> bases</label>
362
+ <label>Longest<input type="number" min={8} max={60} step={1} value={longest} onChange={(event) => { setLongest(event.target.value); setLengths({}); }} aria-label="Longest primer" /> bases</label>
363
+ <p className="dim small"><Glossed seen={seen} text="The melting temperature both primers are aimed at, and the lengths tried for each. Every length in the range is measured; nothing is thrown away unseen." /></p>
364
+ </fieldset>
365
+ </div>
366
+ </>
367
+ )}
368
+ </section>
369
+
370
+ {part !== undefined && stretch !== null && design === null && (
371
+ <section className="card"><p className="trouble" role="status">No primer can be designed at one end of this stretch: it is shorter than the shortest primer asked for, or its end holds a base that is not known for certain.</p></section>
372
+ )}
373
+
374
+ {part !== undefined && design !== null && order !== null && (
375
+ <>
376
+ <section className="card" data-section="pair">
377
+ <h2>The pair</h2>
378
+ <p className="voice">This design</p>
379
+ <PairPicture design={design} names={names} />
380
+ <table className="pair">
381
+ <thead><tr><th>Primer</th><th>5′ → 3′</th><th>Bases</th><th>Tm</th><th>GC</th><th>3′ end</th></tr></thead>
382
+ <tbody>
383
+ {[design.forward, design.reverse].map((end, index) => (
384
+ <tr key={end.which}>
385
+ <td>{order.parts[index]!.name}</td>
386
+ <td><code className="oligo">{end.chosen.report.sequence}</code></td>
387
+ <td>{end.chosen.report.length}</td>
388
+ <td>{end.chosen.report.tm.toFixed(1)} °C</td>
389
+ <td>{(end.chosen.report.gc * 100).toFixed(0)}%</td>
390
+ <td>{end.chosen.report.sequence.at(-1)}</td>
391
+ </tr>
392
+ ))}
393
+ </tbody>
394
+ </table>
395
+ <p className="small">
396
+ <strong>{count(design.length)} bp</strong> product{design.wraps ? ", through the origin" : ""} · melting temperatures {design.tmApart.toFixed(1)} °C apart
397
+ {made !== null && (made.problem === null && made.products[0]!.length === design.length
398
+ ? <span className="good"> · the PCR engine makes one product of {count(design.length)} bp from this pair</span>
399
+ : <span className="trouble"> · the PCR engine does not make one product of this length from this pair{made.problem === null ? "" : `: ${made.problem}`}</span>)}
400
+ </p>
401
+
402
+ <p className="voice">Checks</p>
403
+ {design.warnings.length === 0 ? <p className="small good"><Glossed seen={seen} text="Nothing about this pair looks wrong: the melting temperatures are close, neither primer folds into a hairpin or pairs with the other as a primer dimer, and each binds this template in one place." /></p> : (
404
+ <>
405
+ <ul className="checks">{design.warnings.map((one) => <li key={one.says} className={one.weight}><Glossed seen={seen} text={one.says} /></li>)}</ul>
406
+ <p className="dim small">{stops > 0 ? "The ones in red are likely to spoil the PCR. Try another length for that primer below, or move the stretch a few bases." : "None of these need stop you. They are what to think of first if the PCR gives trouble."}</p>
407
+ </>
408
+ )}
409
+ </section>
410
+
411
+ <section className="card" data-section="considered">
412
+ <h2>What was considered</h2>
413
+ <p className="small"><Glossed seen={seen} text="A primer has to start at its end of the stretch, so the only choice is how long it is. Here is every length tried, with what was measured of it. The score is how far its melting temperature is from the one aimed for, plus 2 if it lacks a GC clamp, plus a little for a GC content off the middle. The lowest wins." /></p>
414
+ <div className="considered">
415
+ <Candidates end={design.forward} name={names.forward} targetTm={design.targetTm} onUse={(length) => setLengths(({ forward: _, ...rest }) => (length === undefined ? rest : { ...rest, forward: length }))} />
416
+ <Candidates end={design.reverse} name={names.reverse} targetTm={design.targetTm} onUse={(length) => setLengths(({ reverse: _, ...rest }) => (length === undefined ? rest : { ...rest, reverse: length }))} />
417
+ </div>
418
+ <p className="dim small">Self is how many bases in a row pair with the primer itself, anywhere and at its 3′ end. Press <em>use</em> to take a different length; the checks and the working follow.</p>
419
+ </section>
420
+
421
+ <section className="card" data-section="working">
422
+ <h2>The working</h2>
423
+ <p className="dim small">Every figure above, opened out. Each was worked out here from the bases and can be followed by hand.</p>
424
+ {[design.forward, design.reverse].map((end, index) => {
425
+ const name = order.parts[index]!.name;
426
+ const { sequence } = end.chosen.report;
427
+ const tm = primerTmWorking(name, sequence);
428
+ const self = selfWorking(name, sequence);
429
+ return (
430
+ <div key={end.which} className="workings">
431
+ <p className="voice">{name}</p>
432
+ {tm !== null && (
433
+ <ShowWorking working={tm}>
434
+ <table className="counts">
435
+ <thead><tr><th>Pair</th><th>Times</th><th>ΔH each</th><th>ΔS each</th><th>ΔH</th><th>ΔS</th></tr></thead>
436
+ <tbody>
437
+ {tm.terms.pairs.map((one) => <tr key={one.pair}><td>{one.pair}</td><td>{one.times}</td><td>{one.dH.toFixed(1)}</td><td>{one.dS.toFixed(1)}</td><td>{(one.times * one.dH).toFixed(1)}</td><td>{(one.times * one.dS).toFixed(1)}</td></tr>)}
438
+ <tr><td>ends</td><td>2</td><td /><td /><td>{tm.terms.ends.dH.toFixed(1)}</td><td>{tm.terms.ends.dS.toFixed(1)}</td></tr>
439
+ <tr><td>salt</td><td /><td /><td /><td /><td>{tm.terms.salt.toFixed(2)}</td></tr>
440
+ <tr><th>sum</th><td /><td /><td /><th>{tm.terms.dH.toFixed(1)}</th><th>{tm.terms.dS.toFixed(2)}</th></tr>
441
+ </tbody>
442
+ </table>
443
+ </ShowWorking>
444
+ )}
445
+ <ShowWorking working={gcWorking(name, sequence)} />
446
+ <ShowWorking working={self}>
447
+ {self.longest > 0 && <PairedBases paired={self.paired} upper={name} lower={`${name} again`} />}
448
+ {self.atEnd > 0 && (self.paired.endShift !== self.paired.shift || self.paired.endFrom !== self.paired.from) && <PairedBases paired={self.paired} upper={name} lower={`${name} again`} run="end" />}
449
+ </ShowWorking>
450
+ <ShowWorking working={scoreWorking(end, end.chosen, design.targetTm)} />
451
+ </div>
452
+ );
453
+ })}
454
+ <p className="voice">The pair</p>
455
+ <ShowWorking working={productWorking(design, part, made?.problem === null ? made.products[0]!.length : undefined)} />
456
+ <ShowWorking working={tmApartWorking(design, names)} />
457
+ {(() => { const cross = crossWorking(design, names); return (
458
+ <ShowWorking working={cross}>
459
+ {cross.longest > 0 && <PairedBases paired={cross.paired} upper={names.forward} lower={names.reverse} />}
460
+ {cross.atEnd > 0 && (cross.paired.endShift !== cross.paired.shift || cross.paired.endFrom !== cross.paired.from) && <PairedBases paired={cross.paired} upper={names.forward} lower={names.reverse} run="end" />}
461
+ </ShowWorking>
462
+ ); })()}
463
+ </section>
464
+
465
+ <section className="card" data-section="order">
466
+ <h2>Order them, and keep them</h2>
467
+ <p className="small">Primers are ordered, not made at the bench. These two lines are what is sent to whoever makes them: a name, and the bases 5′ to 3′.</p>
468
+ <code className="wrap order">{order.lines.map((line) => <span key={line}>{line.replace("\t", " ")}</span>)}</code>
469
+ <fieldset disabled={busy} className="stack">
470
+ <label>Call them<input value={base} onChange={(event) => setBase(event.target.value)} placeholder={usual} maxLength={190} aria-label="What to call the pair" /></label>
471
+ <label>When they arrive, each tube holds, in µL<input type="number" min={0} step={1} value={amount} onChange={(event) => setAmount(event.target.value)} aria-label="Amount in each tube, in µL" /></label>
472
+ <div className="row">
473
+ <button type="button" disabled={held.every(Boolean)} onClick={() => void add(false)} title="Adds the two primers to the lab as parts, known by their sequences. No tubes: there is nothing in the freezer yet.">{held.every(Boolean) ? "The design is kept" : "Keep the design"}</button>
474
+ <button type="button" className="quiet" onClick={() => void add(true)} title="Adds the two primers as parts, and a tube of each. No run is recorded, since nothing was made here.">They have arrived: add a tube of each</button>
475
+ </div>
476
+ </fieldset>
477
+ <p className="dim small">Keeping the design adds two parts. A tube is added only when there is one, and it is recorded as a tube that came into the lab, not as something a run made.</p>
478
+ {said !== null && <p className="small" role="status">{said}</p>}
479
+ {ready !== null && (
480
+ <p className="small good">The lab has a tube of {part.name} and of each primer, so this PCR can be run.
481
+ {onPcr !== undefined && <> <button type="button" onClick={() => onPcr(ready)}>Run the PCR</button></>}
482
+ </p>
483
+ )}
484
+ {ready === null && held.every(Boolean) && <p className="dim small">A PCR needs a tube of {part.name} and of each primer. {templateTube === undefined || templateTube.amount <= 0 ? `There is no tube of ${part.name} with anything in it. ` : ""}{forwardTube === undefined || reverseTube === undefined ? "There is no tube of the primers yet." : ""}</p>}
485
+ </section>
486
+ </>
487
+ )}
488
+ </div>
489
+ );
490
+ return { panel, desk };
491
+ }
492
+
493
+ /**
494
+ * The primer design tool on its own, for a lab that has not drawn its room.
495
+ *
496
+ * @param props - `start` says what to open on; `onPcr` adds a way to go on to the PCR.
497
+ */
498
+ export function PrimerTool(props: Parameters<typeof usePrimerBench>[0]) {
499
+ return <>{usePrimerBench(props).panel}</>;
500
+ }