Code, terminal output, logs and diffs in a dark card: an optional header with a title and a
copy button, line numbers, wrapping, added, removed and highlighted lines, and a small size for
tool output inside a LedgerUI.Components.Trace.trace/1.
<.code_block id="install" title="Terminal" icon="terminal" code={@output} line_numbers wrap />code is a string split into lines. lines is a list instead, each a string or a map with
:text (or :html, already safe HTML) and :variant ("added", "removed", "highlighted"):
<.code_block id="diff" title="mix.exs" lines={[
"defp deps do",
%{text: ~s( {:phoenix, "~> 1.7"},), variant: "removed"},
%{text: ~s( {:phoenix, "~> 1.8"},), variant: "added"},
"end"
]} />Syntax highlighting
language ("elixir", "js") highlights the text of each line on the server with the
lu-code token classes (k keyword, s string/atom, c comment, f function/module,
n number); see highlight/2. No client library is involved. Without language the text is
only escaped. The block (:inner_block) can also hold your own safe HTML, drawn as is.
Copy
copy adds a button (hook LedgerUI.CodeBlock, file priv/static/ledger_ui/hooks/code_block.js)
that copies the code without line numbers. It needs the id.
Summary
Functions
Renders the code block.
Highlights one line of code and returns safe HTML ({:safe, iodata}).
Functions
Renders the code block.
Attributes
id(:string) (required)code(:string) - The code, split into lines. Defaults tonil.lines(:list) - Strings or maps with:text(or:html) and:variant(added, removed, highlighted). Defaults tonil.language(:string) - Highlights each line server-side:elixir,js. Defaults tonil.highlight(:list) - Line numbers drawn highlighted. Defaults to[].title(:string) - Defaults tonil.icon(:string) - Defaults tonil.copy(:boolean) - Defaults tofalse.copy_label(:string) - Defaults to"Copy".copy_text(:string) - What the copy button copies; the code itself whennil. Defaults tonil.line_numbers(:boolean) - Defaults tofalse.start_line(:integer) - Defaults to1.wrap(:boolean) - Defaults tofalse.max_height(:integer) - Defaults tonil.size(:string) - Defaults to"default". Must be one of"default", or"sm".variant(:string) - Defaults to"default". Must be one of"default", or"destructive".class(:any) - Defaults tonil.- Global attributes are accepted.
Slots
actions- Buttons next to the copy button.footer- A row under the code.inner_block- Code as safe HTML (highlighted), drawn as is.
@spec highlight(String.t(), String.t() | nil) :: Phoenix.HTML.safe()
Highlights one line of code and returns safe HTML ({:safe, iodata}).
Supported languages: "elixir" ("ex", "exs") and "js" ("javascript", "ts",
"typescript"); any other value is only escaped. Every piece of the text is escaped.
iex> {:safe, html} = LedgerUI.Components.CodeBlock.highlight("def run(1) # ok", "elixir")
iex> IO.iodata_to_binary(html)
~s|<span class="k">def</span> <span class="f">run</span>(<span class="n">1</span>) <span class="c"># ok</span>|