toJs method

String toJs()

Implementation

String toJs() {
  switch (type) {
    case 'api':
      final url = data['url'];
      final body = data['body'] ?? {};
      final jsonBody =
          body.isNotEmpty ? 'body: JSON.stringify(${_encodeJs(body)}),' : '';
      return '''
fetch("$url", {
method: "POST",
headers: {"Content-Type": "application/json"},
$jsonBody
}).then(res => res.json())
.then(data => console.log("✅ API Success:", data))
.catch(err => console.error("❌ API Error:", err));
''';

    case 'alert':
      return "alert('${_escape(data.toString())}');";

    case 'update':
      final selector = data['selector'];
      final value = _escape(data['value']);
      return "document.querySelector('$selector').innerText = '$value';";

    case 'state':
      final key = _escape(data['key']);
      final value = jsonEncode(data['value']);
      return '''
window.__flintState = window.__flintState || {};
window.__flintState['$key'] = $value;
document.dispatchEvent(new CustomEvent('flintStateUpdate', {detail: {key: '$key', value: $value}}));
''';

    case 'log':
      return "console.log('${_escape(data.toString())}');";

    case 'sequence':
      final actions = (data as List)
          .map((a) => FlintAction._(a['type'], a['data']).toJs())
          .join('\n');
      return actions;

    case 'script':
      return data.toString();

    case 'call':
      // purely Dart-side action — nothing to run on JS
      return '';

    default:
      return '';
  }
}