integrate the playground right into the site

This commit is contained in:
Kat Marchán 2025-01-01 16:43:19 -08:00
parent 8a6163dfcb
commit 1fb26fccb7
No known key found for this signature in database
GPG Key ID: AEB529C08A3C7E9E
13 changed files with 3083 additions and 11 deletions

View File

@ -1,8 +1,10 @@
import { createHighlighter } from "shiki"; import { createHighlighter } from "shiki";
import eleventyPluginVite from "@11ty/eleventy-plugin-vite";
import path from "node:path"; import path from "node:path";
import { readFile } from "node:fs/promises"; import { readFile } from "node:fs/promises";
export default function (eleventyConfig) { export default function (eleventyConfig) {
eleventyConfig.addPlugin(eleventyPluginVite);
eleventyConfig.addPassthroughCopy("src/CNAME"); eleventyConfig.addPassthroughCopy("src/CNAME");
eleventyConfig.addMarkdownHighlighter(shikiHighlight); eleventyConfig.addMarkdownHighlighter(shikiHighlight);

5
.gitignore vendored
View File

@ -1,2 +1,3 @@
docs/ /docs/
node_modules/ /node_modules/
/.11ty-vite/

35
LICENSE Normal file
View File

@ -0,0 +1,35 @@
The following license covers the `/play` page and its related assets:
MIT License
Copyright (c) 2024 Danielle Smith
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
======================================================
The following license covers the rest of the KDL site:
Copyright 2024 Kat Marchán
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

2487
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -2,11 +2,10 @@
"name": "kdl.dev", "name": "kdl.dev",
"version": "1.0.0", "version": "1.0.0",
"description": "", "description": "",
"main": "index.js",
"scripts": { "scripts": {
"clean": "rm -rf docs && mkdir -p docs/styles", "clean": "rm -rf docs && mkdir -p docs/styles",
"static": "cp -r static/* docs", "static": "cp -r static/* docs",
"build": "npm run clean && npm run static && postcss src/styles/global.css > docs/styles/global.css", "build": "npm run clean && npm run static && postcss src/styles/global.css > docs/styles/global.css && postcss src/styles/play.css > docs/styles/play.css",
"dev": "npm run build && eleventy --config=.eleventy.mjs --serve", "dev": "npm run build && eleventy --config=.eleventy.mjs --serve",
"prod": "NODE_ENV=production npm run build && eleventy --config=.eleventy.mjs", "prod": "NODE_ENV=production npm run build && eleventy --config=.eleventy.mjs",
"format": "prettier --write src ./*.js ./.*.js" "format": "prettier --write src ./*.js ./.*.js"
@ -16,12 +15,22 @@
"license": "ISC", "license": "ISC",
"devDependencies": { "devDependencies": {
"@11ty/eleventy": "^3.0.0", "@11ty/eleventy": "^3.0.0",
"@11ty/eleventy-plugin-vite": "^6.0.0-alpha.3",
"@parcel/packager-raw-url": "^2.13.3",
"@parcel/transformer-webmanifest": "^2.13.3",
"@tailwindcss/typography": "^0.3.1", "@tailwindcss/typography": "^0.3.1",
"autoprefixer": "^10.1.0", "autoprefixer": "^10.1.0",
"postcss": "^8.2.1", "postcss": "^8.2.1",
"postcss-cli": "^8.3.1", "postcss-cli": "^8.3.1",
"prettier": "^2.2.1", "prettier": "^2.2.1",
"shiki": "^1.24.2", "shiki": "^1.24.2",
"tailwindcss": "^2.0.2" "svgo": "^3.3.2",
"tailwindcss": "^2.0.2",
"@bgotink/kdl": "^0.2.1",
"monaco-editor": "^0.52.0",
"monaco-themes": "^0.4.4"
},
"@mischnic/parcel-resolver-root": {
"/": "./docs"
} }
} }

View File

@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta <meta
name="description" name="description"
content="kdl is a document language, mostly based on SDLang, with xml-like semantics that looks like you're invoking a bunch of CLI commands!" content="This is the KDL playground: try out KDL documents and see the resulting structure!"
/> />
<title>{{ title }}</title> <title>{{ title }}</title>
@ -16,7 +16,6 @@
<link rel="manifest" href="/site.webmanifest"> <link rel="manifest" href="/site.webmanifest">
<meta name="msapplication-TileColor" content="#da532c"> <meta name="msapplication-TileColor" content="#da532c">
<meta name="theme-color" content="#ffffff"> <meta name="theme-color" content="#ffffff">
</head> </head>
<body> <body>
<main>{{ content }}</main> <main>{{ content }}</main>

24
src/_includes/play.html Normal file
View File

@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
name="description"
content="kdl is a document language, mostly based on SDLang, with xml-like semantics that looks like you're invoking a bunch of CLI commands!"
/>
<title>{{ title }}</title>
<link rel="stylesheet" href="/styles/play.css">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="theme-color" content="#ffffff">
<script type="module" src="play.js"></script>
</head>
<body>
{{ content }}
</body>
</html>

View File

@ -53,7 +53,8 @@ package {
} }
``` ```
For more details, see the [overview below](#overview). For more details, see the [overview below](#overview). [Play with it in your
browser!](./play/)
There's a living There's a living
[specification](https://github.com/kdl-org/kdl/blob/main/SPEC.md), as well as [specification](https://github.com/kdl-org/kdl/blob/main/SPEC.md), as well as
@ -76,8 +77,6 @@ The language is based on [SDLang](https://sdlang.org), with a [number of
modifications and clarifications on its syntax and behavior](#why-not-sdlang). modifications and clarifications on its syntax and behavior](#why-not-sdlang).
We are grateful for their work as an inspiration to ours. We are grateful for their work as an inspiration to ours.
[Play with it in your browser (currently v1 only)!](https://kdl-play.danini.dev/)
</section> </section>
<section class="kdl-section" id="design-and-discussion"> <section class="kdl-section" id="design-and-discussion">
@ -426,7 +425,7 @@ SDLang is an excellent base, but I wanted some details ironed out, and some
things removed that only really made sense for SDLang's current use-cases, including things removed that only really made sense for SDLang's current use-cases, including
some restrictions about data representation. KDL is very similar in many ways, except: some restrictions about data representation. KDL is very similar in many ways, except:
* The grammar and expected semantics are [well-defined and specified](SPEC.md). * The grammar and expected semantics are [well-defined and specified](https://github.com/kdl-org/kdl/blob/main/SPEC.md).
This was the original impetus for working on KDL, followed by details that This was the original impetus for working on KDL, followed by details that
seemed like they could be improved. seemed like they could be improved.
* There is only one "number" type. KDL does not prescribe representations, but * There is only one "number" type. KDL does not prescribe representations, but

19
src/play.md Normal file
View File

@ -0,0 +1,19 @@
---
layout: play.html
title: KDL Playground
---
<header>
<h1>
<a href="https://kdl.dev/" target="_blank">
<img src="/logo.svg" width="64" height="32" />
</a>
Play!
</h1>
<nav class="social">
<a href="https://github.com/kdl-org/kdl-org.github.io" target="_blank">
<img src="/github.svg" width="32" height="32" />
</a>
</nav>
</header>
<div id="input"></div>
<div id="output"></div>

200
src/styles/play.css Normal file
View File

@ -0,0 +1,200 @@
@import url('https://fonts.googleapis.com/css2?family=Nunito:wght@900&display=swap');
html, body {
width: 100%;
height: 100%;
margin: 0;
}
html {
font-size: 100%;
box-sizing: border-box;
padding: 8px;
}
*, *::before, *::after {
box-sizing: inherit;
}
body {
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
display: grid;
gap: 8px;
grid-template-rows: auto 1fr;
grid-template-columns: 1fr 1fr;
grid-template-areas: 'header header' 'input output';
padding: 0;
}
header {
grid-area: header;
display: flex;
align-items: center;
}
nav.social {
margin-left: auto;
}
nav.social a:not(:hover) {
opacity: 0.5;
}
h1 {
color: #FFE5D7;
-webkit-text-stroke: 2px #FFB2B2;
font-family: 'Nunito', cursive;
margin: 0;
display: flex;
align-items: center;
gap: 0.25em;
}
h1 a {
display: flex;
align-items: center;
}
h1 img {
height: 1em;
width: auto;
}
#input {
/* border: 4px solid transparent; */
grid-area: input;
min-height: 100%;
min-width: 100%;
}
.monaco-editor, .monaco-editor .overflow-guard, .monaco-editor .monaco-scrollable-element {
border-radius: 8px;
}
#output {
grid-area: output;
overflow-x: hidden;
overflow-y: auto;
word-break: break-all;
border: 4px solid transparent;
padding: 0 8px;
position: relative;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
border-radius: 8px;
background-color: #2e3440;
color: #D8DEE9;
}
#output.error {
border-color: #f14c4c;
}
.error > * {
opacity: 0.25;
}
.error::after {
content: '⚠️';
position: absolute;
top: 8px;
right: 8px;
}
.node {
}
.name::before {
font-family: codicon;
}
.node.open > .name::before {
content: '\eab4';
}
.node:not(.open) > .name::before {
content: '\eab6';
}
.node:not(.open) > .content {
display: none;
}
.content {
margin: 4px 0 0 8px;
padding: 0 0 0 12px;
display: flex;
flex-direction: column;
gap: 4px;
list-style: none;
border-left: 1px solid #707070;
}
.content:empty:before {
content: 'empty';
color: #707070;
border: 1px dotted #707070;
border-radius: 4px;
font-size: .75rem;
display: inline;
width: fit-content;
padding: 0px 2px;
}
.content > li {
margin: 0;
padding: 0;
}
.name {
display: flex;
align-items: center;
gap: 4px;
border: none;
background: none;
font-size: inherit;
margin: 0;
padding: 0;
cursor: pointer;
font-family: inherit;
font-size: inherit;
color: inherit;
}
.tag {
color: #3dc9b0;
font-size: 0.75rem;
padding: 2px 6px;
border-radius: 4px;
white-space: nowrap;
box-shadow: inset 0 0 0 1px #3dc9b0;
}
.key {
white-space: nowrap;
color: #8FBCBB;
}
.key::after {
content: '=';
margin-left: 4px;
color: #D8DEE9;
}
.value, .property {
display: flex;
align-items: flex-start;
gap: 4px;
}
.boolean, .null {
color: #81A1C1;
}
.string {
color: #A3BE8C;
}
.number {
color: #B48EAD;
}

1
static/github.svg Normal file
View File

@ -0,0 +1 @@
<svg width="98" height="96" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M48.85 0C21.84 0 0 22 0 49.22 0 70.97 14 89.39 33.4 95.9c2.43.49 3.32-1.06 3.32-2.37 0-1.14-.08-5.05-.08-9.12-13.59 2.93-16.42-5.87-16.42-5.87-2.18-5.7-5.42-7.17-5.42-7.17-4.45-3.01.33-3.01.33-3.01 4.93.32 7.52 5.05 7.52 5.05 4.37 7.5 11.4 5.38 14.23 4.07.4-3.18 1.7-5.38 3.08-6.6-10.84-1.14-22.25-5.38-22.25-24.28 0-5.38 1.94-9.78 5.02-13.2-.49-1.22-2.19-6.28.48-13.04 0 0 4.13-1.3 13.43 5.05a46.97 46.97 0 0 1 12.21-1.63c4.13 0 8.33.57 12.22 1.63 9.3-6.35 13.42-5.05 13.42-5.05 2.67 6.76.97 11.82.49 13.04a18.9 18.9 0 0 1 5.01 13.2c0 18.9-11.4 23.06-22.32 24.28 1.78 1.55 3.32 4.48 3.32 9.13 0 6.6-.08 11.9-.08 13.52 0 1.3.89 2.86 3.31 2.37a49.18 49.18 0 0 0 33.4-46.7C97.72 22 75.8 0 48.86 0z" fill="#24292f"/></svg>

After

Width:  |  Height:  |  Size: 832 B

155
static/play/kdl.monarch.js Normal file
View File

@ -0,0 +1,155 @@
function concat(a, b) {
if (!a) return b
if (!b) return a
return `${a}.${b}`
}
function makeStrings(prefix = '') {
return [
[/(#*)"/, { token: concat(prefix, 'string.quote'), bracket: '@open', next: `@${prefix}stringraw.\$1` }],
[/"/, { token: concat(prefix, 'string.quote'), bracket: '@open', next: `@${prefix}string` }],
]
}
function makeString(prefix = '') {
return [
[/[^\\"]+/, concat(prefix, 'string')],
[/@escapes/, concat(prefix, 'string.escape')],
[/\\./, concat(prefix, 'string.escape.invalid')],
[/"/, { token: concat(prefix, 'string.quote'), bracket: '@close', next: '@pop' }]
]
}
function makeStringraw(prefix = '') {
return [
[/[^"#]+/, { token: concat(prefix, 'string') }],
[
/"(#*)/,
{
cases: {
'$1==$S2': { token: concat(prefix, 'string.quote'), bracket: '@close', next: '@pop' },
'@default': { token: concat(prefix, 'string') }
}
}
],
[/["#]/, { token: concat(prefix, 'string') }]
]
}
export const config = {
comment: {
lineComment: '//',
blockComment: ['/*', '*/']
},
brackets: [
['(', ')'],
['{', '}']
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '(', close: ')' },
{ open: '"', close: '"' }
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '(', close: ')' },
{ open: '"', close: '"', notIn: ['string'] }
]
}
export const language = {
tokenPostfix: '.kdl',
defaultToken: 'invalid',
keywords: [
'null', 'true', 'false'
],
typeKeywords: [
],
operators: [
'='
],
brackets: [ ['{','}','delimiter.curly'], ['(',')','delimiter.parenthesis'] ],
escapes: /\\([nrt0\"''\\]|x\h{2}|u\{\h{1,6}\})/,
intSuffixes: /[iu](8|16|32|64|128|size)/,
floatSuffixes: /f(32|64)/,
tokenizer: {
root: [
{ include: '@constant' },
{ include: '@numbers' },
{ include: '@strings' },
{ include: '@whitespace' },
[/\(/, { token: '@brackets', next: '@type_annotation' }],
[/\/-\{/, { token: 'comment.slashdash', next: '@slashdash_children' }],
[/\/-/, { token: 'comment.slashdash', next: '@slashdash' }],
[
/(?![\\{\}<>;\[\]\=,\(\)\s])([\u0021-\uFFFF]+)(=)/,
['identifier', 'operator']
],
[
/(?![\\{\}<>;\[\]\=,\(\)\s])[\u0021-\uFFFF]+/,
'identifier'
],
[/=/, 'operator'],
[/;/, 'delimiter.semicolon'],
[/\\/, 'delimiter.line-break'],
[/[{}()]/, '@brackets'],
],
whitespace: [
[/[ \t\r\n]+/, 'white'],
[/\/\*/, 'comment', '@comment'],
[/\/\/.*$/, 'comment']
],
comment: [
[/[^\/*]+/, 'comment'],
[/\/\*/, 'comment', '@push'],
['\\*/', 'comment', '@pop'],
[/[\/*]/, 'comment']
],
constant: [
[/#null/, 'keyword.constant.null'],
[/#true|#false/, 'keyword.constant.boolean'],
[/#-?inf|#nan/, 'number.float.constant']
],
numbers: [
[/(0o[0-7_]+)(@intSuffixes)?/, 'number.octal'],
[/(0b[0-1_]+)(@intSuffixes)?/, 'number.binary'],
[/[\d][\d_]*(\.[\d][\d_]*)?[eE][+-][\d_]+(@floatSuffixes)?/, 'number.float'],
[/\b(\d\.?[\d_]*)(@floatSuffixes)?\b/, 'number.float'],
[/(0x[\da-fA-F]+)_?(@intSuffixes)?/, 'number.hex'],
[/[\d][\d_]*(@intSuffixes?)?/, 'number.integer']
],
strings: makeStrings(),
string: makeString(),
stringraw: makeStringraw(),
commentstrings: makeStrings('comment'),
commentstring: makeString('comment'),
commentstringraw: makeStringraw('comment'),
type_annotation: [
{ include: '@strings' },
[
/(?![\\{\}<>;\[\]\=,\(\)\s])[\u0021-\u0028\u0030-\uFFFF]+/,
'type.identifier'
],
[/\)/, { token: '@brackets', next: '@pop' }]
],
slashdash: [
{ include: '@commentstrings' },
[/[=;()]|\S/, 'comment.slashdash'],
[/\s/, { token: 'white', next: '@pop' }]
],
slashdash_children: [
{ include: '@whitespace' },
[/[=;()]/, 'comment.slashdash'],
{ include: '@commentstrings' },
[/[^{}]+/, 'comment.slashdash'],
[/\{/, { token: 'comment.slashdash', bracket: '@open', next: '@push' }],
[/\}/, { token: 'comment.slashdash', bracket: '@close', next: '@pop' }]
]
},
}

141
static/play/play.js Normal file
View File

@ -0,0 +1,141 @@
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker.js?url'
import * as monaco from 'monaco-editor/esm/vs/editor/editor.main.js'
import * as KDL from "@bgotink/kdl";
import nordTheme from 'monaco-themes/themes/Nord.json'
import * as KDLMonarch from './kdl.monarch'
self.MonacoEnvironment = {
getWorkerUrl: function (moduleId, label) {
return EditorWorker
}
}
monaco.languages.register({ id: 'kdl' })
monaco.languages.setMonarchTokensProvider('kdl', KDLMonarch.language)
monaco.languages.setLanguageConfiguration('kdl', KDLMonarch.config)
monaco.editor.defineTheme('nord', nordTheme)
monaco.editor.setTheme('nord')
function addTag(el, tag) {
if (!tag) return
const tagEl = document.createElement('span')
tagEl.classList.add('tag')
tagEl.textContent = tag
el.append(tagEl)
}
function buildValue(value) {
const valueEl = document.createElement('span')
if (value === null) {
valueEl.textContent = "null"
valueEl.classList.add('null')
} else if (value === true || value === false) {
valueEl.textContent = value ? 'true' : 'false'
valueEl.classList.add('boolean')
} else if (typeof value === "string") {
valueEl.textContent = JSON.stringify(value)
valueEl.classList.add('string')
} else {
valueEl.textContent = value.toString()
valueEl.classList.add('number')
}
return valueEl
}
/**
* @param {KDL.Node} node
* @returns {HTMLElement}
*/
function buildNodeTree(node) {
const nodeEl = document.createElement('div')
nodeEl.classList.add('node')
nodeEl.classList.add('open')
const nameEl = document.createElement('button')
nameEl.addEventListener('click', () => nodeEl.classList.toggle('open'))
nameEl.classList.add('name')
addTag(nameEl, node.getTag())
nameEl.append(document.createTextNode(node.getName()))
nodeEl.append(nameEl)
const contentEl = document.createElement('ul')
contentEl.classList.add('content')
node.entries.forEach((entry) => {
if (entry.name === null) {
const valueEl = document.createElement('li')
valueEl.classList.add('value')
addTag(valueEl, entry.getTag())
valueEl.append(buildValue(entry.getValue()))
contentEl.append(valueEl)
} else {
const propEl = document.createElement('li')
propEl.classList.add('property')
const keyEl = document.createElement('span')
keyEl.classList.add('key')
keyEl.textContent = entry.getName()
propEl.append(keyEl)
addTag(propEl, entry.getTag())
propEl.append(buildValue(entry.getValue()))
contentEl.append(propEl)
}
})
node.children?.nodes.forEach(child => {
contentEl.append(buildNodeTree(child))
})
nodeEl.append(contentEl)
return nodeEl
}
addEventListener("DOMContentLoaded", (event) => {
const editor = monaco.editor.create(document.getElementById('input'), {
value: 'foo 1 "two" three=(decimal)0xff {\n (thing)bar #true #false #null\n}',
language: 'kdl',
scrollBeyondLastLine: false,
minimap: { enabled: false },
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
fontSize: 16,
automaticLayout: true
})
const model = editor.getModel()
const output = document.getElementById('output')
function parse() {
const markers = []
try {
let document = KDL.parse(model.getValue())
output.classList.remove('error')
output.innerHTML = ''
document.nodes.forEach(node => {
output.append(buildNodeTree(node))
})
} catch (error) {
output.classList.add('error')
if (error instanceof KDL.InvalidKdlError) {
markers.push({
message: error.message,
severity: monaco.MarkerSeverity.Error,
startLineNumber: error.token?.start.line,
startColumn: error.token?.start.column,
endLineNumber: error.token?.end.line,
endColumn: error.token?.end.column,
})
} else {
console.error(error)
markers.push({
message: "Failed to parse KDL",
severity: monaco.MarkerSeverity.Error,
startLineNumber: 1,
startColumn: 1,
})
}
}
monaco.editor.setModelMarkers(model, "owner", markers)
}
model.onDidChangeContent(parse)
parse()
})