Skip to content
This package has changed name, was previously @soleil/svelte-config.
More information
Markdown

@soleil-se/config-svelte

A collection of Svelte components and utilities for WebApp, RESTApp and Widget configurations.

Settings

Enter the title here.

Option 1Option 2

Install locally in your app:

Terminal window
npm i @soleil-se/config-svelte
Migration from version 1

Version 2 has multiple breaking changes when upgrading from version 1.

  1. Update Svelte version

    Ensure your app is using Svelte 5, as Svelte 3 and 4 are no longer supported.
    You can use @soleil-se/run for automatic migration:

    Terminal window
    npx @soleil-se/run migrate-svelte-5

    Read more about @soleil-se/run

  2. Change to type specific selector components

    The NodeSelector, DropdownSelector, and ListSelector now have type-specific wrappers to better reflect the type of content they are selecting and to better align with Sitevision naming conventions.
    Replace generic selectors with the appropriate type-specific component. The generic selectors are still available but should only be used when no type-specific component exists.

    <NodeSelector name="page" label="Page" type="page" />
    <DropdownSelector name="metadata" type="metadata" label="Metadata" />
    <ListSelector name="pages" type="page" label="Pages" />
    <PageSelector name="page" label="Page" />
    <MetadataSelector name="metadata" label="Metadata" />
    <PageList name="pages" label="Pages" />
  3. Update selectable types

    The selectable prop for NodeSelector, DropdownSelector, ListSelector and their type-specific counterparts is now called types to better align with Sitevision naming conventions.

    <PageSelector
    name="page"
    label="Page"
    selectable="sv:page"
    types="sv:page"
    />
    <MetadataSelector
    name="metadata"
    label="Metadata"
    selectable="sv:metadataTextDefinition"
    types="sv:metadataTextDefinition"
    />
    <PageList
    name="pages"
    label="Pages"
    selectable="sv:page"
    types="sv:page"
    />
  4. Update image components

    The old ImageSelector component is renamed to ImageSettings and is no longer a panel; ImageSelector now selects Sitevision image nodes.
    If you previously used ImageSelector for selecting images, replace it with the new ImageSettings component wrapped in a Panel.
    For backwards compatibility, you can pass the legacyNames prop to ImageSettings to support the old naming convention.

    <ImageSelector name="image" label="Image" />
    <Panel heading="Image">
    <ImageSettings name="image" legacyNames />
    </Panel>
  5. Update validation

    Validation is now built in. Remove the @soleil-se/config-validate dependency and use the component validate prop or the validation utilities.

    Terminal window
    npm uninstall @soleil-se/config-validate

    Remove the import and usage of validate from your code.

    import { createConfigApp } from '@soleil-se/config-svelte';
    import { registerConfigValidate } from '@soleil-se/config-validate';
    import { mount } from 'svelte';
    import App from './App.svelte';
    registerConfigValidate();
    createConfigApp(({ target, props }) => mount(App, { target, props }));

Read here for usage with TypeScript.

General UI components for building configuration interfaces.

Wrappers for Sitevision components.

The components above are based on the following base components:

Regular input components.

Custom components.

Only standard config:

  • DirectoryMyApp
    • Directoryconfig
      • App.svelte
      • config.js
    • Directorysrc/
      • …
    • …

With global config:

  • DirectoryMyApp
    • Directoryconfig
      • App.svelte
      • config.js
    • Directoryconfig_global
      • App.svelte
      • config.js
    • Directorysrc/
      • …
    • …

With server side code:

  • DirectoryMyApp
    • Directoryconfig
      • App.svelte
      • config.js
      • index.js
    • Directorysrc/
      • …
    • …

Use Sitevision’s standard save behavior by giving each component a name. The component reads its initial value from the configuration and Sitevision saves it under that name. If both a saved configuration value and a value prop are provided, the saved configuration value takes precedence.

config.js
import { createConfigApp } from '@soleil-se/config-svelte';
import { mount } from 'svelte';
import App from './App.svelte';
createConfigApp(({ target, props }) => mount(App, { target, props }));
App.svelte
<script>
import { Input, Panel } from '@soleil-se/config-svelte';
</script>
<Panel heading="Inställningar">
<Input name="text" label="Text" />
</Panel>

Use this approach when the configuration needs to save values that are not represented by named fields, or when values are managed directly in the root component. The onSave callback must return the complete object to save.

App.svelte
<script>
import { Input, Panel } from '@soleil-se/config-svelte';
import { onSave } from '@soleil-se/config-svelte/utils';
let { values } = $props();
onSave(() => values);
</script>
<Panel heading="Inställningar">
<Input label="Text" bind:value={values.text} />
</Panel>

Use the standard name-based approach unless you need this additional control.

The root component receives saved values through the reactive values prop. When an input is bound to a property on values, changes are reflected in that object.

window.CONFIG_VALUES is a plain object created from the values loaded when the configuration is initialized. It is useful for reading the initial values, but it is not reactive and does not track edits made in the form.

Use the values prop when you need the current values in the component.

<script>
import { Input, Panel } from '@soleil-se/config-svelte';
let { values } = $props();
</script>
<Panel heading="Inställningar">
<Input name="text" label="Text" bind:value={values.text} />
<p>Current text: {values.text}</p>
</Panel>

Using saved values with TypeScript

Simple i18n utility for translating the configuration.

i18n.js
import { createI18n } from '@soleil-se/config-svelte/utils';
export default createI18n({
sv: {
label: 'Välj sida',
hello: 'Hej {name}!',
},
no: {
label: 'Velg side',
hello: 'Hallo {name}!',
},
en: {
label: 'Select page',
hello: 'Hello {name}!',
},
});
App.svelte
<script>
import { Panel, PageSelector } from '@soleil-se/config-svelte';
import i18n from './i18n.js';
const hello = i18n('hello', { name: 'Foo' });
</script>
<Panel>
<PageSelector name="page" label={i18n('label')} />
</Panel>

Generates a unique ID inside the configuration context. Prefixed with input by default.

import { generateId } from '@soleil-se/config-svelte/utils';
const id = generateId(); // input_pcp61fn1u
const idCustomPrefix = generateId('foo'); // foo_pcp61fn1u

Triggers the setup-component event on the element with passed ID.
Read more on developer.sitevision.se

import { setupComponent } from '@soleil-se/config-svelte/utils';
setupComponent('myId');

Get props passed to the app when using server data.

import { getAppProps } from '@soleil-se/config-svelte/utils';
const appProps = getAppProps();
const { myProp } = getAppProps();

Get app context value or object that is created for app when rendering with createAppContext.

import { getAppContext } from '@soleil-se/config-svelte/utils';
const appContext = getAppContext();
const { siteName } = getAppContext();
const siteName = getAppContext('siteName');

It’s not uncommon to need to fetch data from the REST-API in a configuration, for example to populate a dropdown. This utility function is a wrapper around the native fetch that prefixes the URL, handles data format and the response.

ParamTypeDefaultDescription
uriStringURI path for the REST-API resource, e.g. ${nodeId}/properties
[options]Object{}Options object, two custom options, rest is standard fetch options
[options.data]Object{}Data to be passed as JSON query parameter
[options.model]'offline' | 'online''offline'Selects which REST-API model path to use

Returns: Promise<unknown> - Promise containing parsed JSON data.
Throws FetchError - Error object with status property, plus any additional JSON properties returned by the response.

import { fetchRestApi } from '@soleil-se/config-svelte/utils';
// GET – fetch node properties
const data = await fetchRestApi(`${nodeId}/properties`);
// GET – fetch node specific properties
const data = await fetchRestApi(`${nodeId}/properties`, {
data: { properties: ['displayName', 'URL'] },
});
// GET – fetch online (published) data
const data = await fetchRestApi(`${nodeId}/properties`, { model: 'online' });

Use inside a Svelte component with error handling:

App.svelte
<script>
import { PageSelector, Panel, Select } from '@soleil-se/config-svelte';
import { fetchRestApi } from '@soleil-se/config-svelte/utils';
let options = $state([]);
let fetchError = $state(null);
async function onNodeChange(node) {
fetchError = null;
if (!node) {
options = [];
return;
}
try {
const response = await fetchRestApi(`${node}/nodes`);
options = (response ?? []).map(({ id, name }) => ({ value: id, label: name }));
} catch (error) {
console.error('Error fetching data:', error);
fetchError = error;
}
}
</script>
<Panel heading="Inställningar">
{#if fetchError}
<p class="alert alert-danger" role="alert">Kunde inte ladda data ({fetchError.status}).</p>
{/if}
<PageSelector name="node" label="Välj nod" onChange={onNodeChange} />
<Select name="child" label="Välj barn" {options} />
</Panel>

Runs the supplied callback when the host requests values to save. The callback should return the complete object to save. Nested objects are serialized using dot-notation keys.

import { onSave } from '@soleil-se/config-svelte/utils';
onSave(() => ({ foo: 'bar' }));

Converts a nested object to a flat object with dot-notation keys. Arrays are kept as values.

import { flatten } from '@soleil-se/config-svelte/utils';
const values = flatten({ settings: { page: 'page-id' } });
// { 'settings.page': 'page-id' }

Restores a nested object from dot-notation keys.

import { unflatten } from '@soleil-se/config-svelte/utils';
const values = unflatten({ 'settings.page': 'page-id' });
// { settings: { page: 'page-id' } }

Reads a value from a nested object using a dot-notation path.

import { getByPath } from '@soleil-se/config-svelte/utils';
const page = getByPath({ settings: { page: 'page-id' } }, 'settings.page');
// 'page-id'

To pass data from the server to the configuration app, call createAppProps(props, res). The values are available as props on the root Svelte component. In a server-rendered view, getAppProps reads the same props.

index.js
import router from '@sitevision/api/common/router';
import { createAppProps } from '@soleil-se/config-svelte/server';
router.get('/', (req, res) => {
const props = {
foo: 'bar',
fizz: 'buzz',
};
createAppProps(props, res);
});
<script>
let { foo, fizz } = $props();
</script>
<p>{foo}</p>
<p>{fizz}</p>

Using props with TypeScript

Contains information about app context.

Is needed for some components to function.

index.js
import router from '@sitevision/api/common/router';
import { createAppContext } from '@soleil-se/config-svelte/server';
router.get('/', (req, res) => {
createAppContext(res);
});
App.svelte
<script>
import { getAppContext } from '@soleil-se/config-svelte/utils';
const { siteName } = getAppContext()
</script>
<h1>{siteName}</h1>

Validation is handled by the components and a client-side validator registry.
You do not need @soleil-se/config-validate anymore as createConfigApp connects the registry to Sitevision’s global save validation hook.

Mandatory field. Value required.

Set validate on a field to add application-specific rules. A custom validator is run before the default validator for that field.

App.svelte
<script>
import { Input } from '@soleil-se/config-svelte';
function validateMinimumLength(context) {
return context.value.length >= 5
? { success: true }
: { success: false, message: 'Must be at least 5 characters.' };
}
</script>
<Input name="title" label="Title" required validate={validateMinimumLength} />

Must be at least 5 characters.

If you want to split validation into multiple steps, validateWith(context, ...validators) can be used. It runs validators in order and returns the first failure, or { success: true } when they all pass.

<script>
import { Input } from '@soleil-se/config-svelte';
import { validateWith } from '@soleil-se/config-svelte/utils';
function validateMinLength(context) {
return context.value.length >= 5
? { success: true }
: { success: false, message: 'Must be at least 5 characters.' };
}
function validateMaxLength(context) {
return context.value.length <= 10
? { success: true }
: { success: false, message: 'Must be at most 10 characters.' };
}
function validate(context) {
return validateWith(context, validateMinLength, validateMaxLength);
}
</script>
<Input name="title" label="Title" required {validate} />

Must be at least 5 characters.

Must be at most 10 characters.

Field input and change callbacks may return a promise. Components await the callback before validating when validation is due.

Field validators and Sitevision’s save validation hook are synchronous. Run asynchronous checks in an input or change callback (or during initial loading), store the result, and have the synchronous validator read it.

If saving must wait for long running asynchronous operations, make the validator fail while that operation is pending or prevent saving using disableSave during the asynchronous validation process.

<script>
import { PageSelector } from '@soleil-se/config-svelte';
import { fetchRestApi } from '@soleil-se/config-svelte/utils';
let pageChangeError = null;
async function onPageChange(pageId) {
pageChangeError = null;
try {
const properties = pageId ? await fetchRestApi(`${nodeId}/properties`) : undefined;
if (!properties) return;
if (!properties.published) {
throw new Error('Page is not published.');
}
} catch (error) {
pageChangeError = error?.message ?? 'An error occurred while fetching page properties.';
console.error(error);
}
}
function validatePageChange() {
return {
success: !pageChangeError,
message: pageChangeError ?? '',
};
}
</script>
<PageSelector
name="page"
label="Page"
required
onChange={onPageChange}
validate={validatePageChange}
/>

Page is not published.

Components register their validators when mounted and remove them when destroyed. When the editor attempts to save, all registered validators are run and returns true only when they all pass. Failed fields display their messages, and focus moves to the first visible error.

Validation runs on value changes for most controls. Input, Textarea, and NumberSpinner first validate on blur outside a dialog, then revalidate as the value changes; inside a dialog, they validate on save rather than blur.

The registry skips fields that are hidden or inert, including fields outside the active modal dialog. The defaultValidator checks required values and native browser constraints such as input type, min, max, and pattern.

Most fields use defaultValidator and it is run last in the validation sequence.

A custom validator returns an object with a required success boolean and an optional message.
Return { success: true } when the field is valid and { success: false, message: '...' } when it is not.
The message is displayed with the field. Do not return a boolean from the validate prop; the registry converts the result to a boolean for the host.

The component passes the current value and validation state to a custom validator:

PropertyTypeDescription
valueunknownCurrent field value. The component’s prop declarations specify the value type for each field.
elementHTMLElementDOM element associated with the field.
visiblebooleanWhether the field is currently visible.
inertbooleanWhether the field is inert or outside the active modal dialog.
requiredbooleanWhether the field is required, when supported by that component.
disabledbooleanWhether the field is disabled, when supported by that component.
readonlybooleanWhether the field is read-only, when supported by that component.

Use these helpers when implementing a custom control or managing the host save validation directly.

Use validateWithin(root) to validate only registered fields inside an element. It returns a boolean and is useful when implementing custom save flows.
Modal uses it internally so invalid fields keep the dialog open.

import { validateWithin } from '@soleil-se/config-svelte/utils';
if (validateWithin(formElement)) {
saveForm();
}

Use hasAttemptedSave(element) to check whether a global save or a scoped validation for that element has been attempted. The element argument is optional; without it, the helper reports only global save attempts. validateWithin(root) marks its matching elements as attempted.

import { hasAttemptedSave } from '@soleil-se/config-svelte/utils';
if (hasAttemptedSave(fieldElement)) {
// Show validation feedback as the user edits after a save attempt.
}

Register a validator for a custom control. The registered function returns a boolean and only runs when the control is eligible for validation.

import { createValidator } from '@soleil-se/config-svelte/utils';
const validate = createValidator(element, ({ value }) => value.trim().length > 0);
const isValid = validate({ value });

Remove a custom control’s validator when the control is destroyed.

import { removeValidator } from '@soleil-se/config-svelte/utils';
removeValidator(element);

Temporarily disable the host save validation, then call the returned function to restore it.
The Modal component uses this while it is open.

import { disableSave } from '@soleil-se/config-svelte/utils';
const restoreSave = disableSave();
// When the modal closes:
restoreSave();