Skip to content

Shared Bag

createShared(view, pluginId, apiPrefix) returns the per view helper bag. Create it once per page and reuse it. createConfigPage builds it. Helpers that take an id look the element up inside view.

Decision

When Use
Ids, values, config calls, formatting, and the few components that live on the bag Shared Bag
A second bag for the same view The one Shared Bag the page already has

Usage

shared.saveConfigWith(function (config) { config.Enabled = shared.getChecked('chkEnabled'); },
    'saveStatus', { success: 'Settings saved.', error: 'Could not save the settings.' });

The members, by purpose.

  • Elements. getEl, setVisible, bindEvent, bindClick, bindReveal, initCollapsibles.
  • Values. getValue, setValue, getIntValue, getChecked, setChecked.
  • Secrets. bindSecretField, clearSecretField, readSecretField.
  • Status and feedback. setStatus, showAlert, badge, statusBadge, emptySection, renderCards.
  • Config and API. getConfig, saveConfig, saveConfigWith, apiRequest, fetchObjectUrl.
  • Formatting. formatSize, formatDuration, formatRelativeTime, formatDate, toDateInput, getFileName.
  • Utilities. escapeHtml, plural, errorText, debounce, downloadJson, pickJsonFile, generateGuid, copyToClipboard, copyWithFeedback. See Browser Helpers.
  • Behavior helpers. createPoller, createChangeTracker, pollTaskProgress.
  • Placeholders. insertAtCursor, placeholderHint, bindPlaceholders.
  • Selectors. createUserSelector, createUserMultiSelector, createSearchableComboBox, createDebouncedSearch.

The state is pluginId and apiPrefix.

States and Modifiers

  • setVisible(idOrEl, visible) toggles the stolon-hidden class.
  • bindReveal(checkboxId, targetId, invert) shows or hides the target from a checkbox, binds once, and applies the current state on every call. Call it after loading the config.
  • setValue turns null into an empty value.
  • getConfig calls ApiClient.getPluginConfiguration(pluginId), and saveConfig calls ApiClient.updatePluginConfiguration.
  • saveConfigWith(mutator, statusId, messages) re-reads the freshest config, applies mutator(config) (in place or by returning a replacement), saves, and reports on the status element. The messages default to "Saved." and "Save failed.". It returns the save promise and rethrows a failure.
  • apiRequest(endpoint, method, data) calls ApiClient.getUrl(apiPrefix + '/' + endpoint) and ApiClient.fetch with JSON. An empty response resolves to null. Other errors reject with what ApiClient gave, which errorText reads.
  • apiRequest and fetchObjectUrl send the page's language in the X-Jellyfin-Plugin-Language header, from the page's current translations, else the viewer's, so StolonTranslations.RequestLanguage answers in it.
  • formatRelativeTime writes the time in the page's language, such as "3 days ago".
  • createDebouncedSearch(endpoint, delay) returns a searchFn for a Combo Box. It waits delay milliseconds (default 300), calls apiRequest(endpoint + '?query=...'), answers [] for a query under two characters or a failed call, and drops an answer that a newer query replaced.
  • formatSize gives "0 B", then B to TB. formatDuration gives clock time, such as "1:30" or "1:30:00", and an empty string for zero. formatRelativeTime gives "Just now", "N minutes ago", and so on. formatDate(value, { seconds }) uses the viewer's locale. toDateInput gives the local yyyy-mm-dd string for a date input. getFileName gives the last path segment, with either slash.

Gotchas

  • setStatus, renderCards, createPoller, createChangeTracker, pollTaskProgress, createSearchableComboBox, createDebouncedSearch, and the formatters live only on the bag. They have no top level export.
  • Every other component is import only, such as createPaginatedTable, every dialog, createChipSelect, every editor, display, and loading component, BADGE_STATES, and SECRET_KEPT.
  • showAlert and toDateInput are used by no plugin today.

Reference

Generated from the code by scripts/build-docs.mjs. Edit the code, not this section.

createShared

function createShared(view: HTMLElement, pluginId: string, apiPrefix?: string): { pluginId: string; apiPrefix: string; getEl: (id: string) => any; setVisible: (id: string | Element, visible: boolean) => void; setStatus: (elementId: string | Element, message: string, isError?: boolean, opts?: { timeout?: number; state?: 'success' | 'error' | 'warn' | 'info'; }) => void; bindEvent: (id: string, event: string, handler: (e: any) => void) => Element | null; bindClick: (id: string, handler: (e: any) => void) => Element | null; setChecked: (id: string, checked: boolean) => void; getChecked: (id: string) => boolean; setValue: (id: string, value: unknown) => void; getValue: (id: string, fallback?: string) => string; getIntValue: <F extends number | undefined = undefined>(id: string, fallback?: F) => number | F; bindSecretField: (id: string | HTMLInputElement, hasStored: boolean, opts?: SecretFieldOptions) => void; clearSecretField: (id: string | HTMLInputElement) => void; readSecretField: (id: string | HTMLInputElement) => string; debounce: typeof debounce; downloadJson: typeof downloadJson; pickJsonFile: typeof pickJsonFile; bindReveal: (checkboxId: string, targetId: string | Element, invert?: boolean) => void; initCollapsibles: () => void; escapeHtml: typeof escapeHtml; plural: typeof plural; errorText: typeof errorText; insertAtCursor: typeof insertAtCursor; placeholderHint: typeof placeholderHint; bindPlaceholders: typeof bindPlaceholders; badge: (cls: string, label: string) => string; statusBadge: (text: string, stateClass: string) => string; emptySection: (message: string, opts?: { inline?: boolean; }) => string; formatSize: (bytes: number) => string; formatDuration: (seconds: number) => string; formatRelativeTime: (date: Date | number) => string; formatDate: (value: string | number | Date, opts?: { seconds?: boolean; }) => string; toDateInput: (value: string | number | Date) => string; getFileName: (path: string) => string; generateGuid: typeof generateGuid; getConfig: () => Promise<any>; saveConfig: (config: unknown) => Promise<any>; saveConfigWith: (mutator: (config: any) => any, statusId?: string, messages?: SaveMessages) => Promise<any>; renderCards: (containerId: string | Element, cards: CardData[]) => void; copyToClipboard: (text: string) => Promise<boolean>; copyWithFeedback: (btn: HTMLElement | null, text: string, opts?: CopyFeedbackOptions) => Promise<boolean>; fetchObjectUrl: (endpoint: string, params?: Record<string, unknown>) => Promise<string>; createPoller: (fn: () => unknown, intervalMs?: number, opts?: PollerOptions) => Poller; createChangeTracker: (opts?: ChangeTrackerOptions) => ChangeTracker; apiRequest: (endpoint: string, method?: string, data?: unknown) => Promise<any>; showAlert: (message: string) => void; createDebouncedSearch: (endpoint: string, delay?: number) => (query: string, callback: (results: any[]) => void) => void; createUserSelector: (options?: UserSelectorOptions) => UserSelectorHandle; createUserMultiSelector: (options?: UserMultiSelectorOptions) => UserMultiSelectorHandle; createSearchableComboBox: (options: ComboBoxOptions) => ComboBoxHandle; pollTaskProgress: (btn: HTMLButtonElement, taskKey: string, label: string, onComplete?: () => void) => TaskProgressHandle; }

Builds the per view helper bag that a config page uses. Create it once on viewshow and reuse it.

Example

Example Code

<!-- title: Shared Bag -->
<div class="inputContainer">
    <label for="txtName">Name</label>
    <input is="emby-input" type="text" id="txtName" />
</div>
<div class="checkboxContainer">
    <label class="emby-checkbox-label"><input type="checkbox" is="emby-checkbox" id="chkEnabled" /><span class="checkboxLabel">Enabled</span></label>
</div>
<div style="display: flex; flex-wrap: wrap; gap: 10px; align-items: center;">
    <button type="button" id="btnSave" class="raised stolon-button stolon-primary stolon-small"><span>Save</span></button>
    <span id="saveStatus" class="stolon-status-text"></span>
</div>
<div id="out" style="margin-top: 14px;"></div>
<script type="module">
const base = await window.__baseReady;
const shared = base.createShared(document.getElementById('view'), 'preview-plugin', 'Preview');
const out = base.createDefinitionList({ items: [] });
document.getElementById('out').appendChild(out.element);
const show = () => out.setItems([
    { label: 'getValue', value: JSON.stringify(shared.getValue('txtName', 'none')), mono: true },
    { label: 'getChecked', value: String(shared.getChecked('chkEnabled')), mono: true },
    { label: 'formatSize', value: shared.formatSize(5368709120), mono: true },
    { label: 'formatDuration', value: shared.formatDuration(3725), mono: true },
    { label: 'getFileName', value: shared.getFileName('/media/shows/episode.mkv'), mono: true }
]);

shared.getConfig().then((config) => {
    shared.setValue('txtName', config.Name || 'Living room');
    shared.setChecked('chkEnabled', config.Demo);
    show();
});
shared.bindEvent('txtName', 'input', show);
shared.bindEvent('chkEnabled', 'change', show);
shared.bindClick('btnSave', () => shared.saveConfigWith(
    (config) => { config.Name = shared.getValue('txtName'); config.Demo = shared.getChecked('chkEnabled'); },
    'saveStatus', { success: 'Settings saved.', error: 'Could not save the settings.' }));
</script>