src/RadioButton.ts

   1/**

   2 * # Radio Button Widget

   3 * A simple radio button widget, allowing one button to be pressed at a time

   4 * 

   5 * ### Profile

   6 * invoked as `m(RadioButton, {name:, onclick:});`

   7 * 

   8 * ### Attributes (node.attrs):

   9 * - `onclick:() => void` function to execute when button is clicked

  10 * - `name: string` name to show as button text

  11 * - `css: string` css class to assign to button tag

  12 * - `style: string` style string to apply to button tag

  13 * 

  14 * ### Example

  15 * 

  16 * 'script.js'>

  17 * let clicked = 0;

  18 * let radio = '';

  19 * let toggle = '';

  20 * 

  21 * m.mount(root, {view: () => m('.hs-white', [

  22 *    m('h4', `Select Radio Station: ${radio}`),

  23 *    m(hsWidget.RadioButton, { desc: {

  24 *        items: ['1st''2nd','3rd'],

  25 *        clicked: (item) => radio = item

  26 *    }})

  27 * ])});

  28 * 

  29 * 

  30 * 

  31 */

  32

  33/** */

  34import { m, Vnode }         from 'hslayout';

  35import { Layout }           from 'hslayout';

  36import { Selector }         from './Selector';

  37

  38/**

  39 * # Radio Button Widget

  40 * A group of buttons with one or none selected

  41 * 

  42 * ### Profile

  43 * invoked as `m(RadioButton, {desc: { items:[], clicked:}});`

  44 * 

  45 * ### Attributes (node.attrs):

  46 * - `desc:` see {@link Selector.SelectorDesc SelectorDesc}

  47 *     - `clicked:(item:string) => void`    function to execute when button is selected

  48 *     - `selectedItem?: number|string`     the currently selected item, by index or name

  49 *     - `items: string[]`                  names to individual buttons to show

  50 *     - `itemCss?:string[]`                css to apply to each item;

  51 * - `css?: string`                         css class to assign to button group

  52 * - `style?: string`                       style string to apply to button tag

  53 */

  54export class RadioButton extends Selector {

  55    static viewGroup(css:string, node: Vnode) {

  56        css = `${css} ${node.attrs.css || ''}`;

  57        const style = node.attrs.style || '';

  58

  59        return m(css, {style:style}, m(Layout, {

  60            columns: [],

  61            content: node.state.items.map((l:string, i:number) => Selector.renderItem(node, i))

  62        }));

  63    }

  64    oninit(node: Vnode) {

  65        super.oninit(node);

  66        Selector.ensureSelected(node);

  67    }

  68    onupdate(node: Vnode) {

  69        super.onupdate(node);

  70        Selector.ensureSelected(node);

  71    }

  72    view(node: Vnode): Vnode { return RadioButton.viewGroup('.hs-radio-buttons', node); }

  73}

  74

  75