Published
Edited
Jul 16, 2019
1 fork
Importers
9 stars
Insert cell
md`# Svelte Experiments`
Insert cell
md`## Examples`
Insert cell
render(svelte`<h1>Hello world!</h1>`)
Insert cell
render(svelte`<script>
let name = 'world';
</script>

<h1>Hello {name}!</h1>`)
Insert cell
render(svelte`<style>
p {
color: purple;
font-family: 'Comic Sans MS';
font-size: 2em;
}
</style>

<p>Styled!</p>`)
Insert cell
m = render(svelte`<!-- a -->
<script>
import {onMount} from 'svelte';
import {readable} from 'svelte/store';

let svg;

let svgRect = {width: undefined, height: undefined}
$: width = svgRect.width;
$: height = svgRect.height;

function maybeUpdateSvgRect() {
const rects = svg.getClientRects()
console.log(svg, rects, svg.getBoundingClientRect());
if (rects.length < 1) {
return false
}
svgRect = rects[0]
return true
}

export const refresh = maybeUpdateSvgRect

onMount(() => maybeUpdateSvgRect || setTimeout(maybeUpdateSvgRect, 0))

$: console.log({width, height})
</script>
<style>
svg {
display: block;
background: green;
}
</style>

<svelte:window on:resize='{maybeUpdateSvgRect}'/>

<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" bind:this={svg} preserveAspectRatio="none">
<circle r=10 cx={width / 2} cy={height / 2} fill="black"/>
</svg>
`)

Insert cell
getComponent(m).refresh()
Insert cell
nested = svelte`<p>...don't affect this element</p>`
Insert cell
render(svelte`<script>
import Nested from ${nested};
</script>

<style>
.foo {
color: purple;
font-family: 'Comic Sans MS';
font-size: 2em;
}
</style>

<p class="foo ">These styles...</p>
<Nested/>`)
Insert cell
md `### More advanced`
Insert cell
function* exampleTicker() {
yield Promise.resolve(new Date())
while (true) {
yield Promises.delay(1000, new Date());
}
}
Insert cell
exampleInput = html`<input type=range>`
Insert cell
render(svelte`<script>
export let now;
export let value;
$: console.log("NOW", $now, $value)
</script>
The time is now {$now}<br>
The value is {$value}`, {
now: generatedPromises(exampleTicker),
value: readableInput(exampleInput),
})
Insert cell
md `## Under the hood`
Insert cell
compile`<!-- x --><script>
import Nested from ${nested};
</script>

<style>
.foo {
color: purple;
font-family: 'Comic Sans MS';
font-size: 2em;
}
</style>

<p class="foo">These styles...</p>
<Nested/>`

Insert cell
function compile(strings, ...values) {
// Replace values with random strings... and then preprocess to either replace them with properties OR values in require

// TODO(adamb) Choose a gensymPrefix that doesn't exist ANYWHERE in strings
const genSymPrefix = "gensym_923wedsojasjq_"
const rawSyms = []
const symVals = {}
let ix = 0
for (const value of values) {
const sym = genSymPrefix + ix++
rawSyms.push(`"${sym}"`)
symVals[sym] = value
}
const s = strings.reduce((prev, next, i) => `${prev}${next}${rawSyms[i] || ''}`, '')

let name
const nameMatch = s.match(/^\s*<!--\s*([a-zA-Z0-9_]+)/)
if (nameMatch) {
name = nameMatch[1]
}

const compiled = svelteCompiler.compile(s, {format: "cjs", css: true, name})
// HACK(adamb) Once this svelte bug is addressed, put back interpolation checking
// https://github.com/sveltejs/eslint-plugin-svelte3/issues/13
// const unknownSymTypes = []
// svelteCompiler.walk(compiled.ast.instance, {
// enter(node, parent, prop, index) {
// console.log("node", node)
// if (node.type !== "Literal" || !(node.value in symVals)) {
// return
// }
// if (parent.type !== "ImportDeclaration") {
// unknownSymTypes.push(node)
// }
// },
// })
// if (unknownSymTypes.length > 0) {
// throw Error("Interpolation is only allowed in import statements (for now)")
// }

return Object.assign({requires: symVals}, compiled)
}
Insert cell
svelteInternal = await import("svelte@3.6.7/internal/index.mjs")
Insert cell
load = {
const svelteInternal = await import("svelte@3.6.7/internal/index.mjs")
// HACK(adamb) Apply the workaround described in https://github.com/sveltejs/svelte/issues/2086#issuecomment-490989491
function detach(node) {
if(node.parentNode) {
node.parentNode.removeChild(node);
}
}
const hackedOverrides = {detach}
const hackedSvelteInternal = Object.assign(
Object.create(svelteInternal),
hackedOverrides,
)
const requires = ({
"svelte/internal": hackedSvelteInternal,
"svelte": hackedSvelteInternal,
"svelte/store": svelteStore,
})
return function(compiled) {
const css = compiled.css
const bundledRequires = compiled.requires || {}
const fn = eval(`(function(require, exports){${compiled.js.code}})`)
const exports = {}
fn(
name => requires[name] || bundledRequires[name],
exports,
)
// HACK(adamb) Apply workaround described in https://github.com/sveltejs/svelte/issues/2086#issuecomment-490989491
Object.assign(exports, hackedOverrides)
exports[CSSTag] = css
return exports
}
}
Insert cell
CSSTag = Symbol("css")
Insert cell
svelteCompiler = require("svelte@3.6.7/compiler");
Insert cell
// There seems to be a bug in 3.4.4+ that prevents us from loading store.mjs directly
svelteStore = require('https://bundle.run/svelte@3.6.7/store/index.js').catch(() => ({
get: svelteInternal.get_store_value,
readable: window['readable'],
writable: window['writable'],
derived: window['derived'],
}))
Insert cell
md`## API`
Insert cell
function render(component, props, target) {
let t = target || DOM.element('div')
const css = component[CSSTag]
let style
if (css !== undefined) {
const head = document.getElementsByTagName('head')[0]
style = DOM.element('style')
head.appendChild(style)
style.innerHTML = css.code
}
let c = new component.default({target: t, props})
t[componentTag] = c
return Generators.disposable(t, () => {
c.$destroy()
if (t[componentTag] === c) {
delete t[componentTag]
}
t = undefined
c = undefined
if (style !== undefined && style.parentNode) {
style.parentNode.removeChild(style)
}
})
}
Insert cell
componentTag = Symbol("svelte-component")
Insert cell
function getComponent(element) {
return element[componentTag]
}
Insert cell
function svelte(strings, ...values) {
return load(compile(strings, ...values))
}
Insert cell
readable = svelteStore.readable
Insert cell
writable = svelteStore.writable
Insert cell
derived = svelteStore.derived
Insert cell
get = svelteStore.get
Insert cell
function generatedPromises(gen, initialValue) {
return svelteStore.readable(initialValue, set => {
const g = gen()
function afn({value, done}) {
if (done) {
return
}
value.then(v => {
set(v)
afn(g.next())
})
}
afn(g.next())

return () => g.return()
})
}
Insert cell
function readableInput(input) {
return generatedPromises(() => Generators.input(input), input.value)
}
Insert cell
function observe(observable) {
return readable(observable.value, set => {
const inputted = () => set(observable.value)
observable.addEventListener('input', inputted)
return () => observable.removeEventListener('input', inputted)
})
}
Insert cell
Stores = ({
input: readableInput,
resolvePromises: generatedPromises,
})
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more