Interactive JSX
Add small React tools to ordinary .md articles with a jsx-live fence or jsx
shortcode. Hugo compiles JSX; the browser runs the component. No MDX conversion,
Node compilation step, CDN, or npm installation is needed for the bundled React
APIs. The rest of the article keeps Hugo’s normal Markdown rendering.
Explicitly trust executable content
Enable this feature in your site’s configuration, not article front matter:
[params]
jsx = trueThe default is disabled. Enabling it authorizes executable content throughout the site (or the language whose parameters you configure). Review component code and imports like other site JavaScript. This is not a safe language for untrusted contributions or generated code that has not been reviewed.
Ordinary jsx fences, snippet inclusions and files merely attached to a page are
still display-only. Only the explicit jsx-live fence or jsx shortcode mounts a
component. Goldmark’s unsafe HTML setting can remain off.
A component in a Markdown fence
Use a normal JSX module whose default export is a React component:
```jsx-live {title="Counter" caption="Each click adds one." fallback="The counter starts at zero."}
import { useState } from 'react';
import { Row } from 'sidera/ui';
export default function Counter() {
const [count, setCount] = useState(0);
return <Row>
<output className="jsx-metric" aria-live="polite">{count}</output>
<button type="button" onClick={() => setCount(n => n + 1)}>Add one</button>
</Row>;
}
```React hooks belong inside components. JSX is not MDX: **bold**, headings and lists
inside JSX are not parsed as Markdown. Keep explanations outside the fence or use
normal JSX elements such as <strong> and <p> inside it. Do not call createRoot
yourself; Sidera owns the mount point and gives each instance a unique React ID prefix.
A component can also be placed in a paired shortcode:
{{< jsx title="Counter" >}}
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(n => n + 1)}>Count: {count}</button>;
}
{{< /jsx >}}This is a block component, not an in-sentence inline shortcode. In nested folds,
boxes or grid cells, use the normal outer-%/nested-< composition.
Do not embed Hugo shortcode syntax in JavaScript strings without escaping it;
Hugo processes shortcode delimiters before the JSX compiler sees the source.
Page-bundle files and imports
content/posts/encoder/
├── index.md
└── widgets/
├── Encoder.jsx
├── encoding.js
└── encoder.css{{< jsx src="widgets/Encoder.jsx" css="widgets/encoder.css" title="Base64 encoder" />}}Use the explicit self-closing /> form when there is no body. An empty jsx-live
fence with the same src attribute is equivalent. src must be an exact,
case-sensitive .jsx resource key of the current page. No wildcards, traversal,
remote URL or basename guessing. A source file and an inline body cannot compete.
Local imports use Hugo’s page-resource namespace. Write keys relative to the page-bundle root, even from a module inside a subdirectory:
// widgets/Encoder.jsx
import { useState } from 'react';
import { encode } from './widgets/encoding.js';This deliberately uses ./widgets/encoding.js, not ./encoding.js. Hugo’s
importContext resolves resource keys as written; it is not a general
filesystem-relative module resolver. Use explicit extensions. Keeping widget
modules at the bundle root makes simple ./helper.js imports natural. Shared
modules in assets/ and additional installed npm packages follow Hugo’s native
resolution rules; Sidera does not fetch or install dependencies during a build.
Sidera supplies optional layout and core UI components through sidera/ui,
including Stack, Row, Grid, Field, Button, Slider, RadioGroup,
Checkbox, Result, Metric, Badge and Icon. This is a built-in Hugo build alias, not
an npm package to install. It works in inline fences and attached modules, in both
page and sandbox modes. Unused exports are removed by the native build; no chart, math or icon runtime is added by these controls.
The supported shared React package imports are react, react/jsx-runtime,
react-dom and react-dom/client, pinned to 19.3.0 (Scheduler 0.28.0).
All page-mode islands use one React instance through an import map. Do not bundle
a second React copy or install libraries requiring an incompatible React version.
Other React subpaths, compiler plugins and arbitrary package compatibility are not
promised. Modern browsers with ES modules and import maps are required.
Use the explicit css option for a page-local stylesheet, not import './x.css'.
The latter is not supported by this integration’s Hugo 0.166.0 js.Build path and
ordinary CSS imports fail compilation. The stylesheet follows native resource
minification/fingerprinting; URLs in CSS are not rewritten into bundle imports.
Source and compiled assets are public. Hugo can publish original page-bundle attachments too. Not displaying source in the article does not hide code or secrets.
Options
| Name | Contract |
|---|---|
src | Optional exact current-page .jsx resource; excludes a body |
css | Optional exact current-page .css resource |
icons | Optional whitespace-separated named icons to bundle for Icon, e.g. "notebook github"; no full catalog is shipped |
charts | Set to echarts to make the optional local ECharts runtime available to this island |
title | Optional nonblank plain-text label above the component; not an article heading |
caption | Optional nonblank plain-text figure caption below the component |
appearance | plain (default) or card; independent of execution mode |
fallback | Optional nonblank plain text for no-JS/loading/error/print; localized generic text when omitted |
mode | page (default) or sandbox |
height | Sandbox only; integer 160–1200 pixels, default 280 |
Each entry source is limited to 1 MB. This is not a limit on imported libraries or the component’s runtime resource usage. Unknown options, invalid paths and JSX syntax errors fail the build. Missing default exports and rendering/import failures show a local error and the authored fallback without replacing the article.
Titles, captions and appearance
Components are frameless by default: no outer border, background or padding.
Normal vertical separation from surrounding prose remains. appearance="card"
adds a padded, bordered panel; it does not change execution permissions. Internal
controls and result panels keep their styling in either appearance.
{{< jsx src="Calculator.jsx" title="Reading-time estimate" caption="Adjust the speed to compare estimates." appearance="card" />}}A title identifies the tool above its controls; it does not create a heading or TOC entry. A caption describes it below, using the same styling as image and diagram captions. Both are optional: omit a title when the article heading or component already supplies one, and avoid repeating the same text in both places. An isolated iframe is labeled by title, then caption, then a localized default.
Optional layout helpers
Use native elements for controls and meaning. Stack and Row only arrange their
children; they do not introduce another control library or automatically assign
form, toolbar or field semantics.
import { useState } from 'react';
import { Stack, Row } from 'sidera/ui';
export default function Actions() {
const [count, setCount] = useState(0);
return <Stack>
<output aria-live="polite">Count: {count}</output>
<Row style={{ justifyContent: 'flex-end' }}>
<button type="button" onClick={() => setCount(0)}>Reset</button>
<button type="button" onClick={() => setCount(n => n + 1)}>Add one</button>
</Row>
</Stack>;
}| Helper | Default layout |
|---|---|
Stack | Vertical grid, full-width children, standard spacing |
Row | Horizontal flex row, vertically centered, wrapping on small screens |
Both render a single div using the same CSS as jsx-stack / jsx-row. Native
elements with those classes remain supported; wrappers and classes can be mixed.
Normal div props, including id, className, style, aria-*, data-*, event
handlers, children and React refs, pass through. Keep actual forms, labels,
fieldsets and outputs as native elements.
The optional gap prop accepts one of none, small, normal, or large:
| Value | Spacing |
|---|---|
none | Zero |
small | Compact spacing, useful for a label/control group |
normal (default) | Existing theme spacing for that layout; Stack and Row have different defaults |
large | More separation between groups |
Unsupported gap values trigger the component’s normal error fallback. Use style
for a deliberate custom value rather than passing arbitrary CSS to gap.
Responsive Grid
Grid renders a single div and accepts direct children; no GridItem wrappers
are needed. columns is an integer from 1 to 6 (default 2), and gap uses the
same none, small, normal, large scale as Stack/Row. Columns are an upper
bound, not a demand to squeeze controls into unreadable tracks. Grid uses
12rem minimum tracks when room permits and collapses to fewer columns as its
container narrows. A container narrower than 12rem gets one fitting track.
Empty tracks collapse, children keep their document order, and rows have equal
track widths. It is not a masonry layout or a table replacement.
import { Grid, Metric } from 'sidera/ui';
export default function Summary() {
return <Grid columns={3} gap="large">
<Metric label="Words" value="1,800" />
<Metric label="Speed" value="300" unit="words/minute" />
<Metric label="Estimate" value="6" unit="minutes" />
</Grid>;
}Normal div props/ref, className, style, aria-*, data-* and events pass
through. Native CSS remains available for specialized layout; Grid does not add
column-span, breakpoint or layout-language props.
Row alignment
Use standard Flexbox through style; there are no separate align or justify
props. For example, <Row style={{ justifyContent: 'center' }}> centers a group.
justifyContent | Horizontal placement in the default left-to-right row |
|---|---|
flex-start | Start/left (default) |
center | Centered group |
flex-end | End/right |
space-between | First/last items at opposite edges; remaining space between |
space-evenly | Equal free space between items and at both edges |
alignItems controls the cross axis: center is the default; flex-start,
flex-end, baseline, and stretch are useful alternatives. The gap is minimum
spacing, not a replacement for alignment. Wrapped rows distribute space separately
on each line. Repeated alignment choices can instead live in a component-scoped
CSS class; no extra wrapper component is required.
Core UI components
Import the components you need from sidera/ui. They work in both page and sandbox
modes, with native controls and the same theme styles. No provider or additional
package installation is required. Native elements and the existing CSS classes
remain supported; the components are optional conveniences, not a form framework.
Field and native input
Field groups a label, one native control, and optional hint/error messages. Its
child must be a render function: it receives id, aria-describedby and
aria-invalid, which you spread onto the actual control. Ordinary nested input
children are not supported. This avoids cloning children or guessing which nested
element is the control.
import { useState } from 'react';
import { Field, Button, Result, Stack, Row } from 'sidera/ui';
export default function Greeting() {
const [name, setName] = useState('Sidera');
const [submitted, setSubmitted] = useState(false);
const error = submitted && !name.trim() ? 'Enter a name.' : '';
return <Stack>
<Field label="Name" hint="Used only in this component." error={error}>
{control => <input {...control} value={name}
onChange={event => { setName(event.target.value); setSubmitted(false); }} />}
</Field>
<Row><Button variant="primary" onClick={() => setSubmitted(true)}>Greet</Button></Row>
<Result label="Greeting">
<output aria-live="polite">{submitted && !error ? `Hello, ${name}!` : 'Ready when you are.'}</output>
</Result>
</Stack>;
}label is required. hint is optional inline React content; error is an optional
string. A nonempty error is displayed and marks the control invalid. Neither is
an automatic live region. An optional id names the input, not the Field
wrapper; otherwise React generates an instance-safe ID. Do not reuse explicit
IDs across repeated tools. To add other descriptions, merge their IDs with the
supplied aria-describedby, rather than replacing it.
The author owns the control’s value, native props/ref, event handlers, parsing, validation and when an error appears. Keep editable text as a string when empty or partial values matter. Field does not automatically coerce numbers or track blur/submission. It also works with native textarea and select elements.
Controlled choices and sliders
| Component | Required props | Optional props |
|---|---|---|
Slider | label, min, max, value, onValueChange(number) | step (1), formatValue, marks, hint, error, id, disabled, inputProps |
Checkbox | label, checked, onCheckedChange(boolean) | hint, error, id, disabled, inputProps |
RadioGroup | label, options, value, onValueChange(string) | appearance (list), hint, error, id, name, disabled |
These components are controlled: provide both state and its callback. There is no separate default-value API. Disabling a control preserves its value; toggling disabled alone does not call the change callback. Native elements retain normal React event callbacks; the composites use value-named callbacks deliberately.
import { useState } from 'react';
import { Stack, Slider, Checkbox, RadioGroup, Result, Metric } from 'sidera/ui';
export default function Estimate() {
const [enabled, setEnabled] = useState(true);
const [speed, setSpeed] = useState(300);
const [words, setWords] = useState('short');
const count = words === 'short' ? 1800 : 3600;
return <Stack>
<Checkbox label="Enable speed adjustment" checked={enabled} onCheckedChange={setEnabled} />
<Slider label="Reading speed" min={100} max={600} step={25}
value={speed} onValueChange={setSpeed} disabled={!enabled}
formatValue={value => `${value} words/minute`}
marks={[{value:100,label:'100'}, {value:300,label:'300'}, {value:600,label:'600'}]} />
<RadioGroup label="Article length" appearance="segmented" value={words}
onValueChange={setWords} options={[
{value:'short',label:'1,800 words'}, {value:'long',label:'3,600 words'}
]} />
<Result label="Estimate">
<Metric label="Reading time" value={Math.ceil(count / speed)} unit="minutes" />
</Result>
</Stack>;
}Slider uses a native single-thumb range. Bounds/value must be finite, max must
exceed min, step must be positive, and the value must be in range and aligned
with min + n * step (allowing floating-point roundoff). Off-step values are
configuration errors, rather than silently displaying a different thumb value. formatValue
returns a string for the displayed and accessible value; its default is String.
Marks are { value, label } records with finite in-range values and string labels.
Use a few short labels so they remain legible on mobile. Marks label the scale;
step controls snapping. Exact numeric entry is a separate native input/Field.
RadioGroup uses native radios in a labelled fieldset. appearance is list,
segmented or cards; these are visual alternatives, not tab navigation.
Each option has a unique string value, a label, and optional description and
disabled flag. value must match an option or be null for no initial selection.
Names are generated per instance unless the author supplies name. Descriptions
are associated separately from labels. Keep labels short for segments, use cards
or a list for longer descriptions, and do not nest interactive elements inside
option labels. Checkbox similarly keeps its whole label clickable.
Actions, results and metrics
| Component | Contract |
|---|---|
Button | Native button props/ref. variant: primary, secondary (default), quiet; intent: normal (default), danger. Default type="button"; submit/reset are explicit |
Result | Optional label, children, and tone: info (default), neutral, success, warning, danger |
Metric | Required label and displayed value; optional unit and note. Uses a definition list |
Result is a block container that may hold text, tables or several metrics. Its
label names a group; it is not an article heading or a live announcement. Metric
displays the supplied value without parsing, rounding or inferring currency or
whether a negative number is bad. Use native samp for machine output, and a
small native output/status region when an explicit conversion needs announcing.
Avoid announcing the whole result continuously while dragging a slider.
Button width follows normal layout. In Row it normally takes content width;
directly inside Stack it stretches to the grid cell. Use style={{width:'100%'}}
for an explicit full-width button. There is no block or fullWidth prop.
Resetting a controlled tool means updating its React state; native reset alone
does not reset controlled values. Links remain native links, not Button variants.
Native props, styling and boundaries
For composite components, className, style, data-*, event handlers and refs
apply to the root element. Field and Slider/Checkbox have div roots; RadioGroup
has a fieldset; Result has a div; Metric has a dl. The optional Field/Slider/Checkbox
id is reserved for the input; RadioGroup’s id names its fieldset.
Slider/Checkbox inputProps is a narrow escape hatch for native input attributes
and the input ref, for example inputProps={{name:'enabled',value:'yes',ref:input}}
on Checkbox. Extra aria-describedby IDs are merged with hint/error associations.
It cannot replace type, id, controlled state/default state, onChange, disabled,
label/invalid associations, range bounds/step or aria-valuetext. Checkbox permits
native value for form submission; Slider owns its value. Use the top-level
component props for owned behavior. Invalid component configurations use the
normal island error fallback; they are not reader validation messages.
Core components introduce no network, clipboard, persistence or parent-frame operations. Core controls work in the existing opaque sandbox without new permissions; its fixed height and no-JS/error/print fallback remain unchanged. Theme-owned presentation follows the current palette; author labels/messages are not translated automatically. Result tones and paired danger-button fill roles follow site overrides through the bounded frame token bridge, alongside the existing accent roles.
Badges and named icons
Badge is a compact inline span for status/category text. Its tone is neutral
(default), info, success, warning or danger, using the same semantic family
roles as Result. It accepts React children and ordinary span props/ref. It does
not assign a status role, live announcement or click behavior automatically.
Keep meaningful text; color alone is not a status explanation.
Icon reuses Sidera’s named icon registry, including Solar
UI icons, the selected Font Awesome brands and site overrides. Declare every name
the component can use in the island’s icons option. Only those rendered entries
are included in its compiled module, with no icon font, runtime fetch or whole
catalog download.
```jsx-live {icons="notebook github"}
import { Row, Badge, Icon } from 'sidera/ui';
export default function Labels() {
return <Row>
<Badge tone="info"><Icon name="notebook" /> Reading notes</Badge>
<a href="https://github.com/calfzhou/hugo-theme-sidera">
<Icon name="github" /> Sidera source
</a>
</Row>;
}
```For an attached module, use the same option on the shortcode:
{{< jsx src="Summary.jsx" icons="notebook github" />}}The icons list is whitespace-separated, not comma-separated. Unknown declared
names fail the build; duplicate declarations are harmless. Runtime name may
change among declared entries. An undeclared name fails that island through its
normal fallback; name="" renders nothing. No SVG markup prop or child content is
accepted. Artwork still passes the existing trusted-maintainer geometry validation;
native site renderer overrides remain authoritative. Changing selected icon data
or renderer output invalidates the compiled JSX resource during preview rebuilds.
By default Icon’s wrapper and SVG are decorative and hidden from accessibility
APIs. For a meaningful standalone symbol, supply a nonblank text label: the
wrapper becomes a named image. For a button or link, prefer visible action text
and a decorative Icon. Keep icons noninteractive; the enclosing native control
owns focus, keyboard behavior and its accessible name.
Icon has a span root and accepts normal span props/ref, className and style.
The existing --icon-size (default 1em) and --icon-color (default inherited color)
control artwork size/color; geometry and aspect ratio are unchanged. These tokens
also cross the bounded sandbox theme bridge. Do not edit the registry just to
resize one use. Explicit JSX icons are authored content, like the icon shortcode,
and remain visible when params.icons=false disables optional shell decoration.
Both Badge and Icon work in page and sandbox modes with the same API. Their fallback/print behavior is the island’s ordinary authored fallback. Icons preserve the existing licenses/provenance; selecting a brand does not grant trademark rights.
Reactive ECharts
For a chart driven by React state, import EChart from sidera/charts, not
sidera/ui, and declare charts="echarts" on the island. It is an optional Hugo
build alias, not an npm package. Ordinary controls do not load the chart engine.
For fixed authored JSON, keep using the normal chart fence/shortcode.
```jsx-live {charts="echarts" fallback="For y = a × x², y is 25a at x = −5 and x = 5."}
import { useMemo, useState } from 'react';
import { Stack, Slider } from 'sidera/ui';
import { EChart } from 'sidera/charts';
export default function Quadratic() {
const [a, setA] = useState(1);
const option = useMemo(() => ({
tooltip: { trigger: 'axis' },
xAxis: { type: 'value', name: 'x' },
yAxis: { type: 'value', name: 'y' },
series: [{
id: 'curve', name: 'a × x²', type: 'line', showSymbol: false,
data: Array.from({ length: 41 }, (_, i) => {
const x = (i - 20) / 4;
return [x, a * x * x];
}),
}],
}), [a]);
return <Stack>
<Slider label="Coefficient a" min={0.25} max={3} step={0.25}
value={a} onValueChange={setA} />
<EChart option={option} height={320}
label={'y = ' + a + ' × x² for x from −5 to 5.'} />
<p>At x = ±5, y = {25 * a}.</p>
</Stack>;
}
```For a page-bundle component, declare the dependency on its shortcode instead:
{{< jsx src="Explorer.jsx" charts="echarts" />}}
{{< jsx src="Explorer.jsx" charts="echarts" mode="sandbox" height=900 />}}The plot renders directly in its existing JSX environment: page DOM in page mode, or inside the JSX iframe in sandbox mode. There is no nested chart iframe and no permission expansion. One versioned engine asset is shared by chart components in a document; each sandbox has its own JavaScript realm. The pinned ECharts 6.1.0 common bundle and its notices are reused. The engine is requested when a mounted chart has measurable space, not by ordinary islands or a hidden chart that has not become measurable.
Props and supported configuration
| Prop | Contract |
|---|---|
option | Required complete, data-only ECharts option object |
label | Required nonblank accessible description, authored text |
height | Plot height in pixels; integer 200–1200, default 320 |
className, style | Optional styling for the outer chart container |
Width follows the container. height sizes the plot; the shortcode’s sandbox
height sizes the whole iframe, including controls and explanatory text. Do not
assume they are interchangeable. Provide enough iframe height or allow its normal
internal scrolling.
The JSX adapter supports line and bar series. Use a line series with areaStyle
for an area plot. series is an array of 0–50 objects; an empty array clears the
series. The option uses the existing chart vocabulary: title, legend, grid,
xAxis/yAxis, dataset, series, tooltip, axisPointer, dataZoom, color/backgroundColor,
textStyle and animation settings. Data/axis/series configuration stays native
ECharts, rather than a parallel set of Sidera chart props.
Options must be JSON-like plain objects/arrays containing strings, finite numbers, booleans and null. Omit unused properties instead of setting them to undefined. Functions, getters, custom object prototypes, symbol properties, sparse arrays and cycles are rejected without invoking getters or serialization hooks. Limits are 1 MB serialized UTF-8, nesting depth 24, 10,000 items per array and 100,000 visited values. Dataset sources must be arrays of row objects/arrays.
Tooltips are confined rich text. HTML tooltips, image symbols/assets, links, graphics/toolbox, transforms, universal transitions and callback-based options are not accepted. The adapter does not fetch data or revive functions. It does not expose a chart-instance ref, event map, merge policy or export toolbar. These are component contracts, not an extra security sandbox for page-mode author code.
Complete-snapshot updates
A new option object reference replaces the authored configuration with
notMerge: true. Removed settings and series do not linger. Reader-selected
legend/zoom state is not restored; authored selections or zoom bounds in the new
snapshot still apply. The chart remains interactive between snapshots.
- Use
useMemoto keep option identity stable across unrelated React state changes. - Build a new option when data changes; do not mutate a previous option in place.
- Changing label or plot dimensions does not replace the authored snapshot.
- Theme/palette or reduced-motion changes reapply the latest snapshot and may reset reader view state.
- Normal updates reuse the chart instance. React unmounting disconnects observers
and disposes that instance. React
keycan deliberately request a fresh instance. - While loading or hidden, only the latest committed snapshot matters; intermediate updates are not replayed later.
Sidera validates/clones the input instead of mutating the author’s object. Invalid
snapshots hide stale plot output and show a localized error while sibling controls
remain usable. A later valid snapshot can recover the chart. Runtime load failures
show a chart-local error; reload the page after resolving a blocked/missing asset.
Using EChart without declaring charts="echarts" also produces a chart-local error.
Theme, layout and accessibility
Defaults use Sidera’s UI typography, readable text/axis colors, a categorical palette and a transparent background. Explicit supported author options take precedence. Animation is off by default for reactive charts; authors may enable it, but reduced-motion preference overrides animations. The existing bounded adaptive-layout helper handles ordinary single-grid charts; explicit grid geometry and more complex layouts remain author-controlled.
Native ECharts interactions remain inside the plot. A label does not explain every chart: keep meaningful prose or a data alternative nearby, especially when readers need exact values. Supply an island fallback for no-JS and print; these use the authored fallback rather than a captured reader-state chart. Unlike the fixed-JSON chart shortcode, this adapter has no automatic source disclosure/download controls.
Styling and page integration
Start without a component stylesheet. Native buttons, labels, inputs, selects and
textareas inherit Sidera’s typography, palette, focus and disabled treatment.
aria-invalid="true" marks invalid controls; aria-pressed gives toggle buttons
a selected appearance. These defaults are scoped to JSX roots, not ordinary article
content, and are also available in sandbox mode. Errors and invalid-control borders
use --danger, independently of pinned-label styling. Normal input and button
boundaries use --control-border; disabled buttons do not acquire hover styling.
Author-facing CSS classes
These classes are supported authoring conveniences inside a JSX component. Use
them directly with native elements, or alongside Stack and Row. They avoid
recreating ordinary theme styles; custom classes remain welcome for special UI.
| Class | Purpose |
|---|---|
jsx-stack | Vertical layout with standard gaps, without extra paragraph margins |
jsx-field | A label and its control/help text grouped with a smaller gap |
jsx-row | Wrapping row of actions or related values |
jsx-gap-none / jsx-gap-small / jsx-gap-large | Gap modifiers for jsx-stack or jsx-row; omit for normal spacing |
jsx-note | Muted help or secondary text |
jsx-error | Validation message; empty messages take no space |
jsx-result | Result panel with the theme accent and spacing for child elements |
jsx-metric | Prominent numeric value |
Renderer-owned classes such as content-jsx, jsx-root, jsx-title, jsx-status,
jsx-fallback and jsx-frame are not author layout primitives. Do not add these
wrappers yourself or depend on their internal markup to build a component.
jsx-result uses normal UI typography. Use native <samp> for machine output;
it gets the theme’s monospace font. For example, this component needs no CSS file:
import { useId, useState } from 'react';
import { Stack } from 'sidera/ui';
export default function Greeting() {
const id = useId();
const [name, setName] = useState('Sidera');
const error = name.trim() ? '' : 'Enter a name.';
return <Stack>
<Stack gap="small">
<label htmlFor={id}>Name</label>
<input id={id} value={name} onChange={e => setName(e.target.value)}
aria-invalid={!!error} aria-describedby={`${id}-hint ${id}-error`} />
<p id={`${id}-hint`} className="jsx-note">Only used in this component.</p>
</Stack>
<p id={`${id}-error`} className="jsx-error" aria-live="polite">{error}</p>
<output className="jsx-result" aria-live="polite">
{error ? 'Waiting for a name.' : `Hello, ${name}!`}
</output>
</Stack>;
}The layout wrappers and CSS classes alone do not supply accessibility semantics. Core components supply their documented native wiring and interaction; authors still own validation logic, meaningful labels and appropriate live announcements.
Component-specific styles
Custom styles remain useful for unusual geometry, visualizations or deliberate
presentation choices: a connected calendar table, a larger reading output, or a
fixed-height encoded result. Keep those rules with the component via the optional
css resource. Prefer theme tokens such as --text, --muted, --accent,
--surface, --danger and --code over redefining ordinary controls or writing separate
light/dark palettes. Defaults have low specificity so scoped custom classes can
override them without !important. For filled custom controls, pair --accent-fill
with --accent-on-fill and use --accent-fill-hover for the hover background.
These three roles, --danger, --secondary-text and --control-border are included
in the sandbox theme-token bridge.
Page integration
Page mode renders directly into the article. Scope custom CSS to your component’s class. The page is not a CSS or JavaScript sandbox. Components can use browser APIs, read page storage, make network requests (subject to the site’s policy), and alter the page. For example:
export default function LightButton() {
return <button onClick={() => window.Sidera.setColorMode('light')}>Light mode</button>;
}Sidera.setColorMode() accepts light, dark or auto, updates the site’s controls
and preserves the visitor preference when storage is available. Components should
clean up subscriptions/listeners in effects. Component-local state is independent
between mounts; JavaScript module-level variables remain shared on the page.
Do not let theme DOM-enhancement scripts mutate React-owned elements. This feature is intended for small tools, not replacing the article, its headings or navigation.
Optional sandbox
{{< jsx src="widgets/Calculator.jsx" mode="sandbox" height=320 title="Calculator" />}}The component runs in an opaque iframe with allow-scripts only. Its fixed height
is author-controlled; overflowing content can scroll within the frame. A small
validated message channel updates the light/dark palette and theme tokens. There
is no bridge for storage, theme switching, navigation or arbitrary host operations.
Its CSP permits local scripts/styles but blocks connections, images, fonts, forms, objects and nested frames. It has no parent DOM access or usable site localStorage. Libraries that require those capabilities will not work here. The frame gets its own React realm; it cannot share the parent’s live React instance.
This isolates DOM and styling, not CPU/memory consumption. Neither mode makes infinite loops safe. Render error boundaries do not catch every asynchronous or event-handler exception. Do not run untrusted code in either mode.
Loading, fallback and preview
Page-mode modules load near the viewport, including after a closed fold opens. An imported module’s top-level statements run on import, not on first click. There is no automatic source-code disclosure. The fallback text remains visible without JavaScript, during loading or after failure. Print output uses fallback text. Widget values are not server-rendered, included in the article TOC, or dynamically added to search/RSS. Titles, captions and fallback explanations can be indexed; runtime controls are excluded from Sidera’s search body.
Hugo only compiles author code; it does not import or server-render it during builds. Browser globals can therefore be used by client components, but this does not turn dependency compilation into a security sandbox. Keep the build toolchain and any additional installed packages trusted.
Run your normal hugo server --disableFastRender preview. Editing the Markdown,
JSX or imported resources triggers Hugo rebuilds; no separate MDX watcher or Node
server is required. A syntax error should be fixed before publishing, not worked
around by enabling unsafe HTML. For restrictive site CSPs, allow the generated
local modules and authorize the generated inline import map; sandbox mode also
requires same-site frames. The frame’s own policy stays restrictive.