@biolibs/bionet-tools 0.1.10 → 0.1.12

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 (51) hide show
  1. package/README.md +211 -0
  2. package/dist/codons.d.ts +35 -0
  3. package/dist/codons.d.ts.map +1 -1
  4. package/dist/codons.js +55 -0
  5. package/dist/codons.js.map +1 -1
  6. package/dist/fusion-bench.d.ts +62 -0
  7. package/dist/fusion-bench.d.ts.map +1 -0
  8. package/dist/fusion-bench.js +114 -0
  9. package/dist/fusion-bench.js.map +1 -0
  10. package/dist/fusion.d.ts +120 -0
  11. package/dist/fusion.d.ts.map +1 -0
  12. package/dist/fusion.js +176 -0
  13. package/dist/fusion.js.map +1 -0
  14. package/dist/index.d.ts +12 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +12 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/modify.js +4 -4
  19. package/dist/modify.js.map +1 -1
  20. package/dist/ordering.d.ts +147 -0
  21. package/dist/ordering.d.ts.map +1 -0
  22. package/dist/ordering.js +203 -0
  23. package/dist/ordering.js.map +1 -0
  24. package/dist/protocol.d.ts +91 -0
  25. package/dist/protocol.d.ts.map +1 -0
  26. package/dist/protocol.js +278 -0
  27. package/dist/protocol.js.map +1 -0
  28. package/dist/remedy.d.ts +137 -0
  29. package/dist/remedy.d.ts.map +1 -0
  30. package/dist/remedy.js +234 -0
  31. package/dist/remedy.js.map +1 -0
  32. package/dist/tools.d.ts +1 -1
  33. package/dist/tools.d.ts.map +1 -1
  34. package/dist/tools.js +7 -3
  35. package/dist/tools.js.map +1 -1
  36. package/dist/work.d.ts +18 -0
  37. package/dist/work.d.ts.map +1 -0
  38. package/dist/work.js +155 -0
  39. package/dist/work.js.map +1 -0
  40. package/package.json +2 -2
  41. package/src/codons.ts +53 -0
  42. package/src/fusion-bench.tsx +209 -0
  43. package/src/fusion.ts +270 -0
  44. package/src/index.ts +12 -0
  45. package/src/modify.ts +4 -4
  46. package/src/ordering.ts +301 -0
  47. package/src/protocol.ts +332 -0
  48. package/src/remedy.ts +277 -0
  49. package/src/tools.tsx +8 -4
  50. package/src/work.tsx +319 -0
  51. package/tools.css +18 -0
package/src/remedy.ts ADDED
@@ -0,0 +1,277 @@
1
+ /**
2
+ * What to do about a host that will not phosphorylate what you asked it to make.
3
+ *
4
+ * `modify.ts` answers the question. This one is about what follows from the answer, and it is a
5
+ * different kind of thing to be careful about. Diagnosing is cheap to be honest about: either the
6
+ * motif is there or it is not, either the host is held to have the enzyme or it is not. Proposing a
7
+ * way round is where a tool can do real damage, because the ways round are not equivalent, the most
8
+ * computable of them is the least likely to work, and a lab that spends a month on the wrong one
9
+ * has spent a month.
10
+ *
11
+ * So two things are kept apart here, and neither pretends to be the other.
12
+ *
13
+ * **The routes** are laid out with what each costs and how firmly it is held, and none of them is
14
+ * recommended. Which one a lab takes depends on what it has — a tissue culture room, a second
15
+ * selection marker, a purified kinase, patience — and nothing here knows that.
16
+ *
17
+ * **The one that can be computed** is the phosphomimetic: replacing each phosphoserine with a
18
+ * glutamate or an aspartate, which carries a negative charge without needing any enzyme at all.
19
+ * That is arithmetic and {@link phosphomimetic} does it exactly. What it is not is a substitute for
20
+ * phosphorylation, and the honest framing is the whole value of the tool: a phosphoserine carries
21
+ * about two negative charges at neutral pH and a glutamate carries one, in a smaller group of a
22
+ * different shape, and for casein the clusters that bind calcium do so in a way that depends on
23
+ * that shape. It is a way of asking whether charge alone is enough. It is not a way of making
24
+ * phosphorylated casein, and a tool that let somebody believe otherwise would be worse than none.
25
+ */
26
+ import { ProteinAnalysis } from "@biolibs/seqtools";
27
+ import { CODON } from "./codons.js";
28
+ import { DA_PER_KDA } from "./induce.js";
29
+ import type { HostKinases } from "./modify.js";
30
+ import type { Working } from "./pcr-working.js";
31
+
32
+ /** One way round a host that will not do it. */
33
+ export interface Remedy {
34
+ /** Short name, to pick it by. */
35
+ name: string;
36
+ /** What it is, in a sentence or two. */
37
+ what: string;
38
+ /** What it costs the lab: what it needs and what it gives up. */
39
+ costs: string;
40
+ /** How firmly the route is held to work at all. */
41
+ standing: "well established" | "reported" | "worth trying";
42
+ /** Whether anything here can work it out, or it is only described. */
43
+ computable: boolean;
44
+ }
45
+
46
+ /**
47
+ * The ways round a host that will not phosphorylate what it makes, in no order of preference.
48
+ *
49
+ * None is recommended, because which one suits depends on what a lab has — a tissue culture room, a
50
+ * second selection marker, a purified kinase, time — and nothing here knows that. What is said of
51
+ * each is what it costs and how firmly it is held.
52
+ */
53
+ export const REMEDIES: readonly Remedy[] = [
54
+ {
55
+ name: "co-express the kinase",
56
+ what: "Put a kinase into the host alongside the protein, so that the cell does the phosphorylating itself. For a secreted protein the kinase has to reach the same compartment the protein passes through, which is the part that usually decides whether it works.",
57
+ costs: "A second construct, a second selection marker, and a second thing that can go wrong. The kinase's own expression has to be got right before anything can be said about the protein's.",
58
+ standing: "reported", computable: false,
59
+ },
60
+ {
61
+ name: "a host that already has it",
62
+ what: "Express it in something that phosphorylates secreted proteins as a matter of course — a mammalian cell line does, which is what makes milk in the first place.",
63
+ costs: "Slow, expensive, and a different set of skills and equipment. It is why almost nobody makes a food protein this way.",
64
+ standing: "well established", computable: false,
65
+ },
66
+ {
67
+ name: "phosphorylate it afterwards",
68
+ what: "Make the protein unphosphorylated, purify it, and treat it with a purified kinase and ATP in a tube.",
69
+ costs: "The kinase has to be bought or made, and the reaction has to be driven to something like completion on a purified protein, which is not the same as a cell doing it as the protein is made.",
70
+ standing: "reported", computable: false,
71
+ },
72
+ {
73
+ name: "a phosphomimetic",
74
+ what: "Change each serine that would have been phosphorylated to a glutamate or an aspartate, which carries a negative charge with no enzyme needed. The gene is rewritten; nothing is added to the cell.",
75
+ costs: "It is not the same molecule. A phosphoserine carries about two negative charges at neutral pH and a glutamate carries one, in a smaller group of a different shape. It asks whether charge alone is enough; it does not make phosphorylated protein.",
76
+ standing: "worth trying", computable: true,
77
+ },
78
+ {
79
+ name: "measure what you actually get",
80
+ what: "Express it, run the gel, and test the thing you care about — whether micelles form, whether calcium is bound — rather than assuming the answer from whether the host has an enzyme.",
81
+ costs: "Nothing beyond the experiment, and it is the only one of these that tells you where you really are rather than where the literature says you probably are.",
82
+ standing: "well established", computable: false,
83
+ },
84
+ ];
85
+
86
+ /** One residue swapped for something that carries a charge. */
87
+ export interface Swapped {
88
+ /** Where it is, counting from 1 on the protein given. */
89
+ at: number;
90
+ /** What was there, and what it became. */
91
+ was: string;
92
+ now: string;
93
+ }
94
+
95
+ /** A protein with its phosphosites swapped for something charged. */
96
+ export interface Phosphomimetic {
97
+ /** The protein, changed. */
98
+ protein: string;
99
+ /** Each residue that changed. */
100
+ swapped: Swapped[];
101
+ /** What was asked for but could not be changed, because that residue is not one that is phosphorylated. */
102
+ notSwapped: { at: number; was: string; why: string }[];
103
+ /** What it weighs before and after, in daltons, and what that is on a gel. */
104
+ weight: { before: number; after: number } | null;
105
+ kilodaltons: { before: number; after: number } | null;
106
+ /** The pH it carries no net charge at, before and after: the figure this changes most. */
107
+ isoelectric: { before: number; after: number } | null;
108
+ /** What a careful person would know before leaning on it. */
109
+ warnings: string[];
110
+ /** Why nothing could be done, or `null`. */
111
+ problem: string | null;
112
+ }
113
+
114
+ /** What may stand in for a phosphoserine, and how far it gets. */
115
+ const INSTEAD: Readonly<Record<string, { charge: number; says: string }>> = {
116
+ E: { charge: 1, says: "glutamate: one negative charge, and the longer of the two side chains" },
117
+ D: { charge: 1, says: "aspartate: one negative charge, and the shorter side chain" },
118
+ };
119
+
120
+ /** Which residues are phosphorylated at all. */
121
+ const PHOSPHORYLATED = new Set(["S", "T", "Y"]);
122
+
123
+ /**
124
+ * Swap each named residue for something that carries a negative charge.
125
+ *
126
+ * @param protein - The amino acids.
127
+ * @param sites - Where the phosphosites are, counting from 1 on that sequence.
128
+ * @param options - `instead` is what to put there, `E` unless said.
129
+ * @returns The changed protein, what it changed, and what it does and does not reproduce.
130
+ *
131
+ * @example
132
+ * ```ts
133
+ * import { phosphomimetic } from "@biolibs/bionet-tools";
134
+ *
135
+ * const asked = phosphomimetic(casein, [15, 17, 18, 19, 35]);
136
+ * asked.isoelectric; // what the change really does: the charge, not the shape
137
+ * ```
138
+ */
139
+ export function phosphomimetic(protein: string, sites: readonly number[], options: { instead?: "E" | "D" } = {}): Phosphomimetic {
140
+ const chain = protein.replace(/\s+/g, "").toUpperCase();
141
+ const nothing = (problem: string): Phosphomimetic =>
142
+ ({ protein: chain, swapped: [], notSwapped: [], weight: null, kilodaltons: null, isoelectric: null, warnings: [], problem });
143
+ if (chain === "") return nothing("There is no protein here to change.");
144
+ if (!/^[ACDEFGHIKLMNPQRSTVWY]+$/.test(chain)) return nothing("That is written in letters that are not the twenty standard amino acids.");
145
+ const instead = options.instead ?? "E";
146
+ if (!Object.hasOwn(INSTEAD, instead)) return nothing("A phosphomimetic is a glutamate or an aspartate.");
147
+ if (sites.length === 0) return nothing("No sites were given, so there is nothing to change.");
148
+
149
+ const letters = [...chain];
150
+ const swapped: Swapped[] = [];
151
+ const notSwapped: Phosphomimetic["notSwapped"] = [];
152
+ for (const at of [...new Set(sites)].sort((a, b) => a - b)) {
153
+ const was = letters[at - 1];
154
+ if (was === undefined) { notSwapped.push({ at, was: "", why: `This protein has ${chain.length} residues, so there is nothing at ${at}.` }); continue; }
155
+ if (!PHOSPHORYLATED.has(was)) { notSwapped.push({ at, was, why: `${was}${at} is not a serine, a threonine or a tyrosine, so it was never phosphorylated.` }); continue; }
156
+ letters[at - 1] = instead;
157
+ swapped.push({ at, was, now: instead });
158
+ }
159
+ const changed = letters.join("");
160
+
161
+ const figures = (one: string): { weight: number; isoelectric: number } | null => {
162
+ try { const analysis = new ProteinAnalysis(one); return { weight: analysis.molecularWeight(), isoelectric: analysis.isoelectricPoint() }; }
163
+ catch { return null; }
164
+ };
165
+ const before = figures(chain);
166
+ const after = figures(changed);
167
+
168
+ const warnings: string[] = [];
169
+ if (swapped.length > 0) {
170
+ warnings.push(`A phosphoserine carries about two negative charges at the pH of a cell; ${INSTEAD[instead]!.says}. So this reproduces something like half the charge, and none of the shape.`);
171
+ warnings.push("Where phosphoserines sit in a cluster and bind calcium between them — which is what makes casein build a micelle — the geometry matters as much as the charge, and a glutamate does not have it.");
172
+ warnings.push("Treat this as a way of asking whether charge alone is enough, and as something to compare against the real thing rather than to stand in for it.");
173
+ }
174
+ if (swapped.length > 0 && notSwapped.length > 0) warnings.push(`${notSwapped.length} of the sites given could not be changed; they are listed.`);
175
+
176
+ return {
177
+ protein: changed, swapped, notSwapped,
178
+ weight: before === null || after === null ? null : { before: before.weight, after: after.weight },
179
+ kilodaltons: before === null || after === null ? null : { before: before.weight / DA_PER_KDA, after: after.weight / DA_PER_KDA },
180
+ isoelectric: before === null || after === null ? null : { before: before.isoelectric, after: after.isoelectric },
181
+ warnings,
182
+ problem: swapped.length === 0 && notSwapped.length > 0 ? "None of the sites given is a residue that is phosphorylated." : null,
183
+ };
184
+ }
185
+
186
+ /** A gene rewritten so that it encodes a phosphomimetic. */
187
+ export interface MimeticGene {
188
+ /** The bases, changed. */
189
+ sequence: string;
190
+ /** Each codon that changed, by the amino acid it is, counting codons from 1. */
191
+ changed: { codon: number; was: string; now: string; aminoAcid: string }[];
192
+ /** Why nothing could be done, or `null`. */
193
+ problem: string | null;
194
+ }
195
+
196
+ /**
197
+ * Rewrite a coding sequence so that it encodes a phosphomimetic.
198
+ *
199
+ * The protein is what matters; this is how you get a lab something it can order. Each named codon is
200
+ * replaced with one for the substitute, and which codon that is can be the host's commonest, so that
201
+ * what comes out is as readable to the host as what went in.
202
+ *
203
+ * @param cds - The coding sequence, a whole number of codons.
204
+ * @param sites - Where the phosphosites are, counting amino acids from 1.
205
+ * @param options - `instead` is what to encode, `E` unless said; `codon` picks the codon to use for
206
+ * it, which `optimiseCodons` can choose from a host's own usage.
207
+ * @returns The gene, and what changed.
208
+ *
209
+ * @example
210
+ * ```ts
211
+ * import { mimeticGene } from "@biolibs/bionet-tools";
212
+ *
213
+ * mimeticGene(casein, [15, 17, 18, 19, 35], { codon: "GAA" }).sequence;
214
+ * ```
215
+ */
216
+ export function mimeticGene(cds: string, sites: readonly number[], options: { instead?: "E" | "D"; codon?: string } = {}): MimeticGene {
217
+ const bases = cds.replace(/\s+/g, "").toUpperCase();
218
+ if (!/^[ACGT]+$/.test(bases)) return { sequence: bases, changed: [], problem: "A gene to rewrite is written in A, C, G and T, with no uncertain bases." };
219
+ if (bases.length % CODON !== 0) return { sequence: bases, changed: [], problem: `That is ${bases.length} bases, which is not a whole number of codons.` };
220
+ const instead = options.instead ?? "E";
221
+ // The commonest codon for each, where the caller does not pick one from a host's own usage.
222
+ const usual: Readonly<Record<string, string>> = { E: "GAA", D: "GAT" };
223
+ const codon = (options.codon ?? usual[instead] ?? "GAA").toUpperCase();
224
+ if (!/^[ACGT]{3}$/.test(codon)) return { sequence: bases, changed: [], problem: "A codon is three bases of A, C, G and T." };
225
+
226
+ const codons = bases.match(/.{3}/g) ?? [];
227
+ const changed: MimeticGene["changed"] = [];
228
+ for (const at of [...new Set(sites)].sort((a, b) => a - b)) {
229
+ const was = codons[at - 1];
230
+ if (was === undefined || was === codon) continue;
231
+ codons[at - 1] = codon;
232
+ changed.push({ codon: at, was, now: codon, aminoAcid: instead });
233
+ }
234
+ return { sequence: codons.join(""), changed, problem: null };
235
+ }
236
+
237
+ /**
238
+ * The routes open to a lab whose host will not do it, with what each costs.
239
+ *
240
+ * @param host - What is held about the host, from `hostPhosphorylation`, or `null` if it is not known.
241
+ * @returns The routes, and a line about where they came from.
242
+ */
243
+ export function remediesFor(host: HostKinases | null): { routes: Remedy[]; says: string[] } {
244
+ const says: string[] = [];
245
+ if (host === null) {
246
+ says.push("Nothing here says what this host does, which is not the same as its doing nothing. Find out before choosing a way round something that may not be a problem.");
247
+ } else if (host.secretoryKinase === "yes") {
248
+ says.push(`${host.host} is held to have the kinase, so there may be nothing to work round. Measure what you get before changing anything.`);
249
+ } else {
250
+ says.push(`${host.host}: ${host.says}`);
251
+ says.push("None of these is recommended over another. Which suits depends on what the lab has, which nothing here knows.");
252
+ }
253
+ return { routes: [...REMEDIES], says };
254
+ }
255
+
256
+ /**
257
+ * The working behind a phosphomimetic: what changed, and what it does and does not reproduce.
258
+ *
259
+ * @param made - What `phosphomimetic` gave.
260
+ * @returns The workings. Empty if nothing could be changed.
261
+ */
262
+ export function phosphomimeticWorking(made: Phosphomimetic): Working[] {
263
+ if (made.problem !== null || made.swapped.length === 0) return [];
264
+ const round = (value: number): string => value.toLocaleString("en-US", { maximumFractionDigits: 2 });
265
+ const out: Working[] = [{
266
+ of: "what the swap changes",
267
+ comes: made.isoelectric === null ? `${made.swapped.length} residues` : `pH ${made.isoelectric.before.toFixed(2)} → ${made.isoelectric.after.toFixed(2)}`,
268
+ kind: "exact",
269
+ steps: [
270
+ `${made.swapped.length} ${made.swapped.length === 1 ? "residue" : "residues"} changed: ${made.swapped.map((one) => `${one.was}${one.at}${one.now}`).join(", ")}.`,
271
+ ...(made.weight === null ? [] : [`The weight goes from ${round(made.weight.before)} to ${round(made.weight.after)} Da, which is ${round(Math.abs(made.weight.after - made.weight.before))} Da and not something a gel will show.`]),
272
+ ...(made.isoelectric === null ? [] : [`The pH it carries no net charge at goes from ${made.isoelectric.before.toFixed(2)} to ${made.isoelectric.after.toFixed(2)}. That is the figure this really changes, and it is why a mimetic is worth trying at all.`]),
273
+ ],
274
+ rests: "What is computed here is the sequence and what the sequence comes to. Whether a glutamate does the job a phosphoserine did is not a question a sequence can answer: it carries about half the charge, in a smaller group of a different shape, and where a cluster of phosphoserines binds calcium the shape is part of the work. This is a way of asking whether charge alone is enough.",
275
+ }];
276
+ return out;
277
+ }
package/src/tools.tsx CHANGED
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
 
3
3
  /** Getting to a tool: from the instrument it is used at, or from a list of them all. */
4
- import { useState, type ReactNode } from "react";
4
+ import { useEffect, useState, type ReactNode } from "react";
5
5
  import { useLab } from "@biolibs/bionet-react";
6
6
  import { DigestTool } from "./digest-tool.js";
7
7
  import { InductionTool } from "./induce-bench.js";
@@ -9,13 +9,14 @@ import { PcrTool } from "./pcr-tool.js";
9
9
  import { instrumentFor, toolFor, type ToolName } from "./run.js";
10
10
  import { LigationTool } from "./ligate-bench.js";
11
11
  import { AssemblyTool } from "./assembly-bench.js";
12
+ import { FusionTool } from "./fusion-bench.js";
12
13
  import { CodonTool } from "./codon-bench.js";
13
14
  import { VerifyTool } from "./verify-bench.js";
14
15
  import { PrimerTool } from "./primer-bench.js";
15
16
  import { SequencesTool } from "./sequences-tool.js";
16
17
 
17
18
  /** The tools used at a desk and not at an instrument: the lab's sequences, and designing primers. */
18
- export type DeskTool = "sequences" | "primers" | "codons" | "assembly" | "verify";
19
+ export type DeskTool = "sequences" | "primers" | "codons" | "construct" | "assembly" | "verify";
19
20
 
20
21
  /** What each tool is called. */
21
22
  export const TOOL_NAMES: Readonly<Record<ToolName, string>> = { pcr: "PCR", digest: "Digest and gel", ligation: "Ligation", induction: "Induction" };
@@ -65,9 +66,12 @@ export function InstrumentTool({ place, onDone }: { place: string; onDone?: () =
65
66
  export function Tools({ tool: first = "pcr", views = {} }: { tool?: ToolName | DeskTool; views?: Partial<Record<ToolName | DeskTool, ReactNode | ((go: (tool: ToolName | DeskTool) => void) => ReactNode)>> }) {
66
67
  const lab = useLab()?.lab;
67
68
  const [tool, setTool] = useState<ToolName | DeskTool>(first);
69
+ // Followed rather than read once, so that something elsewhere in the window — a list of the work
70
+ // to be done, say — can send somebody to the tool that would carry a step out.
71
+ useEffect(() => { setTool(first); }, [first]);
68
72
  if (lab === null || lab === undefined) return null;
69
73
  const shown = views[tool];
70
- const names: [ToolName | DeskTool, string][] = [["sequences", "Sequences"], ["primers", "Primers"], ["codons", "Codons"], ["assembly", "Assembly"], ["verify", "Check"], ...(Object.keys(TOOL_NAMES) as ToolName[]).map((one): [ToolName, string] => [one, TOOL_NAMES[one]])];
74
+ const names: [ToolName | DeskTool, string][] = [["sequences", "Sequences"], ["primers", "Primers"], ["codons", "Codons"], ["construct", "Construct"], ["assembly", "Assembly"], ["verify", "Check"], ...(Object.keys(TOOL_NAMES) as ToolName[]).map((one): [ToolName, string] => [one, TOOL_NAMES[one]])];
71
75
  return (
72
76
  <div className="tools">
73
77
  <div className="row tight pick" role="tablist" aria-label="Tools">
@@ -75,7 +79,7 @@ export function Tools({ tool: first = "pcr", views = {} }: { tool?: ToolName | D
75
79
  <button key={one} type="button" role="tab" aria-selected={one === tool} className={one === tool ? "" : "quiet"} onClick={() => setTool(one)}>{name}</button>
76
80
  ))}
77
81
  </div>
78
- {(typeof shown === "function" ? shown(setTool) : shown) ?? (tool === "sequences" ? <SequencesTool /> : tool === "assembly" ? <AssemblyTool /> : tool === "codons" ? <CodonTool /> : tool === "verify" ? <VerifyTool />
82
+ {(typeof shown === "function" ? shown(setTool) : shown) ?? (tool === "sequences" ? <SequencesTool /> : tool === "construct" ? <FusionTool /> : tool === "assembly" ? <AssemblyTool /> : tool === "codons" ? <CodonTool /> : tool === "verify" ? <VerifyTool />
79
83
  : tool === "primers" ? <PrimerTool onPcr={() => setTool("pcr")} />
80
84
  : <Tool key={tool} tool={tool} instrument={instrumentFor(lab, tool)} />)}
81
85
  </div>
package/src/work.tsx ADDED
@@ -0,0 +1,319 @@
1
+ "use client";
2
+
3
+ /**
4
+ * Every open proposal, read as one piece of work rather than as a pile of cards.
5
+ *
6
+ * The tools each show the proposals for their own machine, which is right when somebody is standing
7
+ * at that machine. It is no use at all for seeing where a build has got to: eleven proposals spread
8
+ * over four tabs, in the order they happened to be made, with nothing saying which comes first or
9
+ * what is waiting on what. This is the other view — the whole of it, in order, in chains.
10
+ *
11
+ * It asserts nothing. Everything here comes from `planOfWork`, which works the order out from what
12
+ * each proposal makes and what each one needs, so what is drawn cannot drift from what is true.
13
+ */
14
+ import { useState, type ReactNode } from "react";
15
+ import { useAct, useLab } from "@biolibs/bionet-react";
16
+ import { Glossed } from "@biolibs/glossary-react";
17
+ import { FILED_UNDER, UNFILED, planOfWork, saysWork, type Project, type Step } from "./ordering.js";
18
+ import { protocolText, protocolsFor } from "./protocol.js";
19
+
20
+ /** What a step is called, by what kind of run it is. */
21
+ const CALLED: Readonly<Record<string, string>> = {
22
+ pcr: "Copy it", digest: "Cut it", ligation: "Join it", assembly: "Build the ring",
23
+ transformation: "Put it into a host", induction: "Grow it and look for the protein",
24
+ };
25
+
26
+ /**
27
+ * The lab's open proposals as one piece of work: in order, in chains, with what can start now.
28
+ *
29
+ * @param props - `onOpen`, if given, offers a way to go to the tool that would carry a step out,
30
+ * and is handed the proposal.
31
+ *
32
+ * @example
33
+ * ```tsx
34
+ * import { WorkToDo } from "@biolibs/bionet-tools";
35
+ *
36
+ * <WorkToDo onOpen={(plan) => goToTool(plan.kind)} />
37
+ * ```
38
+ */
39
+ export function WorkToDo({ onOpen }: { onOpen?: (plan: Step["plan"]) => void } = {}) {
40
+ const lab = useLab()?.lab;
41
+ const act = useAct();
42
+ // Which project is being looked at, or null for all of them at once.
43
+ const [only, setOnly] = useState<string | null>(null);
44
+ const [filing, setFiling] = useState<string | null>(null);
45
+ const [into, setInto] = useState("");
46
+ // Writing the method out, and taking one somebody else wrote.
47
+ const [method, setMethod] = useState<string | null>(null);
48
+ // The sheet to carry to a bench, which is a different thing from the method: one is for another
49
+ // lab's software to read, the other for a person standing up with gloves on.
50
+ const [sheet, setSheet] = useState<string | null>(null);
51
+ const [taking, setTaking] = useState("");
52
+ const [told, setTold] = useState<string | null>(null);
53
+ if (lab === null || lab === undefined) return null;
54
+ const whole = planOfWork(lab);
55
+ const shown: Project | undefined = only === null ? undefined : whole.projects.find((one) => one.name === only);
56
+ // Looking at one project shows its chains and its steps, and nothing of anybody else's.
57
+ const work = shown === undefined ? whole : (() => {
58
+ const mine = new Set(shown.order.map((one) => one.plan.plan));
59
+ return {
60
+ ...whole, threads: shown.threads, order: shown.order, ready: shown.ready,
61
+ held: shown.order.filter((one) => one.held !== null),
62
+ // What to get first is this project's, not the lab's: showing another project's missing part
63
+ // here would have somebody ordering something their own work does not need.
64
+ toGet: whole.toGet.flatMap((one) => {
65
+ const forSteps = one.forSteps.filter((each) => mine.has(each));
66
+ return forSteps.length === 0 ? [] : [{ ...one, forSteps }];
67
+ }),
68
+ tangled: whole.tangled.filter((one) => mine.has(one)),
69
+ };
70
+ })();
71
+ const said = saysWork(whole);
72
+ const projects = whole.projects;
73
+ const filedAs = (plan: Step["plan"]): string => {
74
+ const says = plan.fields[FILED_UNDER];
75
+ return typeof says === "string" && says.trim() !== "" ? says.trim() : UNFILED;
76
+ };
77
+ const asASheet = (): void => {
78
+ const sheets = protocolsFor(lab, { ...(only === null || only === UNFILED ? {} : { project: only }) });
79
+ setSheet(sheets.length === 0 ? null : sheets.map(protocolText).join("\n\n---\n\n"));
80
+ };
81
+ const writeOut = async (): Promise<void> => {
82
+ const answer = await act("publishMethod", { ...(only === null ? {} : { project: only }) });
83
+ setTold(answer.ok ? null : answer.error);
84
+ setMethod(answer.ok ? JSON.stringify(answer.result, null, 2) : null);
85
+ };
86
+ const take = async (): Promise<void> => {
87
+ const answer = await act("takeMethod", { method: taking, ...(only === null || only === UNFILED ? {} : { project: only }) });
88
+ if (!answer.ok) { setTold(answer.error); return; }
89
+ const got = answer.result as { proposed: string[]; missing: { name: string }[]; alive: { name: string }[] };
90
+ setTaking("");
91
+ setTold(`${got.proposed.length} ${got.proposed.length === 1 ? "step is" : "steps are"} proposed here.`
92
+ + (got.missing.length === 0 ? "" : ` ${got.missing.map((one) => one.name).join(" and ")} has to be got first.`)
93
+ + (got.alive.length === 0 ? "" : ` ${got.alive.map((one) => one.name).join(" and ")} is alive and cannot be sent: make your own.`));
94
+ };
95
+ const file = async (plan: string, name: string): Promise<void> => {
96
+ await act("setField", { on: "plan", id: plan, field: FILED_UNDER, value: name.trim() === "" ? null : name.trim() });
97
+ setFiling(null); setInto("");
98
+ };
99
+ const person = (key: string): string => lab.roster.find((one) => one.key === key)?.person ?? "a device";
100
+ const partName = (checksum: string | undefined): string => lab.parts.find((one) => one.checksum === checksum)?.name ?? "a part";
101
+ const tubeName = (item: string | undefined): string => {
102
+ const held = lab.items.find((one) => one.item === item);
103
+ if (held === undefined) return "a tube";
104
+ return held.part === null ? lab.strains.find((one) => one.strain === held.strain)?.name ?? "a culture" : partName(held.part);
105
+ };
106
+ const stepName = (plan: Step["plan"]): string => CALLED[plan.kind] ?? plan.kind;
107
+ /**
108
+ * Where a step sits in its own piece of work.
109
+ *
110
+ * Counted inside the chain and not across the whole lot, which is safe because a chain is every
111
+ * step joined to every other by what they make and need: a step can only ever wait on one in the
112
+ * same chain. Numbering across all of them would make the numbers in one card jump wherever
113
+ * another chain's steps fell between, for no gain.
114
+ */
115
+ const at = (id: string): number => {
116
+ const thread = work.threads.find((one) => one.steps.some((step) => step.plan.plan === id));
117
+ return (thread?.steps.findIndex((step) => step.plan.plan === id) ?? 0) + 1;
118
+ };
119
+
120
+ const why = (step: Step): ReactNode => {
121
+ if (step.held === null) return <span className="good">could be done now</span>;
122
+ if (step.held.why === "a step before it") {
123
+ return <>waiting on {step.held.steps.map((one) => `step ${at(one)}`).join(" and ")}</>;
124
+ }
125
+ if (step.held.why === "something nobody is making") {
126
+ return <span className="attention">{step.held.parts.map((one) => partName(one)).join(" and ")} has to be ordered or made first</span>;
127
+ }
128
+ return <span className="attention">{step.held.tubes.map(tubeName).join(" and ")} has been retired or run short</span>;
129
+ };
130
+
131
+ /**
132
+ * Giving the work to somebody else, and taking somebody's.
133
+ *
134
+ * Shown whether or not this lab has any work of its own, because a lab taking a method for the
135
+ * first time has none — which is exactly the lab that needs this, and the one that would have
136
+ * found nothing here if it were only drawn beside work that already existed.
137
+ */
138
+ const crossing = (
139
+ <section className="card">
140
+ <h2>Giving it to somebody else</h2>
141
+ <p className="small"><Glossed text="A method is this plan written so another lab can carry it out: every tube replaced by the checksum of what is in it, which is the one name two labs that have never spoken already agree on." /></p>
142
+ <p className="dim small">
143
+ Two things cannot be sent, and it says so rather than pretending. Anything alive: a strain is this lab&rsquo;s own, so whoever follows it makes their own.
144
+ And a starting molecule&rsquo;s sequence, if a keeper chose not to publish it — then it says which molecules are needed and not what they are.
145
+ </p>
146
+ {work.order.length > 0 && (
147
+ <div className="row tight">
148
+ <button type="button" onClick={() => void writeOut()}>Write {only === null ? "it all" : only} out</button>
149
+ {method !== null && <button type="button" className="quiet" onClick={() => setMethod(null)}>Hide it</button>}
150
+ </div>
151
+ )}
152
+ {method !== null && <textarea className="method" value={method} readOnly rows={12} aria-label="The method, to give to somebody" onFocus={(event) => event.currentTarget.select()} />}
153
+ <p className="voice">Taking one</p>
154
+ <form className="stack" onSubmit={(event) => { event.preventDefault(); void take(); }}>
155
+ <label>A method somebody published
156
+ <textarea value={taking} onChange={(event) => setTaking(event.target.value)} rows={4} spellCheck={false}
157
+ placeholder="Paste it here" aria-label="A method to take" />
158
+ </label>
159
+ <div className="row"><button type="submit" disabled={taking.trim() === ""}>Propose its steps here</button></div>
160
+ </form>
161
+ <p className="dim small">Nothing is used and nothing is recorded as done: what lands is proposals, as if somebody here had made them. A molecule it needs that this lab has never heard of is said rather than guessed at.</p>
162
+ {told !== null && <p className="small" role="status">{told}</p>}
163
+ </section>
164
+ );
165
+
166
+ if (work.order.length === 0 && work.tangled.length === 0) {
167
+ return (
168
+ <div className="bionet work">
169
+ <section className="card">
170
+ <h2>The work</h2>
171
+ <p className="empty">Nothing is proposed here. A proposal is a run somebody could carry out, and a lab member or its adviser makes one at the tool that would do it. Several together are read as one piece of work.</p>
172
+ </section>
173
+ {work.order.length > 0 && (
174
+ <section className="card">
175
+ <h2>Taking it to the bench</h2>
176
+ <p className="small">The same work as a sheet to print or carry: what to fetch, what to set a machine to, what to do, and what to record afterwards.</p>
177
+ <p className="dim small">
178
+ Every number on it — a volume, a temperature, a time — is one somebody set or one the lab&rsquo;s own tools worked out.
179
+ Nothing is filled in to make it look finished: what a plan does not say is listed under each step instead, so the hole is found standing at a bench and not halfway through.
180
+ </p>
181
+ <div className="row tight">
182
+ <button type="button" onClick={asASheet}>Write {only === null ? "it all" : only} as a protocol</button>
183
+ {sheet !== null && <button type="button" className="quiet" onClick={() => setSheet(null)}>Hide it</button>}
184
+ </div>
185
+ {sheet !== null && <textarea className="method sheet" value={sheet} readOnly rows={18} aria-label="The protocol, to print or carry" onFocus={(event) => event.currentTarget.select()} />}
186
+ </section>
187
+ )}
188
+
189
+ {crossing}
190
+ </div>
191
+ );
192
+ }
193
+
194
+ return (
195
+ <div className="bionet work">
196
+ <section className="card">
197
+ <h2>The work</h2>
198
+ <p className="small"><Glossed text="Each step is a proposed run: nothing has been used and nothing is recorded as done until somebody carries it out and says so." /></p>
199
+ {said.map((one) => <p key={one} className="small">{one}</p>)}
200
+ {projects.length > 1 && (
201
+ <div className="row tight pick" role="tablist" aria-label="Projects">
202
+ <button type="button" role="tab" aria-selected={only === null} className={only === null ? "" : "quiet"} onClick={() => setOnly(null)}>Everything</button>
203
+ {projects.map((one) => (
204
+ <button key={one.name} type="button" role="tab" aria-selected={only === one.name} className={only === one.name ? "" : "quiet"} onClick={() => setOnly(one.name)}>
205
+ {one.name}{one.ready.length > 0 ? ` · ${one.ready.length} ready` : ""}
206
+ </button>
207
+ ))}
208
+ </div>
209
+ )}
210
+ <p className="dim small">
211
+ Nothing here was declared. A proposal says what it expects to make and what it needs, and where one expects what another needs, the first has to happen first.
212
+ The chain stops at a transformation: what that makes is alive and has no checksum to point at, so what follows is proposed afresh once there is something growing.
213
+ </p>
214
+ </section>
215
+
216
+ {work.order.length > 0 && (
217
+ <section className="card">
218
+ <h2>Taking it to the bench</h2>
219
+ <p className="small">The same work as a sheet to print or carry: what to fetch, what to set a machine to, what to do, and what to record afterwards.</p>
220
+ <p className="dim small">
221
+ Every number on it — a volume, a temperature, a time — is one somebody set or one the lab&rsquo;s own tools worked out.
222
+ Nothing is filled in to make it look finished: what a plan does not say is listed under each step instead, so the hole is found standing at a bench and not halfway through.
223
+ </p>
224
+ <div className="row tight">
225
+ <button type="button" onClick={asASheet}>Write {only === null ? "it all" : only} as a protocol</button>
226
+ {sheet !== null && <button type="button" className="quiet" onClick={() => setSheet(null)}>Hide it</button>}
227
+ </div>
228
+ {sheet !== null && <textarea className="method sheet" value={sheet} readOnly rows={18} aria-label="The protocol, to print or carry" onFocus={(event) => event.currentTarget.select()} />}
229
+ </section>
230
+ )}
231
+
232
+ {crossing}
233
+
234
+ {work.toGet.length > 0 && (
235
+ <section className="card">
236
+ <h2>To get first</h2>
237
+ <p className="small">Nothing proposed makes {work.toGet.length === 1 ? "this" : "these"}, and the lab has no tube of {work.toGet.length === 1 ? "it" : "them"}. Until {work.toGet.length === 1 ? "it arrives" : "they arrive"} the steps that need {work.toGet.length === 1 ? "it" : "them"} cannot start.</p>
238
+ <table>
239
+ <thead><tr><th>What</th><th>For</th></tr></thead>
240
+ <tbody>
241
+ {work.toGet.map((one) => (
242
+ <tr key={one.checksum}>
243
+ <td>{partName(one.checksum) === "a part" ? one.name : partName(one.checksum)} <code>{one.checksum.slice(0, 12)}</code></td>
244
+ <td className="dim">{[...new Set(one.forSteps.map((each) => {
245
+ const thread = work.threads.find((who) => who.steps.some((step) => step.plan.plan === each));
246
+ return `step ${at(each)} of ${thread?.name ?? "the work"}`;
247
+ }))].join(", ")}</td>
248
+ </tr>
249
+ ))}
250
+ </tbody>
251
+ </table>
252
+ </section>
253
+ )}
254
+
255
+ {work.threads.map((thread) => (
256
+ <section className="card" key={thread.name + thread.steps[0]!.plan.plan}>
257
+ <div className="toolhead">
258
+ <h2>{thread.name}</h2>
259
+ <span className="dim small">
260
+ {[...new Set(thread.steps.map((one) => filedAs(one.plan)))].join(", ")} · {thread.steps.length} {thread.steps.length === 1 ? "step" : "steps"}
261
+ </span>
262
+ </div>
263
+ {!thread.clear && <p className="small attention">Something in this one has to be dealt with before it can be finished.</p>}
264
+ <ol className="steps">
265
+ {thread.steps.map((step) => (
266
+ <li key={step.plan.plan} className={step.held === null ? "ready" : "held"}>
267
+ <p className="small">
268
+ <strong>{at(step.plan.plan)}. {stepName(step.plan)}</strong>
269
+ <span className="dim"> · {step.plan.kind}</span>
270
+ {" — "}{why(step)}
271
+ </p>
272
+ <p className="dim small">
273
+ Uses {step.plan.inputs.map((one) => `${one.item === undefined ? partName(one.part) : tubeName(one.item)} as ${one.role}`).join(", ") || "nothing the lab holds"}
274
+ {step.plan.expects.length > 0 && <>, making {step.plan.expects.map((one) => `${one.name} (${one.length.toLocaleString("en-US")} bp${one.circular ? ", circular" : ""})`).join(" and ")}</>}
275
+ {step.plan.expects.length === 0 && (step.plan.kind === "transformation"
276
+ ? <>, making nothing the lab can name: what comes of it is alive</>
277
+ : <>, making nothing it has declared</>)}
278
+ . Proposed by {person(step.plan.by)}.
279
+ </p>
280
+ {step.plan.note !== null && <p className="small why">{step.plan.note}</p>}
281
+ <div className="row tight">
282
+ {onOpen !== undefined && step.held === null && <button type="button" onClick={() => onOpen(step.plan)}>Set it up</button>}
283
+ <button type="button" className="quiet" onClick={() => { setFiling(filing === step.plan.plan ? null : step.plan.plan); setInto(filedAs(step.plan) === UNFILED ? "" : filedAs(step.plan)); }}>
284
+ {filedAs(step.plan) === UNFILED ? "File it under…" : "Move it…"}
285
+ </button>
286
+ <button type="button" className="quiet" onClick={() => void act("settlePlan", { plan: step.plan.plan })}>Set it aside</button>
287
+ </div>
288
+ {filing === step.plan.plan && (
289
+ <form className="row tight" onSubmit={(event) => { event.preventDefault(); void file(step.plan.plan, into); }}>
290
+ <input value={into} onChange={(event) => setInto(event.target.value)} maxLength={200} list="bionet-projects"
291
+ placeholder="Which project" aria-label="Which project to file it under" />
292
+ <datalist id="bionet-projects">{projects.filter((one) => one.filed).map((one) => <option key={one.name} value={one.name} />)}</datalist>
293
+ <button type="submit">{into.trim() === "" ? "Take it out" : "File it"}</button>
294
+ </form>
295
+ )}
296
+ </li>
297
+ ))}
298
+ </ol>
299
+ {thread.ends.length > 0 && (
300
+ <p className="dim small">It ends with {thread.ends.map((one) => partName(one.checksum) === "a part" ? one.name : partName(one.checksum)).join(" and ")}.</p>
301
+ )}
302
+ </section>
303
+ ))}
304
+
305
+ {work.tangled.length > 0 && (
306
+ <section className="card">
307
+ <h2>Cannot be ordered</h2>
308
+ <p className="small trouble">{work.tangled.length} {work.tangled.length === 1 ? "proposal depends" : "proposals depend"} on each other in a circle, so there is no order to carry them out in. Set one aside and propose it again.</p>
309
+ <ul className="checks">
310
+ {work.tangled.map((one) => {
311
+ const plan = lab.plans.find((each) => each.plan === one)!;
312
+ return <li key={one} className="stop">{stepName(plan)} · {plan.kind} · proposed by {person(plan.by)}</li>;
313
+ })}
314
+ </ul>
315
+ </section>
316
+ )}
317
+ </div>
318
+ );
319
+ }