Twotiles Code Visualization

Twotiles is a free and open JavaScript libaray for turning code into visual blocks. The library can be used in any website.

Example

The following uses a simple math example, taking the derivative of a logarithm, to show how code is visualized with the Twotiles library.

Symbolic computation in Python: SymPy

Code Preamble
from sympy import symbols,diff,log
from functools import partial
x=symbols("x")
b=symbols("b")
y=symbols("y")

def call(f, x):
    return f(x)

Using SymPy, one can calculate with symbols. Here, x is a symbol.

5/x - (50 + 14)

\(\displaystyle -64 + \frac{5}{x}\)

log(64.0)

\(\displaystyle 4.15888308335967\)

One can also make an explicit call to the log function.

call(log, 64.0)

\(\displaystyle 4.15888308335967\)

This makes call a special kind of function. Because it takes a function as its first argument, call is a function of “higher order”. But for now we return to the usual way of making a calculation.

log(x * 5)

\(\displaystyle \log{\left(5 x \right)}\)

diff(log(x) * 5, x)

\(\displaystyle \frac{5}{x}\)

diff(log(x),x)

\(\displaystyle \frac{1}{x}\)

def logarithm(b, x):
    return log(x) / log(b)
logarithm(8.0, 64.0)

\(\displaystyle 2.0\)

def log_base(b):
    return partial(logarithm, b)
call(log_base(8.0),64.0)

\(\displaystyle 2.0\)

diff(call(log_base(8.0),x),x)

\(\displaystyle \frac{0.480898346962988}{x}\)

Symbolic computation in JavaScript: EmmyJS

to_infix(
  call(diff(log_base(8.0)), x)
)
to_infix(
  call(diff(log), x)
)

SymPy Recap

Guide

Using Twotiles in a Website

To display graphical blocks, include into your web-site the Scittle, Blockly and indeed the Twotiles library:

<script src="https://cdn.jsdelivr.net/npm/scittle@0.6.22/dist/scittle.js"></script>
<script src="https://unpkg.com/blockly/blockly.min.js"></script>
<script src="https://unpkg.com/blockly/msg/en.js"></script>
<script src="https://kloimhardt.github.io/twotiles/twotiles_core.js"></script>

Then initialize the Twotiles parser …

<script>
var parse = scittle.core.eval_string(twotiles.parse_clj);
</script>

… and Blockly:

<script>
Blockly.defineBlocksWithJsonArray(twotiles.blocks);
</script>

It is convenient to have a render function:

<script>
var brender = (code,divid) =>
Blockly.Xml.clearWorkspaceAndLoadFromXml(Blockly.utils.xml.textToDom(parse(code)),
Blockly.inject(divid,
{"toolbox": twotiles.toolbox,
"sounds": false,
"scrollbars": false,
"trashcan": false}));
</script>

Then graphics can be displayed with

<div id="blocklyDiv" style="height: 100px;"></div>
<script>brender("(log 64)", "blocklyDiv")</script>

which looks like this:

Using EmmyJS

A detailed example of EmmyJS can be found at sicmutils-as-js-book-part1.html

Quarto Notebook of this Page

This page was generated with Quarto out of the file twotiles.qmd