Skip to content

pyhoon/MiniJS-B4X

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MiniJS-B4X

A B4X library for generating JavaScript code programmatically from B4X (B4A/B4J/B4i) code.

Overview

MiniJS-B4X is a B4X library that allows you to generate JavaScript code programmatically from your B4X applications. It provides a fluent API for building JavaScript code structures including functions, loops, conditionals, variables, objects, arrays, and more.

Features

  • Fluent API - Chainable methods for building JavaScript code
  • Code Generation - Generate functions, loops, conditionals, variables, objects, arrays
  • Indentation Management - Automatic indentation handling
  • Comments Support - Single-line, multi-line, and inline comments
  • Control Structures - Functions, if/else, for loops, try/catch
  • Variables - const/let declarations with optional initialization
  • Objects & Arrays - Object literals and array literals
  • Function Calls - Method calls and function calls with arguments
  • Event Listeners - Event listener generation
  • Custom Events - CustomEvent dispatching
  • Template Literals - Template string support

Installation

  1. Copy MiniJS.b4xlib from the release folder to your B4X additional libraries folder
  2. In B4X IDE Libraries Manager tab, check the MiniJS library

Requirements

  • B4J 9.0+ / B4A 10.0+ / B4i 7.0+
  • jCore library

Usage

Basic Example

Sub Process_Globals
    Private jsGen As MiniJS
End Sub

Sub AppStart (Args() As String)
    jsGen.Initialize
    
    ' Generate a sample function
    GenerateSampleFunction
    
    ' Get generated code with script tags
    Dim jsCode As String = jsGen.Generate
    
    ' Or without script tags
    Dim jsCodeRaw As String = jsGen.Generate2
    
    Log(jsCode)
End Sub

Private Sub GenerateSampleFunction
    jsGen.AddMultiLineComment("Sample generated JavaScript function" & CRLF & "Generated by B4J")
    
    ' Start function: function calculateTotal(items, taxRate) {
    jsGen.StartFunction("calculateTotal", Array As String("items", "taxRate"))
    
    ' let subtotal = 0;
    jsGen.DeclareVariable("subtotal", "0", False)
    
    ' for (let i = 0; i < items.length; i++) {
    jsGen.StartForLoop("let i = 0", "i < items.length", "i++")
    
    '     subtotal += items[i].price;
    jsGen.AddLine("subtotal += items[i].price;")
    
    ' }
    jsGen.EndForLoop
    
    ' if (taxRate > 0) {
    jsGen.StartIf("taxRate > 0")
    
    '     const tax = subtotal * taxRate;
    jsGen.DeclareVariable("tax", "subtotal * taxRate", True)
    
    '     return subtotal + tax;
    jsGen.AddLine("return subtotal + tax;")
    
    ' } else {
    jsGen.AddElse
    
    '     return subtotal;
    jsGen.AddLine("return subtotal;")
    
    ' }
    jsGen.EndIf
    
    ' }
    jsGen.EndFunction
End Sub

Generated Output

<script>
    /* 
     * Sample generated JavaScript function
     * Generated by B4J
     */
    function calculateTotal (items, taxRate) {
        let subtotal = 0;
        for (let i = 0; i < items.length; i++) {
            subtotal += items[i].price;
        }
        if (taxRate > 0) {
            const tax = subtotal * taxRate;
            return subtotal + tax;
        } else {
            return subtotal;
        }
    }
</script>

API Reference

Initialization

Method Description
Initialize Initialize the generator

Code Generation

Method Description
Generate As String Generate complete JS code wrapped in <script> tags
Generate2 As String Generate complete JS code without script tags

Indentation

Method Description
IncreaseIndent Increase indentation level
DecreaseIndent Decrease indentation level

Comments

Method Description
AddComment(comment As String) Add single-line comment
AppendComment(comment As String) Append comment to current line
AddMultiLineComment(comment As String) Add multi-line comment block
AddNewLine Add blank line

Functions

Method Description
StartFunction(name As String, parameters() As String) Start function declaration
EndFunction End function declaration

Control Flow

Method Description
StartIf(condition As String) Start if statement
ElseIf(condition As String) Add else if clause
AddElse Add else clause
EndIf End if statement
StartForLoop(initializer, condition, increment) Start for loop
EndForLoop End for loop
StartTry Start try block
AddCatch(event As String) Add catch block
EndTry End try/catch block

Variables

Method Description
DeclareVariable(name, value, isConst) Declare const/let variable

Objects & Arrays

Method Description
CreateObject(name, properties As Map) Create object literal
CreateArray(name, items As List) Create array literal

Function & Method Calls

Method Description
AddFunctionCall(functionName, args()) Call function
AddMethodCall(objectName, methodName, args()) Call method on object

Events

Method Description
AddEventListener(functionName, eventName) Add event listener
AddCustomEventDispatch(eventName, detailData As Map) Dispatch custom event

Console

Method Description
ConsoleLog(message) Generate console.log()
ConsoleError(message, event) Generate console.error()

Conditionals

Method Description
AddConditionalCall(condition, call) Inline conditional call
AddTernary(condition, trueExpr, falseExpr) Ternary operator

Project Structure

MiniJS-B4X/
├── source/
│   ├── MiniJs.bas          # Main class module
│   ├── MiniJS.b4j          # B4J project file
│   └── Objects/            # Compiled output
├── release/
│   ├── MiniJS.b4xlib       # Compiled library
│   └── update.json         # Version info
├── LICENSE
└── README.md

Building from Source

  1. Open source/MiniJS.b4j in B4J
  2. Run the "Create B4xLib" macro (Ctrl+M)
  3. Copy generated .b4xlib to your additional libraries folder

License

See LICENSE file for details.

Author

Aeric - GitHub

Version History

  • 0.60 - Current version
    • Added multi-line comments
    • Added ternary operator support
    • Added custom event dispatch
    • Added object/array creation helpers

About

Generate JS from B4X code

Topics

Resources

License

Stars

2 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors

Languages