Code Input

CodeInput create a code editor with syntax highlight and return its value.

It is built on CodeMirror 6: line numbers, bracket matching, undo history and search (Ctrl/Cmd+F) come with it.

API

Interface

func CodeInput(c *tgframe.Container, label string, conf ...*CodeInputConf) string

Parameters

  • c is Parent container.
  • label is the label for the code input.
  • conf is an optional configuration, at most one.
// CodeInputConf is the configuration for a code input.
type CodeInputConf struct {
	tgframe.Base // ID

	// Language is the language to highlight, leave empty to use `go`.
	// Supported: go, python, javascript, typescript, jsx, tsx, json, cpp,
	// sql, html, css, markdown, yaml, shell. "text" or any other value
	// leaves the code unhighlighted.
	Language string

	// Height is the fewest lines shown; the editor grows with the code from
	// there. default value is 5.
	Height int

	// MaxHeight is the most lines shown before the editor scrolls. 0 lets it
	// grow without limit.
	MaxHeight int

	// Default is the default value of the code input.
	Default string

	// ResetKey drops the app user's input and restores Default whenever it
	// changes, e.g. a hash of the file the code was filled from.
	ResetKey string
}

Example

	code := tgcomp.CodeInput(p.Main, "Code",
		&tgcomp.CodeInputConf{
			Language:  "python",
			Height:    4,
			MaxHeight: 15,
			Default:   "def hello(name):\n    return f\"Hello, {name}!\"\n",
		})
	tgcomp.Code(p.Main, code,
		&tgcomp.CodeConf{ID: "code_input_result", Language: "python"})

Height

The editor starts at Height lines and grows as the code gets longer, so the whole code shows without scrolling. Set MaxHeight to stop growing at that many lines; past it the editor scrolls.

When the code is sent

Like Textarea, typing does not rerun the page. The code is sent when the editor loses focus, or at once on Ctrl+Enter (Cmd+Enter on macOS). Leaving the editor without a change sends nothing.

Keyboard

Tab indents rather than moving focus: a tab for go, two spaces otherwise. To leave the editor by keyboard, press Esc and then Tab.