viewpoint-js-core
Core types for the viewpoint-js macro, providing the [ToJsValue] trait for converting Rust values to JavaScript representations, and utilities for escaping strings for use in JavaScript.
This crate is part of the Viewpoint browser automation framework.
Features
ToJsValuetrait: Convert Rust types to JavaScript value strings- String escaping: Properly escape strings for JavaScript contexts
- CSS attribute escaping: Escape values for CSS attribute selectors
- JSON support: Optional
serde_json::Valueconversion (withjsonfeature)
Installation
Add to your Cargo.toml:
[]
= "0.2"
For JSON support:
[]
= { = "0.2", = ["json"] }
Quick Start
use ;
// Convert Rust values to JavaScript representation
assert_eq!;
assert_eq!;
assert_eq!;
// Escape a string for JavaScript
assert_eq!;
The ToJsValue Trait
The [ToJsValue] trait converts Rust values to their JavaScript representations.
It's used by the js! macro for value interpolation (#{expr}):
use ToJsValue;
// Integers
assert_eq!;
assert_eq!;
// Floats
assert_eq!;
assert_eq!;
assert_eq!;
// Booleans
assert_eq!;
assert_eq!;
// Strings (properly quoted and escaped)
assert_eq!;
assert_eq!;
assert_eq!;
// Option types
assert_eq!;
assert_eq!;
String Escaping Functions
escape_js_string - Double-Quoted Strings
Escapes a string for use in a double-quoted JavaScript string literal:
use escape_js_string;
assert_eq!;
assert_eq!; // Single quotes preserved
assert_eq!; // Double quotes escaped
assert_eq!;
escape_js_string_single - Single-Quoted Strings
Escapes a string for use in a single-quoted JavaScript string literal:
use escape_js_string_single;
assert_eq!;
assert_eq!; // Single quotes escaped
assert_eq!; // Double quotes preserved
escape_js_contents - Without Quotes
Escapes string contents without adding surrounding quotes:
use escape_js_contents;
assert_eq!;
assert_eq!;
assert_eq!;
escape_for_css_attr - CSS Attribute Selectors
Escapes a string for use in CSS attribute selectors within JavaScript:
use escape_for_css_attr;
// For: document.querySelector('[data-testid="submit-button"]')
let attr_value = escape_for_css_attr;
assert_eq!;
// Use in a format string:
let selector = format!;
assert_eq!;
Implementing ToJsValue for Custom Types
You can implement ToJsValue for your own types:
use ;
let user = User ;
assert_eq!;
Integration with Viewpoint
This crate is used internally by viewpoint-js for the js! macro. Most users should use viewpoint-js directly rather than this crate.
License
MIT