# LiveCodes > LiveCodes is a feature-rich, open-source, client-side code playground that supports React, Vue, Svelte, Solid, JavaScript, TypeScript, CSS, Sass, Tailwind CSS, Python, Go, Ruby, PHP, and 90+ languages/frameworks. A large number of starter templates are available to help you get started quickly. Projects can be saved, shared, exported (e.g. to GitHub Gists), deployed (e.g. to GitHub Pages), or embedded in web pages. A powerful yet easy-to-use SDK enables the creation of and communication with embedded playgrounds. With extensive language support and high configurability, LiveCodes can easily adapt to your needs. It offers excellent mobile support, featuring a responsive layout and a touch-friendly code editor. LiveCodes is an outstanding tool for learning, teaching, prototyping, sharing, and testing code. It can be easily self-hosted, if needed, on any static file server. LiveCodes is completely free for unlimited use, with no ads and no account required. Its MIT License also permits commercial use. - [Docs](https://livecodes.io/docs/llms.txt) - [Full Docs](https://livecodes.io/docs/llms-full.txt) - [README](https://raw.githubusercontent.com/live-codes/livecodes/refs/heads/develop/README.md) # LiveCodes A Code Playground That Just Works!

A [feature-rich](https://livecodes.io/docs/features/), open-source, **client-side** code playground for React, Vue, Svelte, Solid, Typescript, Python, Go, Ruby, PHP and [90+ languages/frameworks](https://livecodes.io/docs/languages/). [![LiveCodes: uptime status](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/live-codes/upptime/master/api/live-codes/uptime.json)](https://status.livecodes.io) [![LiveCodes: app version](https://img.shields.io/github/v/release/live-codes/livecodes?label=app)](https://livecodes.io) [![LiveCodes: npm version](https://img.shields.io/npm/v/livecodes)](https://www.npmjs.com/package/livecodes) [![LiveCodes: npm downloads](https://img.shields.io/npm/dm/livecodes)](https://www.npmjs.com/package/livecodes) [![LiveCodes: jsdelivr downloads](https://data.jsdelivr.com/v1/package/npm/livecodes/badge?style=rounded)](https://www.jsdelivr.com/package/npm/livecodes) [![LiveCodes: languages](https://img.shields.io/badge/languages-98-blue)](https://livecodes.io/docs/languages/) [![LiveCodes: docs](https://img.shields.io/badge/Documentation-575757?logo=gitbook&logoColor=white)](https://livecodes.io/docs/) [![LiveCodes: llms.txt](https://img.shields.io/badge/llms.txt-575757?logo=googledocs&logoColor=white)](https://livecodes.io/docs/llms.txt) [![LiveCodes: llms-full.txt](https://img.shields.io/badge/llms--full.txt-575757?logo=googledocs&logoColor=white)](https://livecodes.io/docs/llms-full.txt) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/3d39f15618e048db9d13c2a0e8002b33)](https://app.codacy.com/gh/live-codes/livecodes/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade) [![Lokalise: translated](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/live-codes/lokalise-badge/main/badges/translated.json)](https://app.lokalise.com/public/34958094667a72e9454592.95108106/) [![Lokalise: UI languages](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/live-codes/lokalise-badge/main/badges/languages.json)](https://app.lokalise.com/public/34958094667a72e9454592.95108106/) [![license - MIT](https://img.shields.io/github/license/live-codes/livecodes)](https://github.com/live-codes/livecodes/blob/develop/LICENSE) [![LiveCodes: GitHub repo](https://img.shields.io/github/stars/live-codes/livecodes?style=flat&logo=github)](https://github.com/live-codes/livecodes) [![LiveCodes: GitHub repo](https://img.shields.io/github/forks/live-codes/livecodes?style=flat&logo=github)](https://github.com/live-codes/livecodes) [![Follow us on X (formerly Twitter)](https://img.shields.io/badge/Follow%20@livecodes__io-575757?logo=x)](https://x.com/livecodes_io) [Try it now on livecodes.io](https://livecodes.io) [Documentations](https://livecodes.io/docs) [What makes LiveCodes different?](https://livecodes.io/docs/why) ![LiveCodes list of languages screenshot](https://dev.livecodes.io/docs/img/screenshots/livecodes-overview.jpg) ## A Code Playground That Just Works! - No servers to configure (or pay for!) - No databases to maintain (or pay for!) - No installs - No configuration files - No build steps - No subscription fees (free and open-source) - No account required \* - No limits for usage (unlimited private projects) - 90+ languages/frameworks/processors - Large set of features and integrations - Import code from a wide variety of sources - Use modules from npm, deno.land/x, jsr, GitHub, and others - Easily embed it in your web pages - It runs in the browser (client-side) \* GitHub account is required only for features that use GitHub Integration. ### Quick Start #### Standalone App 1. Go to [livecodes.io](https://livecodes.io) ... and enjoy all the [features](https://livecodes.io/docs/features/)! #### Embedded Playground Add this code to your page: ```html
``` Check documentations for Embedded Playgrounds. #### Self-hosted 1. Download a [release](https://github.com/live-codes/livecodes/releases) 2. Put it on a static file server (for free!) 1, 2, 3, 4 Check the guide for self-hosting (including the built-in setup to deploy to GitHub Pages). ... and it just works! ## Feature Summary - A wide range of [language support](https://livecodes.io/docs/languages/) (90+ languages/frameworks/processors) - [Powerful Editor](https://livecodes.io/docs/features/editor-settings) - Mobile-friendly - [External resources/libraries](https://livecodes.io/docs/features/external-resources) - [Import modules](https://livecodes.io/docs/features/module-resolution) from npm, deno.land/x, jsr, GitHub and others - [Code Pre-fill](https://livecodes.io/docs/features/code-prefill) - [Import](https://livecodes.io/docs/features/import)/[Export](https://livecodes.io/docs/features/export) [projects](https://livecodes.io/docs/features/projects) - [Share](https://livecodes.io/docs/features/share) - [Embed the playground](https://livecodes.io/docs/features/embeds) in any web page - [Display modes](https://livecodes.io/docs/features/display-modes) - [Deploy](https://livecodes.io/docs/features/deploy) - [Starter Templates](https://livecodes.io/docs/features/templates) - [Assets](https://livecodes.io/docs/features/assets) - [Themes](https://livecodes.io/docs/features/themes) - [Dev Tools](https://livecodes.io/docs/features/tools-pane) ([console](https://livecodes.io/docs/features/console), [compiled code viewer](https://livecodes.io/docs/features/compiled-code), [test runner](https://livecodes.io/docs/features/tests)) - [Code formatting](https://livecodes.io/docs/features/code-format) - [Intellisense](https://livecodes.io/docs/features/intellisense) - [Lite mode](https://livecodes.io/docs/features/lite) - [Read-only mode](https://livecodes.io/docs/features/read-only) - [Broadcast](https://livecodes.io/docs/features/broadcast) - [Sync](https://livecodes.io/docs/features/sync) - [Backup/Restore](https://livecodes.io/docs/features/backup-restore) - [Client-side!](https://livecodes.io/docs/why#client-side) - Very [configurable](https://livecodes.io/docs/configuration/) - Developer-friendly build-free environment - Powerful [SDK](https://livecodes.io/docs/sdk/) (available for [JavaScript, TypeScript](https://livecodes.io/docs/sdk/js-ts), [React](https://livecodes.io/docs/sdk/react), [Vue](https://livecodes.io/docs/sdk/vue), [Svelte](https://livecodes.io/docs/sdk/svelte), [Solid](https://livecodes.io/docs/sdk/solid), [Preact](https://livecodes.io/docs/sdk/preact) and [web components](https://livecodes.io/docs/sdk/web-components)) - Comprehensive [Documentations](https://livecodes.io/docs/) - Focused on [privacy and security](https://livecodes.io/docs/features/security) - Free and [Open-Source](https://livecodes.io/docs/license) For details check the [full list of features](https://livecodes.io/docs/features/). ## LiveCodes SDK The Software Development Kit (SDK) provides an easy, yet powerful, interface to embed and communicate with LiveCodes playgrounds. The SDK is provided as a light-weight [npm package](https://livecodes.io/docs/sdk/#npm-package) (or [jsr package](https://livecodes.io/docs/sdk/#jsr)), that is also available from [CDNs](https://livecodes.io/docs/sdk/#cdn). It can be used to create playgrounds with a wide variety of [configurations](https://livecodes.io/docs/configuration/configuration-object) and [embed options](https://livecodes.io/docs/sdk/js-ts#embed-options). In addition, [SDK methods](https://livecodes.io/docs/sdk/js-ts#sdk-methods) allow programmatic communication and control of the playgrounds during runtime. ### Installation ``` npm i livecodes ``` ### Usage Example: ([open in LiveCodes](https://livecodes.io/?x=code/N4IgLglmA2CmIC4QBkIDdYGED2ATWAzgAQDKAIgNJH4C22IANCPgQMYBOEADpNgHaIQjEAAtYAQ1yCAPDVhhxRViPHsC8gLwAdEAFUAKgDEAtAA4dRAPQA+LX1nzFfcXO0g0EWAHcu2dmAtWfjBYPjA3LwhcMBENfA9WWGNI6JEGIgg+KAhxaGM2XNgNAEYAOgAGCxthETAaaABBMDA1QWhxPgBzN1DA9oICNx1hBU6CRABtAF0mcVZIDABRXCg-QTZOHmEaVQBrAFcuRFB2rv3xTvgkWvrhILDQsBkVtAzcN3uFTNh2HWtpSwvawgAC+TAIYAAnnBjiBTp1zpdBKwBndgo9BKDwRxuE8ECcOgiLlcQAArcRocQbXFoh5hQQQGi+fxEYBKdgSEIABXakM67Gw+z4uCIIKIADMBTQiAByaDoWBBFgygDcWl+fHVdg4nNgPPEfIFQtwAAoZQBiT7ib7sGXpYBavhEJT8cUQToIVmO53OnbsA5cT0OjU+n3wxGwT0yv27XDYLx8O3e0MuulgKPmogACVg0Gg2CIAHU-NBcABCJMhn1g5M1qsebxRjkEfbQMCVuwggCUao1WJAEOhhDE8nGCGm2M2YDHE5AKIIXOb8kxTC4AsSAz8M5mc-2EOwNBI8kgXTHwDBIEZzOnxwvUK4hFvTBCELPcMJEcE98IOK2TE+GJIP2GBqBA-CCAAzBBIzYNg0BvqE4gAEZwFISC5NAwhzAsJL3AQcHwOCChgHuyL5uoUggiCQA)) ```js import { createPlayground } from 'livecodes'; createPlayground('#container', { config: { markup: { language: 'markdown', content: '# Hello World!', }, }, view: 'result', }); ``` The [JavaScript SDK](https://livecodes.io/docs/sdk/js-ts) is framework/library agnostic. However, wrapper components are also provided for [React](https://livecodes.io/docs/sdk/react), [Vue](https://livecodes.io/docs/sdk/vue), [Svelte](https://livecodes.io/docs/sdk/svelte), [Solid](https://livecodes.io/docs/sdk/solid), [Preact](https://livecodes.io/docs/sdk/preact) and [web components](https://livecodes.io/docs/sdk/web-components). [TypeScript support](https://livecodes.io/docs/sdk/js-ts#typescript-types) provides type-safety and a great developer experience. React SDK example: ([open in LiveCodes](https://livecodes.io/?x=code/N4IgLglmA2CmIC4QBkIDdYGED2ATWAzgAQBKsAhgMZhEDKAIgNJH4C22IANCPgZQE4QADpGwA7RCC4gAFhVySAPK1hhyRSjPL8CqgLwAdEAFUAKgDEAtAA4jRAPQA+A2OWr1Y8isMg0EWADuQtj8YHaU4mCwYmA+ARC4YDJ6+H6UsJbxiTKcRBBiUBDk0JZ8xbB6AIwAdAAMdk7SMmCs0ACCYGA6ktDkYgDmPtHhvQQEPkbSav0EiADaALrcVJAYAKK4UCGSfIIi0qzaANYArkKIoL0DJ+T98EjNrdIRMdFgkiAAvtwEYACecAuICu-Rud0klDGz0ibw+3xAu2E7wQlz6oNu9xAACsCAAPaGvGKSCCsYKhIioDA4XhEABm-GwrCIAHJoOhYBFePZ+BRqMyANwGfguIUuF6-DTiWkQfpEPREYCisREIiHfinIQIBVKlUqkFg2Ba5lqo64bABMTMzg63UvKIxI0AYiIAAlYNBoNgiAB1ELQXAAQitNu+Ss+guFYnFNAACr0-v0GScxLg5UQABQASjljiIikpWDwhElYmlg2ALzLnyIfkCPh5BBO0DCIAcjgjLlguLJNHwtPITdj8cT2GTuA7EnhvwBhDkqlmCEWPwESIXS5AkIIMYbqg+3CEDPSYxCa6WG5Ov0ZtFUkAGC+A8JJPfv8P+QkIF1fhDA9+BaINkhvoQK77NwdqwkgXzcBgOgQOIkgAMwIVM2DYNAv7ROQABGcAKEgxTQNIKzshC4gEGh8A-GoYAXhCnq6AonyfEAA)) ```jsx import LiveCodes from 'livecodes/react'; const config = { markup: { language: 'markdown', content: '# Hello World!', }, }; const Playground = () => ; export default Playground; ``` Vue SDK example: ([open in LiveCodes](https://livecodes.io/?x=code/N4IgLglmA2CmIC4QBkIDdYGED2ATWAzgAQBqArrEQMoAiA0kfgLbYgA0I+BAxgE4QAHSNgB2iEOxAALWAENc4gDxNYYWUW5TZvAqoC8AHRABVACoAxALQAOI0QD0APgMjlq9SNkrDINBFgA7gLYvGB23KJgsCJgPgEQuGBSevh+3LCW8YlSbEQQIlAQstCWPMWwegCMAHQADHZOklJgTNAAgmBgOuLQsiIA5j7R4b0EBD5Gkmr9BIgA2gC6HLLckBgAorhQIeI8-EKSTNoA1mQCiKC9A2Sy-fBIza2SETHRYOIgAL4cBGAAnnALiArv0bndxNwxs9Im8Pt8QHtBO8EJc+qDbvdfBRoa8YkpEUIiLowGdnLwXEQ8kxgqEiKgMDguEQAGa8bBMIgAcmg6FgES49jQFE5AG4DOSROKKRpRL8ZSJmRB+kQ9ERgFKRJTKUdeKcBAg1RqtVqQWDYAbOTrjrhsAERJy2EbjfKojELQBiIgACVg0Gg2CIAHUQtBcABCB1OynfJ2fMUSxT2AlgMkuDWKKLU3pRVOaoiKelYPCEIgIF6KwZGctKux+QI+XiEMjQMIgBy5xOZgTZ2C5r4-f5wAgyVSzBCLH58JFjicgSEEAAKjeJHw4AjZ6TGIRnSznZF+7KoqkgAzHwHhEGpITAZ-h-wEhAud8IN6Bpox4nvhCnBw4L1dyISPCGA6BAojiAAzBBUzYNg0BniA0SyAARnAChIMU0CSCsayYi8BBwfAA6yCSY5zv6ugKJ8nxAA)) ```html ``` In addition, the SDK allows creating links to playgrounds: ```js import { getPlaygroundUrl } from 'livecodes'; const url = getPlaygroundUrl({ config: { markup: { language: 'markdown', content: '# Hello World!', }, }, }); // this URL can be shared console.log(url); ``` See [SDK docs](https://livecodes.io/docs/sdk/) for more details. ## Documentations Comprehensive documentations for [features](https://livecodes.io/docs/features/), [getting started](https://livecodes.io/docs/getting-started), [configuration](https://livecodes.io/docs/configuration/) and [SDK](https://livecodes.io/docs/sdk/) are available on: https://livecodes.io/docs/ The documentations include demos, code samples, screenshots, [Storybook](https://livecodes.io/stories) and [TypeScript types](https://livecodes.io/docs/sdk/js-ts#typescript-types). See below for documentations for [contributors](#contribution) and [AI models](#for-ai-agents). ## Updates Keep up with the latest changes: - Twitter/X: [@livecodes_io](https://twitter.com/livecodes_io) - Blog: [blog.livecodes.io](https://blog.livecodes.io/) - Development build: [dev.livecodes.io](https://dev.livecodes.io/) ## Feedback We welcome feedback! Please start a new [issue](https://github.com/live-codes/livecodes/issues/new/choose) or [discussion](https://github.com/live-codes/livecodes/discussions/new). For security reports please refer to [SECURITY.md](https://github.com/live-codes/livecodes/blob/develop/SECURITY.md). You may also reach out to us using the [contact form](https://livecodes.io/docs/contact). ## Contribution Contributions are welcome and highly appreciated. A huge shout-out to our wonderful [contributors](https://github.com/live-codes/livecodes/graphs/contributors)! Your hard work makes all the difference! Please refer to the [contribution guide](https://github.com/live-codes/livecodes/blob/HEAD/CONTRIBUTING.md) and [system documentation](https://github.com/live-codes/livecodes/blob/HEAD/docs/docs/contribution/README.md). ## For AI Agents ### llms.txt For developers working with AI agents and language models, we provide specialized documentation files following the [llms.txt specification](https://llmstxt.org/): - [llms.txt](https://livecodes.io/docs/llms.txt) - Concise documentation optimized for LLM context windows - [llms-full.txt](https://livecodes.io/docs/llms-full.txt) - Comprehensive documentation including all referenced URLs These files provide LLM-friendly content in a standardized format, helping language models understand and work with LiveCodes documentation. The format is designed to be both human and LLM readable. ### Intent Skills If you use an AI coding agent, run: ```bash npx @tanstack/intent@latest install ``` This loads the Intent skills for LiveCodes SDK. See [.agents/skills/livecodes/SKILL.md](https://github.com/live-codes/livecodes/blob/HEAD/.agents/skills/livecodes/SKILL.md) for the skill index. ### System Documentation For internal architecture and system documentation, see [docs/docs/contribution/](https://github.com/live-codes/livecodes/blob/HEAD/docs/docs/contribution/README.md). ## Credits LiveCodes uses services that are generously provided by:

Cloudflare Pages

jsDelivr

esm.sh

unpkg

DigitalOcean

bundlejs

dpaste

GitHub

Netlify

SonarCloud

Codacy

BrowserStack

Lokalise

## Third Party Packages Packages used by LiveCodes and their licenses are [listed here](https://github.com/live-codes/livecodes/blob/develop/vendor-licenses.md). ## License [MIT](https://github.com/live-codes/livecodes/blob/HEAD/LICENSE) License © [Hatem Hosny](https://github.com/hatemhosny) ## Sponsor 💚 LiveCodes is free and open-source. The app does not contain ads or require subscription. It allows unlimited usage without any restrictions. By sponsoring LiveCodes, you will be supporting the ongoing development and maintenance of the project, as well as helping to ensure that it remains a valuable resource for the developer community. Please consider [becoming a sponsor](https://livecodes.io/docs/sponsor). --- # Overview [LiveCodes](https://livecodes.io) is an [open-source](./license.html.md) client-side code playground. It is [feature-rich](./features/index.html.md) with support for [90+ languages/frameworks](./languages/index.html.md). It can be used as a [standalone app](./getting-started.html.md)#standalone-app) or [embedded](./features/embeds.html.md) in any web page. A powerful [SDK](./sdk/index.html.md) is available to facilitate embedding and communication with embedded playgrounds. The sections below include the documentation details: ```mdx-code-block import DocCardList from '@theme/DocCardList'; import {useCurrentSidebarCategory} from '@docusaurus/theme-common'; ``` --- # Why Another Playground? There are great products like [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), [JS Bin](https://jsbin.com/), [CodeSandbox](https://codesandbox.io/), [Replit](https://replit.com/) and many others, which LiveCodes does not aim to replace or compete with. On the contrary, it aims to [integrate](./features/integrations.html.md) with as many of these services as their APIs allow. ## What makes LiveCodes different? ### Language Support Currently, there are 90+ languages/frameworks supported. These include: - Web languages (HTML, CSS & JavaScript). - Web frameworks/libraries (e.g. React JSX/TSX, Vue SFC, Svelte SFC, Solid, MDX, Astro). - Languages that transpile to JavaScript (e.g. TypeScript, CoffeeScript, LiveScript, ReScript). - Languages/frameworks that generate CSS (e.g. SCSS, Less, Stylus, Tailwind CSS, UnoCSS). - CSS processors (e.g. PostCSS, Autoprefixer, Lightning CSS, CSS Modules, cssnano). - Traditional programming languages (e.g. Python, Ruby, Go, PHP, C++, R, Lua, Scheme, Perl). - Data manipulation/logic languages (e.g. SQL, Prolog). - Authoring/templating languages (e.g Markdown, AsciiDoc, Pug, Handlebars, Haml). - Low-code/visual editors (e.g. blockly, rich text editor). - Modeling languages/diagram-as-code (e.g. Gnuplot, Graphviz, Mermaid, Vega, Plotly). - Languages that target WebAssembly (e.g. AssemblyScript, WebAssembly Text Format). - ... and many more. For a full list check the [Languages](./languages/index.html.md) section. Generally, if you are a developer (or want to be one), there is a big chance you will find something interesting to do with LiveCodes. ### Client-Side! All processing and code transformations run in the browser on the client-side. After the initial load, the app gets significantly faster without having to wait for server rounds. Lazy-loading is heavily used. Only parts of the app required for the selected languages/features are downloaded. The code you write in LiveCodes does not leave your computer. All projects are private unless you choose to share/export/deploy them. Being a client-side app allows it to be hosted on any static file server or CDN, which removes the high requirements needed by other alternatives (like server storage or memory). This makes LiveCodes available for a large number of developers without requiring them to pay for servers, so it can stay free with unlimited usage 😊. ### Developer Tool LiveCodes aims to be a feature-rich, easy to use playground that can be used for prototyping and education. The other main goal (in fact, that was the motive for its development), is to allow library developers to use it for documentation of their libraries and showcase their products. This can be achieved by [embedding playgrounds](./features/embeds.html.md) in blogs, tutorials, documentation and educational websites. In addition, private (unpublished) modules can be imported with editor auto-completion and [IntelliSense](./features/intellisense.html.md). That can be done using the official app ([livecodes.io](https://livecodes.io)), or as a [self-hosted](./features/self-hosting.html.md) option. Again, being a client-side-only app, LiveCodes becomes more convenient for not needing special server requirements, while features like export and deploy are provided by APIs of external services. LiveCodes does NOT aim to be a social coding platform. It will stay as a backendless developer tool. Other platforms are already doing a great job in this regards. ### Build-Free Development Environment LiveCodes provides many of the tools you may already be using. These include Monaco editor (that powers [VS Code](https://code.visualstudio.com/)), [Prettier](https://prettier.io/), [Emmet](https://emmet.io/), [Babel](https://babeljs.io/), [TypeScript](https://www.typescriptlang.org/), [SCSS](https://sass-lang.com/), [Less](https://lesscss.org/), [PostCSS](https://postcss.org/), [Jest](https://jestjs.io/) and [Testing Library](https://testing-library.com/), among others. [NPM modules](./features/module-resolution.html.md) can be imported as usual. All these tools run seamlessly in the browser without any explicit build step. It feels like a very light-weight version of your own local development environment with the keyboard shortcuts, IntelliSense and code navigation features. It just works™ without having to `npm install` anything. Not even on the server (because there is no server!). This can markedly improve productivity, reduce the mental load required for all the traditional setup and can significantly decrease the barrier to entry for learning new technologies. ### Web Platform The output of code written in LiveCodes is a [web page](./features/result.html.md). Whatever language/syntax you use, the result can ultimately be viewed as a web page which you can interact with, [test](./features/tests.html.md), [share](./features/share.html.md) or [deploy](./features/deploy.html.md). Check the [starter templates](https://livecodes.io?screen=new) for examples. Of course, the app can be still used as a REPL with the output seen in the integrated [console](./features/console.html.md). ### Powerful SDK The LiveCodes app ([standalone](./getting-started.html.md)#standalone-app) or [self-hosted](./features/self-hosting.html.md)) can be [embedded](./features/embeds.html.md) in any web page. A powerful [SDK](./sdk/index.html.md) allows the embedding page to interact with the playground (e.g. run, get/set source code, format, get result page or compiled code, get share URL, listen to changes, run tests, get test results, change layout, etc.). This enables other apps to be built on top of LiveCodes. Your imagination is the limit! ### Free and Open-Source LiveCodes is a free product that allows unrestricted use for the hosted app and for the self-hosted option. It is licensed under the permissive [MIT license](./license.html.md) which allows free commercial use. Please consider [sponsoring LiveCodes](./sponsor.html.md) if you find it useful, to support its maintenance and continued development. :::caution Under Development LiveCodes is currently in **public beta**. It is in active development. However, please take the time to try it. Use [permanent URL](./features/permanent-url.html.md) and pinned [library version](./sdk/index.html.md) to avoid breaking changes. Your feedback and contribution are highly appreciated. ::: Enough talk, let's get started. --- # Getting Started import LiveCodes from '../src/components/LiveCodes.tsx'; There are multiple options: ## Standalone App The easiest way to get started with LiveCodes is to just use the app (https://livecodes.io). It is packed with [features](./features/index.html.md) and offers various ways to [import code](./features/import.html.md). ## Embedded Playgrounds LiveCodes playgrounds can be easily [embedded](./features/embeds.html.md) into any web page. This can be achieved using: ### App Embed Screen The [standalone app](#standalone-app) allows you to embed any project from the [embed screen](./features/embeds.html.md). The UI allows setting embed options and shows a preview of the embedded playground. Copy the generated code snippet (at the bottom of the screen) and add it to the web page that you want to embed the playground in. ### SDK LiveCodes [SDK](./sdk/index.html.md) is available as [npm package](https://www.npmjs.com/package/livecodes) to allow easy embedding and communication with playgrounds. #### Option 1: Using a bundler Install from npm. ```bash npm2yarn npm install livecodes ``` then you can use it like that: ```js title="index.js" import { createPlayground } from 'livecodes'; createPlayground('#container', { template: 'react', // other embed options }); ``` #### Option 2: Load from CDN ESM: import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import CodeBlock from '@theme/CodeBlock'; export const ESMCode = () => { const { siteConfig } = useDocusaurusContext(); return ( {`
\n`}
); }; UMD: export const UMDCode = () => { const { siteConfig } = useDocusaurusContext(); return ( {`
\n\n `}
); }; #### Add your own content You may use any of the methods to [prefill the playground](./features/code-prefill.html.md) with your own code. Example: ```js title="index.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' } }); ``` export 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', }; Live demo: (this is an interactive playground - try editing the code!) Please refer to the section on [Embedded Playgrounds](./features/embeds.html.md) for more details. ## Self-Hosting LiveCodes can be hosted on any static file server or CDN. The easiest way is to download the app from [releases](https://github.com/live-codes/livecodes/releases), extract the folder and add it to your website. Please check the section on [self-hosting](./features/self-hosting.html.md) for other methods of self-hosting, including the built-in setup to deploy to GitHub pages and how to use the SDK with the self-hosted app. --- # Features ## Overview _LiveCodes_ is an open-source, client-side, code playground that runs in the browser. It enables quick prototyping and experimenting with a wide variety of [technologies](../languages/index.html.md) (including 90+ languages, frameworks and processors) without having to manually setup a development environment for each. The [result](./result.html.md) is displayed as a regular web page. The rapid feedback of previewing the result page without waiting for build steps significantly boosts productivity. ![LiveCodes screenshot](../../static/img/screenshots/features-1.jpg) ![LiveCodes screenshot](../../static/img/screenshots/features-2.jpg) ![LiveCodes screenshot](../../static/img/screenshots/features-3.jpg) In this page, a quick overview of the important features are presented. A more detailed description of each feature is described in the following sections. ## Powerful Editor The default code editor is the powerful editor that powers [VS Code](https://code.visualstudio.com/), featuring code-completion, go-to-definition, multi-cursor support and other powerful features you got used to. The editor is very [customizable](./editor-settings.html.md). It supports [keyboard shortcuts](./keyboard-shortcuts.html.md), [code formatting](./code-format.html.md), [Emmet abbreviations](./editor-settings.html.md)#emmet) and even [Vim and Emacs bindings](./editor-settings.html.md)#editor-modes). ## Mobile-friendly The responsive layout allows working on devices with different screen sizes. On mobile, a lighter-weight touch-friendly code editor (CodeMirror 6) is used, so that you can experiment your ideas on the go. ## External Code/Libraries [External scripts/stylesheets](./external-resources.html.md) can be added to the web page. There is a UI screen that helps you search for and add NPM libraries and google fonts. Moreover, [NPM modules can be imported](./module-resolution.html.md) without the need for any `npm install`s. ## Import and Code Pre-fill Code can be [imported](./import.html.md) from a variety of sources including GitHub gist, GitHub file, directory in a GitHub repo, Gitlab snippet, Gitlab file, directory in a Gitlab repo, JS Bin, raw code, code in web page DOM and code in zip file. You can also [pre-fill code](./code-prefill.html.md) using various ways. ## Share/Export Projects can be easily [shared](./share.html.md) as URLs or QR codes. In addition, you may [export](./export.html.md) any project as HTML, JSON or zip file containing source code files. You may also export to other services like GitHub gists, CodePen or JSFiddle. ## Embed Projects can be [embedded](./embeds.html.md) in any web page. The embed screen allows you to customize the embed options and preview the resulting playground. An easy-to-use, yet powerful, [SDK](../sdk/index.html.md), that allows [communication](../sdk/js-ts.html.md)#sdk-methods) between the embedding page and the playground. ## Deploy Projects can be [deployed](./deploy.html.md) to public URLs that can be shared with others. This is hosted for free on GitHub Pages. ## Starter Templates A large number of [starter templates](./templates.html.md) are available. They can be used to get you started with most of the supported technologies. ![Starter templates](../../static/img/screenshots/templates-1.jpg) ## Assets Your own local assets (e.g. images, icons, fonts, local scripts and stylesheets) can be added to the app and then used in any project. The assets are made available even when the projects are shared, exported or deployed. ## Dev Tools [Tools](./tools-pane.html.md) like [console](./console.html.md), [compiled code viewer](./compiled-code.html.md) and [test runner](./tests.html.md) can significantly improve your development experience. ## Broadcast You can [broadcast](./broadcast.html.md) source code or result in real-time to others. This can be of great value as an educational tool and for demo purposes. ## Sync/Backup/Restore Do you work on multiple devices? No Problem! You may [sync](./sync.html.md), [backup and restore](./backup-restore.html.md) your data any time on any device. ## Themes LiveCodes comes with dark and light themes. In addition, a theme color can be set to change the app color. ## i18n LiveCodes supports [internationalization](./i18n.html.md) for multiple languages. ## Client-side! LiveCodes runs in the browser, where all the processing/transpilation occurs, with no server rounds required. So, after the initial load, it becomes pretty fast. It can be hosted on any static file server or CDN. No `npm install`s. Just the browser! ## Developer-friendly LiveCodes makes it easy to [get started](../getting-started.html.md). It is highly [configurable](../configuration/index.html.md). Lots of features can be configured by URL [query params](../configuration/query-params.html.md). The [SDK](../sdk/index.html.md) facilitates [embedding](./embeds.html.md) playgrounds and allows easy [communication](../sdk/js-ts.html.md)#sdk-methods) with them. The SDK is available for use in [JS/TS](../sdk/js-ts.html.md), [Preact](../sdk/preact.html.md), [React](../sdk/react.html.md), [Solid](../sdk/solid.html.md), [Svelte](../sdk/svelte.html.md), [Vue](../sdk/vue.html.md) and [Web Components](../sdk/web-components.html.md). ## Comprehensive Documentations Rich documentations with screenshots, code samples and live demos are available. They cover the app [features](../features/index.html.md), [configuration](../configuration/index.html.md), [supported languages](../languages/index.html.md) and [SDK](../sdk/index.html.md) (including [TypeScript Types](../api/globals.md)). A gallery of usage examples is provided as a [storybook](pathname:///../stories). ## Focused on Privacy Projects are private by default. The code you write in LiveCodes never leaves your computer, unless you choose to [share](./share.html.md), [export](./export.html.md), [broadcast](./broadcast.html.md) or [sync](./sync.html.md) it. User data is stored in the browser. ## Free and Open-Source LiveCodes is free, with no limits for use and no ads. No account is even required (unless [GitHub integration](./github-integration.html.md) is needed). Do you want to [self-host](./self-hosting.html.md) it for commercial use? No problem! It is [MIT-licensed](../license.html.md) 🎉. Please consider [sponsoring LiveCodes](../sponsor.html.md) ❤. This was a quick overview of the important features of LiveCodes. A more detailed description of each feature is described in the following sections. --- # Projects A _LiveCodes_ project is a combination of markup, styles & scripts that result in a **single web page**. Check the section about the [Result Page](./result.html.md) to have more details about how this page is constructed. There is no concept of file system or, for example, organizing multiple files in a directory structure of a single project. :::info Simple Concept code in [markup editor](#markup-editor) + code in [style editor](#style-editor) + code in [script editor](#script-editor) + [external resources](./external-resources.html.md) => [result page](./result.html.md) ::: ## Markup Editor Code added in this editor eventually represents the page markup (HTML). Examples for languages supported include HTML, Markdown, Pug, Haml. ## Style Editor Code added in this editor eventually represents the page styles (CSS). Examples for languages supported include CSS, SCSS, SASS, Less, Stylus. In addition, many CSS processors are supported (e.g. Autoprefixer, postcss-preset-env, postcss-import-url, PurgeCSS, Tailwind CSS). ## Script Editor Code added in this editor eventually represents the page scripts. These are either: - Languages compiled to JavaScript (e.g TypeScript, JSX, CoffeeScript) - Languages that are interpreted by a JavaScript runtime (e.g. PHP - interpreted by [Uniter runtime](https://github.com/asmblah/uniter), Scheme - interpreted by [BiwaScheme](https://www.biwascheme.org)) - Languages running in WASM (e.g. Python - [Pyodide](https://pyodide.org/), AssemblyScript). For the full list of supported languages, check the [Languages section](../languages/index.html.md). ## Organizing Projects Projects can be saved to the local device browser storage from Project menu → Save / Project menu → Save as → Fork (New Project) or using the keyboard shortcut Ctrl + S. The list of saved projects can be accessed from Project menu → Open. ![LiveCodes Projects](../../static/img/screenshots/saved-projects-1.jpg). Saved projects can be sorted by title or date (asc/desc). They can also be filtered by language and/or tags. You may, as well, search for a project by title or description. Project title, description and tags can be edited from Project menu → Project Info. Projects can be [imported](./import.html.md), [exported](./export.html.md), [synchronized](./sync.html.md), [backed up and restored](./backup-restore.html.md). [Assets](./assets.html.md) and [code snippets](./snippets.html.md) are stored in the browser storage and can be used across projects. ## Related - [Result Page](./result.html.md) - [Templates](./templates.html.md) - [Code Snippets](./snippets.html.md) - [Assets](./assets.html.md) - [External Resources](./external-resources.html.md) - [Import](./import.html.md) - [Export](./export.html.md) - [Backup/Restore](./backup-restore.html.md) - [Sync](./sync.html.md) - [Share](./share.html.md) - [Broadcast](./broadcast.html.md) --- # Templates import TemplateList from '../../src/components/TemplateList'; A new project can be based on any of the provided [starter templates](#starter-templates) or [user templates](#user-templates). A new project (from template) can be started from: - Project menu → New - [Welcome Screen](./welcome.html.md) → New - Direct URL: https://livecodes.io?new ## Starter Templates A Large number of starter templates are available. They act as starting points and example usage for the [languages](../languages/index.html.md) available in LiveCodes. A direct link for a starter template has the following format: `?template={template_name}` (e.g. https://livecodes.io/?template=react) The list of template names are documented [here](../api/internal/type-aliases/TemplateName.md). ### Template List The following list of starter templates are available: ## User Templates Any project loaded in LiveCodes can be saved as a user template, to be used later as a starting point for new projects. A project can be saved as a user template from Project menu → Save as → Template. It can then be accessed from Project menu → New ... → My Templates. A user template can be set as [default template](./default-template-language.html.md) to be automatically loaded when loading the app. User templates are scoped to the currently [logged-in user](./user-management.html.md). They can be [backed up/restored](./backup-restore.html.md) and [synced](./sync.html.md) the same as other user data. ## Related - [Default Template/Language](./default-template-language.html.md) - [Project](./projects.html.md) - [Code Snippets](./snippets.html.md) - [User management](./user-management.html.md) - [Backup/Restore](./backup-restore.html.md) - [Sync](./sync.html.md) - [Languages](../languages/index.html.md) --- # CSS import LiveCodes from '../../src/components/LiveCodes.tsx'; The [result page](./result.html.md) can be styled with CSS using various methods, including: ## Style Editor Code added to [style editor](./projects.html.md)#style-editor) is [compiled](#languages) and [processed](#css-processors), then added as CSS to the [result page](./result.html.md) `head` element. ![LiveCodes styles](../../static/img/screenshots/css-processors.jpg) ### Languages LiveCodes supports multiple languages that compile to CSS, including [SCSS](../languages/scss.html.md), [Sass](../languages/sass.html.md), [Less](../languages/less.html.md) and [Stylus](../languages/stylus.html.md). Code authored in any of these languages is compiled to CSS before being added to the [result page](./result.html.md). The style language can be selected from the style editor menu. In embedded playgrounds, the language can be configured via the configuration object property [`style.language`](../configuration/configuration-object.html.md)#style) ### CSS Processors The (compiled) CSS code can be processed by one or more of the supported CSS processors. Examples of these include: [Autoprefixer](../languages/autoprefixer.html.md), [postcss-preset-env](../languages/postcssPresetEnv.html.md), [Lightning CSS](../languages/lightningcss.html.md), [CSS Modules](../languages/cssmodules.html.md), [cssnano](../languages/cssnano.html.md), ...etc. Multiple CSS processors can be enabled at the same time. The code is processed in the order of processors placed in the style editor menu of the app. Processors are enabled in the [standalone app](../getting-started.html.md)#standalone-app) from the style editor menu, by switching on the toggles of the required processors. In embedded playgrounds, processors are enabled via the [`processors`](../configuration/configuration-object.html.md)#processors) property of the [configuration object](../configuration/configuration-object.html.md). ### Style Imports [Bare modules](./module-resolution.html.md)#bare-module-imports) used with `@import` rules are supposed to be npm modules. These are converted to [full URLs from CDN](./module-resolution.html.md)#cdn-providers). #### Example This code: ```css @import 'github-markdown-css/github-markdown.css'; ``` becomes: ```css @import 'https://unpkg.com/github-markdown-css/github-markdown.css'; ``` Packages that specify a stylesheet as the main module can be imported like that: ```css @import 'github-markdown-css'; ``` demo: The content can be inlined in the compiled CSS by enabling the processor [postcss-import-url](../languages/postcssImportUrl.html.md). ### Compiled CSS Compiled CSS (following compilation of style language, and all enabled processors) is added to the [result page](./result.html.md) `head` element. The compiled code can be inspected in the [compiled code viewer](./compiled-code.html.md) in the [tools pane](./tools-pane.html.md). ### Auto-update When [`autoupdate`](../configuration/configuration-object.html.md)#autoupdate) is enabled (default), in contrast to [markup editor](./projects.html.md)#markup-editor) and [script editor](./projects.html.md)#script-editor), changes in style editor code does NOT trigger a full reload of the [result page](./result.html.md). The updated CSS code is sent to the page and applied without a reload. The page can be force-reloaded by clicking the run button or using the keyboard shortcut: Shift + Enter. ## External Resources External stylesheets can be added in [external resources](./external-resources.html.md) screen. These are added to the [result page](./result.html.md) before the compiled style editor code. This allows code in style editor to override CSS properties in external stylesheets. External stylesheets can be added to embedded playgrounds using the [configuration object](../configuration/configuration-object.html.md) property [`stylesheets`](../configuration/configuration-object.html.md)#stylesheets). ## CSS Presets CSS presets like [Normalize.css](https://necolas.github.io/normalize.css/) and [Reset CSS](https://meyerweb.com/eric/tools/css/reset/) can be selected in [external resources](./external-resources.html.md)#css-presets) screen. ## Stylesheets Imported in Script Editor ### External Stylesheets CSS stylesheets imported in the script editor are added to the [result page](./result.html.md) `head` element. _The URL has to end with **`.css` extension**_. For example, adding this in the script editor (JavaScript): ```js import 'https://unpkg.com/github-markdown-css/github-markdown.css'; ``` adds this to the page `head`: ```html ``` Currently, compiling imported stylesheets (e.g. SCSS) is not supported. Similar to [imports in style editor](#style-imports), bare imports are converted to full URLs from CDN. For example: ```js import 'github-markdown-css/github-markdown.css'; ``` becomes: ```html ``` ### `./style.css` Importing the URLs (`./style.css` or `./styles.css`) gets the style editor compiled/processed CSS **string** as the module's default export. Example: ```js import styles from './style.css'; console.log(styles); // => compiled CSS as string ``` ## CSS Modules CSS modules are supported and are [documented separately](../languages/cssmodules.html.md). ## CSS Frameworks Multiple CSS frameworks are supported including [Tailwind CSS](../languages/tailwindcss.html.md), [UnoCSS](../languages/unocss.html.md) and [WindiCSS](../languages/windicss.html.md). ## Styles in Markup & Script Of course, styles and stylesheets can still be added as usual in markup and script editors (via HTML elements and/or DOM). ## Related - [Projects](./projects.html.md) - [External resources](./external-resources.html.md) - [Module resolution](./module-resolution.html.md) --- # Result Page The output of a LiveCodes project is a single HTML page. This includes the (compiled) code from editors (markup + style + script) and [external resources](./external-resources.html.md) (CSS + JS), in addition to customizations specified in [custom settings](../advanced/custom-settings.html.md). This page is loaded in a [sandboxed iframe](https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/) with a unique origin to enforce [security](./security.html.md). The page code is sent to the iframe in the browser (no code is sent to the server). ## Result page structure This is the pseudo-code for the structure of the result page (inspired by [CodePen docs](https://blog.codepen.io/documentation/preview-template/)). ```html { Config.title }* { Config.head }* { CSS preset }** { External CSS }** { Editor CSS } { Language(s) run-time CSS }*** { Language(s) run-time JS }*** { Import map }**** { Editor HTML } { External JS }** { Editor JS } { Spacing script (if enabled) }***** { Test scripts (if enabled) }****** ``` \* See [Configuration Object](../configuration/configuration-object.html.md). \*\* See [External Resources](./external-resources.html.md). \*\*\* Although most languages are compiled and then the compiled code is used, some languages require run-time scripts or styles to run in the result page. \*\*\*\* See [Module Resolution](./module-resolution.html.md). \*\*\*\*\* See [Show Sapcings](#show-spacings). \*\*\*\*\*\* See [Tests](./tests.html.md). ## Result page zoom The zoom button in the [tools pane](./tools-pane.html.md) below result page, allows you to toggle result page zoom (1x/0.5x/0.25x). ![Result page zoom](../../static/img/screenshots/zoom.jpg) ## Open in new window From the [tools pane](./tools-pane.html.md), the result page can be viewed in a separate window. ![Open in new window](../../static/img/screenshots/new-window.jpg) :::caution Please note that the URL of the result page shown in the new window is a [temporary URL](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL#parameters), for local preview. Sharing this URL will not work. If you need to share a project, use the [Share screen](./share.html.md). While, if you need to share the result page use the `result` [display mode](./display-modes.html.md) or the [broadcast](./broadcast.html.md) feature. ::: ## Show Spacings The spacing between elements on the result page can be measured by adding [Spacing.js](https://spacingjs.com/) to the result page. ![Show Spacings](../../static/img/screenshots/spacing.jpg) 1. Enable `Show Spacing` setting in the Settings menu. 2. Move your cursor to an element and press Alt on Windows, or Option on a Mac. 3. Move your cursor to another element, the measurement results will be there. :::note `Show Spacing` is only available when viewing the result page in the app. It is not added to the result page for example when [exported](./export.html.md) or [deployed](./deploy.html.md). ::: ## Scroll Position By default, the result page scroll position is maintained after reloads. To disable this behavior, set the [query param](../configuration/query-params.html.md) `scrollPosition` to `false`. Example: https://livecodes.io?scrollPosition=false --- # External Resources ## Stylesheets and Scripts URLs to external CSS stylesheets and JS scripts can be added to the page from the UI using the Project menu → External Resources. In addition, there is a button to the External Resources in the toolbar below the editors. import RunInLiveCodes from '../../src/components/RunInLiveCodes.tsx'; URLs to stylesheets/scripts should be added each in a separate line. Stylesheets and scripts are loaded in the [result page](./result.html.md) before editor codes. Thus, CSS properties defined in external stylesheets can be overridden in the style editor. Global javascript variables defined in external scripts are available to code in the script editor. ![External Resources](/img/screenshots/resources.jpg) Importing and Exporting code to other services (e.g. Codepen and Github gists) takes into consiedration the external resources. ## Search for NPM Packages Package search allows finding NPM Packages and adding URLs to default scripts/stylesheets (hosted by [jsDelivr](https://www.jsdelivr.com/)). Specific package version can be specified. Examples for search terms: ``` jque jquery jquery@3 jquery@3.6 jquery@3.6.3 ``` ![External Resources Search](/img/screenshots/resources-search.jpg) ## Fonts Fonts can be added from [Google fonts](https://fonts.google.com/). ## CSS Presets CSS presets currently include [Normalize.css](https://necolas.github.io/normalize.css/) and [Reset CSS](https://meyerweb.com/eric/tools/css/reset/). ## Related - [Module resolution](./module-resolution.html.md) - [Assets](./assets.html.md) --- # Tools Pane import LiveCodes from '../../src/components/LiveCodes.tsx'; The resizeable tools pane (below the result page) provides an area for developer tools. This currently includes: - [Console](./console.html.md) - [Compiled code viewer](./compiled-code.html.md) - [Tests](./tests.html.md) - Open result page in new window (not in embeds) - [Broadcast](broadcast.html.md) status (not in embeds) - Loading spinner that appears when the result page is loading The pane can be resized by dragging the bar. Clicking a tool button toggles opening/closing the pane. Double-click toggles maximize/close. It can be configured to have any of the following states: - `closed` (default) - `open` - `full` - `none` e.g. https://livecodes.io/?console=open&js=console.log('hello')
opens the console and sets JavaScript code. Demo: (console=open)

 

Demo: (console=full) --- # Console import LiveCodes from '../../src/components/LiveCodes.tsx'; Console messages are shown in the integrated console (in the [tools pane](./tools-pane.html.md), below the result page), without having to open the native browser console. Messages can be sent to the console using the standard `console` methods in the code editor (e.g. `console.log`, `console.warn`, `console.error`, `console.table`, ...etc). The console can also be used as REPL (read–eval–print loop) using the integrated console input. The code is evaluated in the context of the result page (i.e. variables defined in the script editor are accessible for evaluation in the console input). Also code completion works in the console input. e.g. https://livecodes.io/?ts&console=full
sets TypeScript as the active editor and shows the console maximized. Demo: (console=full)

 

:::tip Setting the querystring `languages` only shows these languages. Selecting one language and setting console to `full` gives an environment similar to a REPL. ::: Demo: (Python - print to console) --- # Compiled Code import LiveCodes from '../../src/components/LiveCodes.tsx'; The resulting compiled/transpiled code can be seen in the compiled code viewer (in the [tools pane](./tools-pane.html.md)) in real-time, as you type. This works for all compiled code (e.g. Markdown, Pug, SCSS, Less, Stylus, Typescript, CoffeeScript, ...etc.). This can be a great tool for learning. As you write code, you see the compiled code and the resulting page at the same time. The compiled code viewer shows the code compiled from the currently active editor (markup/style/script). This includes the CSS produced by CSS processors (e.g. Autoprefixer), if enabled. ![Compiled Code Viewer](./../../static/img/screenshots/compiled-code-1.jpg) e.g. https://livecodes.io/?ts&compiled=full
sets TypeScript as the active editor and shows compiled code viewer maximized. This demo shows TypeScript code along with the compiled Javascript code, similar to the [official TypeScript Playground](https://www.typescriptlang.org/play): --- # Tests import LiveCodes from '../../src/components/LiveCodes.tsx'; ## Overview Automated tests can be added for projects. The tests are run in the context of the result web page. The automated tests are run by the Jest testing framework, which runs totally in the browser. In addition, other [testing libraries](#supported-testing-libraries) are also supported. Screenshots: ![Livecodes Tests](/img/screenshots/tests.jpg) ![Livecodes Tests](/img/screenshots/test-editor.jpg) ## Use Cases - Automated tests increase the confidence in the code and can improve the quality of projects. - Allows Test-driven development (TDD). - Can be used for education and training by preparing projects with tests that are required to pass by the students' implementation (similar to freeCodeCamp). - Can be used by websites that offer coding challenges (similar to Codewars). ## Demos Demo: (template=jest)

 

Demo: (template=jest-react) ## Tests Panel The "Tests" panel is located in the "[Tools pane](./tools-pane.html.md)" below the result page. In the tests panel, you can find: - "Run" button: To run tests (keyboard shortcut: Ctrl/Cmd + Alt + t). - "Watch" button toggle: To watch the project and re-run tests automatically when code changes. - "Reset" button: Resets test results. - "Edit" button: Opens a code editor to edit tests (not in embeds). - Test results. :::info Note Please note that the tests panel are hidden by default in [embedded playgrounds](./embeds.html.md) unless the [project has tests](../configuration/configuration-object.html.md)#tests). In such case, the panel is added to the [tools pane](./tools-pane.html.md). However, the test editor is not shown. The [SDK](../sdk/index.html.md) can control the visibility of the different tools in the tools pane (see [`tools`](../configuration/configuration-object.html.md)#tools) property of the [configuration object](../configuration/configuration-object.html.md)). The tests panel and the test editor are always shown in the [full standalone app](../getting-started.html.md)#standalone-app). ::: ## Supported Languages The testing code can be written using JavaScript, TypeScript, JSX or TSX. However, since the tests run against the result web page, they can test projects that use any language/framework. This is [a demo](https://livecodes.io/?x=id/xyi6usem2sf&tests) for running tests against a Ruby project. Languages may have test modules. This is [an example](https://livecodes.io/?x=id/665ar3bpqka&console=full) of running [Python doctest](https://docs.python.org/3/library/doctest.html) tests: ## Importing Code Functions, objects or values can be exported from the `script` code like a regular ES module. These can then be imported in the test code for usage. This is only available for code in the `script` editor. The testing code also have access to global objects like `window`. Example: ```js // in the script editor export default function greet() { return 'Hello, World!'; } export const add = (x, y) => x + y; window.multiply = (x, y) => x * y; ``` ```js // in the test editor import greet, { add } from './script'; // relative import without extension describe('test imported', () => { test('greet', () => { expect(greet()).toBe('Hello, World!'); }); test('add', () => { expect(add(1, 2)).toBe(3); }); }); describe('test global', () => { test('multiply', () => { expect(window.multiply(2, 3)).toBe(6); }); }); ``` ## Supported Jest features - [Jest globals](https://jestjs.io/docs/api): `expect`, `test`, `xtest`, `it`, `fit`, `xit`, `describe`, `fdescribe`, `xdescribe`, `beforeAll`, `afterAll`, `beforeEach`, `afterEach` - Jest function mocks: `jest.fn`, `jest.mocked`, `jest.replaceProperty`, `jest.spyOn` These can be directly used in the test editor, without the need for any imports. Autocomplete is available in Monaco editor for Jest API. ## Supported testing libraries In addition to Jest, you may wish to use other supported testing libraries. These have to be explicitly imported to the testing code. ### Testing library Simple and complete testing utilities that encourage good testing practices. - DOM Testing Library ```js import { getByLabelText, getByText, getByTestId, queryByTestId, waitFor, } from '@testing-library/dom'; ``` - React Testing Library ```js import { render, fireEvent, waitFor, screen } from '@testing-library/react'; ``` - jest-dom ```js import '@testing-library/jest-dom'; ``` - user-event ```js import userEvent from '@testing-library/user-event'; ``` ### Chai Jest assertions can be used in the tests. However, if you prefer Chai, it can be easily used. Autocomplete is also available in Monaco editor for Chai API. ```js import { assert } from 'chai'; ``` ## Examples Usage examples are provided in the starter templates (Jest Starter and Jest/React Starter). :::caution The test code is added to the result page and runs in its context. Please note that script errors (e.g. import or syntax errors) may prevent the tests from loading. ::: ## SDK The [SDK](../sdk/index.html.md) allows [running tests](../sdk/js-ts.html.md)#runtests) and collecting results. --- # Module Resolution import LiveCodes from '../../src/components/LiveCodes.tsx'; ## NPM Modules ### Bare Module Imports In LiveCodes you can use node-style bare module imports for npm modules like you do in your local development. However, there are no installation or build steps required. e.g. consider the following code: ```js import { v4 } from 'uuid'; document.body.innerHTML = v4(); ``` If you run it directly in the browser, you get this error: ``` Uncaught TypeError: Failed to resolve module specifier "uuid". Relative references must start with either "/", "./", or "../". ``` However, in LiveCodes, bare module imports are transformed to full URLs that are imported from CDN (by default: [esm.sh](https://esm.sh/)) which provides ESM versions of NPM packages. `import { v4 } from 'uuid';`
becomes
`import { v4 } from 'https://esm.sh/uuid';` This is made possible by using [import maps](https://github.com/WICG/import-maps).

Demo:

 

You can import from React like that: ```js import { useState } from 'react'; ``` Demo: It just works without a build step and without you having to worry about. And when you [export your project](./export.html.md) to another service (e.g. CodePen) or as HTML, the full URL imports are used, so your code continues to work. :::tip It is recommended to use this method for dependencies over using [external scripts](./external-resources.html.md). The dependencies are explicitly stated in the code. And if you move to a local development environment, your bundler will take care of importing them and doing other optimizations like [tree-shaking](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking). ::: ### CommonJS Modules CommonJS module `require`s are also supported (they are converted to ESM imports). So this also works (although not recommended - use ESM imports instead): ```js const { v4 } = require('uuid'); document.body.innerHTML = v4(); ``` Exercise: Copy the previous code snippet and paste it in the playground below. Check the generated code in the compiled code viewer. :::info Script code that contains `import`, `export` or `require` gets served in a script tag with [`type="module"`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). ::: ### NPM Package Search NPM packages can be searched and added as script tags from the [External Resources](./external-resources.html.md) screen. ## Deno Modules Modules imported from [deno.land/x](https://deno.land/x) (or any other URL ending in `.ts`, `.jsx` or `.tsx`) are automatically transpiled (ts -> js) and bundled by [bundlejs](https://bundlejs.com/) (using [esbuild](https://esbuild.github.io/)), including their relative imports. The project on LiveCodes that imports these modules does not need to be using TypeScript. Example: ```js import { uuid } from 'https://deno.land/x/uuid/mod.ts'; document.body.innerHTML = uuid(); ``` [Open in LiveCodes]() ## JSR Modules Modules can be imported from [jsr.io](https://jsr.io/) using the prefix `jsr:`. The project on LiveCodes that imports these modules does not need to be using TypeScript. Example: ```js import { yassify } from 'jsr:@kwhinnery/yassify'; document.body.innerHTML = yassify('Hello, World!'); ``` [Open in LiveCodes]() ## GitHub/GitLab/Bitbucket Modules can also be similarly imported from GitHub, Gitlab or Bitbucket. Also these imports are transpiled and bundled (see [Deno Modules](#deno-modules)). ```js import { flatten } from 'https://github.com/remeda/remeda/blob/master/src/flatten.ts'; console.log(flatten([[1, 2], [3], [4, 5]])); // -> [1, 2, 3, 4, 5] ``` [Open in LiveCodes]() :::tip If you do not want the import URL to be bundled (e.g. in Deno or GitHub imports), add `#nobundle` to the end of URL. Example: ```js import { flatten } from 'https://github.com/remeda/remeda/blob/master/src/flatten.ts#nobundle'; ``` If you want to bundle (and transpile) any import URL, prefix it with `bundle:` (see below). ::: ## pkg.pr.new Unpublished npm packages can be imported while still under development using the [pkg.pr.new](https://pkg.pr.new/) service. Use the prefix `pr:` or `pkg.pr.new:`. Example: ```js import { Bench } from 'pr:tinybench@a832a55'; // or // import { Bench } from 'pr:tinylibs/tinybench/tinybench@a832a55'; ``` ## CDN Providers By default, npm modules are imported from [esm.sh](https://esm.sh/). You may choose another provider by using a CDN prefix. These are examples of importing the library `uuid`: `uuid` → https://esm.sh/uuid ([info](https://esm.sh)) `esm.sh:uuid` → https://esm.sh/uuid ([info](https://esm.sh/)) `skypack:uuid` → https://cdn.skypack.dev/uuid ([info](https://www.skypack.dev/)) `jsdelivr:uuid` → https://cdn.jsdelivr.net/npm/uuid ([info](https://www.jsdelivr.com/)) `esm.run:uuid` → https://esm.run/uuid ([info](https://esm.run/)) `unpkg:uuid` → https://unpkg.com/uuid?module ([info](https://unpkg.com/)) `esbuild:uuid` → https://esbuild.vercel.app/uuid ([info](https://esbuild.vercel.app/)) `bundlejs:uuid` → https://deno.bundlejs.com/?file&q=uuid ([info](https://bundlejs.com/)) `bundle:uuid` → https://deno.bundlejs.com/?file&q=uuid ([info](https://bundlejs.com/)) `deno:uuid` → https://deno.bundlejs.com/?file&q=https://deno.land/x/uuid/mod.ts ([info](https://bundlejs.com/)) `npm:uuid` → https://esm.sh/uuid ([info](https://esm.sh)) `node:uuid` → https://esm.sh/uuid ([info](https://esm.sh)) `jsr:@std/uuid` → https://esm.sh/jsr/@std/uuid ([info](https://esm.sh)) `pr:tinybench@a832a55` → https://esm.sh/pr/tinybench@a832a55 ([info](https://esm.sh)) `pkg.pr.new:tinybench@a832a55` → https://esm.sh/pkg.pr.new/tinybench@a832a55 ([info](https://esm.sh)) `jspm:uuid` → https://jspm.dev/uuid ([info](https://jspm.org) - [DEPRECATED](https://jspm.org/jspm-dev-deprecation)) Example: ```js import { useState } from 'esm.sh:react'; ``` :::caution Please note that importing the same module (even for dependencies) from different CDNs may cause conflicts. Example: ```js // this will NOT work! import React, { useState } from 'esm.sh:react'; // React from esm.sh import { createRoot } from 'skypack:react-dom/client'; // React from skypack.dev ``` ::: ### Change Default CDN Default CDN can be changed on project-level using the [custom settings](../advanced/custom-settings.html.md) property `defaultCDN` which accepts a string representing one of the CDN aliases listed above. Example: This assigns [Skypack](https://www.skypack.dev/) as the default CDN for all imports of the project ```json { "defaultCDN": "skypack" } ``` ### Package Version Most CDN providers allow specifying package version using the format:
`{pkgName}@{version}/{path}`. Example: ```js import latest from 'lodash'; import v3 from 'lodash@3'; console.log(latest.VERSION); // -> 4.17.21 console.log(v3.VERSION); // -> 3.10.1 ``` ## Custom Module Resolution Module resolution described in this page mainly depends on [import maps](https://github.com/WICG/import-maps). The generated import map is added to the [result page](./result.html.md). You may wish to override or customize module resolution behavior (e.g. change URL, CDN, specify version, import custom unpublished library, ...etc. ), however you cannot add another import map script because [currently multiple import maps are not yet supported](https://github.com/WICG/import-maps#multiple-import-map-support). LiveCodes allows you to add your custom import map by one of the following methods: #### Custom Settings In the standalone app, via the [custom settings](../advanced/custom-settings.html.md) property `imports`. Example: ```json title="Custom Settings" { "imports": { "my-lib": "https://my-server.com/path/to/library.js" } } ``` #### SDK For embedded playgrounds, use the [SDK](../sdk/index.html.md) embed option [`config.imports`](../configuration/configuration-object.html.md)#imports). Example: ```js title="index.js" import { createPlayground } from 'livecodes'; const config = { imports: { 'my-lib': 'https://my-server.com/path/to/library.js', }, // other configurations ... }; createPlayground('#container', { config }); ``` Please note that you may also provide [custom type definitions](./intellisense.html.md)#custom-types) for your custom modules for editor intellisense and better development experience. ## Related - [Import](./import.html.md) - [External Resources](./external-resources.html.md) - [Projects](./projects.html.md) - [Intellisense](./intellisense.html.md) --- # IntelliSense import LiveCodes from '../../src/components/LiveCodes.tsx'; The [code editor](./editor-settings.html.md)#code-editor) provides a rich experience with [intellisense](https://code.visualstudio.com/docs/editor/intellisense) and autocompletion. Many of the features required for this are based on TypeScript types that are either inferred by the editor or supplied as data definition files. This not only works when the editor language is TypeScript, but also works with others like JavaScript and JSX. Example: ![LiveCodes Autocomplete](../../static/img/screenshots/autocomplete.jpg) ## Types for imported npm packages LiveCodes will try to automatically find type definitions for npm modules imported in the editor. These are examples for automatically loading React types with autocomplete and hover info: ![LiveCodes Intellisense](../../static/img/screenshots/intellisense-1.jpg) ![LiveCodes Intellisense](../../static/img/screenshots/intellisense-2.jpg) ## TypeScript TwoSlash The code editor supports [TypeScript TwoSlash](https://github.com/microsoft/TypeScript-Website/tree/v2/packages/ts-twoslasher). This can be very useful for debugging, sharing and teaching TypeScript. This is supported in [JavaScript](../languages/javascript.html.md), [TypeScript](../languages/typescript.html.md), [JSX](../languages/jsx.html.md) and [TSX](../languages/tsx.html.md). This also includes [Babel](../languages/babel.html.md), [Sucrase](../languages/sucrase.html.md), [Solid](../languages/solid.html.md), [React Native](../languages/react-native.html.md), etc. ![TypeScript TwoSlash](../../static/img/screenshots/twoslash.jpg) ![TwoSlash in JSX](../../static/img/screenshots/twoslash-jsx.jpg) ## Custom Types If no type definitions are found, or if you want to provide your own (e.g. for a module that is not hosted on npm), custom type definition files can be used. In the standalone app, these can be provided in [custom settings](../advanced/custom-settings.html.md) using the `types` property. This takes an object with the key representing the module name and the value representing the URL of the file. Example: ```json title="Custom Settings" { "types": { "my-module": "https://cdn.jsdelivr.net/npm/my-module@1.0.0/types/my-module.d.ts", "my-other-module": "https://my-website.com/my-other-module/my-other-module.d.ts" } } ``` For embedded playgrounds, these can be provided in the [configuration object](../configuration/configuration-object.html.md) using the [`types`](../configuration/configuration-object.html.md)#types) property. This can be combined with the [`imports`](../configuration/configuration-object.html.md)#imports) property to provide [importmap](./module-resolution.html.md)#custom-module-resolution) for runtime implementation of your custom modules. This is an example of how to create a playground that provides the implementation of the custom module: `my-module` and its type definition to provide editor intellisense: ```js import { createPlayground } from 'livecodes'; const config = { activeEditor: 'script', script: { language: 'javascript', content: `import { foo } from 'my-module';\n\nconsole.log(foo());` }; imports: { 'my-module': 'https://my-website.com/my-module/index.js', }, types: { 'my-module': 'https://my-website.com/my-module/my-module.d.ts', }, }; createPlayground('#container', {config}); ``` Please note that the URLs used for `types` and `imports` properties may be full URLs or [data URLs](./data-urls.html.md). This can be of great use for library authors who want to provide playgrounds for documenting their libraries that are not (yet) published to npm. ## Demo Let's assume we have this TypeScript module: ```ts title="Greeter.ts" export class Greeter { private morningGreetings = ['Good morning', 'Have a good day', 'How are you today?']; private eveningGreetings = ['Good evening', 'Good night', 'Sleep well']; private randomSelector(array: string[]) { return array[Math.floor(Math.random() * array.length)]; } public morning() { return this.randomSelector(this.morningGreetings); } public evening() { return this.randomSelector(this.eveningGreetings); } } ``` which compiles to this JavaScript: ```js title="Greeter.js" export class Greeter { constructor() { this.morningGreetings = ['Good morning', 'Have a good day', 'How are you today?']; this.eveningGreetings = ['Good evening', 'Good night', 'Sleep well']; } randomSelector(array) { return array[Math.floor(Math.random() * array.length)]; } morning() { return this.randomSelector(this.morningGreetings); } evening() { return this.randomSelector(this.eveningGreetings); } } ``` and this type definition: ```ts title="Greeter.d.ts" export declare class Greeter { private morningGreetings; private eveningGreetings; private randomSelector; morning(): string; evening(): string; } ``` The JavaScript output (Greeter.js) and the data definition file (Greeter.d.ts) should be hosted online or converted to data URLs (see [assets](./assets.html.md) and [data URLs](./data-urls.html.md)). Then, they can be used like that: export const customModules = { editor: 'monaco', activeEditor: 'script', script: { language: 'typescript', content: "import { Greeter } from 'my-greeter';\n\nconst greeter = new Greeter();\n// now `greeter` has autocomplete\n\ndocument.body.innerText = greeter.morning();\n\n// this should show error in the editor\n// Property 'morningGreetings' is private and only accessible within class 'Greeter'\nconsole.log(greeter.morningGreetings);", }, imports: { 'my-greeter': 'data:text/javascript;charset=UTF-8;base64,ZXhwb3J0IGNsYXNzIEdyZWV0ZXIgew0KICAgIGNvbnN0cnVjdG9yKCkgew0KICAgICAgICB0aGlzLm1vcm5pbmdHcmVldGluZ3MgPSBbJ0dvb2QgbW9ybmluZycsICdIYXZlIGEgZ29vZCBkYXknLCAnSG93IGFyZSB5b3UgdG9kYXk/J107DQogICAgICAgIHRoaXMuZXZlbmluZ0dyZWV0aW5ncyA9IFsnR29vZCBldmVuaW5nJywgJ0dvb2QgbmlnaHQnLCAnU2xlZXAgd2VsbCddOw0KICAgIH0NCiAgICByYW5kb21TZWxlY3RvcihhcnJheSkgew0KICAgICAgICByZXR1cm4gYXJyYXlbTWF0aC5mbG9vcihNYXRoLnJhbmRvbSgpICogYXJyYXkubGVuZ3RoKV07DQogICAgfQ0KICAgIG1vcm5pbmcoKSB7DQogICAgICAgIHJldHVybiB0aGlzLnJhbmRvbVNlbGVjdG9yKHRoaXMubW9ybmluZ0dyZWV0aW5ncyk7DQogICAgfQ0KICAgIGV2ZW5pbmcoKSB7DQogICAgICAgIHJldHVybiB0aGlzLnJhbmRvbVNlbGVjdG9yKHRoaXMuZXZlbmluZ0dyZWV0aW5ncyk7DQogICAgfQ0KfQ0K', }, types: { 'my-greeter': 'data:text/typescript;charset=UTF-8;base64,ZXhwb3J0IGRlY2xhcmUgY2xhc3MgR3JlZXRlciB7DQogIHByaXZhdGUgbW9ybmluZ0dyZWV0aW5nczsNCiAgcHJpdmF0ZSBldmVuaW5nR3JlZXRpbmdzOw0KICBwcml2YXRlIHJhbmRvbVNlbGVjdG9yOw0KICBtb3JuaW5nKCk6IHN0cmluZzsNCiAgZXZlbmluZygpOiBzdHJpbmc7DQp9DQo=', }, }; ## Related - [Module Resolution](./module-resolution.html.md) - [Data Urls](./data-urls.html.md) - [Assets](./assets.html.md) - [Custom Settings](../advanced/custom-settings.html.md) - [Configuration Object](../configuration/configuration-object.html.md) --- # Code Format Code formatting is supported for most [languages](../languages/index.html.md). ## Code Formatters The code formatter used for each language is specified in the [language documentation](../languages/index.html.md) page. For example: - [Prettier](https://prettier.io/) is used for many languages including HTML, CSS, JavaScript, TypeScript, JSX, TSX. - [gofmt](https://pkg.go.dev/cmd/gofmt) (via [GopherJS](https://github.com/gopherjs/gopherjs)) is used for Go. - [Parinfer](https://shaunlebron.github.io/parinfer/) is used for Scheme, Common Lisp and ClojureScript. ## Format Button Code formatting for the code in the active editor can be triggered by the `Format` button below the editor. ![code format](../../static/img/screenshots/format-1.jpg) ## Keyboard Shortcut Code formatting can also be trigger by the keyboard shortcut Alt + Shift + F. ## Format on-save Format on-save can be enabled from the Settings menu → Format on-save. ## Format Options Some format options can be configured from [Editor Settings](./editor-settings.html.md) screen. These include [Prettier](https://prettier.io/) [configuration options](https://prettier.io/docs/en/options.html) for: - Indentation (Spaces/Tabs) - Tab size - Use Semicolons - Use Single Quotes - Use Trailing Commas ## Configuration Code format can be configured using the [configuration object](../configuration/configuration-object.html.md) properties: - [`formatOnsave`](../configuration/configuration-object.html.md)#formatonsave) - [`useTabs`](../configuration/configuration-object.html.md)#usetabs) - [`tabSize`](../configuration/configuration-object.html.md)#tabsize) - [`semicolons`](../configuration/configuration-object.html.md)#semicolons) - [`singleQuote`](../configuration/configuration-object.html.md)#singlequote) - [`trailingComma`](../configuration/configuration-object.html.md)#trailingcomma) ## SDK Method: `format` The code format can be programmatically triggered by the [SDK](../sdk/index.html.md) method [`format`](../sdk/js-ts.html.md)#format). --- # Command Menu The command menu allows running a large set of commands from the UI. It is keyboard-friendly and allows for searching and selecting commands. Most of the functionality of LiveCodes can be achieved using the command menu, which can really improve productivity and DX. It can be triggered from the keyboard by pressing Ctrl + K (or + K on Mac), or from the Help Menu. ![Open Command Menu from UI](../../static/img/screenshots/command-menu-1.jpg) The available commands cover a wide range of functionality, like showing and hiding UI elements (e.g. different editors, the [result page](./result.html.md), [console](./console.html.md), [compiled code viewer](./compiled-code.html.md), and [tests](./tests.html.md)), changing [languages](../languages), loading [starter templates](./templates.html.md), opening different screens (e.g. new project, opening saved projects, [import](./import.html.md), [embeds](./embeds.html.md), [deploy](./deploy.html.md), [share](./share.html.md) and more). In addition many commands can be executed from the command menu, such as running code, formatting code, changing settings (e.g. autorun, autosave, changing [themes](./themes.html.md), [editor settings](./editor-settings.html.md), and more). ![LiveCodes Command Menu](../../static/img/screenshots/command-menu-2.jpg) ![LiveCodes Command Menu](../../static/img/screenshots/command-menu-3.jpg) ![LiveCodes Command Menu](../../static/img/screenshots/command-menu-4.jpg) ## Using the Command Menu Commands can be navigated and selected by: - The mouse: scrolling and clicking - The keyboard: using the up and down arrow keys to navigate, pressing Enter to select, Backspace to move to parent category and Esc to close the command menu. - Searching: typing in the search box for fuzzy search. ![LiveCodes Command Menu](../../static/img/screenshots/command-menu-5.jpg) ![LiveCodes Command Menu](../../static/img/screenshots/command-menu-6.jpg) ## Keyboard Shortcuts If a command has a keyboard shortcut, it will be shown in the command menu. In addition, the whole list of keyboard shortcuts can be opened from the command menu (by searching for "Keyboard Shortcuts") or from the UI from the Help Menu. ![Keyboard Shortcuts](../../static/img/screenshots/keyboard-shortcuts.jpg) --- # Keyboard Shortcuts Many commands can be executed from the keyboard using keyboard shortcuts. The full list can be found in the [Keyboard Shortcuts screen](https://livecodes.io/?screen=keyboard-shortcuts), which can be accessed from the Help Menu or from the [command menu](./command-menu.html.md) by pressing Ctrl + K (or + K on Mac) and searching for "Keyboard Shortcuts". The code editor shortcuts are the same as VS Code, which can be found [here](https://code.visualstudio.com/docs/getstarted/keybindings#_basic-editing). ![Keyboard Shortcuts](../../static/img/screenshots/keyboard-shortcuts.jpg) --- # User Settings A user can select various settings that are stored locally in the browser and are subsequently used. User settings can be configured in Settings menu. These include settings like: - Auto-update - Auto-save - Delay (before auto-update and auto-save) - [Format on-save](./code-format.html.md)#format-on-save) - [Theme](./themes.html.md) (light/dark) - [Theme color](./themes.html.md)#theme-color) - [Recover unsaved projects](./recover.html.md) - [Show spacing](./result.html.md)#show-spacings) - Layout (responsive/vertical/horizontal) - [Sync](./sync.html.md) - Show [welcome screen](./welcome.html.md) - [App language](./i18n.html.md) The settings selected in the [`Editor Settings`](./editor-settings.html.md) screen are also saved locally as user settings. User settings are scoped to the currently [logged-in user](./user-management.html.md). They can be [backed up/restored](./backup-restore.html.md) and [synced](./sync.html.md) the same as other user data ([projects](./projects.html.md), [user templates](./templates.html.md)#user-templates), [assets](./assets.html.md), [code snippets](./snippets.html.md)). ## Related - [User management](./user-management.html.md) - [Project](./projects.html.md) - [Templates](./templates.html.md) - [Backup/Restore](./backup-restore.html.md) - [Sync](./sync.html.md) --- # Editor Settings LiveCodes allows a lot of flexibility for configuring which code editor to use and its settings. `Editor Settings` screen can be accessed from Settings menu → Editor Settings. import RunInLiveCodes from '../../src/components/RunInLiveCodes.tsx'; ![LiveCodes Editor Settings](../../static/img/screenshots/editor-settings-1.jpg) ![LiveCodes Editor Settings](../../static/img/screenshots/editor-settings-2.jpg) ![LiveCodes Editor Settings](../../static/img/screenshots/editor-settings-3.jpg) A preview code editor is displayed to preview the settings in real time. The settings selected in the `Editor Settings` screen are saved locally to [user settings](./user-settings.html.md) and are used subsequently. These include: {/* ### Enable AI Code Assistant Enables the [AI code assistant](./ai.html.md). (Free and no account required) */} ### Code Editor The following code editors are supported: - [**Monaco Editor**](https://microsoft.github.io/monaco-editor/): This is the code editor that powers [**VS Code**](https://code.visualstudio.com/). It is [feature-rich](https://code.visualstudio.com/docs/editor/codebasics) and supports autocomplete with [**IntelliSense**](https://code.visualstudio.com/docs/editor/intellisense) (including [types for custom libraries](./intellisense.html.md)). However, it requires a relatively large download and is not supported in mobile browsers. - [**CodeMirror**](https://codemirror.net/): Has [many editing features](https://codemirror.net/docs/extensions/), including autocomplete, with good **mobile support**. - [**CodeJar**](https://medv.io/codejar/): A **lightweight** code editor with very basic editing features. [PrismJs](https://prismjs.com/) is used for syntax highlighting. Please note that some editor settings are not supported in CodeJar (see below). This can be configured using the [`editor`](../configuration/configuration-object.html.md)#editor) configuration option. By default, Monaco editor is used on desktop, CodeMirror is used on mobile and CodeJar is used in [codeblocks](./display-modes.html.md)#codeblock), in [lite mode](./lite.html.md) and in [readonly](../configuration/configuration-object.html.md)#readonly) playgrounds. ### Editor Options These include: - [Editor theme](../configuration/configuration-object.html.md)#editortheme) - [Font family](../configuration/configuration-object.html.md)#fontfamily) - [Font size](../configuration/configuration-object.html.md)#fontsize) - [Indentation](../configuration/configuration-object.html.md)#usetabs) (Spaces/Tabs) - [Tab size](../configuration/configuration-object.html.md)#tabsize) - [Line numbers](../configuration/configuration-object.html.md)#linenumbers) - [Word-wrap](../configuration/configuration-object.html.md)#wordwrap) - [Auto-close brackets and quotes](../configuration/configuration-object.html.md)#closebrackets) - [Fold (collapse) regions](../configuration/configuration-object.html.md)#foldregions) - [Minimap](../configuration/configuration-object.html.md)#minimap) ### Emmet Allows using [**Emmet**](https://emmet.io/) [abbreviations and actions](https://docs.emmet.io/). See [`emmet`](../configuration/configuration-object.html.md)#emmet) configuration option. (Not supported in CodeJar) ### Editor Modes Allows using [**Vim**](https://vimhelp.org/) and [**Emacs**](https://www.gnu.org/software/emacs/manual/html_node/emacs/Basic.html) keyboard bindings. See [`editorMode`](../configuration/configuration-object.html.md)#editormode) configuration option. (Not supported in CodeJar) ### Format Options These are [**Prettier**](https://prettier.io/) [configuration options](https://prettier.io/docs/en/options.html) used for code formatting. In addition to those specified in [Editor Options](#editor-options), the following options are available: - [Use Semicolons](../configuration/configuration-object.html.md)#semicolons) - [Use Single Quotes](../configuration/configuration-object.html.md)#singlequote) - [Use Trailing Commas](../configuration/configuration-object.html.md)#trailingcomma) --- # Internationalization (i18n) import LiveCodes from '../../src/components/LiveCodes.tsx'; LiveCodes currently supports UI internationalization. By default, the UI language will be automatically detected based on your browser settings. You can easily switch between supported UI languages using the i18n menu, allowing you to explore and use LiveCodes in your preferred language! If you are interested in contributing to the translation of LiveCodes, please refer to the [i18n Contribution Guide](https://github.com/live-codes/livecodes/blob/develop/docs/docs/contribution/i18n.html.md). ![I18n menu](../../static/img/screenshots/i18n-1.jpg) ![LiveCodes in Chinese](../../static/img/screenshots/i18n-2.jpg) Demo: ([Embedded playground](./embeds.html.md) with `appLanguage: 'zh-CN'`) ## Using SDK Set the [configuration object](../configuration/configuration-object.html.md) property [`appLanguage`](../configuration/configuration-object.html.md)#applanguage) to a supported language code. ```js import { createPlayground } from 'livecodes'; createPlayground('#container', { template: 'javascript', config: { appLanguage: 'auto' } }); ``` ## Using query params Add the [query parameter](../configuration/query-params.html.md) `appLanguage` with your preferred language code. https://livecodes.io?template=javascript&appLanguage=fr ## Related - [User Settings](./user-settings.html.md) - [Editor Settings](./editor-settings.html.md) - [Query params](../configuration/query-params.html.md) - [i18n Contribution Guide](https://github.com/live-codes/livecodes/blob/develop/docs/docs/contribution/i18n.html.md) --- # Default Template/Language When the app is loaded, by default, the last used [language](../languages/index.html.md) is selected. The app can also be configured to load a default [user template](./templates.html.md)#user-templates). If you do not already have any user templates, save any loaded project as template: Project menu → Save as → Template. Then, in the user templates screen (Project menu → New ... → My Templates), find your template and click "Set as default". If you wish to clear that selection, find the default template in user templates and click "unset". If you want to temporarily not load the default template/language add the [query param](../configuration/query-params.html.md) `no-defaults`. Example: https://livecodes.io?no-defaults ## Related - [Templates](./templates.html.md) - [Query params](../configuration/query-params.html.md) --- # Assets Adding local assets (e.g. images, fonts, stylesheets, scripts) that are not hosted online is such a common need that a UI was developed to allow easily adding them. The assets are saved locally on the user's device and are available across projects (i.e the same image can be used in different projects without having to add it multiple times). In addition, assets are supported in [sync](./sync.html.md), [backup](./backup-restore.html.md)#backup) and [restore](./backup-restore.html.md)#restore). The `Assets` screen can be accessed from Settings menu → Assets ![Assets](/img/screenshots/assets-1.jpg) import RunInLiveCodes from '../../src/components/RunInLiveCodes.tsx'; Assets are either: - Encoded as [data URLs](./data-urls.html.md). - Uploaded to a [GitHub Pages](https://pages.github.com/). This requires login with a [GitHub account](./github-integration.html.md) (allowing access to repos). A **public** repo called `livecodes-assets` is created if not present. The assets are pushed to `gh-pages` branch. They can then be accessed by URLs like: https://\{user\}.github.io/livecodes-assets/assets/... When an asset item is clicked, the URL is copied to clipboard. The URL can then be used in projects. ![Assets](/img/screenshots/assets-2.jpg) --- # Code Snippets LiveCodes supports saving and organizing code snippets in different languages. Code snippets are saved locally on user's device. However, they are supported in [sync](./sync.html.md), [backup](./backup-restore.html.md)#backup) and [restore](./backup-restore.html.md)#restore). Code snippets screen can be accessed from Settings menu → Code Snippets. ![Code Snippets](../../static/img/screenshots/snippets-1.jpg) import RunInLiveCodes from '../../src/components/RunInLiveCodes.tsx'; Each snippet has a title, description, language and code. ![Code Snippets](../../static/img/screenshots/snippets-add.jpg) After adding snippets they can be sorted (by date modified or title), filtered (by language) or searched. ![Code Snippets](../../static/img/screenshots/snippets-list.jpg) Code snippets can then be copied to clipboard and pasted in projects. ## Related - [Projects](./projects.html.md) - [Assets](./assets.html.md) --- # Import ## Overview LiveCodes supports importing code from a wide variety of [sources](#sources). This can be achieved using one of the following methods: ### UI The Import screen can be accessed from the Project menu → Import. import RunInLiveCodes from '../../src/components/RunInLiveCodes.tsx'; ![LiveCodes Import](../../static/img/screenshots/import-1.jpg) ![LiveCodes Import](../../static/img/screenshots/import-2.jpg) ### Query Param A URL of any of the [sources](#sources) can be imported by adding it as a value to [query param](../configuration/query-params.html.md) key: `x`. Example: https://livecodes.io/?x=https://gist.github.com/f01deb828a42f363502fbae7964d48e9 ### Bookmarklet Instead of manually copy/pasting URLs to import, adding [**"Edit in LiveCodes"** bookmarklet](../bookmarklet.html.md) to the browser bookmarks bar can be a more convenient way. It opens LiveCodes in a new window and imports the current webpage URL. ### SDK For [embedded playgrounds](./embeds.html.md), use the [SDK](../sdk/index.html.md) property [`EmbedOptions.import`](../sdk/js-ts.html.md)#import). ## Examples - GitHub File: URL: https://github.com/lodash/lodash/blob/master/isObject.js [Open in LiveCodes](https://livecodes.io/?x=https://github.com/lodash/lodash/blob/master/isObject.js) - GitHub Directory: URL: https://github.com/bradtraversy/50projects50days/tree/master/expanding-cards [Open in LiveCodes](https://livecodes.io/?x=https://github.com/bradtraversy/50projects50days/tree/master/expanding-cards) - GitHub Gist: URL: https://gist.github.com/f01deb828a42f363502fbae7964d48e9 [Open in LiveCodes](https://livecodes.io/?x=https://gist.github.com/f01deb828a42f363502fbae7964d48e9) - JS Bin: URL: https://jsbin.com/iwovaj/73/embed?html,js,output [Open in LiveCodes](https://livecodes.io/?x=https://jsbin.com/iwovaj/73/embed?html,js,output) - Vue Playground: URL: [https://play.vuejs.org/#eNp9kUFKAzEUhq/yyKYKtUW6K9OCli4UUVFxlU2Z...](https://play.vuejs.org/#eNp9kUFKAzEUhq/yyKYKtUW6K9OCli4UUVFxlU2Zvk5TM0lIXsbCMGdw7QG8g+fxAl7Bl5RWF9Jd3v//7+cLrxUXzg2aiGIsilB65QgCUnRTaVTtrCdoweMKOlh5W0OPoz1ppCmtCQR1qGCS/JPejWpwZpcY4Ov94/vzDZ45eSpNMdzVciEPhLXTC0KeAIr1+bRtc0nXFUOesqqMiwTNWc1teiIF+1KwVQwP26IvKDDCSlWDTbCG6du0K0Vpa6c0+jtHihGlGEN2krfQ2r5eZ418xP5eL9dYvvyjb8I2aVLcewzoG5Ti4NHCV0g7e/54i1t+H0wmj5rTR8wHDFbHxLiLXUazZOw/uUx7lW+gTPUU5ltCE/afSqAp2eW8FHyX2ZGv/+KOBqO8J00nuh/8Wasi) [Open in LiveCodes](https://livecodes.io/?x=https%3A%2F%2Fplay.vuejs.org%2F%23eNp9kUFKAzEUhq%2FyyKYKtUW6K9OCli4UUVFxlU2Zvk5TM0lIXsbCMGdw7QG8g%2BfxAl7Bl5RWF9Jd3v%2F%2F7%2BcLrxUXzg2aiGIsilB65QgCUnRTaVTtrCdoweMKOlh5W0OPoz1ppCmtCQR1qGCS%2FJPejWpwZpcY4Ov94%2FvzDZ45eSpNMdzVciEPhLXTC0KeAIr1%2BbRtc0nXFUOesqqMiwTNWc1teiIF%2B1KwVQwP26IvKDDCSlWDTbCG6du0K0Vpa6c0%2BjtHihGlGEN2krfQ2r5eZ418xP5eL9dYvvyjb8I2aVLcewzoG5Ti4NHCV0g7e%2F54i1t%2BH0wmj5rTR8wHDFbHxLiLXUazZOw%2FuUx7lW%2BgTPUU5ltCE%2FafSqAp2eW8FHyX2ZGv%2F%2BKOBqO8J00nuh%2F8Wasi) ## Sources Import is supported from any of the following: - GitHub gist - GitHub file - Directory in a GitHub repo - Gitlab snippet - Gitlab file - Directory in a Gitlab repo - JS Bin - [Shared projects](./share.html.md) - Raw code - Code in web page DOM - Local file(s) - Code in zip file (Local or URL) - Code in image - OCR (Local or URL) - Projects shared in official playgrounds of [TypeScript](https://www.typescriptlang.org/play) and [Vue](https://play.vuejs.org/) - [Exported project JSON](./export.html.md) (single project and bulk import) Import sources are identified by URL patterns (e.g. origin, pathname and extension). :::tip Local files can be imported from the "Import Screen" or by dragging and dropping the file(s) in the editor. ::: ## File Selection For sources that provide multiple files (e.g. GitHub/GitLab directories, GitHub gists, GitLab snippets and local files), a best guess is tried to load files in respective editors. Best results are when there are 3 files and each file is in a language (identified by file extension) that can be loaded to a different editor, for example: - index.html, style.css, script.js - default.pug, app.scss, main.ts The following file names are given higher priority: - Markup files starting with `index.` or `default.` - Style files starting with `style.` or `styles.` - Script files starting with `script.`, `app.`, `main.` or `index.` While README, markdown files and files with no extension are given lower priority. Alternatively, files can be specified using the `files` [query param](../configuration/query-params.html.md). It takes a **comma-separated list** of filenames. The first 3 found files are loaded. If 1 or 2 files are specified, only these will be loaded. The first matching file is shown by default in the active editor. The query params should have the following format: `?x={url}&files={file1},{file2},{file3}` Example: `?x={url}&files=Counter.tsx,counter.scss,counter.html` The active editor can be specified using the [`activeEditor`](../configuration/configuration-object.html.md)#activeeditor) (or its alias `active`) [query param](../configuration/query-params.html.md). It takes the name of the editor (`markup`, `style` or `script`) or its ID (`0`, `1` or `2`) to be shown by default. Example: `?x={url}&activeEditor=style` or `?x={url}&active=1` ## Import Shared Projects [Shared Projects](./share.html.md) can be imported using the value of the query param `x` generated by the Share screen. This starts with either: - `code/`: for compressed base64-encoded project config - `id/`: for short URLs recognized by shared project id. Example: https://livecodes.io/?x=id/bi9qszw86w3 ## Import Code from DOM If the source URL does not match one of the supported origins (GitHub, GitLab and JS Bin), the URL is fetched, its response text is parsed as [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) and code is extracted from elements that match specific CSS selectors. (By default: `.livecodes [data-lang="{language}"]`) :::info Example ```html
This is identified as <strong>HTML</strong> code
``` The HTML editor is prefilled with: `This is identified as HTML code` Please note that the code should be html-encoded to avoid interference with the HTML of the page. ::: Example: https://livecodes.io/?x=https://live-codes.github.io/livecodes-examples/prefill-from-code-blocks.html Alternatively, custom CSS selectors can be specified using [query params](../configuration/query-params.html.md): `?x={url}&{language}-selector={selector}` The following example loads the content of the first element that matches the CSS selector `h3` as `html`: https://livecodes.io/?html-selector=h3&x=https://live-codes.github.io/livecodes-examples/prefill-from-code-blocks.html Of course, [embedded playgrounds](./embeds.html.md) can be prefilled with code from the same embedding page. This works well for documentation and educational websites. [This is a demo](https://live-codes.github.io/livecodes-examples/prefill-from-code-blocks.html) for automatic extraction of code blocks to prefill editors by creating "Edit in LiveCodes" links. Also embedded editors are prefilled from the code blocks. ([View source](https://github.com/live-codes/livecodes-examples/blob/master/prefill-from-code-blocks.html)) ## Import Raw Code If the response text could not be parsed as DOM or no elements matched the CSS selectors, it is assumed to be raw code and the response text is loaded to editor. If the URL ends with an extension it is used to identify the language, otherwise it is assumed to be `html`. Alternatively, the language of raw code can be specified using [query params](../configuration/query-params.html.md): `?x={url}&raw={language}` ## Import from CodePen Currently, CodePen API does not allow directly importing code from Pens. However, you can export any saved Pen as a [zip file](https://blog.codepen.io/documentation/exporting-pens/#export-zip-1) or [Github gist](https://blog.codepen.io/documentation/exporting-pens/#save-as-github-gist-2) and then import it to LiveCodes. The format that Codepen exports is well understood by LiveCodes. Most Pens can be imported with no or minimal changes. **Note:** External resources (styles/scripts) are not exported with source code in zip file export of CodePen. However, export to GitHub gist does export these. So if a Pen with external resources exported as zip file is not imported properly, try exporting to GitHub gist or manually add the [external resources](./external-resources.html.md). ## Import Code from Image (OCR) Code can be extracted from images (local or via URL) using [Tesseract.js](https://github.com/naptha/tesseract.js), a library for Optical Character Recognition (OCR). To ensure accurate identification, the text in the image should be clear, have high contrast against the background, and be free from unrelated text. Language detection is performed using [highlight.js](https://highlightjs.readthedocs.io/en/latest/api.html#highlightauto), which makes its best guess based on the content. Best results are obtained when the image is generated using LiveCodes "[Code to Image](./code-to-image.html.md)" feature. ## Import Exported LiveCodes Projects A [single project exported as JSON](./export.html.md)#exporting-a-single-project) can be imported in the same or a different device from the import screen under the tab "Import Project JSON". The JSON file can be supplied as a local file upload or from a URL. Similarly, [multiple projects exported in bulk](./export.html.md)#exporting-multiple-projects) can be imported from the tab "Bulk Import". ## Related - [Code prefill](./code-prefill.html.md) - [Export](./export.html.md) - [External resources](./external-resources.html.md) - [Module resolution](./module-resolution.html.md) - [Projects](./projects.html.md) --- # Export ## Exporting A Single Project Project export can be accessed from the Project menu → Export. ![LiveCodes Export](../../static/img/screenshots/export-1.jpg) Any project can be exported to: - **Project (JSON):** a JSON file containing project [configuration object](../configuration/configuration-object.html.md). This can be used to later [import](./import.html.md)#import-exported-livecodes-projects) that project on the same or a different device or to share a copy of the project with others. - **Source (ZIP):** a zip file containing the project configuration file as JSON, in addition to the source code in separate files. This can be useful for opening the code in an external IDE. - **Result (HTML):** [result page](./result.html.md) as a single html file. Can be used for the purpose of demo or deploy. - **GitHub gist** (_requires login with [GitHub account](./github-integration.html.md)_): creates a **public** GitHub gist on the user's GitHub account containing the source code as separate files. - **CodePen:** creates a [CodePen](https://codepen.io/) prefilled with the project code. If the used [languages/frameworks](./../languages/index.html.md) are not supported in CodePen (e.g. Astro, Svelte, Python, ...etc), the compiled code is exported so that it continues to work there. [Bare module imports](./module-resolution.html.md) are converted to esm imports, for example: ```js ``` becomes: ```js import React from 'https://cdn.skypack.dev/react'; ``` - **JSFiddle:** creates a [JSFiddle](https://jsfiddle.net/) prefilled with the project code. Exported code may be modified like with CodePen (see above). ## Exporting Multiple Projects Multiple projects can be exported in bulk from the [Saved Projects](./projects.html.md) screen (Project menu → Open) using the button `Export All`. ![saved projects](../../static/img/screenshots/export-2.jpg) This produces a JSON file containing an array of project configuration objects. They can be later imported in the same or a different device using the `Bulk Import` functionality in the [Import screen](./import.html.md)#import-exported-livecodes-projects). All the currently visible projects will be exported. If projects are filtered (e.g. by language, tag or search query), only the shown projects are exported. ## Related - [Projects](./projects.html.md) - [Import](./import.html.md) - [Backup/Restore](./backup-restore.html.md) - [Sync](./sync.html.md) - [Share](./share.html.md) --- # Share It is easy to share LiveCodes projects! A URL is generated to load the shared project. This URL can be copied or shared to different social media. The share screen can be accessed from the share icon at the top right or from the Project menu → Share. ![LiveCodes Share](../../static/img/screenshots/share-1.jpg) By default, the generated URL encodes the project configuration in a base-64-encoded compressed query string. This step is generated locally in the browser without sending the code to any server. However, depending on the size of the project, the URL can be very long. The length of the URL is indicated in the share screen. [Try not to use very long URLs](https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers) to ensure cross-browser compatibility. When requested by the user, short URLs can be generated. This requires sending the project configuration (**including source code**) to a server that saves the code and provides a short Id which can be used to retrieve the project. ![LiveCodes Share - short URL](../../static/img/screenshots/share-2.jpg) :::caution Generating a short URL for sharing requires sending the project configuration (**including source code**) to LiveCodes share service. **It cannot then be deleted**. ::: :::info Note The app hosted on [`https://livecodes.io`](https://livecodes.io) uses an API endpoint specifically provided to generate short URLs for LiveCodes share service. We will make every effort to keep that online and available for free use, so long as it is not abused. Please help keep it available by not abusing it and by [sponsoring the project](../sponsor.html.md). Short URLs generated by LiveCodes share service are **private** — the links are not published anywhere on the site, and the IDs are non-sequential. However, _static_ [**self-hosted apps**](./self-hosting.html.md) use the free service [dpaste](https://dpaste.com/) for short URLs which are [**deleted after 365 days**](https://dpaste.com/help). If this is a significant issue for you, you may want to use the [docker setup](../advanced/docker.html.md) instead, which provides a self-hosted implementation for the share service among other features. LiveCodes [sponsors](../sponsor.html.md) (Bronze sponsors and above) get access to a hosted implementation. ::: QR code can be generated for the share URL. This can then be scanned by any QR code scanner (e.g. mobile/tablet camera) to load the project on other devices without having to send the link. Please note that generating QR code also requires generating a short URL (code is sent to the share service - see above). ![LiveCodes Share - QR code](../../static/img/screenshots/share-3.jpg) ## Related - [Export](./export.html.md) - [Import](./import.html.md) - [Deploy](./deploy.html.md) - [Broadcast](./broadcast.html.md) - [Backup / Restore](./backup-restore.html.md) - [Sync](./sync.html.md) - [Permanent URL](./permanent-url.html.md) --- # Welcome Screen --- # Recover Unsaved --- # Code to Image LiveCodes has a feature called "Code to Image" that allows converting the code in the code editor into nice-looking images (or code screenshots), that can be downloaded or shared. This can be accessed from the camera icon in the toolbar below the editor. Clicking the icon will open the "Code to Image" screen and load the code in the editor. ![Code to Image](../../static/img/screenshots/code-to-image-1.jpg) Code can be modified in the "Code to Image" screen and then downloaded as image or shared. ![Code to Image](../../static/img/screenshots/code-to-image-2.jpg) There are many options to configure the image to be generated, including background color, border radius, image size, padding, shadow, window style, share URL, editor theme, opacity, code font, image format, etc. There are multiple presets that can be used or the options can be manually configured. ![Code to Image](../../static/img/screenshots/code-to-image-3.jpg) ![Code to Image](../../static/img/screenshots/code-to-image-4.jpg) ![Code to Image](../../static/img/screenshots/code-to-image-5.jpg) ![Code to Image](../../static/img/screenshots/code-to-image-6.jpg) --- # Display Modes import LiveCodes from '../../src/components/LiveCodes.tsx'; The [configuration](../configuration/configuration-object.html.md) option [`mode`](../configuration/configuration-object.html.md)#mode), also available as [query param](../configuration/query-params.html.md), can be used to select different display modes. The following display modes are supported: ## `full` This is the default mode with toolbars, editor and result panes. Example: https://livecodes.io/?template=react Screenshot: (App in full mode) ![full-mode](../../static/img/screenshots/mode-full.jpg) Demo: (Embedded playground in full mode) ## `focus` This hides most of UI buttons and menus and keeps only the essential elements: editors, editor titles, result page, console, and run and share buttons. It can be toggled during runtime from the full mode through the UI from a button in the lower left corner. Also the query param `?mode=focus`. Example: https://livecodes.io/?template=react&mode=focus Screenshot: (focus mode) ![focus-mode](../../static/img/screenshots/mode-focus.jpg) ## `simple` This mode is mainly useful for embedded playgrounds. It shows only 1 editor with the output (result page +/- console). The content of other editors can be set using [SDK](../sdk/index.html.md) [config](../configuration/configuration-object.html.md) even though the editors are not shown. By default, `codemirror` editor is used, however, this can be changed by the [`editor`](../configuration/configuration-object.html.md)#editor) option. By default, the layout is `responsive` but can also be overridden by the [`layout`](../configuration/configuration-object.html.md)#layout) option to `vertical` or `horizontal`. Demo: JS with console Demo: JSX & Result page (Monaco editor, add CSS) export const simpleConfig = { mode: 'simple', layout: 'vertical', activeEditor: 'script', editor: 'monaco', tools: { status: 'none' }, script: { language: 'jsx', content: `import { atom, useAtom } from 'jotai';\n\nconst countAtom = atom(0);\n\nconst Counter = () => {\n const [count, setCount] = useAtom(countAtom);\n const inc = () => setCount((c) => c + 1);\n return (\n <>\n {count} \n \n );\n};\n\nconst App = () => (\n
\n

Hello Jotai

\n

Enjoy coding!

\n \n
\n);\n\nexport default App;\n`, }, style: { language: 'css', content: '.App {\n font-family: sans-serif;\n text-align: center;\n}\n'.trimStart(), }, }; ## `lite` Loads a light-weight, minimal code editor, with limited playground features. See the section about [lite mode](./lite.html.md) for details Example: https://livecodes.io/?mode=lite&template=react Demo: ## `editor` Hides the results pane and works as editor only. Example: https://livecodes.io/?mode=editor&template=react Demo: ## `codeblock` A read-only mode showing only the code block without editor interface. On mouse-over a copy button appears that allows to copy the code. This is specially useful when embedded. Example: https://livecodes.io/?mode=codeblock&template=react Demo: By default, in `codeblock` mode, the light-weight `CodeJar` editor is used (in read-only mode). You can override this by setting the `editor` option. Refer to [Editor Settings](./editor-settings.html.md)#code-editor) for details. Example: https://livecodes.io/?mode=codeblock&editor=monaco&template=react Demo: ## `result` Shows the result page only, with a drawer at the bottom (which can be closed) that allows opening the project in the full playground. Example: https://livecodes.io/?mode=result&template=react Demo: The tools pane (e.g. console/compiled code viewer) is hidden by default in `result` mode. It can be shown if set to `open` or `full`. Refer to [Tools pane](./tools-pane.html.md) documentation for details. Example: https://livecodes.io/?mode=result&tools=console|full&&js=console.log("Hello%20World!") Demo: ## Display Mode vs Default View :::info "Display Mode" is different from "[Default View](./default-view.html.md)". In `editor` display mode, only the editor is loaded and the result page is not available. While `editor` default view shows the editor by default, and the result page can be shown by dragging the split gutter. The same applies for `result` display mode and default view. ::: --- # Default View import LiveCodes from '../../src/components/LiveCodes.tsx'; The playground can be loaded in one of the following views: ## `split` Both the code editor and the result page are visible. This is the default. Example: https://livecodes.io/?view=split Demo: ## `editor` The code editor is visible, while the result page is collapsed. The result page can be shown by dragging the split gutter, or clicking the "Toggle Result" button. Example: https://livecodes.io/?view=editor Demo: ## `result` The result page is visible, while the code editor is collapsed. The code editor can be shown by dragging the split gutter, or clicking one of the editor tabs. Example: https://livecodes.io/?view=result Demo: ## Display Mode vs Default View :::info "[Display Mode](./display-modes.html.md)" is different from "Default View". In `editor` display mode, only the editor is loaded and the result page is not available. While `editor` default view shows the editor by default, and the result page can be shown by dragging the split gutter. The same applies for `result` display mode and default view. ::: --- # Themes import ThemeDemo from '../../src/components/ThemeDemo.tsx'; LiveCodes comes with dark and light themes. In addition, a theme color can be set to change the app color. ## Theme Dark/Light theme can be set in: - UI, either: - Dark/Light theme switch in toolbar - Settings menu → Dark theme switch - [Query params](../configuration/query-params.html.md): `?theme=dark` or `?theme=light`. e.g. https://livecodes.io/?theme=light - [Configuration object](../configuration/configuration-object.html.md): [`theme`](../configuration/configuration-object.html.md)#theme) property. ![LiveCodes dark theme](../../static/img/screenshots/themes-1.jpg)
LiveCodes dark theme
![LiveCodes light theme](../../static/img/screenshots/themes-2.jpg)
LiveCodes light theme
## Theme Color Similarly, a theme color can be set in: - UI: Settings menu → Color - [Query params](../configuration/query-params.html.md): `?themeColor={color}`. e.g. https://livecodes.io/?themeColor=lightblue - [Configuration object](../configuration/configuration-object.html.md): [`themeColor`](../configuration/configuration-object.html.md)#themecolor) property. ![LiveCodes alternate theme color](../../static/img/screenshots/themes-3.jpg)
Change theme color from UI
![LiveCodes custom theme color](../../static/img/screenshots/themes-4.jpg)
Custom theme color
## Demo :::info Note Please note that editor themes can be set in the [editor settings](./editor-settings.html.md) or using the [`editorTheme`](../configuration/configuration-object.html.md)#editortheme) configuration option. --- # Mobile Support LiveCodes provides a responsive layout that adapts to different screen sizes. Don't wait to be on your desk. Try your ideas on the go! Projects that you create on mobile can be easily [shared](./share.html.md) or [synchronized](./sync.html.md) across devices. You can even share using QR code. ![Responsive layout](../../static/img/screenshots/responsive.jpg) By default, LiveCodes uses the touch-friendly [CodeMirror 6](https://codemirror.net/) editor on mobile. This is configurable in the [editor settings](./editor-settings.html.md) and can be changed at any time. --- # Embedded Playgrounds import LiveCodes from '../../src/components/LiveCodes.tsx'; ## Overview LiveCodes playgrounds can be embedded in any web page. The playground can be [prefilled with code](./code-prefill.html.md) in any supported language. This can be very useful in documentation websites, technical blogs, educational websites and others. Demo: The embedding web page can communicate with the playground using a powerful [SDK](../sdk/index.html.md) (e.g. edit/format code, watch for code changes, get the compiled code or result page HTML, run tests, change layout, ...etc). ## Create Embedded Playground ### App Embed Screen In the [standalone app](../getting-started.html.md)#standalone-app), the Embed Screen can be accessed from Project menu → Embed. import RunInLiveCodes from '../../src/components/RunInLiveCodes.tsx'; It shows a preview of the embedded playground, allows customizations of [embed options](../sdk/js-ts.html.md)#embed-options) and provides generated code that can be added to the web page that will embed the playground. ![LiveCodes embed](../../static/img/screenshots/embed-1.jpg) ![LiveCodes embed](../../static/img/screenshots/embed-2.jpg) ![LiveCodes embed](../../static/img/screenshots/embed-3.jpg) :::info Note Please note that the Embed Screen sends the project code to [LiveCodes share service](./share.html.md) to generate a short URL for usage in the embed code. ::: The setting "Embed Type" allows selection from different variations of the generated code: - Using the SDK from CDN. - Using the SDK with a bundler (e.g. vite, parcel, webpack, etc). - Using the React SDK. - Using the Vue SDK. - Using iframe and [query params](../configuration/query-params.html.md). - Using HTML code that the SDK can use to [auto-prefill](./code-prefill.html.md)#auto-prefill-from-page-dom) the playground. ### SDK The LiveCodes [SDK](../sdk/index.html.md) can be used to embed playgrounds, specify [embed](../sdk/js-ts.html.md)#embed-options) and [configuration](../configuration/index.html.md) options and allows communication with the embedded playground with many [SDK methods](../sdk/js-ts.html.md)#sdk-methods). This method provides more control and allows advanced scenarios. ## Avoid Breaking Changes To avoid breaking changes that would cause the embedded playgrounds to stop working as expected with later updates, follow these recommendations: - Use a [permanent URL](./permanent-url.html.md) to a pinned version of the LiveCodes app for [`EmbedOptions.appUrl`](../sdk/js-ts.html.md)#appurl). The code generated in the Embed screen uses that by default. - Specify the version of the SDK used. The code generated in the Embed screen also does that. - For project code, [specify the versions](./module-resolution.html.md)#package-version) of the imported packages and [external resources](./external-resources.html.md). [Custom import maps](./module-resolution.html.md)#custom-module-resolution) can be set to control the module import behavior. Check the [Permanent URL](./permanent-url.html.md) section for more details. ## Differences from Full App Some of the features of the full standalone app are not available or shown by default in embedded playgrounds, either because of security reasons, being not useful when embedded or because of space limitations. ### Features Not Available - All features that require saving/loading from browser storage: e.g. [projects](./projects.html.md), [assets](./assets.html.md), [code snippets](./snippets.html.md), [user settings](./user-settings.html.md), [default template/language](./default-template-language.html.md), [recover unsaved](./recover.html.md), [backup/restore](./backup-restore.html.md). - All features that require authentication: e.g. [login/logout](./github-integration.html.md), [sync](./sync.html.md), [deploy](./deploy.html.md), [importing](./import.html.md) from private github repos. - [Broadcast](./broadcast.html.md). - App menus. - Some tools in [tools pane](./tools-pane.html.md): e.g. open result page in new window, broadcast status. - [Welcome screen](./welcome.html.md). ### Features Not Shown by Default - [External resources](./external-resources.html.md) button (below the editor) and external resources screen are only shown if the loaded project has external resources (e.g. via [`EmbedOptions.config.stylesheets`](../configuration/configuration-object.html.md)#stylesheets) and [`EmbedOptions.config.scripts`](../configuration/configuration-object.html.md)#scripts)). - [Tests](./tests.html.md) are not shown in [tools pane](./tools-pane.html.md) unless the loaded project has tests (e.g. via [`EmbedOptions.config.tests`](../configuration/configuration-object.html.md)#tests)). Test editor is not available. - Loading [starter templates](./templates.html.md) can be achieved by the [SDK](../sdk/index.html.md) ([`EmbedOptions.template`](../sdk/js-ts.html.md)#template)), not from the UI. - [Importing](./import.html.md) from external sources can be achieved by the [SDK](../sdk/index.html.md) ([`EmbedOptions.import`](../sdk/js-ts.html.md)#import)), not from the UI. - Getting a [share](./share.html.md) URL can be achieved by the [SDK](../sdk/index.html.md) ([`getShareUrl`](../sdk/js-ts.html.md)#getshareurl) method), not from the UI. ## Security - All user code, [result page](./result.html.md) and compilers run in [sandboxed iframes](https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/) with a unique origin. - Embedded playgrounds do not have access to the parent page, or to sensitive data like user cookies and localstorage of the embedding page origin. Communications with the SDK occur by means of [`postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) calls. ## Related - [SDK](../sdk/index.html.md) - [Code prefill](./code-prefill.html.md) - [Configuration](../configuration/index.html.md) - [Embed options](../sdk/js-ts.html.md)#embed-options) - [SDK methods](../sdk/js-ts.html.md)#sdk-methods) - [Permanent URL](./permanent-url.html.md) - [Lite mode](./lite.html.md) - [Read-only](./read-only.html.md) --- # Code Prefill import LiveCodes from '../../src/components/LiveCodes.tsx'; There are many ways to pre-fill code into playgrounds: ## LiveCodes SDK This is the recommended way to create playgrounds and pre-fill them with code. When creating an embedded playground using the [LiveCodes SDK](../sdk/index.html.md), the following [embed options](../sdk/js-ts.html.md)#embed-options) allow pre-fill with code: ### `config` [`EmbedOptions.config`](../sdk/js-ts.html.md)#config) Loads a [configuration object](../configuration/configuration-object.html.md) (or a URL to JSON file representing the configuration object) ```js import { createPlayground } from "livecodes"; const options = { config: { markup: { language: "html", content: "

Hello World!

", }, style: { language: "css", content: "h1 { color: blue; }", }, }, }; createPlayground("#container", options); ``` ### `import` [`EmbedOptions.import`](../sdk/js-ts.html.md)#import) Allows [importing](./import.html.md) from many sources. Examples: - Import GitHub directory: ```js import { createPlayground } from "livecodes"; const options = { import: "https://github.com/bradtraversy/50projects50days/tree/master/progress-steps", }; createPlayground("#container", options); ```

- Import [shared projects](./share.html.md): ```js import { createPlayground } from "livecodes"; const options = { import: "id/6ys2b8txf33", }; createPlayground("#container", options); ``` See the [import](./import.html.md) docs for more information. ### `template` [`EmbedOptions.template`](../sdk/js-ts.html.md)#template) Loads one of the [starter templates](./templates.html.md). ```js import { createPlayground } from "livecodes"; const options = { template: "react", }; createPlayground("#container", options); ``` ## Query params [Query parameters](../configuration/query-params.html.md) can provide easy and powerful ways for configuring the playground. Example: {'https://livecodes.io/?md=**Hello World!**'} ## Markdown Code Blocks [Markdown to LiveCodes](../markdown-to-livecodes.html.md) allows converting Markdown code blocks into LiveCodes playgrounds by adding the `livecodes` parameter to the code block language meta. This is useful for documentation, tutorials, and blog posts where you want to make code examples editable and runnable without writing any JavaScript. Example: ````md {1} ```jsx livecodes import { useState } from "react"; function App() { const [count, setCount] = useState(0); return (

You clicked {count} times.

); } export default App; ``` ```` ## Auto Pre-fill from page DOM The [LiveCodes SDK](../sdk/index.html.md) UMD script can automatically convert static code blocks on the page into interactive playgrounds. This is useful for documentation, tutorials, and blog posts where you want to make code examples editable and runnable without writing any JavaScript. ### How It Works Add the LiveCodes UMD script to your page with the `data-prefill` attribute. On page load, the script finds all elements with the class `livecodes` and replaces each one with an embedded playground. The code content is extracted from elements that have a `data-lang` attribute inside the `.livecodes` element. The `data-lang` attribute is used to determine which language and code editor to use. ```html livecodes render=link

Hello World!

```

### Multiple Languages You can include multiple `
` blocks with different `data-lang` values to populate several editors in the same playground. For example, to create a playground with HTML, CSS, and TypeScript:

```html livecodes render=link

This code is in HTML code blocks
With HTML tags
body {
  text-align: center;
}
.blue {
  color: blue;
}
const p = document.createElement('p');
p.classList.add('blue');
p.innerHTML = 'hello from Typescript!';
document.body.appendChild(p);
```

### Configuration via Data Attributes Each `.livecodes` element can optionally accept the following data attributes: **`data-options`**: A JSON string representing [embed options](../sdk/js-ts.html.md)#embed-options), such as `appUrl`, `config`, `import`, `loading`, `params`, and `template`. ```html livecodes render=link
console.log('Hello World!');
```

**`data-height`**: A number (in pixels) or a CSS value representing the height of the playground (see below). ### Setting the Height The playground height can be set using inline styles: ```html {1} livecodes render=link

Hello World!

```

Alternatively, the height can be set using the `data-height` attribute. ```html {1} livecodes render=link

Hello World!

```

### Escaping Code It is recommended to escape code inside the code blocks using HTML entities (e.g. `<` instead of `<` and `>` instead of `>`) to avoid being evaluated by the browser as HTML. However, this is not strictly required. Example: ```html
    <h1>Hello World!</h1>
  
``` :::caution The `data-prefill` attribute must be set on the ``} ); }; ## Get Permanent URL You can get the permanent URL for the app from the [About screen](pathname:///../?screen=about) (Help menu → About). By default, the code generated in the [Embed screen](./embeds.html.md)#app-embed-screen) uses permanent URL. Alternatively, open the browser console of the standalone app (e.g. https://livecodes.io), and run this: export const GetPermanentUrl = () => { const { siteConfig } = useDocusaurusContext(); return ( {`await livecodes.exec('showVersion');\n // output: // App Version: ${siteConfig.customFields.appVersion} (https://github.com/live-codes/livecodes/releases/tag/v${siteConfig.customFields.appVersion}) // SDK Version: ${siteConfig.customFields.sdkVersion} (https://www.npmjs.com/package/livecodes/v/${siteConfig.customFields.sdkVersion}) // Git commit: 0698f9f (https://github.com/live-codes/livecodes/commit/0698f9f) // App Permanent URL: https://v${siteConfig.customFields.appVersion}.livecodes.io/ // SDK Permanent URL: https://cdn.jsdelivr.net/npm/livecodes@${siteConfig.customFields.sdkVersion}/livecodes.js `} ); }; :::caution Please note that this only applies to the LiveCodes app and its dependencies. [NPM imports](./module-resolution.html.md) in [project code](./projects.html.md)#script-editor) that do not specify versions use the latest version. [Package versions](./module-resolution.html.md)#package-version) can be specified in the import. [Custom import maps](./module-resolution.html.md)#custom-module-resolution) can be set to control the module import behavior. Example: ```js import lodash from 'lodash@4.17.21'; console.log(lodash.VERSION); // -> 4.17.21 ``` It is recommended to also specify versions of [external resources](./external-resources.html.md). ::: #### Full Example: export const FullCode = () => { const { siteConfig } = useDocusaurusContext(); return ( {`
\n`}
); }; ## Related - [Embedded playgrounds](./embeds.html.md) - [Share](./share.html.md) - [SDK](../sdk/index.html.md) - [`exec` SDK method](../sdk/js-ts.html.md)#exec) --- # Data URLs > **Data URLs**, URLs prefixed with the `data:` scheme, allow content creators to embed small files inline in documents. > > — [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs) Sometimes, you need to use an external file (e.g. script, stylesheet) that is not hosted online. In this case, you can use data URLs to embed the file in your code. These can then be used similar to regular URLs (e.g. for ` ``` However, if `imports` is specified as follows: ```json { "imports": { "moment": "https://cdn.jsdelivr.net/npm/moment@2.29.4/dist/moment.js" } } ``` The import map becomes like this: ```html ``` :::info Note Currently, multiple import maps are not yet supported. https://crbug.com/927119 When bare module imports are encountered, LiveCodes adds an import map to the result page. If you need to add custom import map or override the automatically generated one, you need to add them to `imports` config property or `imports` [customSettings](#customsettings) property. ::: ### `types` Type: `[key: string]: string | { autoload?: boolean ; declareAsModule?: boolean ; url: string }` Default: `{}` Allows providing custom [TypeScript type declarations](https://www.typescriptlang.org/docs/handbook/2/type-declarations.html) for better [editor intellisense](../features/intellisense.html.md). It is an object where each key represents module name and value represents the types. This can be a URL to a type declaration file. For example, if this is the type declaration file: ```ts title="https://my-custom-domain/my-type-declarations.d.ts" declare module 'my-demo-lib' { export class Greeter { morning(): string; evening(): string; } } ``` It can be used like that: ```json { "types": { "my-demo-lib": "https://my-custom-domain/my-type-declarations.d.ts" } } ``` Alternatively, the value for module name can be an object with the following properties: - `url`: `string` (required). The URL to type declaration file. - `autoload`: `boolean` (optional). By default, the types are only loaded when the module is imported in code. If `autoload` property is set to `true`, the types are loaded regardless if the module was imported. - `declareAsModule`: `boolean` (optional). Declares the types as module with the supplied module name. Example: ```json { "types": { "my-demo-lib": { "url": "https://my-custom-domain/types.d.ts", "autoload": true, "declareAsModule": true } } } ``` ### `tests` Type: `undefined` | `Partial` Default: `{ language: 'typescript', content: '' }` Configures the [language](../features/tests.html.md)#supported-languages) and content of [tests](../features/tests.html.md). ### `version` Type: `Readonly` [`string`](../api/interfaces/Config.md#description) Default: Current LiveCodes Version. This is a read-only property which specifies the current LiveCodes version. It can be shown using the SDK [`exec`](../sdk/js-ts.html.md)#exec) method. ```js // in browser console of full app (e.g. https://livecodes.io) await livecodes.exec('showVersion'); ``` Version specified in [exported](../features/export.html.md) projects allows automatically upgrading the project configuration when imported by an app with a newer version. ## App Settings These are properties that define how the app behaves. ### `readonly` Type: [`boolean`](../api/interfaces/Config.md#readonly) Default: `false` If `true`, editors are loaded in read-only mode, where the user is not allowed to change the code. By default, when `readonly` is set to `true`, the light-weight code editor [CodeJar](../features/editor-settings.html.md)#code-editor) is used. If you wish to use another editor, set the [editor](#editor) property. ### `allowLangChange` Type: [`boolean`](../api/interfaces/Config.md#allowlangchange) Default: `true` If `false`, the UI will not show the menu that allows changing editor language. ### `view` Type: [`"split" | "editor" | "result"`](../api/interfaces/Config.md#view) Default: `"split"` The [default view](../features/default-view.html.md) for the playground. ### `mode` Type: [`"full" | "focus" | "simple" | "lite" | "result" | "editor" | "codeblock"`](../api/interfaces/Config.md#mode) Default: `"full"` Sets the [display mode](../features/display-modes.html.md). ### `tools` Type: [`Partial<{ enabled: Array<'console' | 'compiled' | 'tests'> | 'all'; active: 'console' | 'compiled' | 'tests' | ''; status: 'closed' | 'open' | 'full' | 'none' | ''; }>`](../api/interfaces/Config.md#tools) Default: `{ enabled: 'all', active: '', status: '' }` Sets enabled and active tools and status of [tools pane](../features/tools-pane.html.md). Example: ```json { "tools": { "enabled": ["console", "compiled"], "active": "console", "status": "open" } } ``` ### `zoom` Type: [`1 | 0.5 | 0.25`](../api/interfaces/Config.md#zoom) Default: `1` Sets result page [zoom level](../features/result.html.md)#result-page-zoom). ## User Settings These are properties that define the [user settings](./../features/user-settings.html.md), including [editor settings](../features/editor-settings.html.md). {/* ### `enableAI` Type: [`boolean`](../api/interfaces/Config.md#enableai) Default: `false` If `true`, [AI code assistant](../features/ai.html.md) is enabled. */} ### `autoupdate` Type: [`boolean`](../api/interfaces/Config.md#autoupdate) Default: `true` If `true`, the result page is automatically updated on code change, after time [delay](#delay). ### `autosave` Type: [`boolean`](../api/interfaces/Config.md#autosave) Default: `false` If `true`, the project is automatically saved on code change, after time [delay](#delay). ### `autotest` Type: [`boolean`](../api/interfaces/Config.md#autotest) Default: `false` If `true`, the project is watched for code changes which trigger tests to auto-run. ### `delay` Type: [`number`](../api/interfaces/Config.md#delay) Default: `1500` Time delay (in milliseconds) following code change, after which the result page is updated (if [`autoupdate`](#autoupdate) is `true`) and/or the project is saved (if [`autosave`](#autosave) is `true`). ### `formatOnsave` Type: [`boolean`](../api/interfaces/Config.md#formatonsave) Default: `false` If `true`, the code is automatically [formatted](../features/code-format.html.md) on saving the project. ### `layout` Type: [`"horizontal"| "vertical" | "responsive" | undefined`](../api/interfaces/Config.md#layout) Default: `"responsive"` Sets the app layout to horizontal or vertical. If set to `"responsive"` (the default) or `undefined`, the layout is vertical in small screens when the playground height is larger than its width, otherwise horizontal. ### `theme` Type: [`"light" | "dark"`](../api/interfaces/Config.md#theme) Default: `"dark"` Sets the app [theme](../features/themes.html.md) to light/dark mode. ### `themeColor` Type: [`string | undefined`](../api/interfaces/Config.md#themecolor) Default: `"hsl(214, 40%, 50%)"` A string representing a [CSS color value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value), used to set the app [theme color](../features/themes.html.md). It can be any valid CSS color value, such as `"#4DB39E"`, `"rgb(245, 225, 49)"`, `"hsl(324, 40%, 50%)"` and `"lightblue"`. ### `editorTheme` Type: [`EditorTheme[] | string | undefined`](../api/interfaces/Config.md#editortheme) Default: `undefined` Sets the code editor themes. :::info Note You can preview and set editor themes in the [editor settings screen](pathname:///../?screen=editor-settings). ::: Three [code editors](#editor) are supported in LiveCodes: **Monaco** (the default on desktop), **CodeMirror** (the default on mobile) and **CodeJar** (the default in [codeblocks](../features/display-modes.html.md)#codeblock), in [lite mode](../features/lite.html.md) and in [readonly](#readonly) playgrounds). Each editor has its own set of themes, represented by the types: [`MonacoTheme`](../api/internal/type-aliases/MonacoTheme.md), [`CodemirrorTheme`](../api/internal/type-aliases/CodemirrorTheme.md) and [`CodejarTheme`](../api/internal/type-aliases/CodejarTheme.md). The `editorTheme` property can be used to set the editor theme for each editor and on light/dark modes. It can be set to an array of [`EditorTheme`](../api/internal/type-aliases/EditorTheme.md) items or a string of comma-separated items. Each item can be composed of: ` editor:` `theme-name` `@app-theme` Where: - `editor` is the name of the editor (`"monaco" | "codemirror" | "codejar"`). [Optional] - `theme-name` is the name of the theme (e.g. `"monokai"`). [Required] Valid theme names can be found here: - Monaco: [`MonacoTheme`](../api/internal/type-aliases/MonacoTheme.md) - CodeMirror: [`CodemirrorTheme`](../api/internal/type-aliases/CodemirrorTheme.md) - CodeJar: [`CodejarTheme`](../api/internal/type-aliases/CodejarTheme.md). - `app-theme` is the name of the app theme (`"dark" | "light"`). [Optional] Examples: - `"vs"` - `"monaco:twilight, codemirror:one-dark"` - `["vs@light"]` - `["vs@light", "vs-dark@dark"]` - `["monaco:vs@light", "codemirror:github-light@light", "dracula@dark"]` Each `EditorTheme` item requires a theme name. The theme name can optionally be preceded with the editor name separated by a colon to specify the editor (e.g. `"monaco:monokai"`). It can also optionally be followed by the app theme separated by "@" (e.g. `"monokai@dark"`). Multiple `EditorTheme` items can be supplied (as array items or in the comma-separated string) to specify the theme for each editor and in dark and light modes. The order matters. The first valid item in the array or string for the current editor (`monaco`, `codemirror` or `codejar`) and app theme (`light` or `dark`) will be used. If no items match the current editor and app theme, the default theme for the editor and app theme will be used. ### `appLanguage` Type: [`AppLanguage | undefined`](../api/interfaces/Config.md#applanguage) Default: `undefined` Spoken language code that sets the app UI language (e.g. `"ar"`, `"zh-CN"`). Used in translations for internationalization. If `undefined` (the default), the language is automatically detected based on the user's browser settings and falls back to English, if detection fails or the language is not supported. ### `recoverUnsaved` Type: [`boolean`](../api/interfaces/Config.md#recoverunsaved) Default: `true` Enables [recovering last unsaved project](../features/recover.html.md) when the app is reopened. ### `welcome` Type: [`boolean`](../api/interfaces/Config.md#welcome) Default: `true` If `true`, the [welcome screen](../features/welcome.html.md) is displayed when the app loads. ### `showSpacing` Type: [`boolean`](../api/interfaces/Config.md#showspacing) Default: `false` Enables [showing element spacing](../features/result.html.md)#show-spacings) in the result page. ### `editor` Type: [`"monaco" | "codemirror" | "codejar" | "auto" | undefined`](../api/interfaces/Config.md#editor) Default: `undefined` Selects the [code editor](../features/editor-settings.html.md)#code-editor) to use. If `undefined` (the default):
Monaco editor is used on desktop,
CodeMirror is used on mobile and in `simple` mode,
while CodeJar is used in [`codeblock` mode](../features/display-modes.html.md)#codeblock), in [`lite` mode](../features/lite.html.md) and in [`readonly`](#readonly) playgrounds. If set to `auto`, Monaco editor is used on desktop and CodeMirror is used on mobile regardless of other settings. ### `fontFamily` Type: [`string | undefined`](../api/interfaces/Config.md#fontfamily) Default: `undefined` Sets the [code editor](../features/editor-settings.html.md) font family. ### `fontSize` Type: [`number | undefined`](../api/interfaces/Config.md#fontfamily) Default: `undefined` Sets the [code editor](../features/editor-settings.html.md) font size. If `undefined` (the default), the font size is set to 14 for the full app and 12 for [embeds](../features/embeds.html.md). ### `useTabs` Type: [`boolean`](../api/interfaces/Config.md#usetabs) Default: `false` If `true`, lines are indented with tabs instead of spaces. Also used in [code formatting](../features/code-format.html.md). ### `tabSize` Type: [`number`](../api/interfaces/Config.md#tabsize) Default: `2` The number of spaces per indentation-level. Also used in [code formatting](../features/code-format.html.md). ### `lineNumbers` Type: [`boolean | "relative"`](../api/interfaces/Config.md#linenumbers) Default: `true` Show line numbers in [code editor](../features/editor-settings.html.md). If set to `"relative"`, line numbers are shown relative to the current line. This can be useful with [vim mode](#editormode). ### `wordWrap` Type: [`boolean`](../api/interfaces/Config.md#wordwrap) Default: `false` Enables word-wrap for long lines. ### `closeBrackets` Type: [`boolean`](../api/interfaces/Config.md#closebrackets) Default: `true` Use auto-complete to close brackets and quotes. ### `foldRegions` Type: [`boolean`](../api/interfaces/Config.md#foldregions) Default: `false` When set to `true`, regions marked by `#region` and `#endregion` comments are folded when the project is loaded. ### `minimap` Type: [`boolean`](../api/interfaces/Config.md#minimap) Default: `false` Enables minimap in code editor. ### `emmet` Type: [`boolean`](../api/interfaces/Config.md#emmet) Default: `true` Enables [Emmet](../features/editor-settings.html.md)#emmet). ### `editorMode` Type: [`"vim" | "emacs" | undefined`](../api/interfaces/Config.md#editormode) Default: `undefined` Sets [editor mode](../features/editor-settings.html.md)#editor-modes). ### `semicolons` Type: [`boolean`](../api/interfaces/Config.md#semicolons) Default: `true` Configures Prettier [code formatter](../features/code-format.html.md) to use [semi-colons](https://prettier.io/docs/en/options.html#semicolons). ### `singleQuote` Type: [`boolean`](../api/interfaces/Config.md#singlequote) Default: `false` Configures Prettier [code formatter](../features/code-format.html.md) to use [single quotes instead of double quotes](https://prettier.io/docs/en/options.html#quotes). ### `trailingComma` Type: [`boolean`](../api/interfaces/Config.md#trailingcomma) Default: `true` Configures Prettier [code formatter](../features/code-format.html.md) to use [trailing commas](https://prettier.io/docs/en/options.html#trailing-commas). --- # Query Parameters import LiveCodes from '../../src/components/LiveCodes.tsx'; A flexible and convenient way to configure the app is to use URL query parameters. It allows configuration of a wide range of options, including those of the [configuration object](./configuration-object.html.md) and [embed options](../sdk/js-ts.html.md)#embed-options).
Example: ``` https://livecodes.io?js=console.log('Hello World!')&console=open ``` ## Usage - All properties of [configuration object](./configuration-object.html.md) and [embed options](../sdk/js-ts.html.md)#embed-options) that have values of primitive types (e.g. string, number, boolean) can be assigned to a query parameter with the same name. These include: [config](../sdk/js-ts.html.md)#config), [import](../sdk/js-ts.html.md)#import), [lite](../configuration/configuration-object.html.md)#mode), [loading](../sdk/js-ts.html.md)#loading), [template](../sdk/js-ts.html.md)#template), [view](../configuration/configuration-object.html.md)#view), [title](./configuration-object.html.md)#title), [description](./configuration-object.html.md)#description), [activeEditor](./configuration-object.html.md)#activeeditor), [cssPreset](./configuration-object.html.md)#csspreset), [readonly](./configuration-object.html.md)#readonly), [allowLangChange](./configuration-object.html.md)#allowlangchange), [mode](./configuration-object.html.md)#mode), [autoupdate](./configuration-object.html.md)#autoupdate), [autosave](./configuration-object.html.md)#autosave), [delay](./configuration-object.html.md)#delay), [formatOnsave](./configuration-object.html.md)#formatonsave), [theme](./configuration-object.html.md)#theme), [themeColor](./configuration-object.html.md)#themecolor), [appLanguage](./configuration-object.html.md)#applanguage), [recoverUnsaved](./configuration-object.html.md)#recoverunsaved), [welcome](./configuration-object.html.md)#welcome), [showSpacing](./configuration-object.html.md)#showspacing), [layout](./configuration-object.html.md)#layout), [editor](./configuration-object.html.md)#editor), [editorTheme](./configuration-object.html.md)#editortheme), [fontFamily](./configuration-object.html.md)#fontfamily), [fontSize](./configuration-object.html.md)#fontsize), [useTabs](./configuration-object.html.md)#usetabs), [tabSize](./configuration-object.html.md)#tabsize), [lineNumbers](./configuration-object.html.md)#linenumbers), [wordWrap](./configuration-object.html.md)#wordwrap), [closeBrackets](./configuration-object.html.md)#closebrackets), [emmet](./configuration-object.html.md)#emmet), [editorMode](./configuration-object.html.md)#editormode), [semicolons](./configuration-object.html.md)#semicolons), [singleQuote](./configuration-object.html.md)#singlequote), [trailingComma](./configuration-object.html.md)#trailingcomma). Example: ``` ?theme=light&delay=500&lineNumbers=false ``` - Any value given for booleans except `"false"` (including no value) will be considered `true`. Example: all these are considered `true` ``` ?lite=true ?lite=1 ?lite=any ?lite ``` while this is considered `false` ``` ?lite=false ``` - Parameters that expect array of values can be supplied with comma separated values. These include: [tags](./configuration-object.html.md)#tags), [languages](./configuration-object.html.md)#languages), [processors](./configuration-object.html.md)#processors), [stylesheets](./configuration-object.html.md)#stylesheets), [scripts](./configuration-object.html.md)#scripts). Example: ``` ?processors=tailwindcss,autoprefixer ``` - Custom Settings can be set like this: ``` ?customSettings={template:{prerender:false}} ``` or this: ``` ?customSettings.template.prerender=false ``` - Values set in the URL query parameters override those set in [configuration object](./configuration-object.html.md). - Unlike [user settings](../features/user-settings.html.md) that are set in the UI which are saved and subsequently used, those that are set in query parameters are not automatically saved. - Additional query parameters include: - `no-defaults`: `boolean` (Default: `false`). If `true`, the app will not load the [default template/language](../features/default-template-language.html.md). - `x`: `string`. Alias to [`import`](../sdk/js-ts.html.md)#import) (a URL to [import](../features/import.html.md)). - `files`: `string`. A comma-separated [list of files to import](../features/import.html.md)#file-selection). - `raw`: [`Language`](../api/type-aliases/Language.md). When used with `import` or `x`, imports the URL as code of the provided language. - `language`: [`Language`](../api/type-aliases/Language.md). The language to load by default in the editor. - `lang`: [`Language`](../api/type-aliases/Language.md). Alias to `language`. - `active`: `"markup" | "style" | "script" | 0 | 1 | 2`. Alias to [`activeEditor`](./configuration-object.html.md)#activeeditor). - `tools`: `"open" | "full" | "closed" | "console" | "compiled" | "tests" | "none"` The [tools pane](../features/tools-pane.html.md) status. - `console`: `"open" | "full" | "closed" | "none"` The [console](../features/console.html.md) status. - `compiled`: `"open" | "full" | "closed" | "none"` The [compiled code viewer](../features/compiled-code.html.md) status. - `tests`: `"open" | "full" | "closed" | "none"` The [tests panel](../features/tests.html.md) status. - `scrollPosition`: `boolean` (Default: `true`). If `false`, the [result page](../features/result.html.md) [scroll position](../features/result.html.md)#scroll-position) will not be maintained after reload. - Any [`Language`](../api/type-aliases/Language.md) can used as a query parameter, and the value will be used as its code. Example: ``` https://livecodes.io?js=console.log('Hello World!') ``` :::info Examples For usage examples, check [storybook](pathname:///../stories/?path=/story/embed-options-params--select-language) and [unit tests](https://github.com/live-codes/livecodes/blob/develop/src/livecodes/config/__tests__/build-config.spec.ts). ::: {/* TODO: add docs for languageSelector and ToolsStatus */} --- # LiveCodes SDK import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import LiveCodes from '../../src/components/LiveCodes.tsx'; The Software Development Kit (SDK) provides an easy, yet powerful, interface to embed and communicate with LiveCodes playgrounds. The SDK is provided as a light-weight [npm package](#npm-package) (or [jsr package](#jsr)), that is also available from [CDNs](#cdn). It can be used to create playgrounds with a wide variety of [configurations](../configuration/configuration-object.html.md) and [embed options](js-ts.html.md)#embed-options). In addition, [SDK methods](js-ts.html.md)#sdk-methods) allow programmatic communication and control of the playgrounds during runtime. The [JavaScript SDK](js-ts.html.md) is framework/library agnostic. However, wrapper components are also provided for popular libraries (currently [React](react.html.md), [Preact](preact.html.md), [Vue](vue.html.md), [Solid](solid.html.md) and [Svelte](svelte.html.md)), in addition to a [web component](web-components.html.md). [TypeScript support](js-ts.html.md)#typescript-types) provides type-safety and a great developer experience. ## SDK Demo This is an example of an editable embedded playground using the SDK. ## Installation ### NPM Package This is a single npm package for the SDK which provides support for JavaScript/TypeScript, Preact, React, Solid, Svelte, Vue and Web Components. Install the library from npm: ```bash npm2yarn npm install livecodes ``` then it can be used like that: ```js title="index.js" import { createPlayground } from 'livecodes'; createPlayground('#container', { // embed options }); ``` ### JSR The SDK is also available as a [JSR package](https://jsr.io/@livecodes/sdk). Install it with Deno: ```bash deno add jsr:@livecodes/sdk ``` then it can be used like that: ```js title="index.js" import { createPlayground } from 'jsr:@livecodes/sdk'; createPlayground('#container', { // embed options }); ``` ### CDN Alternatively, it can just be loaded from a CDN. ESM: import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import CodeBlock from '@theme/CodeBlock'; export const ESMCode = () => { const { siteConfig } = useDocusaurusContext(); return ( {`
\n`}
); }; UMD: export const UMDCode = () => { const { siteConfig } = useDocusaurusContext(); return ( {`
\n\n `}
); }; :::note The UMD version allows [automatic code pre-fill](../features/code-prefill.html.md)#auto-pre-fill-from-page-dom) from the page DOM when `data-prefill` attribute is added to the script tag. ::: :::info In the full [standalone app](../getting-started.html.md)#standalone-app), the JavaScript SDK is accessible via the global variable `livecodes`, which can be interacted with in the browser console. ::: ## Usage The SDK is currently provided in the following variations: - [JavaScript/TypeScript](./js-ts.html.md) - [Preact](./preact.html.md) - [React](./react.html.md) - [Solid](./solid.html.md) - [Svelte](./svelte.html.md) - [Vue](./vue.html.md) - [Web Components](./web-components.html.md) ## Headless Mode The SDK also has a [headless mode](./headless.html.md). In this mode, no visible output is displayed in the embedding web page. However, all [SDK methods](../sdk/js-ts.html.md)#sdk-methods) are accessible. This provides the power of leveraging the wide range of features and language support offered by LiveCodes, while retaining full control over the UI. ## SDK Playground! A demo page that shows the usage of the SDK can be [found here](https://live-codes.github.io/livecodes-examples/sdk-demo.html) ([source](https://github.com/live-codes/livecodes-examples/blob/gh-pages/sdk-demo.html)). Or edit the SDK playground in LiveCodes. How meta! :) P.S. You may want to use the "Full Screen" button! --- # JavaScript/TypeScript SDK import LiveCodes from '../../src/components/LiveCodes.tsx'; import RunInLiveCodes from '../../src/components/RunInLiveCodes.tsx'; This is the core SDK on which others ([Preact](preact.html.md), [React](react.html.md), [Solid](solid.html.md), [Svelte](svelte.html.md), [Vue](vue.html.md) and [Web Components](web-components.html.md) SDKs) are built on top. It is a light-weight, zero-dependencies library that allows creating, embedding and communication with LiveCodes playgrounds. It also allows easily creating links to playgrounds. ## Installation Please refer to the [SDK installation](./index.html.md)#installation) section. :::info In the full [standalone app](../getting-started.html.md)#standalone-app), the JavaScript SDK is accessible via the global variable `livecodes`, which can be interacted with in the browser console. ::: ## TypeScript Types TypeScript types are [documented here](../api/globals.md) and can be imported from the library. ```ts import type { EmbedOptions, Playground } from 'livecodes'; ``` The following 2 functions are exported by the library: ## `createPlayground` Type: [`(container: string | Element, options?: EmbedOptions) => Promise`](../api/functions/createPlayground.md) The library exports the function `createPlayground` which has 2 parameters: - `container` (required): `HTMLElement` or a string representing a CSS selector. This is the container where the playground is rendered. If not found, an error is thrown (except in [headless mode](./headless.html.md), in which this parameter is optional and can be omitted). - `options` (optional): an object with embed options ([EmbedOptions](../api/interfaces/EmbedOptions.md)). The `createPlayground` function returns a promise which resolves to an object that exposes the SDK methods ([Playground](../api/interfaces/Playground.md)). ```ts import { createPlayground, type EmbedOptions } from 'livecodes'; const options: EmbedOptions = { // appUrl: ... // config: ... // headless: ... // import: ... // loading: ... // params: ... // template: ... }; createPlayground('#container', options).then((playground) => { // the `playground` object exposes the SDK methods // e.g. playground.run() }); ``` :::caution Throws The `createPlayground` function throws an error (promise is rejected) in any of the following conditions: - The first parameter ([`container`](#createplayground)) is not an element or not found (by CSS selector), except in [headless mode](./headless.html.md). - The embed option [`appUrl`](#appurl) is supplied and is not a valid URL. - The embed option [`config`](#config) is supplied and is not an object or a valid URL. - Any of the [SDK methods](#sdk-methods) was called after calling the [`destroy`](#destroy) method. ::: ### Multiple Sources When multiple sources are provided in the [embed options](#embed-options), each is converted to a [configuration object](../configuration/configuration-object.html.md) and the properties are merged. In case there are conflicts between the properties of the configurations, they are overridden in the following order: - [`template`](#template) (lowest precedence) - [`import`](#import) - [`config`](#config) - [`params`](#params) (highest precedence) ## `getPlaygroundUrl` Type: [`(options?: EmbedOptions) => string`](../api/functions/getPlaygroundUrl.md) Gets the URL to playground (as a string) from the provided [options](#embed-options). This can be useful for providing links to run code in playgrounds. Example: ```html
# Hello World!
Open in playground ``` export const getPlaygroundUrlDemo = { html: `
# Hello World!
\nOpen in playground\n`, }; ## `compress` Type: `(uncompressed: string) => string` A utility function that allows compressing the stringified config object (e.g. for [sharing in URL hash](../tutorials/creating-shareable-urls.html.md)). It encodes it in base64 with a few tweaks to make it URI safe. This is the `compressToEncodedURIComponent` function re-exported from [`lz-string`](https://www.npmjs.com/package/lz-string) for convenience. ```js import { compress } from 'livecodes'; const config = { markup: { language: 'html', content: '

Hello World!

', }, }; const compressed = compress(JSON.stringify(config)); ``` ## `decompress` Type: `(compressed: string) => string | null` A utility function that allows decompressing the config object (compressed by [`compress`](#compress)). It decodes it to a string that should be `JSON.parse`d. This is the `decompressFromEncodedURIComponent` function re-exported from [`lz-string`](https://www.npmjs.com/package/lz-string) for convenience. ```js import { decompress } from 'livecodes'; const decompressed = decompress(compressedString); if (decompressed) { try { const config = JSON.parse(decompressed); } catch { // invalid JSON } } ``` ## Embed Options Type: [`EmbedOptions`](../api/interfaces/EmbedOptions.md) The [`createPlayground`](#createplayground) and [`getPlaygroundUrl`](#getplaygroundurl) functions accept an optional object that allows providing different options to the playground. This object can have the following optional properties: ### `appUrl` Type: [`string`](../api/interfaces/EmbedOptions.md#appurl) Default: `"https://livecodes.io/"` Allows loading the playground from a custom URL (e.g. a [self-hosted app](../features/self-hosting.html.md) or a [permanent URL](../features/permanent-url.html.md)). If supplied with an invalid URL, an error is thrown. ### `config` Type: [`string | Partial`](../api/interfaces/EmbedOptions.md#config) Default: `{}` A [configuration object](../configuration/configuration-object.html.md) or a URL to a JSON file representing a configuration object to load. If supplied and is not an object or a valid URL, an error is thrown. ### `headless` Type: [`boolean`](../api/interfaces/EmbedOptions.md#headless) Default: `false` When set to `true`, the playground is loaded in [headless mode](./headless.html.md). ### `import` Type: [`string`](../api/interfaces/EmbedOptions.md#import) A resource to [import](../features/import.html.md) (from any of the supported [sources](../features/import.html.md)#sources)). ### `loading` Type: [`"eager" | "lazy" | "click"`](../api/interfaces/EmbedOptions.md#loading) Default: `"lazy"` Sets how the playground loads: - `"eager"`: The playground loads immediately. - `"lazy"`: A playground embedded low down in the page will not load until the user scrolls so that it approaches the viewport. - `"click"`: The playground does not load automatically. Instead, a "Click-to-load" screen is shown. ### `params` Type: [`UrlQueryParams`](../api/interfaces/EmbedOptions.md#params) An object that represents [URL Query parameters](../configuration/query-params.html.md), that can be used to configure the playground. These 2 snippets produce similar output: ```js import { createPlayground } from 'livecodes'; // use config createPlayground('#container', { config: { markup: { language: 'markdown', content: '# Hello World!', }, }, }); // use params createPlayground('#container', { params: { md: '# Hello World!' } }); ``` ### `template` Type: [`TemplateName`](../api/interfaces/EmbedOptions.md#template) A [starter template](../features/templates.html.md) to load. Allowed valued can be found [here](../api/interfaces/EmbedOptions.md#template). ## SDK Methods The [`createPlayground`](#createplayground) function returns a promise which resolves to an object ([`Playground`](../api/interfaces/Playground.md)) that exposes some useful SDK methods that can be used to interact with the playground. These methods include: ### `load` Type: [`() => Promise`](../api/interfaces/Playground.md#load) When the embed option `loading` is set to `click`, the playground is not loaded automatically. Instead, a screen is shown with "Click to load" button. Calling the SDK method `load()` allows loading the playground. If the playground was not loaded, calling any other method will load the playground first before executing. ```js import { createPlayground } from 'livecodes'; createPlayground('#container').then(async (playground) => { await playground.load(); // playground loaded }); ``` ### `run` Type: [`() => Promise`](../api/interfaces/Playground.md#run) Runs the [result page](../features/result.html.md) (after any required compilation for code). ```js import { createPlayground } from 'livecodes'; createPlayground('#container').then(async (playground) => { await playground.run(); // new result page is displayed }); ``` ### `format` Type: [`(allEditors?: boolean) => Promise`](../api/interfaces/Playground.md#format) [Formats the code](../features/code-format.html.md). By default, the code in all editors (markup, style and script) is formatted. If you wish to format only the active editor, pass the value `false` as an argument. ```js import { createPlayground } from 'livecodes'; createPlayground('#container').then(async (playground) => { await playground.format(); // code in editors is formatted }); ``` ### `getShareUrl` Type: [`(shortUrl?: boolean) => Promise`](../api/interfaces/Playground.md#getshareurl) Gets a [share url](../features/share.html.md) for the current project. By default, the url has a long query string representing the compressed encoded config object. If the argument `shortUrl` was set to `true`, a short url is generated. ```js import { createPlayground } from 'livecodes'; createPlayground('#container').then(async (playground) => { const longUrl = await playground.getShareUrl(); const shortUrl = await playground.getShareUrl(true); }); ``` ### `getConfig` Type: [`(contentOnly?: boolean) => Promise`](../api/interfaces/Playground.md#getconfig) Gets a config object representing the playground state. This can be used to restore state if passed as [embed option](#createplayground) property on creating playground, or can be manipulated and loaded in run-time using [`setConfig`](#setconfig) method. ```js import { createPlayground } from 'livecodes'; createPlayground('#container').then(async (playground) => { const config = await playground.getConfig(); }); ``` ### `setConfig` Type: [`(config: Partial) => Promise`](../api/interfaces/Playground.md#setconfig) Loads a new project using the passed configuration object. If it is a string, it is assumed to be a URL to a JSON file that contains the configuration object. It throws an error if the config object (or URL) is invalid. ```js 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 }); ``` ### `getCode` Type: [`() => Promise`](../api/interfaces/Playground.md#getcode) Gets the playground code (including source code, source language and compiled code) for each editor (`markup`, `style`, `script`), in addition to result page HTML. ```js import { createPlayground } from 'livecodes'; createPlayground('#container').then(async (playground) => { const code = await playground.getCode(); // source code, language and compiled code for the script editor const { content, language, compiled } = code.script; // result page HTML const result = code.result; }); ``` ### `show` Type: [`(panel: 'editor' | 'markup' | 'style' | 'script' | 'console' | 'compiled' | 'tests' | 'result' | 'toggle-result', options?: { full?: boolean; line?: number; column?: number; zoom?: 1 | 0.5 | 0.25 }) => Promise`](../api/interfaces/Playground.md#show) Shows the selected panel, which is either: - Active Editor: `editor` - Specific Editor: `markup`, `style` or `script` - Tool: `console`, `compiled` or `tests` - Result page: `result` or `toggle-result` The second optional argument is an object: - It may have the boolean property `full`, which If `true`, selected editor or result page will take the full vertical and horizontal space of the playground, while tools will take the full vertical and half the horizontal space, leaving some space for the active editor. - The optional properties `line` and `column` allow scrolling to line/column number in the shown editor. - The optional property `zoom` sets the result page [zoom level](../features/result.html.md)#result-page-zoom) (the selected panel must be `result`). ```js import { createPlayground } from 'livecodes'; createPlayground('#container').then(async (playground) => { const delay = (duration) => new Promise((resolve) => { setTimeout(resolve, duration); }); await playground.show('toggle-result'); await delay(2000); await playground.show('style'); await delay(2000); await playground.show('result', { full: true }); await delay(2000); await playground.show('script'); await delay(2000); await playground.show('result', { zoom: 0.5 }); await delay(2000); await playground.show('console', { full: true }); }); ``` ### `runTests` Type: [`() => Promise<{ results: TestResult[] }>`](../api/interfaces/Playground.md#runtests) Runs project [tests](./../features/tests.html.md) (if present) and gets test results. ```js import { createPlayground } from 'livecodes'; createPlayground('#container').then(async (playground) => { const { results } = await playground.runTests(); }); ``` ### `watch` Type: [docs](../api/interfaces/Playground.md#watch) ```ts ((event: 'load', fn: () => void) => { remove: () => void }) & ((event: 'ready', fn: (data: { config: Config }) => void) => { remove: () => void }) & ((event: 'code', fn: (data: { code: Code; config: Config }) => void) => { remove: () => void }) & ((event: 'console', fn: (data: { method: string; args: any[] }) => void) => { remove: () => void }) & ((event: 'tests', fn: (data: { results: TestResult[]; error?: string }) => void) => { remove: () => void }) & ((event: 'destroy', fn: () => void) => { remove: () => void }); ``` Allows to watch for various playground events. It takes 2 arguments: event name and a callback function that will be called on every event. In some events, the callback function will be called with an object that supplies relevant data to the callback function (e.g. code, console output, test results). The `watch` method returns an object with a single method `remove`, which when called will remove the callback from watching further events. ```js import { createPlayground } from 'livecodes'; createPlayground('#container').then((playground) => { const codeWatcher = playground.watch('code', ({ code, config }) => { // this will run on every code change console.log('code:', code); console.log('config:', config); }); const consoleWatcher = playground.watch('console', ({ method, args }) => { // this will run on every console output console[method](...args); }); const testsWatcher = playground.watch('tests', ({ results }) => { // this will run when tests run results.forEach((testResult) => { console.log('status:', testResult.status); // "pass", "fail" or "skip" console.log(testResult.errors); // array of errors as strings }); }); // then later codeWatcher.remove(); consoleWatcher.remove(); testsWatcher.remove(); // events are no longer watched }); ``` These are the events that can be watched and the description of their callback functions: - `"load"`: Called when the playground first loads. ```ts ( event: "load", fn: () => void ) => { remove: () => void } ``` - `"ready"`: Called when a new project is loaded (including when [imported](../features/import.html.md)) and the playground is ready to run. ```ts ( event: "ready", fn: (data: { config: Config }) => void ) => { remove: () => void } ``` - `"code"`: Called when the playground "content" is changed (see [`getCode`](./js-ts.html.md)#getcode) and [`getConfig`](./js-ts.html.md)#getconfig)). This includes changes in: - Code (in editors) - Editor languages - [CSS processors](../features/css.html.md)#css-processors) - [External resources](../features/external-resources.html.md) - Project info (e.g. allows adding content in page head and attributes to `` element) - [Custom settings](../advanced/custom-settings.html.md) (e.g. allows changing [import maps](../features/module-resolution.html.md)#custom-module-resolution)) - Project title - [Test](../features/tests.html.md) code ```ts ( event: "code", fn: (data: { code: Code; config: Config }) => void ) => { remove: () => void } ``` - `"console"`: Called when the playground console gets new outputs. The callback method is passed an object with 2 properties: `"method"` (e.g. `"log"`, `"error"`, etc.) and `"args"` (the arguments passed to the method, as an array). ```ts ( event: "console", fn: (data: { method: string; args: any[] }) => void ) => { remove: () => void } ``` - `"tests"`: Called when tests run and test results are available (see [`runTests`](./js-ts.html.md)#runtests)). ```ts ( event: "tests", fn: (data: { results: TestResult[]; error?: string }) => void ) => { remove: () => void } ``` - `"destroy"`: Called when the playground is destroyed. ```ts ( event: "destroy", fn: () => void ) => { remove: () => void } ``` ### `onChange` **Deprecated**: Use [`watch`](#watch) method instead. Type: [`(fn: ChangeHandler) => { remove: () => void }`](../api/interfaces/Playground.md#onchange) Allows to watch the playground for changes. It takes a callback function that will be called on every change. The callback function will be called with an object that has 2 properties: `code` and `config`, representing the current codes and configuration objects (see [`getCode`](#getcode) and [`getConfig`](#getconfig)). The `onChange` method returns an object with a single method `remove`, which when called will remove the callback from watching changes. ```js import { createPlayground } from 'livecodes'; createPlayground('#container').then((playground) => { const watcher = playground.onChange(({ code, config }) => { // this will run on every code change console.log('code:', code); console.log('config:', config); }); // then later watcher.remove(); // changes are no longer watched }); ``` ### `exec` Type: [`(command: APICommands, ...args: any[]) => Promise<{ output: any } | { error: string }>`](../api/interfaces/Playground.md#exec) Execute custom commands, including: - `"setBroadcastToken"`: Sets [broadcast `userToken`](../features/broadcast.html.md)#technical-details). ```js // in browser console of full app (e.g. https://livecodes.io) await livecodes.exec('setBroadcastToken', 'my-token'); ``` - `"showVersion"`: Logs the current LiveCodes app version, SDK version, git commit SHA, [permanent app URL](../features/permanent-url.html.md) and SDK URL in the browser console. ```js // in browser console of full app (e.g. https://livecodes.io) await livecodes.exec('showVersion'); ``` ### `destroy` Type: [`() => Promise`](../api/interfaces/Playground.md#destroy) Destroys the playground instance, and removes event listeners. Further call to any SDK methods throws an error. ```js import { createPlayground } from 'livecodes'; createPlayground('#container').then(async (playground) => { await playground.destroy(); // playground destroyed // any further SDK call throws an error }); ``` ## Styles ### Default Styles By default, the container element is styled when the SDK is initialized (including width, height, border, etc.). To disable default styles, set the container element attribute `data-default-styles` to `"false"` before initializing. Example: ```html
``` ### Height By default, the playground container height is set to `"300px"`. To change the height, either disable the default styles and override them, or simply set the `data-height` attribute to a number (in pixels) or any valid CSS value for `height` property (e.g. `"100%"` to take the full height of its parent element). Example: ```html
``` ## Demo export const sdkDemo = { js: `import { createPlayground } from "livecodes";\n\nconst params = {\n html: "

Hello World!

",\n css: "h1 {color: blue;}",\n js: 'console.log("Hello, LiveCodes!")',\n console: "open",\n};\n\ncreatePlayground('#container', { params });\n`, html: '
', }; ## Related - [Preact SDK](./preact.html.md) - [React SDK](./react.html.md) - [Solid SDK](./solid.html.md) - [Svelte SDK](./svelte.html.md) - [Vue SDK](./vue.html.md) - [Web Components SDK](./web-components.html.md) - [Embedded Playgrounds](../features/embeds.html.md) --- # Preact SDK import LiveCodes from '../../src/components/LiveCodes.tsx'; The Preact SDK is a thin wrapper around the [JavaScript SDK](js-ts.html.md) to provide an easy to use Preact component, yet retaining the full power, by having access to the [SDK methods](js-ts.html.md)#sdk-methods). ## Demo export const preactSDKDemo = { jsx: `import LiveCodes from "livecodes/preact";\n\nconst App = () => {\n const params = {\n html: "

Hello World!

",\n css: "h1 {color: blue;}",\n js: 'console.log("Hello, World!")',\n console: "open",\n };\n\n return ;\n};\n\nexport default App;\n`, }; ## Installation Please refer to the [SDK installation](./index.html.md)#installation) section. ## Usage The Preact component is provided as the default export from `livecodes/preact`. ```jsx title="JSX" livecodes render=link import LiveCodes from 'livecodes/preact'; export default () => ; ``` ### TypeScript Support Prop types are exported as `Props` from `livecodes/preact`. ```tsx title="TSX" livecodes render=link import LiveCodes, { type Props } from 'livecodes/preact'; const options: Props = { // embed options }; export default () => ; ```

For convenience, the following types are also exported from `livecodes/preact`:
`Code`, `Config`, `EmbedOptions`, `Language`, `Playground`. TypeScript types are [documented here](../api/globals.md). ### Props All [embed options](js-ts.html.md)#embed-options) are available as props with the corresponding types. Example: ```jsx title="JSX" livecodes render=link import LiveCodes from 'livecodes/preact'; const config = { markup: { language: 'markdown', content: '# Hello World!', }, }; export default () => ; ```

In addition, the following props are also available: - `className` Type: `string`. Class name(s) to add to playground container element. Example: ```jsx title="JSX" livecodes render=link import LiveCodes from 'livecodes/preact'; export default () => ; ``` - `height` Type: `string`. Sets the [height of playground container](js-ts.html.md)#height) element. Example: ```jsx title="JSX" livecodes render=link import LiveCodes from 'livecodes/preact'; export default () => ; ``` - `style` Type: `Record`. Defines styles to add to playground container element. Styles set here override the [default styles](js-ts.html.md)#default-styles). Example: ```tsx title="JSX" livecodes render=link import LiveCodes from 'livecodes/preact'; const style = { margin: 'auto', width: '80%', }; export default () => ; ``` - `sdkReady` Type: `(sdk: Playground) => void`. A callback function, that is provided with an instance of the [JavaScript SDK](js-ts.html.md) representing the current playground. This allows making use of full capability of the SDK by calling [SDK methods](js-ts.html.md)#sdk-methods). Example: ```tsx title="TSX" livecodes render=link import { useState } from 'preact/hooks'; import LiveCodes, { type Props } from 'livecodes/preact'; import type { Playground } from 'livecodes'; export default () => { const [playground, setPlayground] = useState(); const onReady = (sdk: Playground) => { setPlayground(sdk); }; const run = async () => { await playground?.run(); }; const options: Props = { config: { markup: { language: 'html', content: '

Hello World!

', }, }, }; return ( <> ); }; ``` ### Reactive Props Changing any prop will cause the playground to reload with the new options. However, changing the `config` prop is an exception — it updates the playground in place using the SDK method [`setConfig`](js-ts.html.md)#setconfig), without triggering a full reload. This allows for a smooth update experience when only the configuration changes. Example: ```jsx title="JSX" livecodes render=link import { useState } from 'preact/hooks'; import LiveCodes from 'livecodes/preact'; export default () => { const [config, setConfig] = useState({ markup: { language: 'html', content: '

Hello World!

', }, }); function switchToMarkdown() { setConfig({ markup: { language: 'markdown', content: '# Hello World! (from Markdown)', }, }); } return ( <> ); }; ``` ## Storybook See [storybook](pathname:///../stories/preact/) for usage examples. ## Related - [SDK Installation](./index.html.md)#installation) - [JS/TS SDK](./js-ts.html.md) - [React SDK](./react.html.md) - [Solid SDK](./solid.html.md) - [Svelte SDK](./svelte.html.md) - [Vue SDK](./vue.html.md) - [Web Components SDK](./web-components.html.md) - [Embedded Playgrounds](../features/embeds.html.md) --- # React SDK import LiveCodes from '../../src/components/LiveCodes.tsx'; The React SDK is a thin wrapper around the [JavaScript SDK](js-ts.html.md) to provide an easy to use react component, yet retaining the full power, by having access to the [SDK methods](js-ts.html.md)#sdk-methods). ## Demo export const reactSDKDemo = { jsx: `import LiveCodes from "livecodes/react";\n\nconst App = () => {\n const params = {\n html: "

Hello World!

",\n css: "h1 {color: blue;}",\n js: 'console.log("Hello, World!")',\n console: "open",\n };\n\n return ;\n};\n\nexport default App;\n`, }; ## Installation Please refer to the [SDK installation](./index.html.md)#installation) section. ## Usage The React component is provided as the default export from `livecodes/react`. ```jsx title="JSX" livecodes render=link lang=react import LiveCodes from 'livecodes/react'; export default () => ; ``` ### TypeScript Support Prop types are exported as `Props` from `livecodes/react`. ```tsx title="TSX" livecodes render=link lang=react.tsx import LiveCodes, { type Props } from 'livecodes/react'; const options: Props = { // embed options }; export default () => ; ```

For convenience, the following types are also exported from `livecodes/react`:
`Code`, `Config`, `EmbedOptions`, `Language`, `Playground`. TypeScript types are [documented here](../api/globals.md). ### Props All [embed options](js-ts.html.md)#embed-options) are available as props with the corresponding types. Example: ```jsx title="JSX" livecodes render=link lang=react import LiveCodes from 'livecodes/react'; const config = { markup: { language: 'markdown', content: '# Hello World!', }, }; export default () => ; ```

In addition, the following props are also available: - `className` Type: `string`. Class name(s) to add to playground container element. Example: ```jsx title="JSX" livecodes render=link lang=react import LiveCodes from 'livecodes/react'; export default () => ; ``` - `height` Type: `string`. Sets the [height of playground container](js-ts.html.md)#height) element. Example: ```jsx title="JSX" livecodes render=link lang=react import LiveCodes from 'livecodes/react'; export default () => ; ``` - `style` Type: `Record`. Defines styles to add to playground container element. Styles set here override the [default styles](js-ts.html.md)#default-styles). Example: ```tsx title="JSX" livecodes render=link lang=react import LiveCodes from 'livecodes/react'; const style = { margin: 'auto', width: '80%', }; export default () => ; ``` - `sdkReady` Type: `(sdk: Playground) => void`. A callback function, that is provided with an instance of the [JavaScript SDK](js-ts.html.md) representing the current playground. This allows making use of full capability of the SDK by calling [SDK methods](js-ts.html.md)#sdk-methods). Example: ```tsx title="TSX" livecodes render=link lang=react.tsx import { useState } from 'react'; import LiveCodes, { type Props } from 'livecodes/react'; import type { Playground } from 'livecodes'; export default () => { const [playground, setPlayground] = useState(); const onReady = (sdk: Playground) => { setPlayground(sdk); }; const run = async () => { await playground?.run(); }; const options: Props = { config: { markup: { language: 'html', content: '

Hello World!

', }, }, }; return ( <> ); }; ``` ### Reactive Props Changing any prop will cause the playground to reload with the new options. However, changing the `config` prop is an exception — it updates the playground in place using the SDK method [`setConfig`](js-ts.html.md)#setconfig), without triggering a full reload. This allows for a smooth update experience when only the configuration changes. Example: ```jsx title="JSX" livecodes render=link lang=react import { useState } from 'react'; import LiveCodes from 'livecodes/react'; export default () => { const [config, setConfig] = useState({ markup: { language: 'html', content: '

Hello World!

', }, }); function switchToMarkdown() { setConfig({ markup: { language: 'markdown', content: '# Hello World! (from Markdown)', }, }); } return ( <> ); }; ``` ## Storybook See [storybook](pathname:///../stories/react/) for usage examples. ## Related - [SDK Installation](./index.html.md)#installation) - [Preact SDK](./preact.html.md) - [Solid SDK](./solid.html.md) - [Svelte SDK](./svelte.html.md) - [Vue SDK](./vue.html.md) - [Web Components SDK](./web-components.html.md) - [Embedded Playgrounds](../features/embeds.html.md) --- # Solid SDK import LiveCodes from '../../src/components/LiveCodes.tsx'; The Solid SDK is a thin wrapper around the [JavaScript SDK](js-ts.html.md) to provide an easy to use Solid component, yet retaining the full power, by having access to the [SDK methods](js-ts.html.md)#sdk-methods). ## Demo export const solidSDKDemo = { solid: `import LiveCodes from "livecodes/solid";\n\nconst App = () => {\n const params = {\n html: "

Hello World!

",\n css: "h1 {color: blue;}",\n js: 'console.log("Hello, World!")',\n console: "open",\n };\n\n return ;\n};\n\nexport default App;\n`, }; ## Installation Please refer to the [SDK installation](./index.html.md)#installation) section. ## Usage The Solid component is provided as the default export from `livecodes/solid`. ```jsx title="JSX" livecodes render=link lang=solid import LiveCodes from 'livecodes/solid'; export default () => ; ``` ### TypeScript Support Prop types are exported as `Props` from `livecodes/solid`. ```tsx title="TSX" livecodes render=link lang=solid.tsx import LiveCodes, { type Props } from 'livecodes/solid'; const options: Props = { // embed options }; export default () => ; ```

For convenience, the following types are also exported from `livecodes/solid`:
`Code`, `Config`, `EmbedOptions`, `Language`, `Playground`. TypeScript types are [documented here](../api/globals.md). ### Props All [embed options](js-ts.html.md)#embed-options) are available as props with the corresponding types. Example: ```jsx title="JSX" livecodes render=link lang=solid import LiveCodes from 'livecodes/solid'; const config = { markup: { language: 'markdown', content: '# Hello World!', }, }; export default () => ; ```

In addition, the following props are also available: - `class` Type: `string`. Class name(s) to add to playground container element. Example: ```jsx title="JSX" livecodes render=link lang=solid import LiveCodes from 'livecodes/solid'; export default () => ; ``` - `height` Type: `string`. Sets the [height of playground container](js-ts.html.md)#height) element. Example: ```jsx title="JSX" livecodes render=link lang=solid import LiveCodes from 'livecodes/solid'; export default () => ; ``` - `style` Type: `JSX.CSSProperties`. Defines styles to add to playground container element. Styles set here override the [default styles](js-ts.html.md)#default-styles). Example: ```tsx title="JSX" livecodes render=link lang=solid import LiveCodes from 'livecodes/solid'; const style = { margin: 'auto', width: '80%', }; export default () => ; ``` - `sdkReady` Type: `(sdk: Playground) => void`. A callback function, that is provided with an instance of the [JavaScript SDK](js-ts.html.md) representing the current playground. This allows making use of full capability of the SDK by calling [SDK methods](js-ts.html.md)#sdk-methods). Example: ```tsx title="TSX" livecodes render=link lang=solid.tsx import { createSignal } from 'solid-js'; import LiveCodes, { type Props } from 'livecodes/solid'; import type { Playground } from 'livecodes'; export default () => { const [playground, setPlayground] = createSignal(); const onReady = (sdk: Playground) => { setPlayground(sdk); }; const run = async () => { await playground()?.run(); }; const options: Props = { config: { markup: { language: 'html', content: '

Hello World!

', }, }, }; return ( <> ); }; ``` ### Reactive Props Changing any prop will cause the playground to reload with the new options. However, changing the `config` prop is an exception — it updates the playground in place using the SDK method [`setConfig`](js-ts.html.md)#setconfig), without triggering a full reload. This allows for a smooth update experience when only the configuration changes. Example: ```jsx title="JSX" livecodes render=link lang=solid import { createSignal } from 'solid-js'; import LiveCodes from 'livecodes/solid'; export default () => { const [config, setConfig] = createSignal({ markup: { language: 'html', content: '

Hello World!

', }, }); function switchToMarkdown() { setConfig({ markup: { language: 'markdown', content: '# Hello World! (from Markdown)', }, }); } return ( <> ); }; ``` ## Storybook See [storybook](pathname:///../stories/solid/) for usage examples. ## Related - [SDK Installation](./index.html.md)#installation) - [JS/TS SDK](./js-ts.html.md) - [Preact SDK](./preact.html.md) - [React SDK](./react.html.md) - [Svelte SDK](./svelte.html.md) - [Vue SDK](./vue.html.md) - [Web Components SDK](./web-components.html.md) - [Embedded Playgrounds](../features/embeds.html.md) --- # Svelte SDK import LiveCodes from '../../src/components/LiveCodes.tsx'; The Svelte SDK is a thin wrapper around the [JavaScript SDK](js-ts.html.md) to provide an easy to use Svelte component, yet retaining the full power, by having access to the [SDK methods](js-ts.html.md)#sdk-methods). It requires Svelte 5 and uses [runes](https://svelte.dev/docs/svelte/what-are-runes) for reactivity. ## Demo export const svelteSDKDemo = { svelte: `\n\n\n`, }; ## Installation Please refer to the [SDK installation](./index.html.md)#installation) section. ## Usage The Svelte component is provided as the default export from `livecodes/svelte`. ```html title="Svelte" livecodes render=link lang=svelte ``` ### TypeScript Support Prop types are exported as `Props` from `livecodes/svelte`. ```html title="Svelte (TypeScript)" livecodes render=link lang=svelte ```

For convenience, the following types are also exported from `livecodes/svelte`:
`Code`, `Config`, `EmbedOptions`, `Language`, `Playground`. TypeScript types are [documented here](../api/globals.md). ### Props All [embed options](js-ts.html.md)#embed-options) are available as props with the corresponding types. Example: ```html title="Svelte" livecodes render=link lang=svelte ```

In addition, the following props are also available: - `class` Type: `string`. Class name(s) to add to playground container element. Example: ```html title="Svelte" livecodes render=link lang=svelte ``` - `height` Type: `string`. Sets the [height of playground container](js-ts.html.md)#height) element. Example: ```html title="Svelte" livecodes render=link lang=svelte ``` - `style` Type: `Record`. Defines styles to add to playground container element. Styles set here override the [default styles](js-ts.html.md)#default-styles). Example: ```html title="Svelte" livecodes render=link lang=svelte ``` - `sdkReady` Type: `(sdk: Playground) => void`. A callback function, that is provided with an instance of the [JavaScript SDK](js-ts.html.md) representing the current playground. This allows making use of full capability of the SDK by calling [SDK methods](js-ts.html.md)#sdk-methods). Example: ```html title="Svelte (TypeScript)" livecodes render=link lang=svelte ``` ### Reactive Props Changing any prop will cause the playground to reload with the new options. However, changing the `config` prop is an exception — it updates the playground in place using the SDK method [`setConfig`](js-ts.html.md)#setconfig), without triggering a full reload. This allows for a smooth update experience when only the configuration changes. Example: ```html title="Svelte" livecodes render=link lang=svelte ``` ## Storybook See [storybook](pathname:///../stories/svelte/) for usage examples. ## Related - [SDK Installation](./index.html.md)#installation) - [JS/TS SDK](./js-ts.html.md) - [Preact SDK](./preact.html.md) - [React SDK](./react.html.md) - [Solid SDK](./solid.html.md) - [Vue SDK](./vue.html.md) - [Web Components SDK](./web-components.html.md) - [Embedded Playgrounds](../features/embeds.html.md) --- # Vue SDK import LiveCodes from '../../src/components/LiveCodes.tsx'; The Vue SDK is a thin wrapper around the [JavaScript SDK](js-ts.html.md) to provide an easy to use vue component, yet retaining the full power, by having access to the [SDK methods](js-ts.html.md)#sdk-methods). ## Demo export const vueSDKDemo = { vue: `\n\n\n`, }; ## Installation Please refer to the [SDK installation](./index.html.md)#installation) section. ## Usage The Vue component is provided as the default export from `livecodes/vue`. ```html title="Vue" livecodes render=link lang=vue ``` ### TypeScript Support Prop types are exported as `Props` from `livecodes/vue`. ```html title="Vue" livecodes render=link lang=vue ```

For convenience, the following types are also exported from `livecodes/vue`:
`Code`, `Config`, `EmbedOptions`, `Language`, `Playground`. TypeScript types are [documented here](../api/globals.md). ### Props All [embed options](js-ts.html.md)#embed-options) are available as props with the corresponding types. Example: ```html title="Vue" livecodes render=link lang=vue ```

In addition, the following prop is also available: - `height` Type: `string`. Sets the [height of playground container](js-ts.html.md)#height) element. Example: ```html title="Vue" livecodes render=link lang=vue ``` ### Events - `"sdkReady"` Type: `(sdk: Playground) => void`. When the playground initializes, the event `"sdkReady"` is emitted. The event handler function is provided with an instance of the [JavaScript SDK](js-ts.html.md) representing the current playground. This allows making use of full capability of the SDK by calling [SDK methods](js-ts.html.md)#sdk-methods). Example: ```html title="Vue" livecodes render=link lang=vue ``` ### Styles Styles can be applied to the component [as usual](https://vuejs.org/guide/essentials/class-and-style.html#binding-html-classes). By default, a set of [default styles](js-ts.html.md)#default-styles) are applied to the playground container. Styles passed to the component override these default styles. Example: ```html title="Vue" livecodes render=link lang=vue ``` ### Reactive Props Changing any prop will cause the playground to reload with the new options. However, changing the `config` prop is an exception — it updates the playground in place using the SDK method [`setConfig`](js-ts.html.md)#setconfig), without triggering a full reload. This allows for a smooth update experience when only the configuration changes. Example: ```html title="Vue" livecodes render=link lang=vue ``` ## Storybook See [storybook](pathname:///../stories/vue/) for usage examples. ## Related - [SDK Installation](./index.html.md)#installation) - [JS/TS SDK](./js-ts.html.md) - [Preact SDK](./preact.html.md) - [React SDK](./react.html.md) - [Solid SDK](./solid.html.md) - [Svelte SDK](./svelte.html.md) - [Web Components SDK](./web-components.html.md) - [Embedded Playgrounds](../features/embeds.html.md) --- # Web Components SDK import LiveCodes from '../../src/components/LiveCodes.tsx'; The Web Components SDK is a wrapper around the [JavaScript SDK](js-ts.html.md) to provide an easy to use custom element (``), yet retaining the full power, by having access to the [SDK methods](js-ts.html.md)#sdk-methods). ## Demo export const webComponentsSDKDemo = { markup: { language: 'html', content: ` `, }, }; ## Installation Please refer to the [SDK installation](./index.html.md)#installation) section. ## Usage The custom element is registered by importing `livecodes/web-components`. ### Using a bundler ```html title="HTML" ``` ### Using a CDN Alternatively, you can load the web components SDK directly from a CDN using a script tag: import CodeBlock from '@theme/CodeBlock'; export const UMDCode = () => ( {` `} ); ### TypeScript Support Types are exported from `livecodes/web-components` for convenience: ```ts title="TypeScript" import type { EmbedOptions, Playground } from 'livecodes/web-components'; ```

The following types are available:
`Code`, `Config`, `EmbedOptions`, `Language`, `Playground`. TypeScript types are [documented here](../api/globals.md). ### Declarative Code via Children \{#declarative-children} You can provide code for the playground declaratively using child elements inside a wrapper `