function normalizeCode(code) { return code .trim() .replace(/^```go/, '') .replace(/^```/, '') .replace(/```$/, '') .replace(/<([^>]+)>/g, '') .trim() } function updatePlaygroundView(goplay, id, code) { const textarea = document.getElementById(`textarea-${id}`) textarea.value = code textarea.style.height = textarea.scrollHeight + 'px'; textarea.style.overflowY = 'hidden'; textarea.addEventListener('input', function() { this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px'; }) const toolRun = document.getElementById(`hugo-goplay-tool-${id}-run`) const toolTry = document.getElementById(`hugo-goplay-tool-${id}-try`) const toolShare = document.getElementById(`hugo-goplay-tool-${id}-share`) toolRun.addEventListener('click', () => { const parent = document.getElementById(id) const pre = document.createElement('pre') const container = document.createElement('code') container.classList.add('text') pre.appendChild(container) parent.replaceChildren(pre) goplay.renderCompile(container, textarea.value); }); [toolTry, toolShare].forEach((v) => { v.addEventListener('click', async () => { const shareUrl = await goplay.share(code) window.open(shareUrl, '_blank').focus(); }) }); } function createFieldPlayground(goplay, id, code) { code = createFieldPlaygroundCode(code) updatePlaygroundView(goplay, id, code) } function createPlaygroundWithAutoImportMail(goplay, id, code) { let lines = normalizeCode(code).split("\n") let results = ["package main", ""] let imports = [] let body = [] lines.forEach((line) => { if (line.substr(0, 7) === '@import') { imports.push(' ' + line.replace('@import', '').trim()) } else { body.push(" " + line) } }) if (imports.length > 0) { results.push("import (") imports.forEach((v) => { results.push(v) }) results.push(")", "") } results.push("func main() {") body.forEach((v, i) => { if (i == 0 && v.trim() == "") { return } results.push(v) }) results.push("}", "") updatePlaygroundView(goplay, id, results.join("\n")) } function createFieldPlaygroundCode(code) { code = normalizeCode(code) let lines = code.split("\n"); for (let i in lines) { lines[i] = [' ', lines[i]].join('') } code = lines.join("\n"); return `package main import ( "fmt" "html/template" "strings" "gitnet.fr/deblan/go-form/form" "gitnet.fr/deblan/go-form/theme" ) func main() { ${code} r(form.NewForm(field)) } func r(f *form.Form) { render := theme.NewRenderer(theme.Html5) tpl, _ := template.New("example").Funcs(render.FuncMap()).Parse(\`{{ form_widget (.Form.GetField "Foo") }}\`) b := new(strings.Builder) tpl.Execute(b, map[string]any{"Form": f}) fmt.Println(b.String()) }` }