spytial-core
v2.3.0
Published
A fully client-side application for SpyTial.
Maintainers
Readme
spytial-core
A tree-shakable TypeScript implementation of spytial, usable for language integration.
- Client-side only: No Node.js dependencies and tree-shakable.
- Custom Elements for easy embedding in web apps
- Selector Synthesis: Auto-generate CnD selector expressions from examples
- Schema Descriptions: Generate LLM-friendly descriptions of data structures
Installation
npm install spytial-core- View on npm
- Developer Guide
- YAML Specification (CDN) — Stable CDN-hosted copy of
docs/YAML_SPECIFICATION.md. For immutability pin to a tag or commit (e.g.,@v1.8.0or@<commit-sha>). Agents can fetch it with a simple GET (e.g.,fetch(url).then(r => r.text())).
Quick Start
Basic Layout
import { LayoutInstance, parseLayoutSpec, SGraphQueryEvaluator } from 'spytial-core';
// Your CnD spec
const spec = `
right(friend)
align left(Student)
color blue(Professor)
`;
const layoutSpec = parseLayoutSpec(spec);
const evaluator = new SGraphQueryEvaluator();
evaluator.initialize({ sourceData: myDataInstance });
const layoutInstance = new LayoutInstance(layoutSpec, evaluator);
const result = layoutInstance.generateLayout(myDataInstance);
// Use result.layout with your visualization librarySelector Synthesis
import {
synthesizeAtomSelector,
synthesizeBinarySelector,
createOrientationConstraint,
createColorDirective
} from 'spytial-core';
// User selects nodes in your UI
const selectedAtoms = [aliceAtom, bobAtom, charlieAtom];
// Synthesize a selector that matches these atoms
const selector = synthesizeAtomSelector([{
atoms: selectedAtoms,
dataInstance: myInstance
}]);
// Generate CnD directives
const colorDirective = createColorDirective(selector, '#ff0000');
const orientationConstraint = createOrientationConstraint(selector, ['right']);
// Full spec
const cndSpec = `
${orientationConstraint}
${colorDirective}
`;See the full documentation for advanced synthesis features.
Projection Controls
For Forge/Alloy instances with projections, use applyProjectionTransform as a pre-layout step to project over types, then use the ProjectionControls component to let users select atoms:
import { applyProjectionTransform, ProjectionControls, LayoutInstance } from 'spytial-core';
// Define projections (which types to project over)
const projections = [{ sig: 'State', orderBy: 'next' }];
const selections = {}; // user selections: type → chosen atom
// Apply projection as a pre-layout data transformation
const projResult = applyProjectionTransform(dataInstance, projections, selections);
// Generate layout on the projected instance
const layoutResult = layoutInstance.generateLayout(projResult.instance);
// Render projection controls with the projection choices
<ProjectionControls
projectionData={projResult.choices}
onProjectionChange={(type, atomId) => {
selections[type] = atomId;
// Re-apply projection and regenerate layout
const newProj = applyProjectionTransform(dataInstance, projections, selections);
const newLayout = layoutInstance.generateLayout(newProj.instance);
}}
/>The choices returned from applyProjectionTransform() includes:
type: The signature being projectedprojectedAtom: The currently selected atomatoms: All available atoms for this type
See webcola-demo/projection-controls-demo-vanilla.html for a working example.
Node Highlighting
Visualize selector and evaluator results by highlighting nodes directly in the graph. This feature allows you to examine selector results in context without triggering a layout refresh.
Unary Selectors (Single Nodes)
// Evaluate a unary selector
const result = evaluator.evaluate('Student');
const nodeIds = result.selectedAtoms();
// Highlight the nodes
const graph = document.querySelector('webcola-cnd-graph');
graph.highlightNodes(nodeIds);Binary Selectors (Node Pairs)
// Evaluate a binary selector
const result = evaluator.evaluate('friend');
const pairs = result.selectedTwoples(); // [["Alice", "Bob"], ["Charlie", "Diana"]]
// Highlight with visual correspondence
graph.highlightNodePairs(pairs);
// Or with badges showing 1/2 correspondence
graph.highlightNodePairs(pairs, { showBadges: true });Clear Highlights
// Remove all node highlights
graph.clearNodeHighlights();Visual Styling
- Unary selectors: Orange border with glow effect
- Binary selectors:
- First elements: Blue border (e.g., the source of a relation)
- Second elements: Red border (e.g., the target of a relation)
- Optional badges: Shows "1" and "2" to indicate correspondence
See webcola-demo/node-highlighter-demo.html for an interactive demo.
CDN
You can use the browser bundle directly from a CDN:
- jsDelivr:
https://cdn.jsdelivr.net/npm/spytial-core/dist/browser/spytial-core-complete.global.js - unpkg:
https://unpkg.com/spytial-core/dist/browser/spytial-core-complete.global.js
Once loaded, use via the global spytialcore object:
<script src="https://cdn.jsdelivr.net/npm/spytial-core/dist/browser/spytial-core-complete.global.js"></script>
<script>
const { synthesizeAtomSelector, synthesizeBinarySelector } = spytialcore;
// Your code here
const selector = synthesizeAtomSelector([...]);
</script>Note: For backward compatibility,
window.CndCoreandwindow.CnDCoreare also available as aliases forwindow.spytialcore.
API Reference
Schema Descriptor API
Generate schema-level descriptions of data instances for LLM consumption or documentation.
generateAlloySchema(dataInstance, options?)
Generate an Alloy-style schema with signatures and fields.
import { generateAlloySchema } from 'spytial-core';
const schema = generateAlloySchema(dataInstance, {
includeBuiltInTypes: false, // Exclude built-in types like Int, String
includeTypeHierarchy: true, // Include 'extends' clauses
includeArityHints: false // Add multiplicity hints (one, lone, some, set)
});
// Example output:
// sig Node {
// left: Node
// right: Node
// key: Int
// }Options:
includeBuiltInTypes(default:false) - Include built-in types (Int, String, etc.)includeTypeHierarchy(default:true) - Show type inheritance withextendsincludeArityHints(default:false) - Add multiplicity keywords (experimental)
generateSQLSchema(dataInstance, options?)
Generate SQL CREATE TABLE statements for types and relations.
import { generateSQLSchema } from 'spytial-core';
const schema = generateSQLSchema(dataInstance, {
includeBuiltInTypes: false,
includeTypeHierarchy: true
});
// Example output:
// CREATE TABLE Node (
// id VARCHAR PRIMARY KEY
// );
//
// CREATE TABLE left (
// source_Node VARCHAR REFERENCES Node(id),
// target_Node VARCHAR REFERENCES Node(id)
// );Options:
includeBuiltInTypes(default:false) - Include built-in typesincludeTypeHierarchy(default:true) - Add comments showing type inheritance
generateTextDescription(dataInstance, options?)
Generate a human-readable plain text description.
import { generateTextDescription } from 'spytial-core';
const description = generateTextDescription(dataInstance, {
includeBuiltInTypes: false
});
// Example output:
// Types:
// - Node (5 atoms)
// - Person (3 atoms)
//
// Relations:
// - left: Node -> Node (2 tuples)
// - friend: Person -> Person (4 tuples)Options:
includeBuiltInTypes(default:false) - Include built-in types
Synthesis Functions
synthesizeAtomSelector(examples, maxDepth?)- Generate unary selectors (for atoms)synthesizeBinarySelector(examples, maxDepth?)- Generate binary selectors (for pairs)synthesizeAtomSelectorWithExplanation(examples, maxDepth?)- With provenance treesynthesizeBinarySelectorWithExplanation(examples, maxDepth?)- With provenance tree
Helper Functions
createOrientationConstraint(selector, directions)- Generate orientation constraint stringscreateAlignmentConstraint(selector, alignment)- Generate alignment constraint stringscreateColorDirective(selector, color)- Generate color directive strings
React Components
ProjectionControls- Interactive UI for selecting projection atoms (Forge/Alloy)CombinedInputComponent- Complete data visualization with REPL and layout interfaceInstanceBuilder- Visual graph editor for building data instancesReplInterface/PyretReplInterface- REPL components for interactive evaluation
Core Classes
LayoutInstance- Generate layouts from CnD specsSGraphQueryEvaluator- Evaluate selector expressionsAlloyDataInstance,JSONDataInstance, etc. - Data format adapters
WebCola Graph API
The <webcola-cnd-graph> custom element provides methods for interacting with the rendered graph:
Node Highlighting
highlightNodes(nodeIds: string[])- Highlight nodes by ID (unary selectors)highlightNodePairs(pairs: string[][], options?)- Highlight node pairs with first/second correspondence (binary selectors)clearNodeHighlights()- Remove all node highlights
Relation Highlighting
getAllRelations()- Get all unique relation nameshighlightRelation(relName: string)- Highlight edges by relation nameclearHighlightRelation(relName: string)- Clear relation highlighting
Layout Management
renderLayout(instanceLayout, options?)- Render a layout with optional prior positionsoptions.priorState: prior layout state for visual continuity (usegetLayoutState()to capture)- Prior state enables reduced iterations to preserve positions across renders.
generateSequenceLayouts({ instances, spytialSpec, mode? })- Generate layouts for a sequence of instances with inter-step continuity.mode:"ignore_history"(default) |"stability"|"change_emphasis"|"random_positioning"
clear()- Clear the graph and reset stategetNodePositions()- Get current positions of all nodes
See docs/ for detailed documentation.
MIT
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
