lively4-core

Lively4 Script Examples in Markdown

This document demonstrates how scripts work in Lively4 markdown files, based on the working mermaid example.

Key Concepts

1. Script Context and DOM Access

In Lively4 markdown, scripts execute within the context of the markdown component:

// Get the lively-markdown component that contains this script
const markdownComponent = lively.query(this, "lively-markdown")

// Access the shadow root for DOM manipulation
const root = markdownComponent.shadowRoot

2. ES6 Module Imports

Scripts can use ES6 import syntax to load external libraries:

import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10.9.1/dist/mermaid.esm.min.mjs';

3. DOM Manipulation in Shadow Root

Query and manipulate elements within the component’s shadow DOM:

// Find elements in the shadow root, not global document
const elements = root.querySelectorAll('code');

// Create and append elements normally
const container = document.createElement('div');
targetElement.parentNode.replaceChild(container, targetElement);

Working Example Pattern

Based on the mermaid integration, here’s the pattern that works:

Example Code Block to Process

This is an example-trigger code block that should be transformed by the script above.

Key Learnings from Mermaid Example

  1. Component Context: this refers to the script element, use lively.query(this, "lively-markdown") to get the container
  2. Shadow DOM: Access via markdownComponent.shadowRoot for proper DOM scoping
  3. ES6 Imports: Work directly in script tags without module bundlers
  4. Timing: Scripts execute immediately, no need for DOMContentLoaded in this context
  5. DOM Manipulation: Standard DOM APIs work within the shadow root scope

Best Practices

This pattern enables powerful interactive markdown documents in Lively4!