Svelte
Svelte
Supported Versions
- Svelte 4+
- TypeScript 5+
Cosmos Web Components are custom elements built using StencilJS, designed to be framework-agnostic and highly performant. This guide provides steps to integrate Cosmos web components into a Svelte application.
Installation
Cosmos uses Red Bull's custom fonts to display text content inside components for different languages.Please follow the guide for Font Faces to learn more about the different ways to provide them.
Cosmos Web Components are available through Red Bull's proprietary npm registry. Access to this registry requires setting up an .npmrc file in the project root with the propert authentication details.
Add the following lines to the .npmrc file:
@cosmos:registry=https://artifactory.redbullmediahouse.com/artifactory/api/npm/rbds-npm-local/
//artifactory.redbullmediahouse.com/artifactory/api/npm/rbds-npm-local/:_auth=cy1yYm1oLXJlYWRvbmx5LXJiZHM6QVA4bTJXZVNhN2Q5bTZYVUpIcVZmdGtTOGpR
//artifactory.redbullmediahouse.com/artifactory/api/npm/rbds-npm-local/:always-auth=trueNote: The provided authentication token is public and read-only.
To install the Cosmos, run:
npm install @cosmos/webBasic Usage
Cosmos Web Components need to be registered with the browser's Custom Element Registry. This is done by invoking the defineCustomElements function from the loader module.
import App from "./App.svelte";
import { defineCustomElementCosmosButton } from "@cosmos/web";
defineCustomElementCosmosButton();
const app = new App({
target: document.getElementById("app")!,
});
export default app;Once defined, you can use the components in your Svelte components as you would any native HTML element.
<cosmos-button>Click Me!</cosmos-button>
Properties
Properties can be passed to a web component using attribute binding or property binding.
<script lang="ts">
const selectedCountries = ['AT', 'DE'];
</script>
<cosmos-select
value={selectedCountries}
help-text="Select one or more countries."
label="Countries"
multiple
name="countries"
placeholder="Pick a country"
>
<cosmos-option value="AT">
<cosmos-flag slot="prefix" code="AT"></cosmos-flag>
Austria
</cosmos-option>
<cosmos-option value="DE">
<cosmos-flag slot="prefix" code="DE"></cosmos-flag>
Germany
</cosmos-option>
<cosmos-option value="CH">
<cosmos-flag slot="prefix" code="CH"></cosmos-flag>
Switzerland
</cosmos-option>
</cosmos-select>Slots
Cosmos Web Components can have named and unnamed slots for content insertion.
<cosmos-badge shape="pill">
<cosmos-icon-label slot="prefix"></cosmos-icon-label>
Snowboarding
</cosmos-badge>Events
Custom events emitted by Cosmos Web Components can be listened to using Svelte's on:event directive.
<script lang="ts">
let cosmosInputRef: HTMLCosmosInputElement;
function handleInputChange(event: CustomEvent<{ value: string }>) {
console.log('Input changed:', event.detail.value);
}
</script>
<cosmos-input
bind:this="{cosmosInputRef}"
label="Name"
name="name"
placeholder="Max"
required
required-label="Required"
validation-message="Please input your name"
on:inputchange="{handleInputChange}"
></cosmos-input>💡 Pro Tip
When using TypeScript, it's important to note that event.target refers to the actual custom element. It might be necessary to typecast the event target for stronger typing.
💡 Pro Tip
Although Cosmos Web Components - derived from the HTMLElement interface - can handle native DOM events, they might not always be the most semantic choice. Custom events are designed to propagate actions to the semantic elements housed within the component's shadow DOM.
When faced with similar behaviors between native and custom events, always opt for custom events.
Methods
Public methods on a Cosmos Web Component can be called by obtaining a reference to the component and then calling the method.
☝️ Watch out
Be mindful of the asynchronous nature of public methods and ensure that the component is defined before attempting to call them.
<script lang="ts">
let cosmosInputRef: HTMLCosmosInputElement;
async function checkInputValidity() {
if (cosmosInputRef) {
const isValid = await cosmosInputRef.inputCheckValidity();
console.log('Input validity:', isValid);
}
}
</script>
<form on:submit|preventDefault={checkInputValidity}>
<cosmos-input
bind:this={cosmosInputRef}
label="Name"
name="name"
placeholder="Max"
required
required-label="Required"
validation-message="Please input your name"
></cosmos-input>
<cosmos-button type="submit">Submit</cosmos-button>
</form>Common Issues to Avoid
Differences from Native Elements
While Cosmos Web Components may share names with native HTML elements, their APIs may differ. Always refer to component-specific documentation to verify behaviors.
Self-closing Tags
Custom elements require explicit closing tags, unlike some HTML elements that use self-closing tags.
<!-- ✅ Correct -->
<cosmos-input></cosmos-input>
<!-- ❌ Incorrect -->
<cosmos-input />Need More Details?
Please refer to individual component documentation for a complete API overview.