@cosmol-studio/cosmol-viewer 0.5.0-rc.4 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 COSMol Viewer Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,204 @@
1
+ # JavaScript / WASM bindings
2
+
3
+ Before running the commands below, complete the [WASM build and npm package preparation](DEV.md).
4
+
5
+ Rust declarations own JS names, signatures, documentation and ownership.
6
+ `#[checked_wasm]` generates typed Tsify/Serde input adapters from those declarations;
7
+ structured values share their runtime converters and generated TypeScript types. wasm-pack builds this crate directly and runs the matching official
8
+ wasm-bindgen extractor. Its JavaScript and `.d.ts` output is used unchanged.
9
+ See [BINDING_CONTRACT.md](BINDING_CONTRACT.md) for architectural constraints and
10
+ [DEV.md](DEV.md) for build commands.
11
+
12
+ For a runnable frontend page with CK molecules, proteins, selections, animation
13
+ and screenshots, see [the browser example](examples/browser/README.md).
14
+
15
+ ## Typed JavaScript API
16
+
17
+ The npm package is `@cosmol-studio/cosmol-viewer`. Install prereleases with
18
+ `npm install @cosmol-studio/cosmol-viewer@rc`; stable releases use the default
19
+ `latest` tag. The package name does not rename the Rust crate or generated
20
+ `cosmol_viewer_wasm.js` / `.wasm` files.
21
+
22
+ `Viewer` owns the browser runner and a request/feedback transport endpoint.
23
+ The runner exclusively owns the core `App`; viewer handles do not share or lock
24
+ it. `Scene` and `Animation` are reusable handles over the existing core models,
25
+ not compressed payload strings.
26
+
27
+ Place the rendering surface in your page before running the JavaScript:
28
+
29
+ ```html
30
+ <canvas id="molecule-viewer" width="800" height="600"
31
+ style="width:800px;height:600px"></canvas>
32
+ <canvas id="animation-viewer" width="800" height="600"
33
+ style="width:800px;height:600px"></canvas>
34
+ ```
35
+
36
+ `Viewer.new(canvasId)` binds a viewer to a canvas without rendering. Call
37
+ `viewer.render(scene)` or `viewer.play(animation)` afterwards. The viewer never
38
+ creates a canvas or chooses a position in the page.
39
+
40
+ ```js
41
+ import { Viewer, Scene, Animation, Sphere } from "@cosmol-studio/cosmol-viewer";
42
+
43
+ const scene = Scene.new();
44
+ scene.set("atom", Sphere.new(new Float32Array([0, 0, 0]), 1.0));
45
+ const viewer = Viewer.new("molecule-viewer");
46
+ await viewer.render(scene);
47
+
48
+ scene.setScale(1.2);
49
+ viewer.update(scene);
50
+ const png = await viewer.takeScreenshot(); // Uint8Array of PNG bytes
51
+
52
+ const animation = Animation.new(0.1, -1n, true);
53
+ animation.addFrame(scene);
54
+ scene.setScale(1.4);
55
+ animation.addFrame(scene);
56
+ const playing = Viewer.new("animation-viewer");
57
+ await playing.play(animation);
58
+
59
+ viewer.close();
60
+ playing.close();
61
+ viewer.free();
62
+ playing.free();
63
+ animation.free();
64
+ scene.free();
65
+ ```
66
+
67
+ - `Viewer.new(canvasId)` binds an existing canvas without starting the renderer.
68
+ Instance `render(scene)` and `play(animation)` start or replace its content.
69
+ `render` stops previous animation playback; `close()` leaves the canvas intact.
70
+ A closed viewer cannot restart. Create a new viewer to reuse the canvas.
71
+ - Borrowed scenes/animations remain usable after render, play, update, or addFrame.
72
+ Frames and the static scene capture snapshots, matching the core API.
73
+ - Cloned binding handles share state; `scene.cloneScene()` explicitly makes an
74
+ independent scene. Mount/update snapshot state and prepare GPU data internally.
75
+ - `update` and camera logging queue typed requests and return without blocking.
76
+ Native IPC and browser queues enter the same core `App` message handler.
77
+ Browser queues wake the renderer instead of polling continuously.
78
+ - Screenshot requests are FIFO barriers: later updates wait until capture.
79
+ Async screenshot calls share a request-ID counter across cloned handles, so
80
+ concurrent replies cannot overwrite or consume each other's images. Closing
81
+ the viewer rejects pending screenshot waits.
82
+ - Coordinates use `Float32Array`; RGB colors use `Uint8Array`; loop counts use
83
+ `bigint`. Async failures reject, and synchronous failures throw.
84
+ - Scene also supports CK-backed molecular/protein displays through `select`,
85
+ `add`, `set` and `recenterOn`, in addition to positioned primitives.
86
+
87
+ `Scene.add(item, style?)` and `Scene.set(name, item, style?)` accept `Sphere`,
88
+ `Stick`, CK objects and selections. `Sphere.new(center, radius)` and
89
+ `Stick.new(start, end, radius)` create reusable positioned shapes; `.color(rgb)`
90
+ and `.opacity(value)` return styled copies. Scenes snapshot shapes on insertion.
91
+ Shapes already carry their material, so passing an extra scientific style fails.
92
+ Omitting the style uses the Rust core defaults: Molecule uses BallAndStick and
93
+ Protein uses Cartoon. Atom selections use Sphere regardless of their source;
94
+ bond selections use Stick and residue selections use Cartoon.
95
+
96
+ ## COSMolKit scientific objects
97
+
98
+ In a browser application, importing the Viewer npm entry initializes both CK
99
+ and Viewer WASM modules automatically:
100
+
101
+ ```js
102
+ import * as ck from "@cosmol-studio/cosmolkit";
103
+ import * as cv from "@cosmol-studio/cosmol-viewer";
104
+
105
+ const mol = ck.Molecule.fromSdf(sdf);
106
+ const oxygen = cv.select(mol).atoms().element(ck.Element.fromSymbol("O"));
107
+ const scene = cv.Scene.new();
108
+ scene.add(mol, cv.Style.ballAndStick());
109
+ scene.add(oxygen, cv.Style.sphere().scale(1.4));
110
+ scene.recenterOn(mol);
111
+ const viewer = cv.Viewer.new("molecule-viewer");
112
+ await viewer.render(scene);
113
+ ```
114
+
115
+ `Style.stick()` accepts molecular atoms or bonds; `select(mol).bonds().aromatic()`
116
+ reads CK aromatic flags. For a CK Protein, pass `protein` directly with
117
+ `Style.cartoon().rainbowResidues()`, `Style.sphere()` or `Style.surface()`.
118
+ Explicit selections are only needed for filtering. Protein bond representations
119
+ are not implemented.
120
+
121
+ `add`, `set`, `select` and `recenterOn` share one native import of each live CK
122
+ object. Selections carry their source and can be reused without passing it again.
123
+ Scenes (including clones), selectors and selections retain that import. In-place
124
+ CK edits do not change the cached snapshot; pass a new CK object to import edits.
125
+ No coordinates are generated implicitly. Use `.conformer(id)` when multiple
126
+ 3D conformers exist, or `.coordinates2d()` for stored 2D coordinates.
127
+ `Style` builders return independent styles; free temporary handles normally.
128
+ No viewer-defined Molecule/Protein wrapper is needed or exported.
129
+
130
+ ## Notebook transport is separate
131
+
132
+ Notebook HTML calls `Viewer.openNotebook(canvasId, compressedScene)` or
133
+ `Viewer.playNotebook(canvasId, compressedAnimation)`. These internal transport
134
+ endpoints decode Python payloads and enter the same typed render/play paths.
135
+ Notebook updates, camera logging and viewport overlays are encoded one-way `ViewerCommand`
136
+ messages submitted to `viewer.dispatch(payload)`.
137
+
138
+ Scenes, animations, and commands share the `CMV2:R:<base64>` (raw postcard) or
139
+ `CMV2:G:<base64>` (gzip postcard) format. Postcard data below 1 KiB skips gzip;
140
+ at or above 1 KiB gzip level 1 is always used. The choice depends only on the
141
+ serialized size; there is no compression-ratio check or fallback.
142
+ Old unprefixed and CMV1 formats are rejected: sender and receiver must match.
143
+ The decoder defaults to at most 64 MiB of serialized data; Rust callers can use
144
+ `decode_payload_with_limit` to set another bound. This is a serialized-byte limit,
145
+ not a limit on the final object or GPU memory. Ordinary JS and native IPC do not
146
+ use this notebook codec.
147
+
148
+ Normal JS callers use `update(scene)`, `cameraParameterLogging(enabled)`,
149
+ `showFps(enabled)` and `showCameraParameters(enabled)`;
150
+ they do not serialize commands or scenes. `takeScreenshot()` returns PNG bytes
151
+ to JavaScript only. Notebook transport is one-way: Colab/Jupyter return-value
152
+ RPC and notebook screenshot retrieval are not supported.
153
+ Internal notebook endpoints must remain exported for injected notebook scripts,
154
+ but are not the primary typed API.
155
+
156
+ Overlays are initially hidden, do not capture pointer input, and never request
157
+ continuous repainting. FPS samples existing renderer repaint events (not animation
158
+ frames or GPU timing). After one second without activity, one diagnostic repaint
159
+ shows zero FPS. Diagnostic/screenshot-only paints do not count as activity or
160
+ renew the idle timer; interaction or scene updates resume statistics.
161
+
162
+ ## Contracts and platform boundaries
163
+
164
+ `crates/core/src/binding_contract/registry.rs` registers semantic features, exact
165
+ Rust signatures, Python/JavaScript projections, inspectable defaults, notebook
166
+ endpoints/commands, and platform availability. Rust signatures are checked by
167
+ the compiler. The same metadata is available through Rust
168
+ `binding_contract::to_json()`, Python `binding_contract_json()`, and browser
169
+ `bindingContractJson()`. Registration does not generate PyO3 behavior or require
170
+ identical language ABIs. `Viewer.keep_alive` is native-only: notebooks reject it,
171
+ and JavaScript does not export it.
172
+
173
+ The derive helper is a versioned dependency of the public core crate. For a Rust
174
+ release, publish `cosmol_viewer_derive` before `cosmol_viewer_core` and the facade.
175
+ This build script never publishes packages.
176
+
177
+ ## Test boundaries
178
+
179
+ - `check.py` runs the generated WASM in Node, verifies exports, ownership,
180
+ snapshots, error paths and exclusions, then checks strict TypeScript.
181
+ - `check.py --browser` also renders in real headless Chromium:
182
+ canvas mounting/update/playback, PNG screenshots, and caller-owned canvas preservation.
183
+ - Python binding tests check registered APIs and generated stubs. Notebook tests
184
+ mock Jupyter/Colab display, decode real Python startup/command payloads in WASM,
185
+ and check pre-initialization errors. They are not a full notebook UI test.
186
+
187
+ Install the optional browser test dependencies from the repository root:
188
+
189
+ ```sh
190
+ npm install --prefix target/browser-check --no-save playwright@1.58.2
191
+ target/browser-check/node_modules/.bin/playwright install chromium
192
+ python wasm/check.py --browser
193
+ ```
194
+
195
+ Linux CI uses `playwright install --with-deps chromium`. `PLAYWRIGHT_MODULE` can
196
+ point to another installed Playwright module and `BROWSER_EXECUTABLE` to a local
197
+ Chromium/Chrome executable. These test dependencies are not shipped in npm/wheels.
198
+
199
+ Scene source ownership follows its current content. Replacing or removing named
200
+ content releases its imported source when no other content in that scene uses it.
201
+ Selections and other scenes keep their own references; failed replacements leave
202
+ ownership unchanged. `recenter_on` (JavaScript: `recenterOn`) stores only a center,
203
+ not a lasting reference to the source. Once all owners release an import, passing
204
+ the CK object again imports its current data.