opy_macro_js/helpers.rs
1//! Configurable helper globals exposed to JavaScript invocations.
2
3use std::collections::BTreeMap;
4
5/// Helper surface injected before every invocation.
6///
7/// The runtime always defines the upstream helper `vect` and the six constant
8/// objects `Map`, `Hero`, `Gamemode`, `Color`, `Team`, `Button` (see
9/// `builtInJsFunctions` in the OverPy reference `src/globalVars.ts`). The
10/// constant entries are Workshop catalog data that `workshop-rs` owns, so this
11/// crate ships them empty; populate them with [`Helpers::set_constant`].
12#[derive(Debug, Clone, Default, PartialEq, Eq)]
13pub struct Helpers {
14 entries: BTreeMap<String, Vec<(String, String)>>,
15}
16
17impl Helpers {
18 /// Creates an empty helper set: only the builtin `vect` function and the
19 /// six empty constant objects exist.
20 pub fn new() -> Self {
21 Self::default()
22 }
23
24 /// Adds one `key -> value` entry to the constant object `object`.
25 ///
26 /// Matches the upstream ABI where each entry is an UPPER_SNAKE key mapped
27 /// to a string carrying the object prefix, e.g.
28 /// `set_constant("Map", "KANEZAKA", "Map.KANEZAKA")` makes
29 /// `Map.KANEZAKA === "Map.KANEZAKA"` inside scripts.
30 pub fn set_constant(&mut self, object: &str, key: &str, value: &str) {
31 self.entries
32 .entry(object.to_string())
33 .or_default()
34 .push((key.to_string(), value.to_string()));
35 }
36
37 /// Entries configured for `object`, in insertion order.
38 pub fn entries(&self, object: &str) -> &[(String, String)] {
39 self.entries.get(object).map_or(&[], Vec::as_slice)
40 }
41}