Skip to content

Instantly share code, notes, and snippets.

@dmsnell
Last active September 9, 2019 19:51
Show Gist options
  • Save dmsnell/4dea541df8e38b5acb9d0a8f96c8bb82 to your computer and use it in GitHub Desktop.
Save dmsnell/4dea541df8e38b5acb9d0a8f96c8bb82 to your computer and use it in GitHub Desktop.
Formula-entry and mathematical typesetting block
const { registerBlockType } = wp.blocks;
const { TextareaControl } = wp.components;
const { createElement: el } = wp.element;
const attributes = {
formula: { type: 'string' },
rendered: {
type: 'string',
source: 'attribute',
selector: 'img',
attribute: 'src',
default: ''
}
}
const Edit = ( { attributes: { formula, rendered }, className, isSelected, setAttributes } ) =>
el( 'div', { className }, [
isSelected && el( TextareaControl, {
label: "Formula source",
value: formula,
onChange: newFormula => setAttributes( {
formula: newFormula,
rendered: 'data:image/svg+xml;base64,' + btoa( window.MathJax.tex2svg( newFormula ).innerHTML ),
} ) },
formula
),
el( 'div', {}, el( 'img', { src: rendered } ) )
]
);
const Save = ( { attributes: { rendered }, className } ) =>
el( 'div', { className }, el( 'img', { src: rendered } ) );
registerBlockType(
'dmsnell/formula',
{
title: 'Formula Entry',
icon: 'welcome-write-blog',
category: 'common',
attributes: attributes,
edit: Edit,
save: Save,
}
);
<?php
/**
* Plugin Name: Formula Block
* Plugin URI: http://wordpress.com/
* Description: Enter LaTeX-style formulas interactively
* Version: 1.0
* Author: Dennis Snell <[email protected]>
* Author URI: wordpress.com
* License: GPL-2.0
**/
defined( 'ABSPATH' ) or die( 'Cannot access script directly' );
add_action( 'init', function() {
wp_register_script( 'mathjax-svg', plugins_url( 'tex-mml-svg.js', __FILE__ ), [] );
wp_enqueue_script(
'formula-block-editor',
plugins_url( 'formula-block-editor.js', __FILE__ ),
[ 'mathjax-svg', 'wp-blocks', 'wp-components', 'wp-element' ]
);
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment