### Install LiveCodes SDK with npm
Source: https://livecodes.io/docs/getting-started.html
Install the LiveCodes SDK package using npm. This is the first step for embedding playgrounds using a bundler.
```bash
npm install livecodes
```
--------------------------------
### Create LiveCodes Playground with SDK (CDN - ESM)
Source: https://livecodes.io/docs/getting-started.html
Embeds a LiveCodes playground using the SDK loaded from a CDN via ESM. This example initializes a playground in a container with a React template.
```html
```
--------------------------------
### Create LiveCodes Playground with SDK (CDN - UMD)
Source: https://livecodes.io/docs/getting-started.html
Embeds a LiveCodes playground using the SDK loaded from a CDN via UMD. This example initializes a playground in a container with a React template, utilizing the global 'livecodes' object.
```html
```
--------------------------------
### Prefill LiveCodes Playground with Custom Content
Source: https://livecodes.io/docs/getting-started.html
Demonstrates how to prefill a LiveCodes playground with custom HTML, CSS, and JavaScript content using the SDK. It also configures the playground to open the console.
```js
import { createPlayground } from 'livecodes';
const config = {
markup: {
language: 'markdown',
content: '# Hello LiveCodes!',
},
style: {
language: 'css',
content: 'body { color: blue; }',
},
script: {
language: 'javascript',
content: 'console.log("hello from JavaScript!");',
},
activeEditor: 'script',
};
createPlayground('#container', { config, params: { console: 'open' } });
```
--------------------------------
### Create LiveCodes Playground with SDK (Bundler)
Source: https://livecodes.io/docs/getting-started.html
Demonstrates how to create an embedded LiveCodes playground using the SDK when integrating with a bundler. It initializes a playground in a specified container with a React template.
```js
import { createPlayground } from 'livecodes';
createPlayground('#container', {
template: 'react',
// other embed options
});
```
--------------------------------
### Install Docker, Docker Compose, and Git on Ubuntu
Source: https://livecodes.io/docs/advanced/docker.html
A bash script to automate the installation of Docker, Docker Compose, and Git on Ubuntu systems. It updates package lists, installs Docker and its dependencies, adds the current user to the docker group, installs Docker Compose, and finally installs Git.
```sh
#!/bin/bash
# Update package lists
sudo apt update
# Install Docker
sudo apt install -y ca-certificates curl gnupg lsb-release
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io
# Add current user to docker group
sudo usermod -aG docker $USER
newgrp docker # Apply group changes immediately
# Install Docker Compose
sudo apt install -y docker-compose
# Install Git
sudo apt install -y git
```
--------------------------------
### Build and Serve LiveCodes with npm
Source: https://livecodes.io/docs/features/self-hosting.html
This snippet shows the npm commands to clone the repository, install dependencies, build the application for deployment, serve it locally for testing, and deploy it to GitHub Pages. It also includes a command to start the development server with live reloading.
```shell
git clone https://github.com/{your-username}/livecodes
cd livecodes
npm install
npm run build # build the app to "build" directory
npm run serve # locally serve to http://localhost:8080
# deploy
npm run deploy # build and deploy to GitHub Pages
# for development
npm start # start local development with code watch, rebuild and live-reload
```
--------------------------------
### C# Hello World Example (Wasm)
Source: https://livecodes.io/docs/languages/csharp-wasm.html
A simple 'Hello, LiveCodes C#' program demonstrating basic C# console output in a WebAssembly environment. This is suitable for beginners to test the setup.
```csharp
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello, LiveCodes C#!");
}
}
```
--------------------------------
### Python (Wasm): Install setuptools and get version using micropip
Source: https://livecodes.io/docs/languages/python-wasm.html
Shows how to install external Python packages, specifically 'setuptools', using 'micropip' in a Pyodide environment. It then accesses package information, such as the version, demonstrating explicit package management.
```python
import micropip
await micropip.install("setuptools")
import pkg_resources
print(pkg_resources.get_distribution("setuptools").version)
```
--------------------------------
### Svelte Multi-Component Setup (Markup and Script Editors)
Source: https://livecodes.io/docs/llms-full.txt
Demonstrates how to use a Svelte component in the markup editor that imports and interacts with a component defined in the script editor. This setup allows for modular Svelte development within LiveCodes, utilizing relative imports for components within the same directory. The 'start' prop is passed from the markup component to the script component.
```svelte
```
```svelte
{count}
```
--------------------------------
### Clone and Run LiveCodes Repository
Source: https://livecodes.io/docs/llms-full.txt
These shell commands guide you through obtaining the LiveCodes project from its GitHub repository and starting the application using Docker Compose. It includes cloning the repository, navigating into the project directory, optionally checking out a specific branch, and then running the application in detached mode.
```sh
git clone https://github.com/live-codes/livecodes.git
cd livecodes
git checkout main
docker compose up -d
```
--------------------------------
### Default Editor Theme Example - TypeScript
Source: https://livecodes.io/docs/llms-full.txt
Provides an example of setting a default editor theme using a string. This allows for quick configuration of the editor's visual appearance.
```typescript
"vs"
```
--------------------------------
### Clone and Run LiveCodes Repository
Source: https://livecodes.io/docs/advanced/docker.html
Commands to clone the LiveCodes repository from GitHub and run it using Docker Compose. This assumes Docker and Docker Compose are already installed. It clones the repository, navigates into the directory, and starts the containers in detached mode.
```sh
git clone https://github.com/live-codes/livecodes.git
cd livecodes
# Optionally, checkout a specific branch:
# git checkout main
docker compose up -d
```
--------------------------------
### SolidJS Component Development in LiveCodes
Source: https://context7_llms
Guides for developing SolidJS components using LiveCodes. This includes examples of JSX syntax and Solid's reactivity model. Supports both JavaScript and TypeScript.
```jsx
import { createSignal } from 'solid-js';
function Counter() {
const [count, setCount] = createSignal(0);
return (
);
}
export default Counter;
```
```tsx
import { createSignal, Component } from 'solid-js';
const Counter: Component = () => {
const [count, setCount] = createSignal(0);
return (
);
};
export default Counter;
```
--------------------------------
### Gleam Starter Template Example
Source: https://livecodes.io/docs/languages/gleam.html
A basic Gleam starter template for LiveCodes, demonstrating the integration of standard library functions, custom modules, external functions, and NPM modules.
```gleam
import gleam/io
// Example of an external function (assuming setup as shown previously)
@external(javascript, "my_pkg/greet.js", "hello")
pub fn hello(str: String) -> String
// Example of an npm module (assuming setup as shown previously)
@external(javascript, "npm:uuid", "v4")
pub fn uuid() -> String
pub fn main() {
io.println("Running Gleam starter template...")
io.println(hello("Gleam external functions"))
io.println("Generated UUID: " <> uuid())
}
```
--------------------------------
### Example URL Query Parameters for LiveCodes
Source: https://livecodes.io/docs/llms-full.txt
Demonstrates how to use URL query parameters to specify language and code content for a LiveCodes playground. Any supported language can be used as a parameter.
```url
https://livecodes.io?js=console.log('Hello World!')
```
--------------------------------
### Install LiveCodes SDK via npm
Source: https://raw.githubusercontent.com/live-codes/livecodes/refs/heads/develop/README
This command installs the LiveCodes SDK package using npm. The SDK is a lightweight, zero-dependency package that provides an interface to embed and communicate with LiveCodes playgrounds. It is essential for integrating LiveCodes into your projects.
```bash
npm i livecodes
```
--------------------------------
### Nunjucks Pre-rendered Example
Source: https://livecodes.io/docs/llms-full.txt
Demonstrates a pre-rendered Nunjucks template with a `name` variable passed through custom settings. This shows a basic usage of Nunjucks within LiveCodes.
```html
```
--------------------------------
### Python Configuration Example
Source: https://livecodes.io/docs/api/interfaces/EmbedOptions.html
Example of configuring Python settings for a LiveCodes project. This is useful for projects that require Python execution, often within a WASM environment.
```json
{
"customSettings": {
"scriptType": "text/python",
"wasm": {
"py": "any"
}
}
}
```
--------------------------------
### Vue.js Configuration Example
Source: https://livecodes.io/docs/api/interfaces/EmbedOptions.html
Example of setting up Vue.js for a LiveCodes project. This involves specifying the 'vue' or 'vue3' property, typically to 'any'.
```json
{
"customSettings": {
"vue": "any",
"vue3": "any"
}
}
```
--------------------------------
### ClojureScript Example
Source: https://livecodes.io/docs/llms-full.txt
Shows how to use ClojureScript in LiveCodes, including how to require npm modules and handle DOM events. It also demonstrates using ClojureScript with React and JSX.
```clojurescript
(ns demo
;; you can use npm modules
(:require ["canvas-confetti$default" :as confetti]))
(let [el (js/document.getElementById "test")]
(.addEventListener el "click"
(fn []
(confetti)
(println "test"))))
```
```html
```
--------------------------------
### LiveCodes Dynamic Vento Example
Source: https://livecodes.io/docs/llms-full.txt
Shows a dynamic Vento template example with LiveCodes. It configures the Vento markup and a JavaScript script to set runtime data, disabling pre-rendering to allow for dynamic updates.
```tsx
import LiveCodes from '../../src/components/LiveCodes.tsx';
export const config2 = {
markup: { language: 'vento', content: 'Hello, {{ name }}!' },
script: {
language: 'javascript',
content: 'window.livecodes.templateData = { name: "LiveCodes" };',
},
customSettings: { template: { prerender: false } },
activeEditor: 'script',
};
```
--------------------------------
### Run LiveCodes Docker Compose
Source: https://livecodes.io/docs/advanced/docker.html
Command to build and run LiveCodes using Docker Compose. It requires Docker and Docker Compose to be installed. The HOST_NAME environment variable can be set to configure the domain for the self-hosted instance.
```sh
HOST_NAME=vps.livecodes.io docker compose up --build -d
```
--------------------------------
### Basic Ruby Setup in LiveCodes
Source: https://livecodes.io/docs/languages/ruby.html
A minimal Ruby code snippet designed to run within the LiveCodes environment using the Opal compiler. This serves as a basic template for starting Ruby projects in LiveCodes, showcasing the environment's readiness for Ruby execution.
```ruby
# LiveCodes Ruby Starter Template
# Use puts for console output
puts "Hello, LiveCodes Ruby!"
```
--------------------------------
### JavaScript Example for tools Configuration
Source: https://livecodes.io/docs/api/internal/interfaces/AppConfig.html
An example demonstrating how to configure the tools pane in JavaScript. This includes enabling specific tools like console and compiled, and setting the active tool and pane status.
```javascript
{
"tools": {
"enabled": ["console", "compiled"],
"active": "console",
"status": "open"
}
}
```
--------------------------------
### Install markdown-it-livecodes for Eleventy
Source: https://livecodes.io/docs/llms-full.txt
This command installs the `markdown-it-livecodes` npm package as a development dependency for an Eleventy project. This plugin is required to enable LiveCodes integration within Eleventy's markdown processing pipeline.
```bash
npm install -D markdown-it-livecodes
```
--------------------------------
### Install and Use marked-livecodes
Source: https://livecodes.io/docs/markdown-to-livecodes.html
This snippet demonstrates installing marked and marked-livecodes, followed by using the plugin to parse markdown input with a JavaScript code block, generating an iframe output.
```bash
npm install marked marked-livecodes
```
```javascript
import marked from "marked";
import markedLivecodes from "marked-livecodes";
const input = "```js livecodes \nconsole.log('Hello World!');\n```";
const output = await marked
.use(markedLivecodes, {
/* options */
})
.parse(input);
console.log(output); //
```
--------------------------------
### SCSS Configuration Example
Source: https://livecodes.io/docs/api/interfaces/EmbedOptions.html
Example of configuring SCSS (Sassy CSS) for styling in LiveCodes projects. The 'scss' property is set to 'any', allowing for SCSS input.
```json
{
"customSettings": {
"scss": "any"
}
}
```
--------------------------------
### BBCode Example
Source: https://livecodes.io/docs/llms-full.txt
Demonstrates the usage of BBCode markup within LiveCodes. BBCode is a lightweight markup language used for formatting text, similar to HTML but with a different syntax.
```bbcode
[i]Text[/i]
```
--------------------------------
### Go Example with JavaScript Interoperability in LiveCodes
Source: https://livecodes.io/docs/languages/go.html
This example showcases Go code running in LiveCodes with direct JavaScript interoperability and DOM access. It uses the `syscall/js` package to interact with the browser's JavaScript environment.
```go
// Example Go code demonstrating JS interop and DOM access
// (Actual code would be provided in the LiveCodes editor)
```
--------------------------------
### LiveCodes Pre-rendered Vento Example
Source: https://livecodes.io/docs/llms-full.txt
Demonstrates using LiveCodes with a pre-rendered Vento template. Similar to the Twig example, it configures the Vento markup and provides data via custom settings for compile-time rendering.
```tsx
import LiveCodes from '../../src/components/LiveCodes.tsx';
export const config = {
markup: { language: 'vento', content: 'Hello, {{ name }}!' },
customSettings: { template: { data: { name: 'LiveCodes' } } },
};
export const params = { compiled: 'open' };
```
--------------------------------
### Example LiveCodes URL with Query Parameters
Source: https://livecodes.io/docs/configuration/query-params.html
This example demonstrates how to use URL query parameters to configure the LiveCodes application. The 'js' parameter sets the JavaScript code to run, and the 'console' parameter opens the console. This allows for flexible and convenient app configuration directly through the URL.
```plaintext
https://livecodes.io?js=console.log('Hello World!')&console=open
```
--------------------------------
### Embed LiveCodes Playground with Initial Configuration
Source: https://livecodes.io/docs/llms-full.txt
An example of an embedded, editable LiveCodes playground using the SDK. It includes initial configuration for markup, script, and tool settings.
```jsx
```
--------------------------------
### LiveCodes Component Example: HTML Only
Source: https://livecodes.io/docs/llms-full.txt
Renders a LiveCodes component with only HTML content. This example showcases basic HTML elements and assumes no additional JavaScript or CSS is needed.
```typescript
import LiveCodes from '../../src/components/LiveCodes.tsx';
export const htmlOnlyConfig = {
markup: {
language: 'html',
content: `
Hello, LiveCodes!
This is a paragraph in HTML.
Simple
Structured
Semantic
`,
},
}
```
--------------------------------
### CoffeeScript Example
Source: https://livecodes.io/docs/llms-full.txt
Illustrates the usage of CoffeeScript within the LiveCodes environment. CoffeeScript is a language that compiles into JavaScript, offering a more concise syntax.
```coffeescript
# Example CoffeeScript code
alert "Hello, LiveCodes!"
```
--------------------------------
### LiveCodes Lite Mode Configuration
Source: https://livecodes.io/docs/llms-full.txt
Demonstrates the 'lite' mode of LiveCodes, which loads a minimal code editor with limited playground features. This example uses a configuration object and specifies a React template.
```javascript
import LiveCodes from '../../src/components/LiveCodes.tsx';
```
--------------------------------
### Install gatsby-remark-livecodes for Gatsby
Source: https://livecodes.io/docs/llms-full.txt
This command installs the `gatsby-remark-livecodes` package as a development dependency for a Gatsby project. This plugin is essential for incorporating live code block functionality into Gatsby sites processed by `gatsby-transformer-remark`.
```bash
npm install -D gatsby-remark-livecodes
```
--------------------------------
### Install and Use LiveCodes SDK with a Bundler
Source: https://livecodes.io/docs/llms-full.txt
This snippet demonstrates how to install the LiveCodes SDK using npm and then use it to create an embedded playground within a web page. It requires a bundler like Webpack or Parcel. The `createPlayground` function takes a selector for the container element and an options object to configure the playground.
```bash
npm install livecodes
```
```javascript
import { createPlayground } from 'livecodes';
createPlayground('#container', {
template: 'react',
// other embed options
});
```
--------------------------------
### Example Query Parameters for LiveCodes Configuration
Source: https://livecodes.io/docs/configuration/query-params.html
Demonstrates how to set various configuration options for LiveCodes using URL query parameters. This includes setting theme, delay, and line numbers.
```html
?theme=light&delay=500&lineNumbers=false
```
--------------------------------
### Nunjucks Dynamic Example
Source: https://livecodes.io/docs/llms-full.txt
Illustrates a dynamic Nunjucks template where the `name` variable is set via JavaScript at runtime. This example highlights the dynamic mode of Nunjucks in LiveCodes.
```html
```
--------------------------------
### MDX Configuration Example
Source: https://livecodes.io/docs/languages/mdx.html
This snippet demonstrates the configuration object for MDX in LiveCodes. It includes content for markup (MDX), styling (CSS), and scripting (JSX/React), defining how the MDX content will be rendered.
```javascript
export const mdxConfig = {
markup: {
language: 'mdx',
content: `import { Counter } from './script';
# Counter
`,
},
style: {
language: 'css',
content: `body, body button {
text-align: center;
font: 1em sans-serif;
}`,
},
script: {
language: 'jsx',
content: `import { useState } from "react";
export function Counter() {
const [count, setCount] = useState(0);
return (
You clicked {count} times.
);
}`,
},
}
```
--------------------------------
### Multi-Component Vue Setup with Markup and Script Editors
Source: https://livecodes.io/docs/llms-full.txt
Illustrates a multi-component Vue setup where a main component in the markup editor imports and uses a component defined in the script editor. Supports relative imports and passing props. Includes basic Tailwind CSS import via a style processor.
```vue
export const multi = {
markup: {
language: 'vue',
content: `
`,
},
script: {
language: 'vue',
content: `
{{ count }}
`,
},
style: {
language: 'css',
content: '@import "tailwindcss";
',
},
processors: ['tailwindcss'],
}
```
--------------------------------
### Install remark-livecodes for Astro
Source: https://livecodes.io/docs/llms-full.txt
This command installs the `remark-livecodes` npm package as a development dependency for an Astro project. This plugin is necessary for enabling LiveCodes functionality within Astro markdown or MDX files.
```bash
npm install -D remark-livecodes
```
--------------------------------
### PHP (Wasm) Starter Template
Source: https://livecodes.io/docs/llms-full.txt
Provides a link to the official LiveCodes starter template for PHP (Wasm), allowing users to quickly begin experimenting with PHP in the browser.
```url
https://livecodes.io/?template=php-wasm
```
--------------------------------
### JavaScript Example for Import Maps
Source: https://livecodes.io/docs/llms-full.txt
This JavaScript code demonstrates how to import modules using bare specifiers. LiveCodes automatically generates an import map for these imports in the result page. This example shows imports for 'moment' and 'lodash'.
```javascript
import moment from 'moment';
import { partition } from 'lodash';
```
--------------------------------
### Create LiveCodes Playground with React SDK
Source: https://raw.githubusercontent.com/live-codes/livecodes/refs/heads/develop/README
This example shows how to integrate LiveCodes into a React application using the provided React wrapper component. It defines the playground configuration and renders the LiveCodes component.
```jsx
import LiveCodes from 'livecodes/react';
const config = {
markup: {
language: 'markdown',
content: '# Hello World!',
},
};
const Playground = () => ;
export default Playground;
```
--------------------------------
### Ruby Class and Method Example
Source: https://livecodes.io/docs/languages/ruby.html
Demonstrates defining a Ruby class 'User' with an initializer and an 'admin?' method. It shows object instantiation and method calls, with output directed to the console. This example utilizes Ruby's core syntax and standard object-oriented features.
```ruby
class User
attr_accessor :name
def initialize(name)
@name = name
end
def admin?
@name == 'Admin'
end
end
user = User.new('Bob')
# the output will go to the console
puts user
puts user.admin?
```
--------------------------------
### art-template: Compiler Custom Settings Example (JSON)
Source: https://livecodes.io/docs/languages/art-template.html
Provides custom settings for the art-template compiler, passed as a JSON object to the `compile` method. This example disables minimization by setting `minimize` to `false`.
```json
{
"art-template": {
"minimize": false
}
}
```
--------------------------------
### BBCode Example in LiveCodes (TypeScript/React)
Source: https://livecodes.io/docs/languages/bbcode.html
This snippet demonstrates how to configure and use the LiveCodes component to render BBCode. It specifies the language as 'bbcode' and provides sample content. The compilation behavior is set to 'open'.
```typescript
import LiveCodes from '../../src/components/LiveCodes.tsx';
export const config = {markup: {language: 'bbcode', content: '[i]Text[/i]'}};
export const params = {compiled: 'open'};
```
--------------------------------
### Welcome Screen Configuration
Source: https://livecodes.io/docs/llms-full.txt
Control the display of the welcome screen when the application loads.
```APIDOC
## `welcome`
### Description
Determines whether the welcome screen is displayed when the LiveCodes application loads.
### Method
Configuration (setting a property)
### Parameters
#### Request Body
- **welcome** (boolean) - Optional - If `true`, the welcome screen is shown. Defaults to `true`.
### Request Example
```json
{
"welcome": false
}
```
### Response
#### Success Response (200)
- **welcome** (boolean) - The current state of the welcome screen display.
#### Response Example
```json
{
"welcome": false
}
```
```
--------------------------------
### MJML Example Usage
Source: https://livecodes.io/docs/llms-full.txt
Demonstrates how to use the LiveCodes component to render MJML templates. It shows loading a template directly or from a URL.
```jsx
import LiveCodes from '../../src/components/LiveCodes.tsx';
export const params = {
mjml: '\n\t\n\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t\t\tHello World!\n\t\t\t\t\n\t\t\t\n\t\t\n\t\n\n',
};
```
--------------------------------
### Configuration Properties
Source: https://livecodes.io/docs/llms-full.txt
Details on specific configuration properties like welcome screen, word wrap, and zoom level.
```APIDOC
## Configuration Properties
### welcome
> **welcome**: `boolean`
If `true`, the [welcome screen](https://livecodes.io/docs/features/welcome) is displayed when the app loads.
### wordWrap
> **wordWrap**: `boolean`
Enables word-wrap for long lines.
#### Default
```ts
false
```
### zoom
> **zoom**: `0.25` | `0.5` | `1`
Sets result page [zoom level](https://livecodes.io/docs/features/result#result-page-zoom).
```
--------------------------------
### Get and Set Configuration - JavaScript
Source: https://context7
Demonstrates how to retrieve and modify playground configuration at runtime. It initializes a playground, gets the current configuration using `getConfig()`, modifies it, and then applies the new configuration using `setConfig()`.
```javascript
import { createPlayground } from 'livecodes';
createPlayground('#container').then(async (playground) => {
// Get current configuration
const config = await playground.getConfig();
console.log('Current config:', config);
// Load new configuration
const newConfig = {
markup: {
language: 'html',
content: '
Updated Content
'
},
tools: {
enabled: ['console', 'compiled'],
active: 'console',
status: 'open'
}
};
await playground.setConfig(newConfig);
console.log('Config updated');
});
```
--------------------------------
### Svelte Component Development in LiveCodes
Source: https://context7_llms
Guides for building Svelte components with LiveCodes. Covers Svelte's templating syntax and reactivity.
```svelte
```
--------------------------------
### Haml Dynamic Example Configuration | TypeScript/JavaScript
Source: https://livecodes.io/docs/languages/haml.html
Example configuration for LiveCodes using Haml in dynamic mode. It includes Haml content, JavaScript for dynamic data assignment, and custom settings to disable pre-rendering.
```typescript
export const config2 = {
markup: { language: 'haml', content: '%p Hello, #{name}!' },
script: {
language: 'javascript',
content: 'window.livecodes.templateData = { name: "LiveCodes" };',
},
customSettings: { template: { prerender: false } },
activeEditor: 'script',
};
```
--------------------------------
### LiveCodes Lite Mode Example (URL)
Source: https://livecodes.io/docs/features/display-modes.html
This URL demonstrates accessing LiveCodes in 'lite' mode, which loads a lightweight editor with limited playground features. This mode is suitable for scenarios requiring minimal resources.
```url
https://livecodes.io/?mode=lite&template=react
```
--------------------------------
### doT Dynamic Example with LiveCodes
Source: https://livecodes.io/docs/languages/dot.html
This LiveCodes configuration demonstrates doT's dynamic rendering. It includes the template, JavaScript to set runtime data, and custom settings to enable dynamic mode.
```javascript
export const config2 = {
markup: { language: 'dot', content: 'Hello, {{= it.name }}!' },
script: {
language: 'javascript',
content: 'window.livecodes.templateData = { name: "LiveCodes" };',
},
customSettings: { template: { prerender: false } },
activeEditor: 'script',
};
```
--------------------------------
### Gleam Starter Template
Source: https://livecodes.io/docs/llms-full.txt
A basic Gleam starter template for LiveCodes, demonstrating the integration of standard library functions, custom modules, external functions, and NPM modules.
```gleam
import gleam/io
// Example of an external function (replace with actual implementation if needed)
@external(javascript, "some_external_module", "some_function")
pub fn external_function(input: String) -> String
// Example of an NPM module (replace with actual usage if needed)
@external(javascript, "npm:some_npm_package", "exported_function")
pub fn npm_function(data: String) -> String
pub fn main() {
io.println("Gleam starter template is running!")
// Uncomment and adapt the following lines to test external/npm modules:
// let result_external = external_function("test input")
// io.println("External function result: " ++ result_external)
// let result_npm = npm_function("npm data")
// io.println("NPM function result: " ++ result_npm)
}
```
--------------------------------
### HTML Configuration for LiveCodes Demo
Source: https://livecodes.io/docs/languages/html.html
This configuration demonstrates a basic HTML-only setup for LiveCodes, showcasing how to define HTML content within the markup editor. It's useful for simple HTML examples and testing.
```javascript
export const htmlOnlyConfig = {
markup: {
language: 'html',
content: `
Hello, LiveCodes!
This is a paragraph in HTML.
Simple
Structured
Semantic
`,
},
}
```
--------------------------------
### Jinja: Pre-rendered Example with Navigation and Variable
Source: https://livecodes.io/docs/llms-full.txt
Demonstrates a complete LiveCodes configuration for Jinja templating in pre-rendered mode. It includes Jinja markup for a navigation list and a variable, along with static data provided in custom settings.
```javascript
export const config = {
markup: { language: 'jinja', content: `
{{ a_variable }}
` },
customSettings: { template: { data: {
navigation: [
{ href: "/", caption: "Home" },
{ href: "/about", caption: "About" },
{ href: "/contact", caption: "Contact" },
],
a_variable: "Hello World!",
} } },
};
export const params = { compiled: 'open' };
```
--------------------------------
### SolidJS with TypeScript in LiveCodes
Source: https://livecodes.io/docs/llms.txt
This example shows how to use SolidJS with TypeScript in LiveCodes. TypeScript adds static typing to JavaScript, improving code quality and maintainability. The setup is handled internally by LiveCodes.
```tsx
import { Component, createSignal } from 'solid-js';
interface CounterProps {
initialCount?: number;
}
const Counter: Component = ({ initialCount = 0 }) => {
const [count, setCount] = createSignal(initialCount);
return (
);
};
export default Counter;
```
--------------------------------
### Common Lisp Example
Source: https://livecodes.io/docs/llms-full.txt
Demonstrates basic Common Lisp syntax and functionality in LiveCodes, which uses JSCL as its Common Lisp to JavaScript compiler. It highlights basic Lisp operations.
```commonlisp
(defun greet (name) (format t "Hello, ~a!~%" name))
(greet "LiveCodes")
```
--------------------------------
### React-Markdown: Use remark-livecodes Plugin
Source: https://livecodes.io/docs/markdown-to-livecodes.html
This example demonstrates how to integrate the remark-livecodes plugin with the react-markdown component to render markdown content containing live code blocks. It involves installing the 'remark-livecodes' package and passing the plugin to the remarkPlugins prop.
```bash
npm install remark-livecodes
```
```jsx
import Markdown from 'react-markdown';
import remarkLivecodes from 'remark-livecodes';
const markdown = '```jsx livecodes\nexport default () =>
Hello World
\n```';
export default () => (
{markdown}
);
```
--------------------------------
### Python (Wasm): Stemming words with snowballstemmer
Source: https://livecodes.io/docs/languages/python-wasm.html
Demonstrates using the 'snowballstemmer' library within a Pyodide environment to stem English words. This example highlights direct import of standard Pyodide packages without explicit installation.
```python
import snowballstemmer
stemmer = snowballstemmer.stemmer('english')
print(stemmer.stemWords('go goes going gone'.split()))
```
--------------------------------
### setConfig()
Source: https://livecodes.io/docs/llms-full.txt
Loads a new project configuration into the playground. Accepts a partial configuration object.
```APIDOC
## setConfig(config)
### Description
Loads a new project using the passed configuration object.
### Method
`setConfig(config: Partial): Promise`
### Parameters
#### Request Body
- **config** (Partial) - Required - The configuration object for the new project.
### Response
#### Success Response (200)
- **Config** - The updated configuration object after loading the new project.
### Request Example
```ts
import { createPlayground } from "livecodes";
createPlayground("#container").then(async (playground) => {
const config = {
markup: {
language: "html",
content: "Hello World!",
},
};
const newConfig = await playground.setConfig(config);
// new project loaded
});
```
```
--------------------------------
### Multiple Editor Themes Example - TypeScript
Source: https://livecodes.io/docs/llms-full.txt
Demonstrates how to specify multiple editor themes, including different themes for different editors and light/dark variants. This offers granular control over the editor's styling.
```typescript
"monaco:twilight, codemirror:one-dark"
```
```typescript
["vs@light"]
```
```typescript
["vs@light", "vs-dark@dark"]
```
```typescript
["monaco:vs@light", "codemirror:github-light@light", "dracula@dark"]
```
--------------------------------
### Configuration Management
Source: https://livecodes.io/docs/llms-full.txt
APIs for retrieving and setting the playground's configuration.
```APIDOC
## GET /api/config/get
### Description
Retrieves the current configuration object of the playground. This configuration can be used to restore the playground state or be manipulated and loaded at runtime.
### Method
GET
### Endpoint
/api/config/get
### Parameters
#### Query Parameters
- **contentOnly** (boolean) - Optional - If true, returns only the content-related configuration.
### Request Body
None
### Request Example
```json
{}
```
### Response
#### Success Response (200)
- **config** (object) - The playground configuration object. Structure depends on the playground's state and options.
#### Response Example
```json
{
"config": {
"markup": {
"language": "html",
"content": "
Hello
"
},
"style": {
"language": "css",
"content": "h1 { color: red; }"
},
"script": {
"language": "javascript",
"content": "console.log('Hi');"
}
}
}
```
```
```APIDOC
## POST /api/config/set
### Description
Sets the playground's configuration with a provided configuration object. This can be used to load a previously saved state or apply new settings.
### Method
POST
### Endpoint
/api/config/set
### Parameters
#### Request Body
- **config** (object) - Required - The configuration object to apply to the playground.
### Request Example
```json
{
"config": {
"markup": {
"language": "html",
"content": "
New Content
"
}
}
}
```
### Response
#### Success Response (200)
- **message** (string) - Indicates successful configuration update.
#### Response Example
```json
{
"message": "Configuration updated successfully."
}
```
```
--------------------------------
### Docusaurus MDX Code Block Example
Source: https://livecodes.io/docs/overview.html
This snippet demonstrates how to use MDX components within Docusaurus to render a list of documentation cards. It imports necessary components and utilizes a hook to get items from the current sidebar category.
```mdx
import DocCardList from '@theme/DocCardList';
import {useCurrentSidebarCategory} from '@docusaurus/theme-common';
```
--------------------------------
### run()
Source: https://livecodes.io/docs/llms-full.txt
Executes the project's code, compiling it if necessary, and displays the result in the result pane.
```APIDOC
## run()
### Description
Runs the result page, performing any necessary compilation for the code.
### Method
`run(): Promise`
### Response
#### Success Response (200)
- No specific fields returned, operation is a void promise.
### Request Example
```ts
import { createPlayground } from "livecodes";
createPlayground("#container").then(async (playground) => {
await playground.run();
// new result page is displayed
});
```
```
--------------------------------
### Create LiveCodes Playground with URL Parameters
Source: https://livecodes.io/docs/llms-full.txt
Initializes a LiveCodes playground using URL query parameters for configuration. This method is an alternative to providing a full configuration object and can be simpler for basic setups, such as embedding markdown content. It requires the 'livecodes' SDK to be imported.
```javascript
import { createPlayground } from 'livecodes';
createPlayground('#container', { params: { md: '# Hello World!' } });
```
--------------------------------
### Vue SFC with Languages and Pre-processors
Source: https://livecodes.io/docs/languages/vue.html
Shows how to utilize different languages and pre-processors within Vue Single-File Components (SFCs) using the `lang` attribute. This example demonstrates using Pug for the template, TypeScript for the script with `setup` syntax, and SCSS for the styles, showcasing LiveCodes' flexibility with various language syntaxes.
```html
h1 {{ msg }}
```
--------------------------------
### Create LiveCodes Playground with Configuration
Source: https://livecodes.io/docs/llms-full.txt
Initializes a LiveCodes playground within a specified container element using a configuration object. This allows for detailed setup of the playground's initial state, including markup language and content. It requires the 'livecodes' SDK to be imported.
```javascript
import { createPlayground } from 'livecodes';
createPlayground('#container', {
config: {
markup: {
language: 'markdown',
content: '# Hello World!',
},
},
});
```
--------------------------------
### JavaScript Configuration Example
Source: https://livecodes.io/docs/api/interfaces/EmbedOptions.html
Example of setting the script type to JavaScript for a LiveCodes project. This can be set to various JavaScript subtypes.
```json
{
"customSettings": {
"scriptType": "application/javascript"
}
}
```
--------------------------------
### Babel Configuration Example - JSON
Source: https://livecodes.io/docs/languages/babel.html
Demonstrates the default Babel configuration used by the toolchain. This JSON object specifies presets for environment compatibility, TypeScript support, and React integration.
```json
{
"babel": { "presets": [["env", { "modules": false }], "typescript", "react"]
}
}
```
--------------------------------
### LiveCodes Result Only Mode with Template
Source: https://livecodes.io/docs/llms-full.txt
Shows the 'result' mode, which displays only the result page with an option to open the full playground. This example uses the 'params' prop to set the mode and template.
```javascript
import LiveCodes from '../../src/components/LiveCodes.tsx';
```
--------------------------------
### setConfig() API
Source: https://livecodes.io/docs/llms-full.txt
Loads a new project into the playground using the provided configuration object.
```APIDOC
## setConfig(config)
### Description
Loads a new project into the playground using the provided configuration object.
### Method
`setConfig`
### Endpoint
N/A (Client-side SDK method)
### Parameters
#### Request Body
- **config** (Partial) - Required - The configuration object for the new project.
- **markup** (object) - Optional - Configuration for the markup.
- **language** (string) - Optional - The language of the markup (e.g., 'html').
- **content** (string) - Optional - The content of the markup.
### Request Example
```javascript
const config = {
markup: {
language: "html",
content: "Hello World!",
},
};
const newConfig = await playground.setConfig(config);
```
### Response
#### Success Response (Config)
Returns a Promise that resolves with the updated configuration object of the playground.
- **config** (Config) - The current configuration of the playground.
#### Response Example
```json
{
"markup": {
"language": "html",
"content": "Hello World!"
}
}
```
```
--------------------------------
### Example Editor Theme Configurations - TypeScript
Source: https://livecodes.io/docs/llms-full.txt
Illustrates various ways to configure editor themes using the EditorConfig interface. This includes single themes, multiple themes for different editors, and themes with specific light/dark variants.
```typescript
// Single theme
"vs"
// Multiple themes for different editors
"monaco:twilight, codemirror:one-dark"
// Array of themes
["vs@light"]
// Array of themes with variants
["vs@light", "vs-dark@dark"]
// Mixed array of specific and general themes
["monaco:vs@light", "codemirror:github-light@light", "dracula@dark"]
```