vanjs-bootstrap: 1.0.4 VanJs 1.6 markdown-it: 14markdown-it14highlight: 11highlight11Bootstrap: 5Bootstrap5vanjs-bootstrap: 1.2.0vanjs-bootstrap1.2.0

VanJs Bootstrap Component Demo


Introduction

This document shows how easy it is to build a UI with VanJs and Bootstrap. Using simple examples, this document demonstrates how the library is used. The integrated form generator allows you to create a basic template for your forms.

Why to use VanJs

VanJS (Vanilla JavaScript) is used primarily because it is the world's smallest reactive UI framework, packing modern framework features into an ultra-lightweight, 1.0kB bundle. It bridges the gap between pure vanilla JavaScript and heavy frameworks like React, allowing you to build reactive web apps instantly without complex tooling.

Why to use Bootstrap

Bootstrap is used because it dramatically speeds up web development by providing a ready-made library of responsive, mobile-first UI components. Instead of writing thousands of lines of custom CSS and media queries from scratch, developers can rapidly build complete, functional layouts simply by dropping predefined classes onto HTML elements.

Why to use vanjs-bootstrap

Using vanjs-bootstrap is a great choice if you want to build highly responsive, modern UI applications with Bootstrap while keeping your JavaScript bundle size as small as humanly possible. Developed as a community add-on, vanjs-bootstrap serves as a bridge between VanJS (the world's smallest reactive UI framework at just 1.0kB) and the popular Bootstrap CSS utility library.

Key Alternatives Compared

Strategy Framework Footprint Learning Curve Ideal For
vanjs-bootstrap ~1.0kB + CSS Minimal (1 hour) High-performance miniapps, ultra-lean web tools
React Bootstrap ~42kB+ (React DOM) Steep (JSX + Build steps) Large enterprise web apps with pre-existing React codebases
VanUI Custom / Very Low Low Vanilla VanJS

Credits

  • A big thank you to Tao Xing for his excellent product VanJs.

  • I would like to thank Geoffrey Emmans, an excellent full stack developer, who supported the work on this app

  • Thanks also to the countless programmers around the world who have done the preparatory work with browsers, JavaScript NodeJs and so on for many years.


Button

export function Button ({bsSize, class, color='secondary', outline, dropdown, ...props}, children)

Implements a Bootstrap button

Let’s start with the Button component to understand the underlying principle of this component library. The Button is a function structured like a VanJS tag; it returns an HTML element. The first argument is an object containing attributes, while subsequent arguments represent the children. In essence, these attributes and their values ​​are passed on to the resulting HTML element. However, certain attributes serve specific functions, altering the appearance or behavior of the HTML element.

A simple example is the 'bsSize' attribute: if its value is set to 'sm', the class 'btn-sm' is added to the element.

Most of these specialized attributes can be of the 'van.state' type, allowing you to remotely control the component's appearance within the document. You can try this out for yourself in the demo below.


const { Button, CheckboxInput, Input, RadioSelectInput, SelectInput } = vanB
const { div, h2, span } = van.tags;

var bsSize = van.state('md');
var color = van.state('secondary');
var disabled = van.state(false);
var outline = van.state(false);
var dropdown = van.state(false);
var label = van.state("Button");

function Demo() {

    const OptionsBar = div(
        div({ class: "input-group input-group-sm" },
            span({ class: "input-group-text" }, 'bsSize'),
            RadioSelectInput({
                value: bsSize.val,
                oninput: e => bsSize.val = e.target.value,
                options: 'sm,md,lg', inline: true,
            }),
            span({ class: "input-group-text" }, 'color'),
            SelectInput({
                value: color.val,
                oninput: e => color.val = e.target.value,
                options: ',primary,secondary,success,danger,warning,info,light,dark,link',
            }),
            div({class:  "input-group-text"}, 
                CheckboxInput({ label:'outline', value: outline.val, oninput: e => outline.val = e.target.value }),
            ),
            div({ class: "input-group-text" },
                CheckboxInput({ label: 'disabled', value: disabled.val, oninput: e => disabled.val = e.target.value }),
            ),
            div({ class: "input-group-text" },
                CheckboxInput({ label: 'dropdown', value: dropdown.val, oninput: e => dropdown.val = e.target.value }),
            ),
        ),
    );

    return div({},
        h2('Button Demo'),
        OptionsBar,
        div({ class: "col" },
            Button({ bsSize, color, outline, disabled, dropdown, class: "mt-3" }, label),
        ))
}


container.appendChild(Demo());	

FormBuilder

export function FormBuilder ({dom, values, rowClass="", formClass="", cols, autoRow, bsSize, id, onChange}={})

The FormBuilder is arguably the most important feature in this library. It simplifies the creation of forms to the greatest possible extent. The individual steps for using it are:

  1. Create a FormBuilder with function FormBuilder(args)
  2. Start a new row with addRow(class)
  3. Add a form group with label and input control with add(props)
  4. Add the form into dom tree with variable dom
  5. Add a listener for changes with onChange((name,value,event)=>{})
  6. Check form validation with getFormValid() when onvalidate is used in add

Basic Form

const { div, pre } = van.tags;

// create a display for values
const ValueDisplay = pre({class:'mt-2 p-2 bg-body'});

// create a form builder
const fb = vanB.FormBuilder({
    // set initial values
    values: {name:'Jack', email:'jack@black.com'}
})

// add a change event
fb.onChange( () => ValueDisplay.innerHTML = JSON.stringify(fb.values) )

// add a input control
// only 'name' and 'label' are required 
fb.add({label: 'Name', name: 'name'})

// add a second field with 'type'
fb.add({label: 'Email', name: 'email', type: 'email'})

// add element
fb.addChildren( ValueDisplay );

// append the form to demo container
container.appendChild( fb.dom )

// show values in ValueDisplay
fb.emitChange() // display values

html

Horizontal Form Grid

The specification cols: '2 4' allocates 2 units for the label and 4 units for the input. The 'autoRow' setting eliminates the need to call 'addRow'; 'addRow' is invoked automatically after 12 units.

const fb = vanB.FormBuilder({
    cols:    '2 4',
    autoRow: true,
})
.add({label: 'Name', name: 'name', type: 'text'})
.add({label: 'Email', name: 'email', type: 'email'})
container.appendChild( fb.dom )
html

Input Group

The same pattern can also be used to generate a 'Input Group'; for this, you simply need to set 'inline'.

const fb = vanB.FormBuilder({ inline: true })
.add({label: 'Name', name: 'name', type: 'text'})
.add({label: 'Email', name: 'email', type: 'email'})
container.appendChild( fb.dom );
html

Explore Form Layout and Form Generator Live in this document. For reference see the API document

FormBuilder Arguments

arg comment
dom Container for the form groups to be inserted. If omitted a <form class=formClass /> is created.
values Optional initial values as object {name: value,..}
formClass Class for the generated form tag
rowClass Class for the generated rows if autoRow is true
cols Default cols attribute for addRow
autoRow If true, will add a new row if the columns in a row exceeds 12
bsSize Default Bootstrap size for inserted components. '' or 'sm' or 'lg'
id HTML id of the form. Random id if omitted. It is the prefix for label id (formId-groupId-l) and input id (formId-groupId-i)
inline Generate a Input Group if true
onChange Optional add a listener function(name,value) for input change

FormBuilder Properties

Properties inherited from FormControl.

property comment
values input values as object {name: value,..}
onChange(func) Subscribe input value change events. func=function(name,value,event)
emitChange(name, value) Notify change to all subscribers
handleInput(event) input element oninpup(event) handler
args(props) Function returns completetd props for a input control. Generate 'value', 'oninput' and 'name'.

Own properties.

property comment
dom Container for the form groups to be inserted. You can 'van.add' something here
row Actual row element
rowClass Default row class
cols Default cols attribute for inserted groups
autoRow If true, will add a new row if the columns in a row exceeds 12
colCount Number of colums in actual row
id Form tag id
add(props, ...children) The main function used to insert a form group.
addRow(arg) Add a new row with ...args injected. i.e. addRow({class: "m-2"})
addChildren(...children) van.add(fb.row ?? fb.dom, ...children).
getFormValid() Function returns true/false when all input values are valid. Can be used as Button disabled value
setValues(values) update a set of field values in the form (experimental)
groupIdByName( name )
inputIdByName( name )
labelIdByName( name )
helpers to get the generated id's
getInputElement (name) get the input element by field name

Function add(props, ...children)

The main function used to insert a form group. The props argument decides how the inserted form group is created. The further arguments are added as an appendix to the input component. Children are some form-text or validation info

Add Properties

property comment
name string becomes input name
label string or function becomes a label component
type Type attribute for the input control
oninput Optional for special usage. Is generally generated automatically
input a input control alternative to type. See Custom Input
class class added to the enveloping group
inputClass class added to the input control
bsSize Bootstrap size
cols space separated string "left right" for the Bootstrap column sizes i.e. "3 6"
col Bootstrap column size of the group alternative to cols. Used for form class "row g-3"
id HTML id of group. Will get random id if omited. Label id is "formId-id-l", input id is "formId-id-i"
separated special for FormCheck. Separate label and check if true
isvalid Boolean, adds :is-valid or :is-invalid to input class
onvalidate function(value) {return value_is-valid }. Add a validation check for input and add isvalid argument

FormBuilder Examples

Show different styles

This example shows the different controls and how to use custom styling. See comments in code tab.


const {div, h2, h5, pre} = van.tags;
const fb = vanB.FormBuilder();

// row with border
fb.addRow("m-2 p-2 border border-primary rounded-2");
fb.add({label: 'Name 1', name: 'name1', cols: "2 4"});
fb.add({label: 'Name 2', name: 'name2', cols: "2 4"});

// group with border
fb.addRow("mb-2");
fb.add({class: "m-2 p-2 border border-primary rounded-2", label: 'Label'});

// select field
fb.addRow("mb-2");
fb.add({label: 'Select', name: 'select', type: 'select', 
    options: [['--Please choose an option--',''],['one',1],['two',2],['three',3]],  
    value: 2
});

// combobox field
fb.addRow("mb-2");
fb.add({label: 'Combobox', name: 'combo', type: 'combobox', 
    options: [['--Please choose an option--',''],['one',1],['two',2],['three',3]],  
    value: 2,
    cols: "2",
});

// radio group field
fb.addRow("mb-2");
fb.add({label: 'Radio Select 2', name: 'radios2', type: 'radioselect', cols: "2 4",  
    options: [['one',1],['two',2],['three',3]], inline: true
});

// switch in same row
fb.add({label: 'Switch', name: 'switch', type: 'switch', cols: "2 4", readonly: true}); 

// radio and switch
fb.addRow("mb-2");
fb.add({label: 'Radio', name: 'radio', type: 'radio', cols: "2 4", value: false, class: "mt-2"}); 
fb.add({label: 'Checkbox', name: 'checkbox', type: 'checkbox', cols: "2 4"}); 

// color field
fb.addRow("mb-2");
fb.add({label: 'Color', name: 'color', type: 'color', cols: "2 1"}); 

container.appendChild(fb.dom)
html

Without Labels in a div

A example with special container and pure input controls. Pay attention to the '-i' after the id.

const {div, span} = van.tags;
const fb = vanB.FormBuilder({dom: div()})
.add({id: 'withoutLabelOne', value: 'one'})
.add({id: 'withoutLabelTwo', value: 'two'})
van.add(container, fb.dom, span('values: ', JSON.stringify(fb.values)) );
html

Use Floating Labels

"Floating Labels" are possible but 😒

const fb = vanB.FormBuilder({formClass:"form-floating"})
.add({class: 'form-floating mb-3', label: 'Name', type: 'text', placeholder: 'Enter Name'})
.add({class: 'form-floating mb-3', label: 'Email', type: 'email', placeholder: 'Enter Email'})
container.appendChild( fb.dom );
html

Use getInputElement

This example show how to get a input element without to use a fix id.

const fb = vanB.FormBuilder()
.add({label: 'Counter', name: 'number', type: 'number', value: 1})

const button = vanB.Button({
    onclick: ()=> {
        // getElementById for random id
        const el = fb.getInputElement('number')
        el.value++
        el.classList.toggle('bg-primary')
    }}
    , '+' )

container.appendChild( van.tags.div(fb.dom, button) );
html

Automatic use of aria-labelledby

FormBuilder decides independently whether "label for" or "aria-labelledby" with "span" must be applied. See Html.

const {div, span} = van.tags;

// define a minimal custom input control
const custom = ({oninput, bsSize, ...props}) =>
  div({...props, class: "form-control"}, span('Not labelable'));

const fb = vanB.FormBuilder()
.add({id: 'labeDemo', label: 'Label', input: custom})
container.appendChild( fb.dom );
html

Use Validation

Add a "onvalidate" function to activate validation.

const isEmail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const fb = vanB.FormBuilder()
.add({label: 'Valid Email', onvalidate: v => isEmail.test(v)})
container.appendChild( fb.dom );
html

Validation Feedback

This example demonstrate dynamic validation handling. See Form Validation for details.

const {div, span} = van.tags;
const fb = vanB.FormBuilder()
.add({label: 'Name', onvalidate: v => v}, // value not empty
    // valid feedback
    div({class: 'valid-feedback'}, 'Looks good'), 
    // invalid feedback
    div({class: 'invalid-feedback'}, 'Plase enter a name')
) 
const demo = div(
    fb.dom,
    // dynamic element thank to VanJs
    () => (
      fb.getFormValid() // true if all fields valid 
      ? span({class: 'mt-2 text-primary'},'form is valid') 
      : span({class: 'mt-2 text-danger'},'form is invalid')
    )
)
container.appendChild( demo );
html

Form Layout

Play around with the parameters and see what happens.


const {div, h2, h3, h5, hr, small, span, pre} = van.tags;
const initialOptions = {
    rowClass: "mt-2",
    autoRow: false,
    cols: "",
    bsSize: "",
};
const divClass = 'p-2 my-2 border border-primary-subtle rounded-2';
const DisplayFunc = span({class: 'pt-2 pb-4'});
var editValues;

function OptionForm () {
    var fb = vanB.FormBuilder({
        cols:      "2 4",
        rowClass:  "my-2",
        autoRow:   true,
        bsSize:    "sm",
        values:    initialOptions,
        onChange:  () => showDemoForm(fb.values),
    });

    fb.add({label: 'formClass', name: 'formClass', type: "combobox",
        options: [["none",""], "m-2 p-2 border", "row g-3", "was-validated", "needs-validation"],
    });
    fb.add({label: 'rowClass', name: 'rowClass', type: "combobox",
        options: [["none",""], "mt-2", "mb-2", "p-2", "m-2 p-2 border"],
    });
    fb.add({label: 'cols', name: 'cols', type: "combobox",
        options: [["none",""], "2 4", "3", "3 6"],
    });
    fb.add({label: 'autoRow', name: 'autoRow', type: 'switch', separated: true});
    fb.add({label: 'bsSize', name: 'bsSize', type: 'select',
        options: ["sm",["md",""],"lg"], inline: true
    });

    return fb.dom;
}

function DemoForm (options) {

    var fb = vanB.FormBuilder({
        ...options,
        values: editValues,
        id: "demo-form-layout",
    });

    fb.onChange( () => {editValues = fb.values} );

    // text
    if(!options.autoRow) fb.addRow();
    fb.add({label: 'Text', name: 'text', required: true, },
        div({class:"invalid-feedback"}, "Please enter a valid email here."),
        div({id:"emailHelp", class:"form-text"},small({class:"text-muted"},"We'll never share your email with anyone else.")),
    )

    // textarea
    if(!options.autoRow) fb.addRow();
    fb.add({label: 'Textarea', name: 'textarea', type: 'textarea', required: "1"},
        div({class:"invalid-feedback"}, "Please enter a message in the textarea.")
    )

    // select
    if(!options.autoRow) fb.addRow();
    fb.add({label: 'Select', name: 'select', type: 'select', 
        options: [['--Please choose an option--',''],['one',1],['two',2],['three',3]],  
        required: "1",
    });

    van.add(fb.dom, hr());

    // combobox
    if(!options.autoRow) fb.addRow();
    fb.add({label: 'Combobox', name: 'combo', type: 'combobox',
        options: [['one',1],['two',2],['three',3]],  
        placeholder: 'Please choose an option',
    });

    // radioselect
    if(!options.autoRow) fb.addRow();
    fb.add({label: 'Radio Select', name: 'radios', type: 'radioselect',
        options: [['one',1],['two',2],['three',3]], inline: true, 
        required: "1"
        },
        div({class:"invalid-feedback"}, "Please choose an option")
    );

    // switch checkbox
    fb.addRow(div({class:'row justify-content-center mt-2'},
        div({class:"col-4"}, span('Checkbox'))
    ));
    fb.addRow();

    fb.add({label: 'Switch', name: 'switch', type: 'switch'}); 
    fb.add({label: 'Checkbox', name: 'checkbox', type: 'checkbox', required: true},
        div({class:"invalid-feedback"}, "Example invalid feedback text")
    ); 

    // switch checkbox reverse
    fb.addRow(div({class:'row justify-content-center mt-2'},
        div({class:"col-4"}, span('Checkbox Reverse'))
    ));
    fb.addRow();

    fb.add({label: 'Checkbox', name: 'checkbox-r', type: 'checkbox', required: true, reverse: true},
        div({class:"invalid-feedback"}, "Example invalid feedback text")
    ); 
    fb.add({label: 'Switch', name: 'switch-r', type: 'switch', reverse: true}); 

    // switch checkbox separated
    fb.addRow(div({class:'row justify-content-center mt-2'},
        div({class:"col-4"}, span('Checkbox Separated'))
    ));
    fb.addRow();

    fb.add({label: 'Checkbox', name: 'checkbox-s', type: 'checkbox', required: true, separated: true},
        div({class:"invalid-feedback"}, "Example invalid feedback text")
    ); 
    fb.add({label: 'Switch', name: 'switch-s', type: 'switch', separated: true}); 

    return fb.dom;
}

function showDemoForm(options) {
    // remove empty arguments for clarity
    Object.keys(options).forEach(k=>{if(!options[k]) delete options[k]})
    // replace form
    const demo = DemoForm(options);
    document.getElementById('form-layout-demo-form').replaceChildren(demo);
    // update function example
    DisplayFunc.innerText = `FormBuilder(${JSON.stringify(options)})`;
    // show form only on Html-tab
    htmlOutput = demo; 
}

function Page () {
    return div(
        h5('Options'),
        div({class: divClass+' bg-info-subtle'}, OptionForm()),
        div({class: 'mt-2 mb-3'}, DisplayFunc ),
        h5('Generated Form'),
        div({id: 'form-layout-demo-form', class: divClass}),
    )
}

container.appendChild(Page())

showDemoForm(initialOptions)
html

Form Validation

Bootstrap offers a few options for form validation feedback. Please read the Bootstrap documentation. For detail information read the Mdn web docs.

Browser Built-In Form Validation

The easiest thing is the browser's own validation, which can of course be used here.

  • required: Specifies whether a form field needs to be filled in before the form can be submitted.
  • minlength and maxlength: Specifies the minimum and maximum length of textual data (strings).
  • min and max: Specifies the minimum and maximum values of numerical input types.
  • type: Specifies whether the data needs to be a number, an email address, or some other specific preset type.
  • pattern: Specifies a regular expression that defines a pattern the entered data needs to follow.

Generally, text is displayed when the mouse is moved over the field. This example uses a pattern for the E-mail and Zip field.

const { Input, FormBuilder } = vanB;
function BrowserValidation() {
    const {div, p, span, small} = van.tags;
    const Email = (props) => div({class: "input-group"},
        span({class: "input-group-text", id: "inputGroupPrepend"},"@" ),
        Input({...props, type: "text", pattern:"[^@\s]+@[^@\s]+\.[^@\s]+", required: "1"})
    );
    const fb = FormBuilder({formClass: "row g-3"})
    .add({label: "First name", col: "col-md-4", name: "firstname", type: "text", required: "1"})
    .add({label: "Last name", col: "col-md-4", name: "lastname", type: "text", required: "1"})
    .add({label: "E-mail", col: "col-md-4", name: "email", input: Email})
    .add({label: "City", col: "col-md-6", name: "city", type: "text", required: "1"})
    .add({label: "State", col: "col-md-3",  name: "state", type: "select", required: "1", options: [["Choose...",""],"..."]})
    .add({label: div('Zip ', small({class:"text-body-tertiary"},' 5 digit zip code')), col: "col-md-3", name: "zip", type: "text", pattern: "[0-9]{5}", required: "1"})
    .add({label: "Agree to terms and conditions", col: "col-md-12", name: "agree", type: "checkbox", required: "1"})
    return fb.dom
}
container.appendChild(BrowserValidation())

Client-Side Validation

​Here is the Bootstrap example "Custom styles". The submit button just inserts "was-validated" into classlist.

function CustomStyles() {
    const {div, form, span} = van.tags;
    const { Input, Button, FormBuilder } = vanB;
    const Form = form({class: "row g-3 needs-validation", novalidate: ""});
    const initialValues = {
        firstname: "Mark",
        lastname: "Otto",
        username: "",
        state: "",
        city: "",
        zip: "",
        agree: "",
    }
    const Username = (props) => div({class: "input-group has-validation"},
        span({class: "input-group-text", id: "inputGroupPrepend"},"@" ),
        Input({...props, type: "email", required: "1"}),
        div({class: "invalid-feedback"}, "Please enter your E-mail."),
    );
    const submit = ()=> Form.classList.add("was-validated");
    const reset  = ()=> Form.classList.remove("was-validated");
    const fb = FormBuilder({ dom: Form, values: {...initialValues} })
    .add({label: "First name", col: "col-md-4", name: "firstname", type: "text", required: "1"}, div({class: "valid-feedback"}, "Looks good!"))
    .add({label: "Last name", col: "col-md-4", name: "lastname", type: "text", required: "1"}, div({class: "valid-feedback"}, "Looks good!"))
    .add({label: "E-mail", col: "col-md-4", name: "username", input: Username})
    .add({label: "City", col: "col-md-6", name: "city", type: "text", required: "1"}, div({class: "invalid-feedback"}, "Please provide a valid city."))
    .add({label: "State", col: "col-md-3",  name: "state", type: "select", required: "1", options: [["Choose...",""],"..."]}, div({class: "invalid-feedback"}, "Please select a valid state."))
    .add({label: "Zip", col: "col-md-3", name: "zip", type: "text", required: "1"}, div({class: "invalid-feedback"}, "Please provide a valid zip."))
    .add({label: "Agree to terms and conditions", col: "col-md-12", name: "agree", type: "checkbox", required: "1"}, div({class: "invalid-feedback"}, "You must agree before submitting."));

    return div(
        fb.dom,
        div({class: "col-12 m-3"},
            Button({color: 'primary', onclick: submit}, "Submit"),
            Button({class: "ms-2", onclick: reset}, "Reset")
        ),
    );
}
container.appendChild(CustomStyles())

Dynamic JavaScript Validation

You can indicate invalid and valid form fields with .is-invalid and .is-valid. For simplicity, the isvalid attribute can be used. Since this can also be a van.state, dynamic validation is possible.

Or even simpler, you pass a function onvalidate then the FormBuilder automatically creates an isvalid attribute. You can then use the FormBuilder function getFormValid to check whether all fields are valid. onvalidate functions takes a value as argument and returns true/false.

The next example uses a better e-mail validation and a complex password validation.

function DynamicValidation() {
    const {div, ul, li} = van.tags;
    const { Button, FormBuilder } = vanB;
    const required = v => !!v;
    const isEmail = v => {
        var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(v).toLowerCase());
    }
    const fb = FormBuilder({ rowClass: "mb-2", autoRow: true, cols: "3 6" });
    fb.add({label: "Name", name: "name", type: "text", onvalidate: required});
    fb.add({label: "E-mail", name: "email", type: "text", onvalidate: isEmail}, 
        div({class: "invalid-feedback"}, "Please enter a valid E-mail."), 
        div({class: "valid-feedback"}, "Looks good!")
    );
    fb.add({label: "Password", name: "password", type: "password", 
        onvalidate: v => {
            let regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@.#$!%*?&])[A-Za-z\d@.#$!%*?&]{8,15}$/;
            return regex.test(v)
        }
        }, 
        div({class: "valid-feedback"}, "Looks good!"),
        div({class: "invalid-feedback"}, "Password must include", ul(
            li("At least one lowercase alphabet i.e. [a-z]"),
            li("At least one uppercase alphabet i.e. [A-Z]"),
            li("At least one Numeric digit i.e. [0-9]"),
            li("At least one special character i.e. [‘@’, ‘$’, ‘.’, ‘#’, ‘!’, ‘%’, ‘*’, ‘?’, ‘&’, ‘^’]"),
            li("Also, the total length must be in the range [8-15]")
            )
    ));
    fb.add({label: "Agree to terms and conditions", name: "agree", 
        type: "checkbox", onvalidate: required },
        div({class: "invalid-feedback"}, "You must agree before submitting.")
    );

    const submit = () => modal.Modal({
        header: "Submited",
        body: JSON.stringify(fb.values),
        width: 'fit-content',
    }).open();

    const Btn = Button({color: 'primary', 
        disabled: () => !fb.getFormValid(),
        onclick: submit,
    }, "Submit");

    return div(
        fb.dom,
        div({class: "col-12 m-3"},
            Btn,
        ),
    );
}
container.appendChild(DynamicValidation())

Form Controls

The individual Bootstrap form controls are implemented within the library and can also be used independently. However, since they all essentially serve the same purpose (namely, acting as a user interface for a value within the program) they are simply specified via the "type" parameter within the FormGroup or FormBuilder's 'add' function. The 'add' function uses the 'typeMap' to find the component for a type.

typeMap

type component
'text' Input
'textarea' Input
'select' SelectInput
'radioselect' RadioSelectInput
'checkbox' CheckboxInput
'radio' RadioInput
'switch' FormCheckInput
'combobox' ComboboxInput

A special feature of SelectInput, RadioSelectInput and ComboboxInput is that the options are not specified as children, but as an attribute "options". The value here is a list. See selectOptions for details.

Here is the list of all exported components.

export function Input({class, bsSize, isValid, ...props})
export function Textarea({class, bsSize, isValid, ...props})
export function SelectInput ({class: clas, bsSize, ...props})
export function FormCheckInput ({label: clabel, type, class: clas, style, bsSize, reverse, id, value, ...props})
export const SwitchInput = props => FormCheckInput({...props, type: 'switch'})
export const CheckboxInput = props => FormCheckInput({...props, type: 'checkbox'})
export const RadioInput = props => FormCheckInput({...props, type: 'radio'})
export function ComboboxInput (options = [], style, bsSize, onItemClick, ...props)
export function RadioSelectInput ({options, class: clas, bsSize, inline, id, ...props})
export function FormLabel({class: clas, bsSize, col, ...props}, children)

The 'ComboboxInput' was changed in version 1.2. The new one do not use Bootstraps popper and has a better keyboard handling.

The listed parameters are checked against 'van.state' and can therefore be dynamic. Other parameters in 'props' are simply passed through. You can find the function and appearance of the components in example Form Layout


Custom Input Control

In order to build your own input field, you should consider the following points.

  1. The outer "div" must have the class "form-control". It is ideal to take into account the argument "bsSize" which leads to the classes "form-control-sm" or "form-control-lg".
  2. The "value" argument is used for initialization.
  3. Changes are sent via the "oninput" argument with an "event" as a parameter. Within this library, a fake "event" in the form "{target:{name,value}}" is usually sufficient.
  4. To keep the component dynamic, "van.val()" can be used

This shows how to program an input field to select an alignment. The field should select the string values ​​"left", "right", "center" or "justify". This is followed by a small demonstration form. In the form the field is specified as "input". The specification of “type” can be omitted.

// a custom align control
function AlignInput({value, bsSize, class: clas, style, oninput, color="primary", ...props}) {

    const {div} = van.tags;
    const t = I18n.tPath('align-input');  // title translation

    // create input component
    var divProps = {
        className:  () => {           // merge className
            let res = "d-flex flex-row form-control"; 
            if(van.val(bsSize)) res += ' form-control-' + van.val(bsSize);
            if(van.val(clas)) res += ' ' + van.val(clas);
            return res;
        },
        style: () => {                   // merge style
            let res = "max-width: max-content";
            if(van.val(style)) res += '; ' + van.val(style);
            return res;
        },
        value: van.val(value),
        role: 'group', 
        ...props
    };
    const component = div({...divProps})

    // make the buttons
    const buttonProps = [ // define button props
        {name: 'align left', value: 'left'},
        {name: 'align right', value: 'right'},
        {name: 'align center', value: 'center'},
        {name: 'align justify', value: 'justify'},
    ];
    const setSelect = newValue => {
        const buttons = div(
            ...buttonProps.map( param => vanB.Button({
                bsSize,
                class: "py-1 px-2 me-1",
                onclick: () => {
                    // send new value per mockup event
                    oninput({ target: { name: props.name, value: param.value }});
                    // repaint buttons
                    setSelect(param.value);  
                },
                color,
                outline: newValue !== param.value,
                title:  t(param.name)
            }, vanB.Icon(param.name) ))
        )
        component.replaceChildren( buttons )  
    };

    // set initial value
    if(typeof value !== 'string' || !buttonProps.find( item => item.name === value) ) value = 'left'; // default
    setSelect(value); // put buttons into component

    return component
}


function demo () {
    const { div, h5 } = van.tags;
    // van states for dynamic display
    const state = {
        bsSize: van.state(''),
        color:  van.state('primary'),
        align:  van.state('left'),
    }
    // create a form
    const fb = vanB.FormBuilder({
        rowClass: 'm-2', autoRow: true, cols: '2 4', bsSize: 'sm',
        onChange: (name,value) => {state[name].val = value}
    }) 
    .add({label: 'bsSize', name: 'bsSize', type: 'radioselect', 
        options: [['none',''],'sm','lg'], inline: true
    })
    .add({label: 'color', name: 'color', type: 'select', 
        options: 'primary,secondary,success,danger,warning,info,light,dark,link',
    })
    .add({label: 'Align', name: 'align', bsSize: state.bsSize, color: state.color,
       input: AlignInput  // our custom control
    })

    return div(
        fb.dom,
        h5(() => `align value: ${state.align.val}`)
    )
}

container.appendChild(demo());
html

SelectOptions

function selectOptions (list, dom=false, selected)

The form controls in this library use the selectOptions function. It converts different kind of lists into a uniform format {value, children} that can easily be mapped into a DOM as <option> elments. Is the parameter "dom" "true", the function returns a ready mapped dom option list.

The "list" parameter accepts four notations:

  1. 'TextValue1,TextValue2'
    a komma separated list
  2. ['TextValue1', 'TextValue2'...]
    a array of values
  3. [['Text1', Value1], ['Text2', Value2]...]
    a array of display / value pairs
  4. [ { value: 1, ['children' || 'text' || 'displayValue'] }
    a array of objects

Notations can be mixed inside a array.

For example [ '', ['text 1', 1], ['text 2', 2] ] will be converted to:

[
  {
    value: '',
    children: '',
  },
  {
    value: 1,
    children: 'text 1',
  },
  {
    value: 2,
    children: 'text 2',
  }
]

and with dom=true and selected: "1":

[
 option({value=""}),
 option({value="1", selected: true}, "text 1"),
 option({value="2"}, "text 2"),
]

Form Generator Live

Here, you can easily put together a form by clicking through the options.


Show code
/* online form generator */

const { Icon, Button, SwitchInput, FormBuilder, FormGroup } = vanB;
const { Modal } = modal;
const Marked = t=>t;

const {a, button, div, form, ul, li, h1, h3, span, pre} = van.tags;
const inputTypes = ["", "button", "checkbox", "color", "combobox", "date", "datetime-local", 
  "email", "file", "hidden", "image", "month", "number", "password", "radio","radioselect" ,
  "range", "reset", "search", "submit", "select","switch", "tel", "text", "textarea", "time", "url", 
  "week" ];
const required = v => !!v;
const upperCaseFirst = str => str.charAt(0).toUpperCase() + str.slice(1);
const toLabel = str => String(str).replace(/[-_.]/g,' ').split(' ').map(upperCaseFirst).join(' ');

const ctrl = {
    formRows: van.state([{name:"field1",label:"Field 1"}]),
    selRow: van.state(-1),
    showAppendix: van.state(false),
}


function editGroupDlg(item, header) {
    const form = EditGroupForm(item);
    const dlg = Modal({
        header,
        body: form,
        footer: [
            Button({onclick: ()=>dlg.close(item)}, 'Ok'),
            Button({onclick: ()=>dlg.close(false)}, 'Cancel'),
        ],
        scrollable: true,
        width: '50em',
        class: "modal-fullscreen-lg-down",
        // class: "modal-fullscreen"
    });

    form.addEventListener('keypress', event => { if (event.key === 'Enter') dlg.close(item); });

    // focus first input after open
    dlg.onShown = () => document.getElementById('form-edit-group-name-i').focus();

    return dlg;
}

async function addGroup() {
    var item = {};
    var res = await editGroupDlg(item, 'Add').asyncOpen();
    if(res) {
        ctrl.formRows.val = [...ctrl.formRows.val, item];
        ctrl.selRow.val = ctrl.formRows.val.length-1 ;
    }
}

function deleteGroup() {
    ctrl.formRows.val = ctrl.formRows.val.filter( (item,index) => index !== ctrl.selRow.val );
    ctrl.selRow.val = -1;
}

async function editGroup(index) {
    var item = {...ctrl.formRows.val[index]};
    var res = await editGroupDlg(item, 'Edit').asyncOpen();
    if(res) {
        ctrl.formRows.val[index] = res;
        ctrl.formRows.val = [...ctrl.formRows.val];
    }
}

async function copyToClipboard() {
    try {
        const text = document.getElementById('EditGroupFormCode').innerText;
        await navigator.clipboard.writeText(text);
    } catch (err) {
        console.error('Failed to copy: ', err);
    }
}

function EditGroupForm(item) {

    const groupProps = van.state({...item});
    const isCheck = ()=>["checkbox","radio","switch"].includes(item.type);
    const hasOptions = ()=>["combobox","radioselect","select"].includes(item.type);
    const hasRange = ()=>["number","range"].includes(item.type);
    const hasInline = ()=>["radioselect"].includes(item.type);
    const isTextarea = ()=>item.type === 'textarea';
    const showCheck = van.state(isCheck());
    const showOptions = van.state(hasOptions());
    const showRange = van.state(hasRange());
    const showTextarea = van.state(isTextarea());
    const showInline = van.state(hasInline());
    const setState = v => {
        Object.assign(item, v);        
        groupProps.val = {...item};
        showCheck.val = isCheck();
        showOptions.val = hasOptions();
        showRange.val = hasRange();
        showTextarea.val = isTextarea();
        showInline.val = hasInline();
        // console.log('item',item)
    }

    const Form1 = () => {
        const fb = FormBuilder({autoRow: true, rowClass: "mb-2", cols: "2 4", values: item, id: "form-edit-group"})
        fb.onChange( () => setState(fb.values) );

        const NameBlur = ev => {
            let el = document.getElementById(fb.id+'-label-i')
            if(el && !el.value) {
                el.value = toLabel(fb.values.name);
                fb.values.label = toLabel(fb.values.name);
                fb.emitChange()
            }
        }

        fb.add({label: "name", name: "name", type: "text", onblur: NameBlur})
        fb.add({label: "label", name: "label", type: "text"})
        fb.add({label: "type", name: "type", type: "select", options: inputTypes})
        fb.add({label: "value", name: "value", type: "text"})
        fb.add({label: "placeholder", name: "placeholder", type: "text"})
        return fb.dom;
    }

    const FormAppendix = () => {
        const fb = FormBuilder({autoRow: true, rowClass: "mb-2", cols: "3", values: (item.appendix || {}) })
        fb.onChange( () => setState({appendix: {...fb.values}}) );
        fb.add({label: "form-text", name: "formText", type: "text"})
        fb.add({label: "valid-feedback", name: "validFeedback", type: "text"})
        fb.add({label: "invalid-feedback", name: "invalidFeedback", type: "text"})
        return fb.dom;
    }

    const FormCheck = () => {
        const fb = FormBuilder({values: item} );
        fb.onChange( () => setState(fb.values) );
        fb.addRow("mb-2")
        fb.add({label: "separated", name: "separated", type: "checkbox", col: "col-4"})
        fb.add({label: "reverse", name: "reverse", type: "checkbox", col: "col-4"})
        return fb.dom;
    }

    const FormOptions = () => {
        const fb = FormBuilder({values: item});
        fb.onChange( () => setState(fb.values) );
        fb.addRow("mb-2")
        fb.add({label: "options", name: "options", cols: "2"}, div({class:"form-text"},"values ​​separated by commas"))
        return fb.dom;
    }

    const FormRange = () => {
        const fb = FormBuilder({values: item});
        fb.onChange( () => setState(fb.values) );
        fb.addRow("mb-2")
        fb.add({label: "min", name: "min", type: "number", cols: "2 2"})
        fb.add({label: "max", name: "max", type: "number", cols: "2 2"})
        fb.add({label: "step", name: "step", type: "number", cols: "2 2"})
        return fb.dom;
    }

    const FormTextarea = () => {
        const fb = FormBuilder({values: item});
        fb.onChange( () => setState(fb.values) );
        fb.addRow("mb-2")
        fb.add({label: "rows", name: "rows", type: "number", cols: "2 2"})
        fb.add({label: "cols", name: "cols", type: "number", cols: "2 2"})
        return fb.dom;
    }

    const FormInline = () => {
        const fb = FormBuilder({values: item});
        fb.onChange( () => setState(fb.values) );
        fb.addRow("mb-2")
        fb.add({label: "inline", name: "inline", type: "checkbox", cols: "2 4"})
        return fb.dom;
    }


    const Sample = () => div({class: "row m-2"}, div({class: "col-12 border"},
        span({class: "text-body-secondary"},"sample"),
        FormGroup({...groupProps.val, oninput: ()=>{}})
    ))

    return div({class:"row"},
        Form1(),
        () => showCheck.val ? FormCheck() : '',
        () => showOptions.val ? FormOptions() : '',
        () => showRange.val ? FormRange() : '',
        () => showTextarea.val ? FormTextarea() : '',
        () => showInline.val ? FormInline() : '',
        SwitchInput({label: 'appendix', value: ctrl.showAppendix.val, oninput: ev => ctrl.showAppendix.val = ev.target.value}),
        () => ctrl.showAppendix.val ? FormAppendix() : '',
        Sample
    )
}


// left hand list of groups including edit button

const FormGroupList = () => {

    const drag = dragSort(ctrl.formRows.val, v => ctrl.formRows.val=v);  // create drag sort object

    const list = ul({class: "list-group nomarking", tabindex: "0"},
        ctrl.formRows.val.map( (item,index) => li({
            class: () => "list-group-item" + (ctrl.selRow.val === index ? " active" : ""),
            onclick: () => {ctrl.selRow.val = index},
            ondblclick: () => editGroup(ctrl.selRow.val),
            role: 'button',
            ...drag.dragProps(index),                // inject properties
        }, 
        // `${item.label}  ${item.name}  type: "${item.type || ''}"` 
        `${item.label} (${item.name})` 
        )),
    )

    const buttons = div({class: "btn-group btn-group mb-2"},
        Button({disabled: ()=>ctrl.selRow.val === -1, title: 'edit group', onclick: ()=>editGroup(ctrl.selRow.val)}, Icon('editItem')),
        Button({disabled: ()=>ctrl.selRow.val === -1, title: 'delete group', onclick: deleteGroup}, Icon('deleteItem')),
        Button({title: 'add new group', onclick: addGroup}, Icon('addItem')),
        Button({title: 'copy code to clipboard', onclick: copyToClipboard}, Icon('COPYCLP')),
    )

    return div(
        div({class: "row"}, div({class: "col"}, buttons)),
        div({class: "row"}, div({class: "col"}, list ))
    )
}



function SampleForm() {
    const fb = FormBuilder({ formClass: "row g-3 was-validated" });
    ctrl.formRows.val.forEach(item => {
        const {appendix={}, ...args} = item;
        var children = [];
        if (appendix.formText) children.push(div({ class: "form-text" }, appendix.formText));
        if (appendix.formText) children.push(div({ class: "invalid-feedback" }, appendix.formText));
        if (appendix.formText) children.push(div({ class: "valid-feedback" }, appendix.formText));
        fb.add(args, ...children)
    })
    return fb.dom;
}


function SampleCode() {

    const addCode = value => {
        const {appendix={}, ...args} = value;
        var s = '.add(' + JSON.stringify(args);
        if(appendix.formText) s += `,\n  div({class: "form-text"}, "${appendix.formText}")`;
        if(appendix.invalidFeedback) s += `,\n  div({class: "invalid-feedback"}, "${appendix.invalidFeedback}")`;
        if(appendix.validFeedback) s += `,\n  div({class: "valid-feedback"}, "${appendix.validFeedback}")`;
        s += ')';
        return s;
    }

    const code = ()=> {
        var a = ctrl.formRows.val.map( addCode );
        a.unshift(`const fb = FormBuilder({autoRow: true, rowClass: "mb-2", cols: "4"})`)
        return a.join('\n')
    }
    // return div({class: "overflow-x-auto"}, Marked(`\n\`\`\`javascript\n${code()}\n\`\`\`\n`) );
    return div({class: "overflow-x-auto"}, pre({id: 'EditGroupFormCode'}, code() ));
}



function ResultView() {
    return div(
        ul({ class: "nav nav-tabs", id: "myTab", role: "tablist" },
            li({ class: "nav-item", role: "presentation" },
                button({ class: "nav-link active", id: "form-tab", "data-bs-toggle": "tab", "data-bs-target": "#form-tab-pane", type: "button", role: "tab", "aria-controls": "form-tab-pane", "aria-selected": "true" },
                    "Form",
                ),
            ),
            li({ class: "nav-item", role: "presentation" },
                button({ class: "nav-link", id: "code-tab", "data-bs-toggle": "tab", "data-bs-target": "#code-tab-pane", type: "button", role: "tab", "aria-controls": "profile-tab-pane", "aria-selected": "false" },
                    "Code",
                ),
            ),
        ),
        div({ class: "tab-content", id: "myTabContent" },
            div({ class: "tab-pane fade show active", id: "form-tab-pane", role: "tabpanel", "aria-labelledby": "form-tab", tabindex: "0" },
                SampleForm
            ),
            div({ class: "tab-pane fade", id: "code-tab-pane", role: "tabpanel", "aria-labelledby": "code-tab", tabindex: "0" },
                SampleCode,
            ),
        ),
    )
}  



function Page () {
    return div({class: "container"},
//        div({class: "row"}, h3("Form Generator")),
        div({class: "row"},
            div({class: "col-4"}, FormGroupList),
            div({class: "col-8"}, ResultView),
        )
    )
}

container.appendChild(Page());	


Icons

Icons, the small images used on buttons or in the text, make the UI appealing and clear. One or more libraries such as Font Awesom, Bootstrap or Simple Icons serve as the source. However, it is not uncommon for additional icons to be required that you create yourself, such as your own logo.

This library contains simple functions for displaying and managing icons from different sources.

See icons API

Icon

function Icon( anything, {size, ...props} )

Create a HTMLElement to display a small (1em by default) image. The value of 'size' is a 'style' value and applies to 'width' and 'height', for example '16px', '2.5em', '60%' or 'inherit'. Other '...props' like 'class' or 'style' are passed on.

First argument is

  • the key to an image registered with {@link setIcon}
  • a UTF-8 char
  • a SVG string
  • a object with property 'src' to a image url
  • a HTMLElement or a Icon function
  • a Font Awesome class

example key of icon in iconMap

The 'editItem' was registered with setIcon('editItem', '<svg ...'

container.appendChild(
    vanB.Icon( 'editItem' )
)

example UTF-8 char

container.appendChild(
    vanB.Icon( '🗺️' )
)

example SVG string

container.appendChild(
    vanB.Icon( '<svg viewBox="0 0 10 10" fill="blue"><circle cx="5" cy="5" r="3"/>' )
)

example SVG string with extra attributes

container.appendChild(
    vanB.Icon( 
        '<svg viewBox="0 0 10 10" fill="blue"><circle cx="5" cy="5" r="3"/>',
        {class: 'ms-3 border', size: '2.2em', onclick:()=>console.log('smile')}
    )
)

example Image URL

const {Icon, van} = vanB;
const {h2} = van.tags;
const willi = Icon({
    src: "https://avatars.githubusercontent.com/u/25134550",
    class: "rounded-4 mx-2"
})
const vanjs = Icon({
    src: "https://avatars.githubusercontent.com/u/132869025",
    class: "rounded-4 mx-2"
})
container.appendChild(
    h2({class: "bg-body-tertiary p-3"}, 'Willi', willi, 'likes VanJs', vanjs )
)

example VanJs function

const {circle, path, svg} = van.tags("http://www.w3.org/2000/svg")
const Smiley = (props) => svg({width: "16px", viewBox: "0 0 50 50", ...props},
  circle({cx: "25", cy: "25", "r": "20", stroke: "black", "stroke-width": "2", fill: "yellow"}),
  circle({cx: "16", cy: "20", "r": "2", stroke: "black", "stroke-width": "2", fill: "black"}),
  circle({cx: "34", cy: "20", "r": "2", stroke: "black", "stroke-width": "2", fill: "black"}),
  path({"d": "M 15 30 Q 25 40, 35 30", stroke: "black", "stroke-width": "2", fill: "transparent"}),
)
 
vanB.setIcon('Smiley', Smiley)
container.appendChild(
    vanB.Icon('Smiley', {width: '2.5em'})
)

example Font Awesome class

Font Awesome is not included in this demo, so we show the generated HTML


const html = vanB.Icon( "fa-solid fa-beer-mug-empty" ).outerHTML
container.appendChild(
    van.tags.span( html )    
)

setIcon

function setIcon (key, icon)

Register a Icon to a key. icon should be a function to pass arguments of the function Icon. Icons can also be derived from other icons.

const {setIcon, Icon} = vanB
setIcon('SUN', '<svg viewBox="0 0 512 512" stroke="currentColor" fill="currentColor"><path d="M361.5 1.2c5 2.1 8.6 6.6 9.6 11.9L391 121l107.9 19.8c5.3 1 9.8 4.6 11.9 9.6s1.5 10.7-1.6 15.2L446.9 256l62.3 90.3c3.1 4.5 3.7 10.2 1.6 15.2s-6.6 8.6-11.9 9.6L391 391 371.1 498.9c-1 5.3-4.6 9.8-9.6 11.9s-10.7 1.5-15.2-1.6L256 446.9l-90.3 62.3c-4.5 3.1-10.2 3.7-15.2 1.6s-8.6-6.6-9.6-11.9L121 391 13.1 371.1c-5.3-1-9.8-4.6-11.9-9.6s-1.5-10.7 1.6-15.2L65.1 256 2.8 165.7c-3.1-4.5-3.7-10.2-1.6-15.2s6.6-8.6 11.9-9.6L121 121 140.9 13.1c1-5.3 4.6-9.8 9.6-11.9s10.7-1.5 15.2 1.6L256 65.1 346.3 2.8c4.5-3.1 10.2-3.7 15.2-1.6zM352 256c0 53-43 96-96 96s-96-43-96-96s43-96 96-96s96 43 96 96zm32 0c0-70.7-57.3-128-128-128s-128 57.3-128 128s57.3 128 128 128s128-57.3 128-128z"/></svg>')
setIcon('YELLOW-SUN', props => Icon('SUN', {fill: 'yellow', ...props}))
const output = van.tags.h2( Icon('SUN'), Icon('SPACE'), Icon('YELLOW-SUN') )
container.appendChild( output )

By the way, 'SPACE' is the only predefined icon.


Define a icon library

It is recommended to register the icons in the iconMap with a name and use them in the program under that name. For better organization, you can register them in a JavaScript file that is imported into the main program. Here is an example.

file 'icons.js'

import van from 'vanjs-core';
import {setIcon, debugIcons} from 'vanjs-bootstrap';
// import a image
import logo from './logo.svg?raw';

// SVG strings
const sunStr = '<svg viewBox="0 0 512 512" stroke="currentColor" fill="currentColor"><path d="M361.5 1.2c5 2.1 8.6 6.6 9.6 11.9L391 121l107.9 19.8c5.3 1 9.8 4.6 11.9 9.6s1.5 10.7-1.6 15.2L446.9 256l62.3 90.3c3.1 4.5 3.7 10.2 1.6 15.2s-6.6 8.6-11.9 9.6L391 391 371.1 498.9c-1 5.3-4.6 9.8-9.6 11.9s-10.7 1.5-15.2-1.6L256 446.9l-90.3 62.3c-4.5 3.1-10.2 3.7-15.2 1.6s-8.6-6.6-9.6-11.9L121 391 13.1 371.1c-5.3-1-9.8-4.6-11.9-9.6s-1.5-10.7 1.6-15.2L65.1 256 2.8 165.7c-3.1-4.5-3.7-10.2-1.6-15.2s6.6-8.6 11.9-9.6L121 121 140.9 13.1c1-5.3 4.6-9.8 9.6-11.9s10.7-1.5 15.2 1.6L256 65.1 346.3 2.8c4.5-3.1 10.2-3.7 15.2-1.6zM352 256c0 53-43 96-96 96s-96-43-96-96s43-96 96-96s96 43 96 96zm32 0c0-70.7-57.3-128-128-128s-128 57.3-128 128s57.3 128 128 128s128-57.3 128-128z"/></svg>'
const moonStr = '<svg viewBox="0 0 384 512" stroke="currentColor" fill="currentColor"><path d="M223.5 32C100 32 0 132.3 0 256S100 480 223.5 480c60.6 0 115.5-24.2 155.8-63.4c5-4.9 6.3-12.5 3.1-18.7s-10.1-9.7-17-8.5c-9.8 1.7-19.8 2.6-30.1 2.6c-96.9 0-175.5-78.8-175.5-176c0-65.8 36-123.1 89.3-153.3c6.1-3.5 9.2-10.5 7.7-17.3s-7.3-11.9-14.3-12.5c-6.3-.5-12.6-.8-19-.8z"/></svg>'

// register icons in iconMap

// from loacal url
setIcon('VANLOGO', Icon({src: "img/vanjs.svg"}));

// from imported url with extra props
setIcon('LOGO', Icon(logo, {fill: 'currentColor', stroke: 'currentColor'}));

// from SVG string
setIcon('theme-light', sunStr)
setIcon('theme-dark', moonStr)

file 'app.js'

import van from 'vanjs-core';
import {Icon} from 'vanjs-bootstrap';
import './icons';  // initialize iconMap

const {div, h1} = van.tags;

export default function App() {
    return () => div(
      h1('VanJs ',Icon('VANLOGO'),' is nice'),
    )
}

Show Icons Demo

All registered icons are stored in global variable iconMap Use this Button to display all registered icons in this app.

const {van, Button, Icon, iconMap} = vanB;
const {Modal} = modal;

function ShowIconMap() {
    const keys  = [...iconMap.keys()].sort();
    const {div} = van.tags;
    const dlg = Modal({
        header: "Icon Map",
        body: div(
            ...keys.map( key => div({class: "row"},
                div({class: "col"}, key ),
                div({class: "col bg-white text-black"}, Icon(key) ),
                div({class: "col bg-black text-white"}, Icon(key) ),
                div({class: "col col bg-secondary text-black"}, Icon(key) ),
            ))
        ),
        scrollable: true,
    });
    return Button({onclick: ()=>dlg.open()}, "Show Icons");
}

container.appendChild(ShowIconMap());

spriteify

When SVG icons are used frequently on a page—such as the "copy" button on this site—it makes sense to use a sprite. This is where spriteify comes in. The function returns a sprite containing all the SVGs defined in the iconMap and converts the registered SVGs into references. This sprite can then be appended to the <body> element.

function spriteify (options)

This function is experimental

options:

  • idPrefix = 'icon-',
  • svgClass = '',
  • prettify = false
const {Icon, iconMap, setIcon, getIcon, spriteify } = vanB 
const map = new Map(iconMap); 
const before = map.get('editItem')
const sprite = spriteify({prettify: true, map})
const after = map.get('editItem')
// make output
const { div, h5, pre } = van.tags
const output = div(
    h5('The sprite'),
    pre(sprite),
    h5('Icon before spriteify'),
    pre(before),
    h5('Icon after spriteify'),
    pre(after)
)
container.appendChild(output);

Work with Bootstrap Modal.

Modal functions are removed from vanjs-bootstrap since version 1.2 because it pulls the bootstrap.js and popoer and can not be used in backend without a DOM. Install it like:

install * from modal from "vanjs-bootstrap/modal"

ModalFrame

export function ModalFrame (options)

The function ModalFrame creates a complete modal dom struture like:

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

With "ModalFrame" you only need to specify the van functions for header, body and footer:

const demo = van.tags.div(
    // Button trigger modal
    vanB.Button({"data-bs-toggle": "modal", "data-bs-target": "#exampleModal"}, "Launch demo modal"),

    // Modal
    modal.ModalFrame({
        id:      "exampleModal",
        header:  "Modal title",
        body:    "Modal body text goes here.",
        footer: [
            vanB.Button({"data-bs-dismiss": "modal"}, 'Close'),
            vanB.Button({color: "primary"}, 'Save changes'),
        ]
    })
);

container.appendChild(demo)

...that's all. That saves you a lot of HTML code..

ModalFrame Options

  • header
    body
    footer
    A van dom function or null.

  • id
    An optional dialog id.

  • close
    A boolean value for the close cross in header. Default is true.

  • centered
    A boolean value for centered dialog position. Default is true.

  • scrollable
    A boolean value for scrollable dialog. Default is false.

  • color
    A Bootstrap color name.
    color: "warning"

  • position
    A optional position object like {left: 100, top: 50}

  • width
    A optional dialog width like "20em" or "fit-content"

  • class
    An additional class


You can achieve more flexibility by using the Modal function.

Simple Example

const { div, h5 } = van.tags;
const Demo = vanB.Button({
  onclick: () => modal.Modal({body: h5('Hello World')}).asyncOpen()
}, 'Push')
container.appendChild( Demo )
export function Modal (args, options)

Where "args" are the options used for ModalFrame and "options" are controller options. The function returns an object with properties and functions.

  • dom
    The ModalFrame dom

  • isOpen
    A boolean value

  • modalResult
    A value that corresponds to the argument of the close function.

  • open (left,top)
    Function to open the dialog at a given (optional) position

  • async asyncOpen (left,top)
    Function to open the dialog asynchron and returns modalResult when closed.

  • close (result)
    Function to close the dialog with optional modalResult.

  • dispose ()
    Funtion to remove the dialog from dom.

  • show ()
    Show the dialog.

  • hide (dispose)
    Hide the dialog.

You can also use the bootstrap events

dom.addEventListener('shown.bs.modal', onShown)
  • backdrop
    boolean, default true.
    Includes a modal-backdrop element.
    Alternatively, specify static for a backdrop which doesn’t close the modal when clicked.

  • focus
    boolean, default true
    Puts the focus on the modal when initialized.

  • keyboard
    boolean, default true
    Closes the modal when escape key is pressed.

  • dispose
    boolean, default true
    Dispose dialog on hide.


Confirm Example

const { div, h5 } = van.tags;

const ConfirmDlg = modal.Modal({
    close: false,               // don't show any header
    color: "text-bg-danger",
    centered: false,
    body: h5("Are you sure ?"),
    footer: div({class: ""},
        vanB.Button({onclick: ()=>ConfirmDlg.close(true), bsSize: "sm", class: "me-2"}, 'Yes'),
        vanB.Button({onclick: ()=>ConfirmDlg.close(false), bsSize: "sm"}, 'No'),
    )
});

const DemoConfirm = () => {
    const result = van.state("");
    return div({class: "row"},
        div({class: "col-3"},
            vanB.Button({
                onclick: async () => {
                    result.val = await ConfirmDlg.asyncOpen();
                }
            }, "Confirm")
        ),
        div({class: "col-3"}, () => `Result: ${result.val}`),
    )
}

container.appendChild( DemoConfirm() )

Form Example

const { div } = van.tags;

const LoginDlg = ({name, pw}) => {

    // create the form
    const fb = vanB.FormBuilder({id: "form-login-dlg"});
    fb.add({label: 'Name', name: 'name', value: name, onvalidate: v=>!!v});
    fb.add({label: 'Password', name: 'pw', value: pw, type: 'password', onvalidate: v=>v.length >= 5});

    // create the dialog
    const dlg = modal.Modal({
        header: 'Login',
        body: fb.dom,
        footer: div({class: "btn-group btn-group-sm"},
            vanB.Button({onclick: ()=>dlg.close(fb.values), disabled: ()=>!fb.getFormValid()}, 'Ok'),
            vanB.Button({onclick: ()=>dlg.close(false)}, 'Cancel'),
        )
    });

    // close on Enter pressed
    fb.dom.addEventListener('keypress', event => {
        if (event.key === 'Enter') dlg.close(fb.values);
    });

    // focus first input after open
    dlg.onShown = () => {
        document.getElementById(fb.id + '-name-i').focus()
    };

    return dlg;
};

const DemoForm = () => {
    const result = van.state({name: 'Jack', pw: 'secret'});
    return div({class: "row"},
        div({class: "col-3"},
            vanB.Button({onclick: async () => {
                let res = await LoginDlg(result.val).asyncOpen();
                if (res) result.val = res;
            }
            }, "Login")
        ),
        div({class: "col-3"}, () => `Result: ${JSON.stringify(result.val)}`),
    )
}

container.appendChild( DemoForm() )


i18n

Translation tool. A very simple object for multilingual texts. The texts are stored in the variable 'dict' and are divided into language and chapter.

The current language is set with the 'setLanguage' function. The texts are retrieved with the function 't'. Texts are added with the 'addWords' function.

"i18n" is removed from vanjs-bootstrap. Ok it is realy tiny but do not belong here. But you can import it with

import i18n from "vanjs-bootstrap/i18n"

Example

// import i18n from 'vanjs-bootstrap/i18n; // import extra module
const I18n = i18n(); // create instance
I18n.addWords({
 en: {"hello": "Hello"},
 de: {"hello": "Hallo"}
})
I18n.addWords({ hello: 'Bonjour' }, 'fr');
I18n.addWords({ hello: 'Hola' }, 'es');
I18n.addWords({ hello: '你好' }, 'cn');
I18n.addWords({ hello: 'こんにちは' }, 'jp');

const { div, span } = van.tags;
const { RadioSelectInput, Icon } = vanB;
const { t, setLanguage } = I18n;
const message = span(t('hello'));
const options = Object.keys(I18n.dict).map(lang=>[
 span(
   Icon(`<svg ><use href="#icon-flag-${lang}"/></svg>`,
   {size: '1.5em', class: 'border me-1'}),
   lang
   ), 
 lang
])
const demo = div(
 RadioSelectInput({
   value:'en', inline: true, options, 
   oninput: event=>{
     setLanguage(event.target.value)
     message.innerText = t('hello')
   }
 }),
 message
)
container.appendChild(demo);	

Interface

  • dict
    object tree structured according to language, chapter and subchapter

  • getLanguage()
    current language

  • setLanguage(newLanguage)

  • t('category.key')
    returns the text of the current language to a key. the key contains the category, the subcategory and the actual key, separated by a dot

  • tPath('category')
    returns a t function for a category

  • addWords(words, [lang], [chapter])
    inserts an object tree with texts into the dict


DragSort

A helper to sort a list per drag and drop. Since version 1.1 it is no more part of vanjs-bootstrap core and must imported separately

import dragSort from "vanjs-bootstrap/drag-sort"

export function dragSort (list, setList)
  • list: array to be sorted
  • setList: function to store reordered list

Function DragSort returns an object with all required function. The function dragProps of the object can inject all html attributes like draggable, ondragstart and so on.

The function used to be a React Hook, but works great in VanJs and is now used in this library by TagInput.

During dragging CSS :dragging is set.

Usage example:

const {div, h4} = van.tags;
const gitems = van.state(["A","B","C"])

function MyList () {
    const drag = dragSort(gitems.val, v => gitems.val=v);  // create drag sort object
    const items = gitems.val.map( (item,index) => {
        return van.tags.li({
            class: () => "list-group-item",
            ...drag.dragProps(index)                // inject properties
            },
            item
        )
    });
    return van.tags.ul({class: "list-group"}, ...items)
}

const Page = () => div({}, h4('DragSort Demo'), 'Move the rows with the mouse.',  MyList )
container.appendChild(Page());