A collection of Svelte components and utilities for WebApp, RESTApp and Widget configurations.
Settings
Enter the title here.
Installation
Section titled “Installation”Install locally in your app:
npm i @soleil-se/config-svelteMigration from version 1
Version 2 has multiple breaking changes when upgrading from version 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/runfor automatic migration:Terminal window npx @soleil-se/run migrate-svelte-5Read more about @soleil-se/run
- Change to type specific selector components
The
NodeSelector,DropdownSelector, andListSelectornow 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" /> - Update selectable types
The
selectableprop forNodeSelector,DropdownSelector,ListSelectorand their type-specific counterparts is now calledtypesto better align with Sitevision naming conventions.<PageSelectorname="page"label="Page"selectable="sv:page"types="sv:page"/><MetadataSelectorname="metadata"label="Metadata"selectable="sv:metadataTextDefinition"types="sv:metadataTextDefinition"/><PageListname="pages"label="Pages"selectable="sv:page"types="sv:page"/> - Update image components
The old
ImageSelectorcomponent is renamed toImageSettingsand is no longer a panel;ImageSelectornow selects Sitevision image nodes.
If you previously usedImageSelectorfor selecting images, replace it with the newImageSettingscomponent wrapped in aPanel.
For backwards compatibility, you can pass thelegacyNamesprop toImageSettingsto support the old naming convention.<ImageSelector name="image" label="Image" /><Panel heading="Image"><ImageSettings name="image" legacyNames /></Panel> - Update validation
Validation is now built in. Remove the
@soleil-se/config-validatedependency and use the componentvalidateprop or the validation utilities.Terminal window npm uninstall @soleil-se/config-validateRemove the import and usage of
validatefrom 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.
Components
Section titled “Components”General UI components for building configuration interfaces.
Sitevision
Section titled “Sitevision”Wrappers for Sitevision components.
- ColorSelector
- ContentNodeSelector
- CustomSelector
- FileList
- FileSelector
- FontSelector
- GeolocationList
- ImageList
- ImageSelector
- LLMConfigurationSelector
- LinkSelector
- MetadataSelector
- NumberSpinner
- OAuth2ConfigurationSelector
- PageList
- PageSelector
- SearchIndexSelector
- TagSelector
- TargetAudienceList
- TargetAudienceSelector
- TemplateList
- TemplateSelector
- UserfieldList
- UserList
- UserSelector
- VirtualGroupSelector
Base components
Section titled “Base components”The components above are based on the following base components:
Regular input components.
Custom
Section titled “Custom”Custom components.
Structure
Section titled “Structure”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/
- …
- …
Examples
Section titled “Examples”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.
import { createConfigApp } from '@soleil-se/config-svelte';import { mount } from 'svelte';
import App from './App.svelte';
createConfigApp(({ target, props }) => mount(App, { target, props }));<script> import { Input, Panel } from '@soleil-se/config-svelte';</script>
<Panel heading="Inställningar"> <Input name="text" label="Text" /></Panel>Saving values manually
Section titled “Saving values manually”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.
<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.
Saved values
Section titled “Saved values”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.
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}!', },});<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>generateId
Section titled “generateId”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_pcp61fn1uconst idCustomPrefix = generateId('foo'); // foo_pcp61fn1usetupComponent
Section titled “setupComponent”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');getAppProps
Section titled “getAppProps”Get props passed to the app when using server data.
import { getAppProps } from '@soleil-se/config-svelte/utils';
const appProps = getAppProps();const { myProp } = getAppProps();getAppContext
Section titled “getAppContext”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');fetchRestApi
Section titled “fetchRestApi”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.
| Param | Type | Default | Description |
|---|---|---|---|
| uri | String | URI 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 propertiesconst data = await fetchRestApi(`${nodeId}/properties`);
// GET – fetch node specific propertiesconst data = await fetchRestApi(`${nodeId}/properties`, { data: { properties: ['displayName', 'URL'] },});
// GET – fetch online (published) dataconst data = await fetchRestApi(`${nodeId}/properties`, { model: 'online' });Use inside a Svelte component with error handling:
<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>onSave
Section titled “onSave”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' }));flatten
Section titled “flatten”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' }unflatten
Section titled “unflatten”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' } }getByPath
Section titled “getByPath”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'Server
Section titled “Server”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.
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>Context
Section titled “Context”Contains information about app context.
pageId- ID of current page.portletId- ID of current portlet.siteId- ID of site.siteName- Name of site.- @sitevision/api/server/appInfo
Is needed for some components to function.
import router from '@sitevision/api/common/router';import { createAppContext } from '@soleil-se/config-svelte/server';
router.get('/', (req, res) => { createAppContext(res);});<script> import { getAppContext } from '@soleil-se/config-svelte/utils';
const { siteName } = getAppContext()</script>
<h1>{siteName}</h1>Validation
Section titled “Validation”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.
Custom validators
Section titled “Custom validators”Set validate on a field to add application-specific rules. A custom validator is run before the default
validator for that field.
<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.
Sequential validation
Section titled “Sequential validation”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.
Asynchronous validation
Section titled “Asynchronous validation”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.
How validation runs
Section titled “How validation runs”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.
Validation result
Section titled “Validation result”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.
Validation context
Section titled “Validation context”The component passes the current value and validation state to a custom validator:
| Property | Type | Description |
|---|---|---|
value | unknown | Current field value. The component’s prop declarations specify the value type for each field. |
element | HTMLElement | DOM element associated with the field. |
visible | boolean | Whether the field is currently visible. |
inert | boolean | Whether the field is inert or outside the active modal dialog. |
required | boolean | Whether the field is required, when supported by that component. |
disabled | boolean | Whether the field is disabled, when supported by that component. |
readonly | boolean | Whether the field is read-only, when supported by that component. |
Advanced
Section titled “Advanced”Use these helpers when implementing a custom control or managing the host save validation directly.
validateWithin
Section titled “validateWithin”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();}hasAttemptedSave
Section titled “hasAttemptedSave”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.}createValidator
Section titled “createValidator”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 });removeValidator
Section titled “removeValidator”Remove a custom control’s validator when the control is destroyed.
import { removeValidator } from '@soleil-se/config-svelte/utils';
removeValidator(element);disableSave
Section titled “disableSave”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();