1use regex::Regex;
2use std::collections::HashSet;
3
4#[cfg(feature = "wasm")]
5use wasm_bindgen::prelude::*;
6
7pub struct IsEngine;
10
11impl IsEngine {
12 pub fn compile(source: &str) -> String {
13 compile_is(source)
14 }
15}
16
17#[cfg_attr(feature = "wasm", wasm_bindgen(js_name = compile))]
19pub fn compile_is(source: &str) -> String {
20 let mut js = String::new();
21 let mut reactive_vars = HashSet::new();
22
23 js.push_str("/* === Indonesian Script (.is) Compiled Output === */\n");
25 js.push_str("(function() {\n");
26
27 js.push_str(r#"
29 // Core Runtime Indonesian Script (.is)
30 if (!window.__IS_RUNTIME__) {
31 window.__IS_RUNTIME__ = true;
32 window.__IS_STATE__ = window.__IS_STATE__ || {};
33 window.__IS_LISTENERS__ = window.__IS_LISTENERS__ || {};
34
35 window.__IS_PROXY__ = new Proxy(window.__IS_STATE__, {
36 set(target, prop, value) {
37 target[prop] = value;
38 // Auto update DOM elements bound to this state
39 document.querySelectorAll(`[is-bind="${prop}"], [is-text="${prop}"], [is-model="${prop}"]`).forEach(el => {
40 if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT') {
41 if (el.value != value) el.value = value;
42 } else {
43 el.textContent = value;
44 }
45 });
46 document.querySelectorAll(`[is-show="${prop}"]`).forEach(el => {
47 el.style.display = value ? '' : 'none';
48 });
49 if (window.__IS_LISTENERS__[prop]) {
50 window.__IS_LISTENERS__[prop].forEach(fn => fn(value));
51 }
52 return true;
53 },
54 get(target, prop) {
55 return target[prop];
56 }
57 });
58
59 // Auto setup DOM listeners for input bindings (is-model / is-bind)
60 document.addEventListener('input', function(e) {
61 const modelAttr = e.target.getAttribute('is-model') || e.target.getAttribute('is-bind');
62 if (modelAttr) {
63 window.__IS_PROXY__[modelAttr] = e.target.value;
64 }
65 });
66
67 // Auto setup AJAX / Action attributes (is-jupuk, is-kirim, is-click)
68 document.addEventListener('click', async function(e) {
69 const btn = e.target.closest('[is-jupuk], [is-ambil], [is-kirim], [is-click]');
70 if (!btn) return;
71
72 const jupukUrl = btn.getAttribute('is-jupuk') || btn.getAttribute('is-ambil');
73 const kirimUrl = btn.getAttribute('is-kirim');
74 const targetSel = btn.getAttribute('is-target');
75
76 if (jupukUrl) {
77 e.preventDefault();
78 try {
79 const res = await fetch(jupukUrl);
80 const text = await res.text();
81 if (targetSel) {
82 const targetEl = document.querySelector(targetSel);
83 if (targetEl) targetEl.innerHTML = text;
84 }
85 } catch (err) {
86 console.error('[IndonesianScript] Error fetching:', err);
87 }
88 } else if (kirimUrl) {
89 e.preventDefault();
90 const form = btn.closest('form');
91 const data = form ? Object.fromEntries(new FormData(form)) : {};
92 try {
93 const res = await fetch(kirimUrl, {
94 method: 'POST',
95 headers: { 'Content-Type': 'application/json' },
96 body: JSON.stringify(data)
97 });
98 const text = await res.text();
99 if (targetSel) {
100 const targetEl = document.querySelector(targetSel);
101 if (targetEl) targetEl.innerHTML = text;
102 }
103 } catch (err) {
104 console.error('[IndonesianScript] Error posting:', err);
105 }
106 }
107 });
108 }
109 const $state = window.__IS_PROXY__;
110"#);
111
112 let re_reaktif = Regex::new(r#"(?m)^\s*(reaktif|state)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(.*?);"#).unwrap();
113 let mut processed_source = source.to_string();
114 let mut decl_replacements = Vec::new();
115
116 for caps in re_reaktif.captures_iter(source) {
118 let var_name = caps[2].to_string();
119 let initial_val = caps[3].to_string();
120 reactive_vars.insert(var_name.clone());
121
122 let placeholder = format!("__IS_STATE_DECL_{}__;", var_name);
123 let final_decl = format!(
124 "/* [Indonesian Script] State Reaktif: {} */\n $state.{} = {};\n let {} = $state.{};",
125 var_name, var_name, initial_val, var_name, var_name
126 );
127 decl_replacements.push((placeholder.clone(), final_decl));
128
129 processed_source = processed_source.replace(&caps[0], &placeholder);
130 }
131
132 let re_cetak = Regex::new(r"\b(dudohno|cetak|tulis)\s*\(").unwrap();
136 processed_source = re_cetak.replace_all(&processed_source, "console.log(/* [Indonesian Script: cetak/dudohno] */ ").to_string();
137
138 let re_jupuk = Regex::new(r"\b(jupuk|ambil)\s*\(\s*([^)]+)\s*\)").unwrap();
140 processed_source = re_jupuk.replace_all(&processed_source, "(await fetch($2).then(r => r.json()))").to_string();
141
142 let re_kirim = Regex::new(r"\b(kirim|kirimkan)\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)").unwrap();
144 processed_source = re_kirim.replace_all(&processed_source, "(await fetch($2, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify($3) }).then(r => r.json()))").to_string();
145
146 for var_name in &reactive_vars {
148 let re_assign = Regex::new(&format!(r"\b{}\s*=\s*([^;]+);", regex::escape(var_name))).unwrap();
149 let replacement = format!("$state.{} = $1;", var_name);
150 processed_source = re_assign.replace_all(&processed_source, &replacement).to_string();
151 }
152
153 for (placeholder, final_decl) in decl_replacements {
155 processed_source = processed_source.replace(&placeholder, &final_decl);
156 }
157
158 let re_pilih = Regex::new(r"\b(siji|pilih)\s*\(\s*([^)]+)\s*\)").unwrap();
160 processed_source = re_pilih.replace_all(&processed_source, "document.querySelector($2)").to_string();
161
162 let re_pilih_semua = Regex::new(r"\b(kabeh|pilihSemua)\s*\(\s*([^)]+)\s*\)").unwrap();
164 processed_source = re_pilih_semua.replace_all(&processed_source, "document.querySelectorAll($2)").to_string();
165
166 let re_saat = Regex::new(r"\b(saat|ketika)\s*\(\s*([^,]+)\s*,\s*([^,]+)\s*,\s*([^)]+)\s*\)").unwrap();
168 processed_source = re_saat.replace_all(&processed_source, "(typeof $2 === 'string' ? document.querySelector($2) : $2)?.addEventListener($3, $4)").to_string();
169
170 let re_ganti_html = Regex::new(r"\b(gantiHtml|tumpuk)\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)").unwrap();
172 processed_source = re_ganti_html.replace_all(&processed_source, "(typeof $2 === 'string' ? document.querySelector($2) : $2).innerHTML = $3").to_string();
173
174 let re_umpet = Regex::new(r"\b(sembunyikan|umpetno)\s*\(\s*([^)]+)\s*\)").unwrap();
176 processed_source = re_umpet.replace_all(&processed_source, "(typeof $2 === 'string' ? document.querySelector($2) : $2).style.display = 'none'").to_string();
177
178 let re_tampil = Regex::new(r"\b(tampilkan|tuduhno)\s*\(\s*([^)]+)\s*\)").unwrap();
180 processed_source = re_tampil.replace_all(&processed_source, "(typeof $2 === 'string' ? document.querySelector($2) : $2).style.display = ''").to_string();
181
182 js.push_str(" ");
183 js.push_str(&processed_source);
184 js.push_str("\n})();\n");
185
186 js
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192
193 #[test]
194 fn test_is_engine_compiler_basic() {
195 let code = r#"
196reaktif jumlah = 0;
197function tambah() {
198 jumlah = jumlah + 1;
199 dudohno('Jumlah saiki:', jumlah);
200}
201"#;
202 let compiled = compile_is(code);
203 assert!(compiled.contains("State Reaktif: jumlah"));
204 assert!(compiled.contains("$state.jumlah = 0;"));
205 assert!(compiled.contains("console.log"));
206 assert!(compiled.contains("function tambah()"));
207 }
208}