[title, render callback, attributes]. * * @return array */ function mulabase_block_defs() { $str = array( 'type' => 'string', 'default' => '' ); return array( 'take-home' => array( 'mulabase_sc_take_home', array( 'country' => $str, 'gross' => $str, 'title' => $str ) ), 'mobile-money' => array( 'mulabase_sc_mobile_money', array( 'country' => $str, 'amount' => $str, 'title' => $str ) ), 'fee-table' => array( 'mulabase_sc_fee_table', array( 'country' => $str, 'columns' => $str, 'title' => $str ) ), 'rates' => array( 'mulabase_sc_rates', array( 'countries' => $str, 'indicators' => array( 'type' => 'string', 'default' => 'policy-rate,inflation' ), 'title' => $str ) ), 'calculator' => array( 'mulabase_sc_calculator', array( 'slug' => $str, 'title' => $str ) ), ); } /** * Registers the blocks and the editor script. */ function mulabase_register_blocks() { if ( ! function_exists( 'register_block_type' ) ) { return; } wp_register_script( 'mulabase-blocks', MULABASE_URL . 'assets/blocks.js', array( 'wp-blocks', 'wp-element', 'wp-components', 'wp-block-editor', 'wp-server-side-render', 'wp-i18n' ), MULABASE_VERSION, true ); foreach ( mulabase_block_defs() as $name => $def ) { $callback = $def[0]; register_block_type( 'mulabase/' . $name, array( 'api_version' => 3, 'editor_script' => 'mulabase-blocks', 'style' => 'mulabase', 'attributes' => $def[1], 'render_callback' => function ( $atts ) use ( $callback ) { return call_user_func( $callback, array_filter( (array) $atts, 'strlen' ) ); }, ) ); } } add_action( 'init', 'mulabase_register_blocks' ); /** * Gives the editor the country and calculator lists for its dropdowns. */ function mulabase_block_editor_data() { $data = mulabase_data(); $calcs = array(); foreach ( $data['calculators'] as $c ) { $calcs[] = array( 'value' => $c['slug'], 'label' => $c['countryName'] . ': ' . $c['name'], 'type' => $c['type'], ); } usort( $calcs, function ( $a, $b ) { return strcmp( $a['label'], $b['label'] ); } ); $by_type = function ( $type ) { return array_map( function ( $c ) { return array( 'value' => $c['country'], 'label' => $c['countryName'], ); }, mulabase_main_calculators( $type ) ); }; wp_add_inline_script( 'mulabase-blocks', 'window.MulabaseEditor=' . wp_json_encode( array( 'paye' => $by_type( 'income-tax' ), 'tariff' => $by_type( 'tariff' ), 'calculators' => $calcs, 'countries' => $data['countries'], 'icon' => MULABASE_URL . 'assets/mulabase-mark.svg', ) ) . ';', 'before' ); } add_action( 'enqueue_block_editor_assets', 'mulabase_block_editor_data' ); /** * Inside the editor's canvas (an iframe), loads the widget script and data so * previews are interactive. On the front end nothing loads until a widget is used. */ function mulabase_block_canvas_assets() { if ( ! is_admin() ) { return; } mulabase_enqueue_widget( array_values( mulabase_data()['calculators'] ) ); wp_add_inline_script( 'mulabase', 'window.MulabaseData.editor=true;', 'before' ); } add_action( 'enqueue_block_assets', 'mulabase_block_canvas_assets' );