Executing code cells

Table of Contents

Bugs 🐜 and To do ✅

  • executed cell gets replaced with its output.
  • more robust outputs
    • replace "connected" output on exec
  • Extract transpilation as Transfomers

Examples

jsexample
console.log(document.referrer)
txtUpdated 144w ago
https://dotlit.org/
undefined
jsexample
return new Object({foo: "bar"})
txtUpdated 142.9w ago
{ foo: 'bar' }

Async and Promises

jstest.js
const wait = (ms) => {
  return new Promise(resolve => {
    setTimeout( () => {
      resolve(new Date())
    }, ms)
     
  })
}
return wait(1000)
txtUpdated 143.4w ago
Wed Apr 28 2021 23:44:37 GMT+0100 (BST)
js
return fetch('https://example.com')
       .then( res => res.status )
txtUpdated 143w ago
200
js
return (async fn => {
    const size = await lit.fs.du('/')
    console.log("Local filesystem size:")
    return size
})()
txtUpdated 139.0w ago
Local filesystem size:
423028

Transpiling

The meta syntax for transformers/transpiling is not yet stable, for now use the experimental babel attribute, combined with specifying the source lang in the filename extention. (Currently requires explicitly setting repl to js to execute)

tsjstest.ts
type Options = {[key: number]: string}
const fn = (opts : Options) => {
  const str:string = 12 
  // need linting to make this useful
  return str
}

return fn()
txtUpdated 144.3w ago
12

React jsx

Using the experimental react attribute, a Cell can define its own content as a component, warning due to needing to use the same React instance as the parent application, the below with dynamic import won't work.

jsxjstest.jsx
import React from 'https://cdn.skypack.dev/react'

const Component = props => {
  return <div></div>
}

return <Component/>
txterrorUpdated 142.9w ago
undefined

Instead, get React from the utils in the lit global.

jsxjstest.jsx
const React = lit.utils.React
const { useState } = React
  
const Clicker = props => {
    const [c,setC] = useState(0)
    //console.log(React, useState, c)
    const click = e => setC(c+1)

    return <button onClick={click}>{ "Click me: " + c}</button>
}

return <Clicker/>

Outputs

See Custom Viewers for information on built in viewers and how to create custom ones.

Raw svg string

svgUpdated 139.0w ago

Markdown

js> md
console.log("A __*result*__: **`" +  42/13 + "`**")
return 42
mdUpdated 144.4w ago

A result: 3.230769230769231 42

js> json
return { foo: 'bar'}
jsonUpdated 144.5w ago
{ foo: 'bar' }

Meta: lit global and AST

When executing a Cell this refers to the hast node for that cell.

js> json #this !collapse
return this

To get the mdast for the document, you need to refer to the global lit object.

js> json #ast #position !collapse
return lit.ast

To get info about the location of the current document, see lit.location.

js> json #location !collapse
return lit.location
js> json #utils !collapse
return lit.utils

Finding nodes in the ast can be done either manually or using some of the unist utils available

js> json #heading #title
const select = lit.utils.unist.select.select
return select('heading', lit.ast)   
js> json #headings !collapse
return lit.utils
          .unist.select
          .selectAll('heading', lit.ast)
          .map( h => `${h.depth} ${h.data.id }`)
js> json #sectiontitle !collapse
// get the title of the section containing the currently selected cell
// some utilities still need exposing to achieve this.
const currentPos = {}
const atPosTree = {}
const section = 
return "TBD..."

Mutating Self

Code cell execution which modifies the content of a .lit document outwith of its own (attached) output cell, initially itself, but then try an external doc.

jsmutateme
// Mutated at Sun May 02 2021 12:59:07 GMT+0100 (BST)
jsselfmutate=experimental
const src = lit.file.contents
const unist = lit.utils.unist

const select = unist.select.select
const source = unist.source
const patchSource = unist.patchSource.default

const selector = 'code[meta=#mutateme]'
const node = select(selector, lit.ast)
const pos = node.position

const original = source(pos, src)
const newSrc = "```js #mutateme\n// Mutated at " + new Date() + "\n```"

return patchSource(src, pos, newSrc)
mdwarnUpdated 142.9w ago

⚠️ This uses the still experimental selfmutate attribute, and affects content outside of it's own attached output cell.

Dynamic imports

js
return (async args => {

  const confetti = await 
  import('https://cdn.skypack.dev/canvas-confetti')

  confetti.default({
     origin: {y: 0},
     spread: 55,
     particleCount: 100,
     ticks: 1000,
  })
  return "Wait for it... 🥳"
})()
txtUpdated 84.4w ago
Wait for it... 🥳