react-cheminfo 0.51.0 → 0.52.0

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 (57) hide show
  1. package/README.md +71 -16
  2. package/lib/host/core/connectHost.d.ts +75 -0
  3. package/lib/host/core/connectHost.d.ts.map +1 -0
  4. package/lib/host/core/connectHost.js +171 -0
  5. package/lib/host/core/connectHost.js.map +1 -0
  6. package/lib/host/core/hostStructure.d.ts +52 -0
  7. package/lib/host/core/hostStructure.d.ts.map +1 -0
  8. package/lib/host/core/hostStructure.js +106 -0
  9. package/lib/host/core/hostStructure.js.map +1 -0
  10. package/lib/host/core/index.d.ts +9 -0
  11. package/lib/host/core/index.d.ts.map +1 -0
  12. package/lib/host/core/index.js +5 -0
  13. package/lib/host/core/index.js.map +1 -0
  14. package/lib/host/core/kinds.d.ts +73 -0
  15. package/lib/host/core/kinds.d.ts.map +1 -0
  16. package/lib/host/core/kinds.js +88 -0
  17. package/lib/host/core/kinds.js.map +1 -0
  18. package/lib/host/core/protocol.d.ts +134 -0
  19. package/lib/host/core/protocol.d.ts.map +1 -0
  20. package/lib/host/core/protocol.js +92 -0
  21. package/lib/host/core/protocol.js.map +1 -0
  22. package/lib/host/testing/sciPeaks.d.ts +21 -0
  23. package/lib/host/testing/sciPeaks.d.ts.map +1 -0
  24. package/lib/host/testing/sciPeaks.js +62 -0
  25. package/lib/host/testing/sciPeaks.js.map +1 -0
  26. package/lib/host/testing/standInHost.d.ts +47 -0
  27. package/lib/host/testing/standInHost.d.ts.map +1 -0
  28. package/lib/host/testing/standInHost.js +85 -0
  29. package/lib/host/testing/standInHost.js.map +1 -0
  30. package/lib/host/ui/index.d.ts +3 -0
  31. package/lib/host/ui/index.d.ts.map +1 -0
  32. package/lib/host/ui/index.js +2 -0
  33. package/lib/host/ui/index.js.map +1 -0
  34. package/lib/host/ui/useHostConnection.d.ts +36 -0
  35. package/lib/host/ui/useHostConnection.d.ts.map +1 -0
  36. package/lib/host/ui/useHostConnection.js +62 -0
  37. package/lib/host/ui/useHostConnection.js.map +1 -0
  38. package/lib/host-testing.d.ts +8 -0
  39. package/lib/host-testing.d.ts.map +1 -0
  40. package/lib/host-testing.js +7 -0
  41. package/lib/host-testing.js.map +1 -0
  42. package/lib/host.d.ts +11 -0
  43. package/lib/host.d.ts.map +1 -0
  44. package/lib/host.js +11 -0
  45. package/lib/host.js.map +1 -0
  46. package/package.json +4 -1
  47. package/src/host/core/connectHost.ts +240 -0
  48. package/src/host/core/hostStructure.ts +129 -0
  49. package/src/host/core/index.ts +46 -0
  50. package/src/host/core/kinds.ts +128 -0
  51. package/src/host/core/protocol.ts +197 -0
  52. package/src/host/testing/sciPeaks.ts +66 -0
  53. package/src/host/testing/standInHost.ts +116 -0
  54. package/src/host/ui/index.ts +2 -0
  55. package/src/host/ui/useHostConnection.ts +85 -0
  56. package/src/host-testing.ts +18 -0
  57. package/src/host.ts +11 -0
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Connect a tool to the page that frames it, when there is one.
3
+ *
4
+ * The protocol and its schemas are fetched only then, so a visitor on the site
5
+ * itself never downloads them.
6
+ */
7
+ import { useEffect, useRef } from 'react';
8
+ /** Once per page: React may mount the caller twice, the host is greeted once. */
9
+ let started = false;
10
+ /**
11
+ * Introduce the tool to its parent frame, or to the window that opened it, and
12
+ * serve that host for the life of the page.
13
+ *
14
+ * Call it after the hook that applies the address: effects run in order, so
15
+ * the address has been applied by the time the host is greeted, and a host's
16
+ * structure replaces the one the frame's link named rather than the reverse.
17
+ * The latest `load` is always the one called, so it may close over state.
18
+ * @param tool - What the tool takes and gives.
19
+ * @param handlers - See {@link HostHandlers}.
20
+ */
21
+ export function useHostConnection(tool, handlers) {
22
+ const latest = useRef(handlers);
23
+ useEffect(() => {
24
+ latest.current = handlers;
25
+ });
26
+ useEffect(() => {
27
+ if (started)
28
+ return;
29
+ const host = hostWindow();
30
+ if (host === null)
31
+ return;
32
+ started = true;
33
+ import("../core/connectHost.js")
34
+ .then(({ connectHost }) => {
35
+ connectHost({
36
+ host,
37
+ listen: (listener) => {
38
+ globalThis.addEventListener('message', listener);
39
+ return () => {
40
+ globalThis.removeEventListener('message', listener);
41
+ };
42
+ },
43
+ tool,
44
+ origin: globalThis.location.origin,
45
+ build: latest.current.build ?? null,
46
+ load: (inputs) => {
47
+ latest.current.load(inputs);
48
+ },
49
+ });
50
+ })
51
+ .catch(() => {
52
+ started = false;
53
+ });
54
+ }, [tool]);
55
+ }
56
+ function hostWindow() {
57
+ const { parent, opener } = globalThis.window;
58
+ if (parent !== globalThis.window)
59
+ return parent;
60
+ return opener ?? null;
61
+ }
62
+ //# sourceMappingURL=useHostConnection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useHostConnection.js","sourceRoot":"","sources":["../../../src/host/ui/useHostConnection.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAqB1C,iFAAiF;AACjF,IAAI,OAAO,GAAG,KAAK,CAAC;AAEpB;;;;;;;;;;GAUG;AACH,MAAM,UAAU,iBAAiB,CAC/B,IAAmB,EACnB,QAAsB;IAEtB,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;IAChC,SAAS,CAAC,GAAG,EAAE;QACb,MAAM,CAAC,OAAO,GAAG,QAAQ,CAAC;IAC5B,CAAC,CAAC,CAAC;IAEH,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,OAAO;YAAE,OAAO;QACpB,MAAM,IAAI,GAAG,UAAU,EAAE,CAAC;QAC1B,IAAI,IAAI,KAAK,IAAI;YAAE,OAAO;QAC1B,OAAO,GAAG,IAAI,CAAC;QACf,MAAM,CAAC,wBAAwB,CAAC;aAC7B,IAAI,CAAC,CAAC,EAAE,WAAW,EAAE,EAAE,EAAE;YACxB,WAAW,CAAC;gBACV,IAAI;gBACJ,MAAM,EAAE,CAAC,QAAQ,EAAE,EAAE;oBACnB,UAAU,CAAC,gBAAgB,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;oBACjD,OAAO,GAAG,EAAE;wBACV,UAAU,CAAC,mBAAmB,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;oBACtD,CAAC,CAAC;gBACJ,CAAC;gBACD,IAAI;gBACJ,MAAM,EAAE,UAAU,CAAC,QAAQ,CAAC,MAAM;gBAClC,KAAK,EAAE,MAAM,CAAC,OAAO,CAAC,KAAK,IAAI,IAAI;gBACnC,IAAI,EAAE,CAAC,MAAM,EAAE,EAAE;oBACf,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;gBAC9B,CAAC;aACF,CAAC,CAAC;QACL,CAAC,CAAC;aACD,KAAK,CAAC,GAAG,EAAE;YACV,OAAO,GAAG,KAAK,CAAC;QAClB,CAAC,CAAC,CAAC;IACP,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;AACb,CAAC;AAED,SAAS,UAAU;IACjB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,UAAU,CAAC,MAAM,CAAC;IAC7C,IAAI,MAAM,KAAK,UAAU,CAAC,MAAM;QAAE,OAAO,MAAM,CAAC;IAChD,OAAQ,MAAwB,IAAI,IAAI,CAAC;AAC3C,CAAC"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * A stand-in host for a tool's end-to-end tests, and the messages SciPeaks
3
+ * sends. Node only: it serves a page.
4
+ */
5
+ export type { StandInHost, StandInHostLog, } from './host/testing/standInHost.ts';
6
+ export { readStandInHostLog, startStandInHost, } from './host/testing/standInHost.ts';
7
+ export { SCIPEAKS_ETHYLBENZENE_LOAD, SCIPEAKS_ETHYLBENZENE_MOLFILE, SCIPEAKS_HOST_NAME, } from './host/testing/sciPeaks.ts';
8
+ //# sourceMappingURL=host-testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-testing.d.ts","sourceRoot":"","sources":["../src/host-testing.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,YAAY,EACV,WAAW,EACX,cAAc,GACf,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,0BAA0B,EAC1B,6BAA6B,EAC7B,kBAAkB,GACnB,MAAM,4BAA4B,CAAC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * A stand-in host for a tool's end-to-end tests, and the messages SciPeaks
3
+ * sends. Node only: it serves a page.
4
+ */
5
+ export { readStandInHostLog, startStandInHost, } from "./host/testing/standInHost.js";
6
+ export { SCIPEAKS_ETHYLBENZENE_LOAD, SCIPEAKS_ETHYLBENZENE_MOLFILE, SCIPEAKS_HOST_NAME, } from "./host/testing/sciPeaks.js";
7
+ //# sourceMappingURL=host-testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-testing.js","sourceRoot":"","sources":["../src/host-testing.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAMH,OAAO,EACL,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,0BAA0B,EAC1B,6BAA6B,EAC7B,kBAAkB,GACnB,MAAM,4BAA4B,CAAC"}
package/lib/host.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The host protocol: a page that frames a tool — an electronic lab notebook, a
3
+ * course — hands it typed data, checked against pipeline.cheminfo.org's kinds.
4
+ *
5
+ * Its own door because the schemas are checked with ajv. `useHostConnection`
6
+ * fetches ajv and the connection only when the page is framed, so a site that
7
+ * calls it ships nothing extra to a visitor who opened it directly.
8
+ */
9
+ export * from './host/core/index.ts';
10
+ export * from './host/ui/index.ts';
11
+ //# sourceMappingURL=host.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC"}
package/lib/host.js ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The host protocol: a page that frames a tool — an electronic lab notebook, a
3
+ * course — hands it typed data, checked against pipeline.cheminfo.org's kinds.
4
+ *
5
+ * Its own door because the schemas are checked with ajv. `useHostConnection`
6
+ * fetches ajv and the connection only when the page is framed, so a site that
7
+ * calls it ships nothing extra to a visitor who opened it directly.
8
+ */
9
+ export * from "./host/core/index.js";
10
+ export * from "./host/ui/index.js";
11
+ //# sourceMappingURL=host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.js","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-cheminfo",
3
- "version": "0.51.0",
3
+ "version": "0.52.0",
4
4
  "license": "MIT",
5
5
  "description": "React components, hooks and framework-free helpers shared by the cheminfo sites: site chrome, citations, sharing, routing, pedagogy, charts, and the structure, orbital and 3D molecule viewers",
6
6
  "author": "Luc Patiny",
@@ -18,6 +18,8 @@
18
18
  "./build-info": "./lib/build-info.js",
19
19
  "./conformers": "./lib/conformers.js",
20
20
  "./core": "./lib/core.js",
21
+ "./host": "./lib/host.js",
22
+ "./host-testing": "./lib/host-testing.js",
21
23
  "./ir": "./lib/ir.js",
22
24
  "./molecule3d": "./lib/molecule3d.js",
23
25
  "./molstar/*": "./lib/molstar/*/index.js",
@@ -66,6 +68,7 @@
66
68
  "dependencies": {
67
69
  "@formatjs/icu-messageformat-parser": "^3.5.20",
68
70
  "@tanstack/react-virtual": "^3.14.13",
71
+ "ajv": "^8.20.0",
69
72
  "cheminfo-font": "^1.28.0",
70
73
  "cheminfo-types": "^1.16.0",
71
74
  "convert-to-jcamp": "^7.0.1",
@@ -0,0 +1,240 @@
1
+ /**
2
+ * A tool's side of the host protocol: introduce itself to the page that
3
+ * frames it, take the private port that page answers with, and serve what
4
+ * arrives through it.
5
+ *
6
+ * Free of React and of the DOM — the window is handed in — so a test drives the
7
+ * whole exchange with a fake host and a real `MessageChannel`.
8
+ */
9
+
10
+ import type { CheckedValue, KnownKind } from './kinds.ts';
11
+ import { checkValue, isKnownKind, kindAccepts } from './kinds.ts';
12
+ import type {
13
+ GetRequest,
14
+ HelloMessage,
15
+ HostError,
16
+ HostItem,
17
+ LoadRequest,
18
+ ResultMessage,
19
+ ToolInput,
20
+ ToolInterface,
21
+ UsedItem,
22
+ } from './protocol.ts';
23
+ import {
24
+ HELLO_TYPE,
25
+ PROTOCOL_VERSION,
26
+ isConnect,
27
+ parseRequest,
28
+ } from './protocol.ts';
29
+
30
+ /** The item an input took, and its value as the input's kind reads it. */
31
+ export interface LoadedInput {
32
+ key: string;
33
+ item: HostItem;
34
+ checked: CheckedValue;
35
+ }
36
+
37
+ /** What a window `message` event carries, as far as the protocol reads it. */
38
+ export interface HostMessageEvent {
39
+ data: unknown;
40
+ source: unknown;
41
+ ports: readonly MessagePort[];
42
+ }
43
+
44
+ /** Where the connection runs, and what it serves. */
45
+ export interface HostConnectionOptions {
46
+ /** The page to introduce the tool to: the parent frame, or the opener. */
47
+ host: { postMessage: (message: unknown, targetOrigin: string) => void };
48
+ /** Subscribe to this window's messages; the returned function unsubscribes. */
49
+ listen: (listener: (event: HostMessageEvent) => void) => () => void;
50
+ /** What the tool takes and gives, as `hello` announces it. */
51
+ tool: ToolInterface;
52
+ /** The tool's origin, as `hello` states it. */
53
+ origin: string;
54
+ /** The build that is running, as the About states it, or `null`. */
55
+ build: unknown;
56
+ /**
57
+ * Show the inputs of a new document. Throwing means they could not be read:
58
+ * the error's message goes back to the host, and the document is not marked
59
+ * as applied.
60
+ */
61
+ load: (inputs: readonly LoadedInput[]) => void;
62
+ }
63
+
64
+ /** What choosing the items of a request gave. */
65
+ export type InputSelection =
66
+ { ok: true; inputs: LoadedInput[] } | { ok: false; error: HostError };
67
+
68
+ /**
69
+ * Say `hello` to the host, and serve its requests once it connects.
70
+ *
71
+ * A `connect` is accepted only from the window `hello` went to, and a second
72
+ * one replaces the first — a host that reloads its own script connects again.
73
+ * A document is applied once: the same one again is answered as before and
74
+ * changes nothing, so a host re-sending it never overwrites the user's work.
75
+ * @param options - The window, the tool, and its load function.
76
+ * @returns The function that stops listening and closes the port.
77
+ */
78
+ export function connectHost(options: HostConnectionOptions): () => void {
79
+ const { host, listen, tool, origin, build, load } = options;
80
+ let port: MessagePort | null = null;
81
+ let appliedDocument: string | null = null;
82
+ let appliedUsed: UsedItem[] = [];
83
+
84
+ function serve(data: unknown): void {
85
+ const request = parseRequest(data);
86
+ if (request === null) return;
87
+ const result =
88
+ request.type === 'load' ? applyLoad(request) : answerGet(request, tool);
89
+ port?.postMessage(result);
90
+ }
91
+
92
+ function applyLoad(request: LoadRequest): ResultMessage {
93
+ const { id, document, items } = request;
94
+ if (document === appliedDocument) {
95
+ return { type: 'result', id, ok: true, used: appliedUsed };
96
+ }
97
+ const selection = selectInputs(tool, items);
98
+ if (!selection.ok) {
99
+ return { type: 'result', id, ok: false, error: selection.error };
100
+ }
101
+ try {
102
+ load(selection.inputs);
103
+ } catch (error) {
104
+ const message = error instanceof Error ? error.message : String(error);
105
+ return {
106
+ type: 'result',
107
+ id,
108
+ ok: false,
109
+ error: { code: 'unreadable', message },
110
+ };
111
+ }
112
+ appliedDocument = document;
113
+ appliedUsed = selection.inputs.map(({ key, item }) => ({
114
+ key,
115
+ kind: item.kind,
116
+ }));
117
+ return { type: 'result', id, ok: true, used: appliedUsed };
118
+ }
119
+
120
+ const stopListening = listen((event) => {
121
+ if (event.source !== host || !isConnect(event.data)) return;
122
+ const received = event.ports[0];
123
+ if (received === undefined) return;
124
+ port?.close();
125
+ port = received;
126
+ port.addEventListener('message', (message) => {
127
+ serve(message.data);
128
+ });
129
+ port.start();
130
+ });
131
+
132
+ const hello: HelloMessage = {
133
+ type: HELLO_TYPE,
134
+ version: PROTOCOL_VERSION,
135
+ tool: {
136
+ name: tool.name,
137
+ origin,
138
+ build,
139
+ inputs: tool.inputs,
140
+ outputs: tool.outputs,
141
+ },
142
+ };
143
+ // `hello` says nothing a stranger may not read, and the parent's origin is
144
+ // not knowable until it answers.
145
+ host.postMessage(hello, '*');
146
+
147
+ return () => {
148
+ stopListening();
149
+ port?.close();
150
+ port = null;
151
+ };
152
+ }
153
+
154
+ /**
155
+ * Give each input of the tool one item of a request.
156
+ *
157
+ * Each input tries its kinds in its own order of preference, and takes the
158
+ * first item that falls under one and passes that kind's schema: the tool
159
+ * knows which notation serves it best, whatever order the host listed them in.
160
+ * An item naming another input's `key` is left to that input.
161
+ * @param tool - What the tool takes.
162
+ * @param items - What the host sent.
163
+ * @returns One item per input, or why an input got none.
164
+ */
165
+ export function selectInputs(
166
+ tool: ToolInterface,
167
+ items: readonly HostItem[],
168
+ ): InputSelection {
169
+ const inputs: LoadedInput[] = [];
170
+ for (const input of tool.inputs) {
171
+ const errors: string[] = [];
172
+ const loaded = selectInput(input, items, errors);
173
+ if (loaded !== null) {
174
+ inputs.push(loaded);
175
+ continue;
176
+ }
177
+ if (errors.length > 0) {
178
+ return {
179
+ ok: false,
180
+ error: {
181
+ code: 'invalid',
182
+ message: `No item for ${input.key} has the shape its kind requires, so ${tool.name} loaded nothing.`,
183
+ errors,
184
+ },
185
+ };
186
+ }
187
+ return {
188
+ ok: false,
189
+ error: {
190
+ code: 'no-input',
191
+ message: `No item is a ${KIND_LIST.format(input.kinds)}, so ${tool.name} loaded nothing.`,
192
+ },
193
+ };
194
+ }
195
+ return { ok: true, inputs };
196
+ }
197
+
198
+ function selectInput(
199
+ input: ToolInput,
200
+ items: readonly HostItem[],
201
+ errors: string[],
202
+ ): LoadedInput | null {
203
+ for (const accepted of input.kinds) {
204
+ if (!isKnownKind(accepted)) continue;
205
+ for (const item of items) {
206
+ if (item.key !== undefined && item.key !== input.key) continue;
207
+ if (!kindAccepts(accepted, item.kind)) continue;
208
+ const loaded = checkItem(input.key, accepted, item, errors);
209
+ if (loaded !== null) return loaded;
210
+ }
211
+ }
212
+ return null;
213
+ }
214
+
215
+ function checkItem(
216
+ key: string,
217
+ accepted: KnownKind,
218
+ item: HostItem,
219
+ errors: string[],
220
+ ): LoadedInput | null {
221
+ const outcome = checkValue(accepted, item.value);
222
+ if (outcome.valid) return { key, item, checked: outcome.checked };
223
+ for (const error of outcome.errors) errors.push(`${item.kind} ${error}`);
224
+ return null;
225
+ }
226
+
227
+ function answerGet(request: GetRequest, tool: ToolInterface): ResultMessage {
228
+ // Nothing goes back yet: no tool declares an output.
229
+ return {
230
+ type: 'result',
231
+ id: request.id,
232
+ ok: false,
233
+ error: {
234
+ code: 'no-output',
235
+ message: `${tool.name} has nothing to give back yet.`,
236
+ },
237
+ };
238
+ }
239
+
240
+ const KIND_LIST = new Intl.ListFormat('en', { type: 'disjunction' });
@@ -0,0 +1,129 @@
1
+ /**
2
+ * A structure a host handed over, read into the molecule a tool works on.
3
+ *
4
+ * Every tool of the family that takes a structure takes it the same way — in
5
+ * the three notations a notebook keeps, the one that says the most first — so
6
+ * the kinds, the parsing and the sentence a host reads when it fails are
7
+ * written once, here.
8
+ */
9
+
10
+ import type { Molecule } from 'openchemlib';
11
+
12
+ import { sourceMolecule } from '../../structure/core/sourceMolecule.ts';
13
+ import { structureError } from '../../structure/core/structureError.ts';
14
+ import type { StructureSource } from '../../structure/core/structureSource.ts';
15
+
16
+ import type { LoadedInput } from './connectHost.ts';
17
+ import type { CheckedValue } from './kinds.ts';
18
+
19
+ /**
20
+ * The kinds a structure input accepts, in order of preference: a molfile
21
+ * carries the layout its author drew, an idcode the exact structure, a SMILES
22
+ * only the connectivity.
23
+ */
24
+ export const STRUCTURE_KINDS = [
25
+ 'chem.molfile',
26
+ 'chem.ocl.id',
27
+ 'chem.smiles',
28
+ ] as const;
29
+
30
+ /** A checked value holding a structure. */
31
+ export type StructureValue = Extract<
32
+ CheckedValue,
33
+ { kind: (typeof STRUCTURE_KINDS)[number] }
34
+ >;
35
+
36
+ /**
37
+ * The function a tool hands `useHostConnection` as `load` when its input is a
38
+ * structure.
39
+ *
40
+ * The structure is parsed before `show` is called, so one that cannot be read
41
+ * is answered `unreadable` with a sentence the host can show, and nothing on
42
+ * the tool's screen changes.
43
+ * @param show - Puts the molecule on screen, under the host's label for it.
44
+ * @param key - The input the structure arrives on.
45
+ * @returns The `load` function.
46
+ */
47
+ export function hostStructureLoader(
48
+ show: (molecule: Molecule, label: string | undefined) => void,
49
+ key = 'structure',
50
+ ): (inputs: readonly LoadedInput[]) => void {
51
+ return (inputs) => {
52
+ for (const { key: inputKey, item, checked } of inputs) {
53
+ if (inputKey !== key || !isStructureValue(checked)) continue;
54
+ show(readHostMolecule(checked), item.label);
55
+ }
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Read a structure a host sent.
61
+ *
62
+ * A molfile whose atoms all sit on one point — SciPeaks stores some that way —
63
+ * is laid out again, so a tool that draws it does not draw one dot.
64
+ * @param checked - The value, already checked against its kind.
65
+ * @returns A molecule with at least one atom.
66
+ * @throws {Error} When the notation does not parse or describes no atoms; the
67
+ * message is the sentence the host is answered with.
68
+ */
69
+ export function readHostMolecule(checked: StructureValue): Molecule {
70
+ const notation = NOTATIONS[checked.kind];
71
+ let molecule: Molecule;
72
+ try {
73
+ molecule = sourceMolecule(hostStructureSource(checked));
74
+ } catch (error) {
75
+ const { message } = structureError(error);
76
+ throw new Error(
77
+ `The ${notation} could not be read, so nothing was loaded: ${message}`,
78
+ { cause: error },
79
+ );
80
+ }
81
+ if (molecule.getAllAtoms() === 0) {
82
+ throw new Error(
83
+ `The ${notation} describes no atoms, so nothing was loaded.`,
84
+ );
85
+ }
86
+ if (atomsCoincide(molecule)) molecule.inventCoordinates();
87
+ return molecule;
88
+ }
89
+
90
+ /**
91
+ * A structure a host sent, as the notation a depiction is drawn from.
92
+ * @param checked - The value, already checked against its kind.
93
+ * @returns The notation and its text; an idcode keeps its coordinates.
94
+ */
95
+ export function hostStructureSource(checked: StructureValue): StructureSource {
96
+ if (checked.kind === 'chem.molfile') {
97
+ return { kind: 'molfile', value: checked.value.molfile };
98
+ }
99
+ if (checked.kind === 'chem.ocl.id') {
100
+ const { idCode, coordinates } = checked.value;
101
+ return coordinates === ''
102
+ ? { kind: 'idcode', value: idCode }
103
+ : { kind: 'idcode', value: idCode, coordinates };
104
+ }
105
+ return { kind: 'smiles', value: checked.value.smiles.trim() };
106
+ }
107
+
108
+ const NOTATIONS: Record<StructureValue['kind'], string> = {
109
+ 'chem.molfile': 'molfile',
110
+ 'chem.ocl.id': 'idcode',
111
+ 'chem.smiles': 'SMILES',
112
+ };
113
+
114
+ function atomsCoincide(molecule: Molecule): boolean {
115
+ const atoms = molecule.getAllAtoms();
116
+ if (atoms < 2) return false;
117
+ const x = molecule.getAtomX(0);
118
+ const y = molecule.getAtomY(0);
119
+ for (let atom = 1; atom < atoms; atom++) {
120
+ if (molecule.getAtomX(atom) !== x || molecule.getAtomY(atom) !== y) {
121
+ return false;
122
+ }
123
+ }
124
+ return true;
125
+ }
126
+
127
+ function isStructureValue(checked: CheckedValue): checked is StructureValue {
128
+ return Object.hasOwn(NOTATIONS, checked.kind);
129
+ }
@@ -0,0 +1,46 @@
1
+ export type {
2
+ HostConnectionOptions,
3
+ HostMessageEvent,
4
+ InputSelection,
5
+ LoadedInput,
6
+ } from './connectHost.ts';
7
+ export { connectHost, selectInputs } from './connectHost.ts';
8
+ export type { StructureValue } from './hostStructure.ts';
9
+ export {
10
+ STRUCTURE_KINDS,
11
+ hostStructureLoader,
12
+ hostStructureSource,
13
+ readHostMolecule,
14
+ } from './hostStructure.ts';
15
+ export type {
16
+ CheckOutcome,
17
+ CheckedValue,
18
+ KnownKind,
19
+ MolfileValue,
20
+ OclIdValue,
21
+ SmilesValue,
22
+ } from './kinds.ts';
23
+ export { checkValue, isKnownKind, kindAccepts } from './kinds.ts';
24
+ export type {
25
+ GetRequest,
26
+ HelloMessage,
27
+ HostError,
28
+ HostErrorCode,
29
+ HostItem,
30
+ HostRequest,
31
+ LoadRequest,
32
+ ResultMessage,
33
+ ToolInput,
34
+ ToolInterface,
35
+ ToolOutput,
36
+ UsedItem,
37
+ } from './protocol.ts';
38
+ export {
39
+ CONNECT_TYPE,
40
+ HELLO_TYPE,
41
+ MAX_ITEMS,
42
+ MAX_LABEL_LENGTH,
43
+ PROTOCOL_VERSION,
44
+ isConnect,
45
+ parseRequest,
46
+ } from './protocol.ts';