Skip to content

Commit

Permalink
feat: add conum handling (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
lask79 committed Feb 23, 2025
1 parent abcd281 commit 1667f77
Show file tree
Hide file tree
Showing 7 changed files with 223 additions and 10 deletions.
123 changes: 121 additions & 2 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ All {shiki-languages} and {shiki-themes} are supported.
|Dynamic Line Number color
|Depending on the used background color of the theme the line number color will be adjusted to be better readable.

|Customizable Callout Styling
|Customize the appearance of callouts (conums) with theme-aware colors and optional borders. Colors automatically adjust based on the theme's background for optimal readability.

|===

== Why Shiki instead of Highlight.js?
Expand All @@ -69,6 +72,9 @@ It offers a wide range of themes and can tokenize code in any language that VS C
* *Minimal Client-Side Processing*: Since Shiki does the heavy lifting at build time, there is minimal processing required on the client-side, leading to better performance especially on less powerful devices.


NOTE: At the moment only Shiki in version 0.14.1 is supported.
We have to evaluate if the newer Shiki versions can be used as well.

== Prerequisites

In order to use this extension, you must be using at least Node.js 16 and Antora 3.
Expand Down Expand Up @@ -98,7 +104,7 @@ Open the Antora playbook file and add the extension as follows:
----
antora:
extensions:
- 'antora-shiki-extension' #<1>
- require: 'antora-shiki-extension' #<1>
asciidoc:
attributes:
Expand All @@ -122,8 +128,70 @@ asciidoc:
source-highlighter: shiki
----

You may want to start with this syntax so you don't have to remember to switch to it later when you want to specify configuration.
=== Configuration Options

The extension supports the following configuration options:

[%header,cols="1,1,2"]
|===
|Option |Default |Description

|theme
|nord
|The default theme to use for syntax highlighting

|themes
|[]
|Additional themes to load

|languages
|[asciidoc, java, js, shell, bash, console, zsh, yaml, xml, diff]
|Languages to support

|use_line_numbers
|false
|Enable line numbers globally

|conums_override
|true
|Enable custom styling for callouts (conums)

|conums_bg_color
|auto
|Background color for callouts. If not specified, uses a dimmed version of the theme's foreground color

|conums_fg_color
|auto
|Foreground color for callouts. If not specified, automatically chooses black or white based on background brightness

|conums_show_border
|false
|Whether to show a border around callouts
|===

==== Callout Styling

When `conums_override` is enabled (default), the extension provides theme-aware callout styling:

* By default, callouts use a background color derived from the theme's foreground color
* The text color is automatically chosen to ensure readability
* Borders are disabled by default but can be enabled with `conums_show_border: true`
* You can override both background and foreground colors using `conums_bg_color` and `conums_fg_color`

Example configuration with custom colors:

[source,yaml]
----
antora:
extensions:
- require: 'antora-shiki-extension'
conums_override: true # Enable custom styling
conums_bg_color: '#4a5568' # Dark slate background
conums_fg_color: '#ffffff' # White text
conums_show_border: true # Show borders
----

NOTE: If you simply want to use the callout style defined in your custom antora css please simply set `conums_override` to false.

=== Add handlebars templates

Expand Down Expand Up @@ -280,6 +348,57 @@ The following use cases will be shown:
* Line numbers with specific beginning
* Disable line numbers on single source block
* Disable line numbers on specific page
* Use custom CSS styling for callouts
* Use theme-aware callout colors with border
* Use custom callout colors
* Use dark theme callout colors

=== Use custom CSS styling for callouts

.Antora Playbook
[source,yaml]
----
antora:
extensions:
- require: 'antora-shiki-extension'
conums_override: false # Use your custom CSS styling
----

=== Use theme-aware callout colors with border

.Antora Playbook
[source,yaml]
----
antora:
extensions:
- require: 'antora-shiki-extension'
conums_show_border: true # Add borders to callouts
----

=== Use custom callout colors

.Antora Playbook
[source,yaml]
----
antora:
extensions:
- require: 'antora-shiki-extension'
conums_bg_color: '#2563eb' # Blue background
conums_fg_color: '#ffffff' # White text
----

=== Use dark theme callout colors

.Antora Playbook
[source,yaml]
----
antora:
extensions:
- require: 'antora-shiki-extension'
conums_bg_color: '#1e293b' # Dark slate background
conums_fg_color: '#94a3b8' # Light gray text
conums_show_border: true # Add subtle border
----

=== Default usage with default theme: nord

Expand Down
10 changes: 10 additions & 0 deletions data/css/shiki.css
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,13 @@ code.shiki.has-line-numbers .line::before {
padding: 0.6em;
border-radius: 4px;
}

.doc pre.shiki > code.shiki.override-conums i.conum[data-value] {
color: var(--shiki-conum-fg-color);
background-color: var(--shiki-conum-bg-color);
border: none;
}

.doc pre.shiki > code.shiki.override-conums.with-conum-border i.conum[data-value] {
border: 1px solid;
}
20 changes: 19 additions & 1 deletion docs/modules/ROOT/pages/code.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,26 @@ The following use cases will be shown:
----
antora:
extensions:
- require: 'antora-shiki-extension'
- require: 'antora-shiki-extension' #<1>
----
<1> test

=== Default usage with default theme: nord and callouts

.Antora Playbook
[source,yaml,theme=github-light]
----
antora:
extensions:
- 'antora-shiki-extension' #<1>
asciidoc:
attributes:
source-highlighter: shiki #<2>
----
<1> Register the antora extension
<2> Set the source-highlighter to shiki
<3> test

.Result
[source,javascript]
Expand Down
61 changes: 55 additions & 6 deletions lib/shiki/ShikiSyntaxHighlighter.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class ShikiSyntaxHighlighter {
logger.debug(' > Source file: ' + node.document.reader.file)

// Use the function with your XML string
return moveConumsInsidePreviousLineSpan(node.getContent())
return moveConumsInsidePreviousLineSpan(node.getContent(), logger)
}

handlesHighlighting () {
Expand Down Expand Up @@ -63,14 +63,61 @@ class ShikiSyntaxHighlighter {
}
}

function calculateConumColors(backgroundColor, highlighter, theme, config = {}) {
// If both colors are configured, use them
if (config.conumsBgColor && config.conumsFgColor) {
return {
background: config.conumsBgColor,
foreground: config.conumsFgColor
}
}

// Get theme's foreground color
const themeFg = highlighter.getForegroundColor(theme)

// Calculate background color (default or configured)
const bgColor = config.conumsBgColor || (() => {
// By default, use a slightly dimmed version of the theme's foreground color
return adjustBrightness(themeFg, -15)
})()

// Calculate foreground color (default or configured)
const fgColor = config.conum_fg_color || (() => {
// Calculate brightness of the background color
const r = parseInt(bgColor.substr(1, 2), 16)
const g = parseInt(bgColor.substr(3, 2), 16)
const b = parseInt(bgColor.substr(5, 2), 16)
const brightness = (r * 299 + g * 587 + b * 114) / 1000

// For dark backgrounds, use a light foreground and vice versa
return brightness < 128 ? '#ffffff' : '#000000'
})()

return {
background: bgColor,
foreground: fgColor
}
}

function encloseInPreAndCodeTags (html, theme, lang, useLineNumbers, backgroundColor, startNumber, lineNumberColor) {
const { highlighter, config } = ShikiSyntaxHighlighter.extensionContext
const lineNumberClass = useLineNumbers ? 'has-line-numbers' : ''
const backgroundColorStyle = backgroundColor ? `style="--shiki-background-color: ${backgroundColor};"` : ''

// Handle conum styling classes
let conumClasses = ''
let conumStyles = ''
if (config.conumsOverride) {
conumClasses = 'override-conums' + (config.conumsShowBorder ? ' with-conum-border' : '')
const conumColors = calculateConumColors(backgroundColor, highlighter, theme, config)
conumStyles = `--shiki-conum-bg-color: ${conumColors.background}; --shiki-conum-fg-color: ${conumColors.foreground};`
}

const backgroundColorStyle = backgroundColor ? `style="--shiki-background-color: ${backgroundColor}; ${conumStyles}"` : ''
const startAtLineNumberStyle = startNumber ? `--shiki-line-number-start: ${startNumber};` : ''
const lineNumberColorStyle = lineNumberColor ? ` --shiki-line-number-color: ${lineNumberColor};` : ''
const lineNumberStyle = `style="${startAtLineNumberStyle}${lineNumberColorStyle}"`

return `<pre class="shiki highlight ${theme}" ${backgroundColorStyle}><code ${lang ? ` data-lang="${lang}"` : ''} class="shiki ${lineNumberClass}"${lineNumberStyle}>${html}</code></pre>`
return `<pre class="shiki highlight ${theme}" ${backgroundColorStyle}><code ${lang ? ` data-lang="${lang}"` : ''} class="shiki ${lineNumberClass} ${conumClasses}"${lineNumberStyle}>${html}</code></pre>`
}

function removeGeneratedPreAndCodeTags (html, theme, logger) {
Expand Down Expand Up @@ -131,8 +178,10 @@ function calculateLineNumbers (node, opts, config) {
return toBoolean(blockLevelLineNumbers ?? pageLevelLineNumbers ?? siteLevelLineNumbers)
}

function calculateLineNumberColor (backgroundColor, highlighter, theme) {
// return highlighter.getForegroundColor(theme)
function calculateLineNumberColor (backgroundColor, highlighter, theme, config = {}) {
// Allow override from config
if (config.lineNumberColor) return config.lineNumberColor

// Convert hex to RGB
const r = parseInt(backgroundColor.substr(1, 2), 16)
const g = parseInt(backgroundColor.substr(3, 2), 16)
Expand Down Expand Up @@ -163,7 +212,7 @@ function adjustBrightness (hex, percent) {
return '#' + rr + gg + bb
}

function moveConumsInsidePreviousLineSpan (xmlString) {
function moveConumsInsidePreviousLineSpan (xmlString, logger) {
const dom = new JSDOM(xmlString)
const document = dom.window.document

Expand Down
13 changes: 13 additions & 0 deletions lib/utils/validate-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ function validateConfig (config, packageName, logger) {
languages = defaultLanguages,
useLineNumbers = defaultUseLineNumbers,
registerLanguages = [],
conumsOverride = false,
conumsBgColor,
conumsFgColor,
conumsShowBorder = false,
...unknownOptions
} = config

Expand All @@ -29,13 +33,22 @@ function validateConfig (config, packageName, logger) {
languages,
useLineNumbers,
registerLanguages,
conumsOverride,
conumsBgColor,
conumsFgColor,
conumsShowBorder,
}

logger.info(`Registering ${packageName} with config`)
logger.info(` > Default Theme: ${validatedConfig.theme}`)
logger.info(` > Themes to load: ${Array.from(validatedConfig.themes).join(', ')}`)
logger.info(` > Supported languages: ${Array.from(validatedConfig.languages).sort().join(', ')}`)
logger.info(` > Use line numbers: ${validatedConfig.useLineNumbers}`)
if (validatedConfig.conumsOverride) {
logger.info(` > Override conums: true`)
logger.info(` > Conum colors: bg=${validatedConfig.conumsBgColor || 'default'}, fg=${validatedConfig.conumsFgColor || 'default'}`)
if (validatedConfig.conumsShowBorder) logger.info(` > Conum border: enabled`)
}

return validatedConfig
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "antora-shiki-extension",
"version": "1.0.0-alpha.6",
"version": "1.0.0",
"description": "An antora extension to use shiki as a build-time syntax highligher.",
"author": "Lasse Knudsen <lasse.knudsen79@gmail.com>",
"main": "lib/index.js",
Expand Down
4 changes: 4 additions & 0 deletions test/local-antora-playbook.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,7 @@ antora:
# aliases: ['css']
# theme: "github-light"
languages: ["asciidoc", "java", "js", "shell", "bash", "console", "zsh", "yaml", "diff"]
conums_override: true # Enable custom conum styling
# conums_bg_color: '#4a5568' # Optional: Custom background color
# conums_fg_color: '#ffffff' # Optional: Custom foreground color
conums_show_border: false # Optional: Show border around conums (default: false)

0 comments on commit 1667f77

Please sign in to comment.