// KefinTweaks Configuration UI // Adds a configuration button to the Administration section in user preferences // Opens configuration in a modal window (function() { 'use strict'; console.log('[KefinTweaks Configuration] Initializing...'); const MODAL_ID = 'kefinTweaksConfigModal'; let currentLoadedConfig = null; const DISCOVERY_SECTION_DEFINITIONS = [ { key: 'spotlightGenre', label: 'Spotlight Sections (Genre)', defaultName: 'Spotlight' }, { key: 'spotlightNetwork', label: 'Spotlight Sections (Network)', defaultName: 'Spotlight' }, { key: 'genreMovies', label: 'Genre Movies', defaultName: '[Genre] Movies' }, { key: 'studioShows', label: 'Shows from [Studio]', defaultName: 'Shows from [Studio]' }, { key: 'collections', label: 'Collection Spotlight', defaultName: '[Collection Name]', extras: { minimumItems: 10 } }, { key: 'becauseYouWatched', label: 'Because you watched [Movie]', defaultName: 'Because you watched [Movie]' }, { key: 'becauseYouLiked', label: 'Because you liked [Movie]', defaultName: 'Because you liked [Movie]' }, { key: 'starringTopActor', label: 'Starring [Top Actor]', defaultName: 'Starring [Actor]' }, { key: 'directedByTopDirector', label: 'Directed by [Top Director]', defaultName: 'Directed by [Director]' }, { key: 'writtenByTopWriter', label: 'Written by [Top Writer]', defaultName: 'Written by [Writer]' }, { key: 'becauseYouRecentlyWatched', label: 'Because you recently watched [Movie]', defaultName: 'Because you recently watched [Movie]' }, { key: 'starringActorRecentlyWatched', label: 'Starring [Actor] because you recently watched [Movie]', defaultName: 'Starring [Actor] because you recently watched [Movie]' }, { key: 'directedByDirectorRecentlyWatched', label: 'Directed by [Director] because you recently watched [Movie]', defaultName: 'Directed by [Director] because you recently watched [Movie]' }, { key: 'writtenByWriterRecentlyWatched', label: 'Written by [Writer] because you recently watched [Movie]', defaultName: 'Written by [Writer] because you recently watched [Movie]' } ]; // Check if user is admin async function isAdmin() { try { if (window.ApiClient && window.ApiClient.getCurrentUser) { const user = await window.ApiClient.getCurrentUser(); return user && user.Policy && user.Policy.IsAdministrator === true; } } catch (error) { console.warn('[KefinTweaks Configuration] Could not check admin status:', error); } return false; } // Load default configuration from JS file async function loadDefaultConfig() { return new Promise((resolve, reject) => { try { const defaultConfigUrl = window.KefinTweaksConfig?.kefinTweaksRoot ? `${window.KefinTweaksConfig.kefinTweaksRoot}/kefinTweaks-default-config.js` : null; if (!defaultConfigUrl) { reject(new Error('No default config URL found')); return; } // Check if already loaded if (window.KefinTweaksDefaultConfig) { console.log('[KefinTweaks Configuration] Using cached default config'); resolve(window.KefinTweaksDefaultConfig); return; } // Create script element to load the JS file const script = document.createElement('script'); script.src = defaultConfigUrl; script.async = true; script.onload = () => { if (window.KefinTweaksDefaultConfig) { console.log('[KefinTweaks Configuration] Loaded default config:', window.KefinTweaksDefaultConfig); resolve(window.KefinTweaksDefaultConfig); } else { reject(new Error('Default config file loaded but window.KefinTweaksDefaultConfig is not defined')); } }; script.onerror = (error) => { reject(new Error(`Failed to load default config file: ${defaultConfigUrl}`)); }; document.head.appendChild(script); } catch (error) { console.error('[KefinTweaks Configuration] Error loading default config:', error); reject(error); } }); } // Get KefinTweaks configuration from JS Injector or load defaults async function getKefinTweaksConfig() { try { // First, try to get config from JS Injector const pluginId = await findJavaScriptInjectorPlugin(); const injectorConfig = await getJavaScriptInjectorConfig(pluginId); // Find KefinTweaks-Config script const kefinTweaksScript = injectorConfig.CustomJavaScripts?.find( script => script.Name === 'KefinTweaks-Config' ); if (kefinTweaksScript && kefinTweaksScript.Script) { // Extract config from script content // The script should contain: window.KefinTweaksConfig = {...}; const scriptMatch = kefinTweaksScript.Script.match(/window\.KefinTweaksConfig\s*=\s*({[\s\S]*});/); if (scriptMatch && scriptMatch[1]) { try { const config = JSON.parse(scriptMatch[1]); // Store enabled state globally for use in modal (defaults to true if not set) window.KefinTweaksConfigEnabled = config.enabled !== false; console.log('[KefinTweaks Configuration] Loaded config from JS Injector:', config); return config; } catch (parseError) { console.error('[KefinTweaks Configuration] Error parsing config from script:', parseError); } } } // If no config found in JS Injector, load defaults console.log('[KefinTweaks Configuration] No config found in JS Injector, loading defaults'); const rawDefaultConfig = await loadDefaultConfig(); const defaultConfig = JSON.parse(JSON.stringify(rawDefaultConfig)); const currentConfigSource = currentLoadedConfig || window.KefinTweaksCurrentConfig || window.KefinTweaksConfig || {}; const currentKefinRoot = currentConfigSource.kefinTweaksRoot || defaultConfig.kefinTweaksRoot; defaultConfig.kefinTweaksRoot = currentKefinRoot; // Ensure enabled field is set (defaults to true if not present) if (defaultConfig.enabled === undefined) { defaultConfig.enabled = true; } // Store enabled state globally for use in modal window.KefinTweaksConfigEnabled = defaultConfig.enabled !== false; // Note: scriptRoot is no longer used - scripts are loaded from kefinTweaksRoot + '/scripts/' // Save defaults to JS Injector for future use await saveConfigToJavaScriptInjector(defaultConfig); return defaultConfig; } catch (error) { console.error('[KefinTweaks Configuration] Error getting config, falling back to defaults:', error); // Fallback to defaults if anything fails try { return await loadDefaultConfig(); } catch (fallbackError) { console.error('[KefinTweaks Configuration] Error loading default config as fallback:', fallbackError); // Return empty config structure as last resort return { kefinTweaksRoot: '', scripts: {}, homeScreen: {}, exclusiveElsewhere: {}, search: {}, skins: [], defaultSkin: null, themes: [], customMenuLinks: [] }; } } } // Inject responsive CSS for the configuration modal function injectConfigModalCSS() { const styleId = 'kefintweaks-config-modal-css'; if (document.getElementById(styleId)) return; const style = document.createElement('style'); style.id = styleId; style.textContent = ` #${MODAL_ID} .modal-content-wrapper { max-width: 90vw; width: 1400px; max-height: 90vh; overflow-y: auto; background: var(--background-color, #1a1a1a); border-radius: 8px; } #${MODAL_ID} .content-primary { max-width: 1400px; margin: 0 auto; padding: 1.5em; } #${MODAL_ID} .paperList { background: rgba(255, 255, 255, 0.03); border-radius: 8px; padding: 1em; } #${MODAL_ID} .listItem { transition: background-color 0.2s ease; } #${MODAL_ID} .listItem:hover { background-color: rgba(255, 255, 255, 0.02); } #${MODAL_ID} textarea.fld { resize: vertical; min-height: 200px; } #${MODAL_ID} details summary { user-select: none; overflow: visible; } #${MODAL_ID} details summary:hover { opacity: 0.8; } #${MODAL_ID} pre { white-space: pre-wrap; word-wrap: break-word; } /* Custom section collapsible styling */ #${MODAL_ID} .custom-section-summary { position: relative; list-style: none; } #${MODAL_ID} .custom-section-summary::-webkit-details-marker { display: none; } #${MODAL_ID} .custom-section-summary::marker { display: none; } #${MODAL_ID} details[open] .custom-section-summary .material-icons { transform: rotate(90deg); } #${MODAL_ID} .custom-section-summary .material-icons { transition: transform 0.2s ease; } /* Recently released subsection styling */ #${MODAL_ID} .recently-released-subsection-summary { position: relative; list-style: none; } #${MODAL_ID} .recently-released-subsection-summary::-webkit-details-marker { display: none; } #${MODAL_ID} .recently-released-subsection-summary::marker { display: none; } #${MODAL_ID} details[open] .recently-released-subsection-summary .material-icons { transform: rotate(90deg); } #${MODAL_ID} .recently-released-subsection-summary .material-icons { transition: transform 0.2s ease; } /* Seasonal season collapsible styling */ #${MODAL_ID} .seasonal-season-summary { position: relative; list-style: none; } #${MODAL_ID} .seasonal-season-summary::-webkit-details-marker { display: none; } #${MODAL_ID} .seasonal-season-summary::marker { display: none; } #${MODAL_ID} details[open] .seasonal-season-summary .material-icons { transform: rotate(90deg); } #${MODAL_ID} .seasonal-season-summary .material-icons { transition: transform 0.2s ease; } /* Seasonal section collapsible styling (sections within seasons) */ #${MODAL_ID} .seasonal-section-summary { position: relative; list-style: none; } #${MODAL_ID} .seasonal-section-summary::-webkit-details-marker { display: none; } #${MODAL_ID} .seasonal-section-summary::marker { display: none; } #${MODAL_ID} details[open] .seasonal-section-summary .material-icons { transform: rotate(90deg); } #${MODAL_ID} .seasonal-section-summary .material-icons { transition: transform 0.2s ease; } /* Discovery section type collapsible styling */ #${MODAL_ID} .discovery-section-type-summary { position: relative; list-style: none; } #${MODAL_ID} .discovery-section-type-summary::-webkit-details-marker { display: none; } #${MODAL_ID} .discovery-section-type-summary::marker { display: none; } #${MODAL_ID} details[open] .discovery-section-type-summary .material-icons { transform: rotate(90deg); } #${MODAL_ID} .discovery-section-type-summary .material-icons { transition: transform 0.2s ease; } /* Responsive design */ @media (max-width: 768px) { #${MODAL_ID} .modal-content-wrapper { width: 95vw; max-height: 95vh; } #${MODAL_ID} .content-primary { padding: 1em; } #${MODAL_ID} .paperList { padding: 0.75em; } #${MODAL_ID} [style*="grid-template-columns"] { grid-template-columns: 1fr !important; } } @media (max-width: 480px) { #${MODAL_ID} .content-primary { padding: 0.75em; } #${MODAL_ID} .pageTitle { font-size: 1.5em; } #${MODAL_ID} input.fld, #${MODAL_ID} textarea.fld { font-size: 16px; /* Prevents zoom on iOS */ } } `; document.head.appendChild(style); } // Show confirmation modal for editing script root configuration function showScriptRootEditConfirmation() { return new Promise((resolve) => { if (!window.ModalSystem) { resolve(false); return; } const modal = window.ModalSystem.create({ id: 'scriptRootEditConfirmation', title: 'Edit KefinTweaks Root URL', content: `
Editing the Root URL is useful if you are hosting the scripts yourself or if you want to use a specific KefinTweaks version. Scripts will be loaded from this root URL + '/scripts/'. There is no validation done for the URL provided so please ensure it is valid. In any case, you can easily revert this setting.
`, footer: ` `, closeOnBackdrop: true, closeOnEscape: true, onOpen: (modalInstance) => { const confirmBtn = modalInstance.dialogFooter?.querySelector('#confirmEditScriptRoot'); const cancelBtn = modalInstance.dialogFooter?.querySelector('#cancelEditScriptRoot'); if (confirmBtn) { confirmBtn.addEventListener('click', () => { modalInstance.close(); resolve(true); }); } if (cancelBtn) { cancelBtn.addEventListener('click', () => { modalInstance.close(); resolve(false); }); } } }); }); } // Build the configuration page content function buildConfigPageContent(config) { const scripts = config.scripts || {}; const homeScreen = config.homeScreen || {}; const exclusiveElsewhere = config.exclusiveElsewhere || {}; const search = config.search || {}; const customMenuLinks = config.customMenuLinks || []; const skins = config.skins || []; const themes = config.themes || []; // Get all skin names for autocomplete const allSkinNames = skins.map(skin => skin.name).filter(Boolean); const isEnabled = window.KefinTweaksConfigEnabled !== false; return `

Feature Configuration

Toggle individual KefinTweaks features on or off. Existing configurations are maintained when disabling features.
${buildScriptToggles(scripts)}

Home Screen Configuration

Configure custom home screen sections and discovery features
${buildHomeScreenConfig(homeScreen)}

Exclusive Elsewhere Configuration

Configure exclusive elsewhere branding behavior
${buildExclusiveElsewhereConfig(exclusiveElsewhere)}

Skin Configuration

Configure default skin and available skins for all users
Default Skin
Select a default skin for all users

Enable/Disable Skins

Disabled skins will not appear in the appearance dropdowns for users
All themes are created with love by community members like you. Don't forget to thank them for their work and time if you appreciate their creations. KefinTweaks has not contributed to the creation of any of the skins below and is only attempting to facilitate their accessibility.
${buildSkinToggles(skins)}
Skins JSON
Add additional skins that will be available to all users. Each skin can have multiple CSS files for different server versions. Hidden skins (included automatically by KefinTweaks) are not shown here.
View Example Format
[
  {
    "name": "Custom Skin",
    "author": "username",
    "url": [
      {
        "majorServerVersions": [10, 11],
        "urls": ["https://cdn.jsdelivr.net/gh/username/custom-theme.css"]
      }
    ],
    "colorSchemes": []
  },
  {
    "name": "Custom Skin 2",
    "author": "username 2",
    "url": [
      {
        "majorServerVersions": [10],
        "urls": ["https://cdn.jsdelivr.net/gh/username/custom-theme2.css"]
      }
    ],
    "colorSchemes": []
  }
]

Theme Configuration

Configure additional themes available to all users
Themes JSON
Add additional themes that will be available to all users. Each theme should have a name and URL pointing to a CSS file.
View Example Format
[
  {
    "name": "Custom Dark Theme",
    "url": "https://cdn.jsdelivr.net/gh/username/custom-dark-theme.css"
  },
  {
    "name": "Custom Light Theme",
    "url": "https://cdn.jsdelivr.net/gh/username/custom-light-theme.css"
  }
]
`; } // Extract GitHub repository URL from skin configuration function getSkinGitHubUrl(skin) { // Check if skin has explicit github field if (skin.github) { return skin.github; } // Try to extract from jsdelivr GitHub CDN URLs if (skin.url && Array.isArray(skin.url)) { for (const urlObj of skin.url) { if (urlObj.urls && Array.isArray(urlObj.urls)) { for (const url of urlObj.urls) { // Match pattern: https://cdn.jsdelivr.net/gh/{owner}/{repo}@... const match = url.match(/https:\/\/cdn\.jsdelivr\.net\/gh\/([^\/]+)\/([^\/@]+)/); if (match) { const owner = match[1]; const repo = match[2]; return `https://github.com/${owner}/${repo}`; } } } } } return null; } // Build skin toggle switches function buildSkinToggles(skins) { return skins.map(skin => { const isEnabled = skin.enabled !== false; // Default to true if not set const isHidden = skin.hidden === true; const githubUrl = getSkinGitHubUrl(skin); // Determine tooltip text let tooltipText = ''; if (isHidden) { tooltipText = 'This skin is included automatically by KefinTweaks'; } else if (githubUrl) { tooltipText = 'View on GitHub'; } return `
${githubUrl ? ` ${skin.name} info ` : `
${skin.name}
`}
${buildJellyfinCheckbox(`skin_${skin.name.replace(/[^a-zA-Z0-9]/g, '_')}`, isEnabled, '', { 'data-skin-name': skin.name })}
`; }).join(''); } // Build script toggle switches function buildScriptToggles(scripts) { const scriptNames = [ { key: 'watchlist', label: 'Watchlist', desc: 'Allows your users to add items to their Watchlist. The Watchlist page shows an overview of all items on a user\'s Watchlist, as well as their Series Progress and Movie History. It also includes a Statistics page with an overview of your user watched stats.' }, { key: 'homeScreen', label: 'Enhanced Home Screen', desc: 'Add custom home screen sections and a "discovery engine" to your Home Page. Create sections based on Genre, Tags, Playlists, Collections or Search Terms for specific Item Types. Use the "Spotlight" feature to highlight specific sections with an image carousel/slideshow.' }, { key: 'search', label: 'Enhanced Search', desc: 'Search speed is improved by searching less content types by default. Provides options to specify which content type to search. Fully compatible with both the Jellysearch Search from Jellyfin Enhanced plugin and the Meilisearch plugin.' }, { key: 'infiniteScroll', label: 'Infinite Scroll', desc: 'Adds infinite scrolling to the library pages for Movies and TV' }, { key: 'removeContinue', label: 'Remove Continue', desc: 'Adds the ability to remove items from the Continue Watching sections' }, { key: 'skinManager', label: 'Skin Manager', desc: 'Skin selection and management - adds skin dropdown to header and display preferences' }, { key: 'headerTabs', label: 'Header Tabs', desc: 'Allows direct navigation to specific Tab sections of a given library page. Full support for default Jellyfin landing pages.' }, { key: 'customMenuLinks', label: 'Custom Menu Links', desc: 'Add custom menu links to the left side navigation menu' }, { key: 'breadcrumbs', label: 'Breadcrumbs', desc: 'Breadcrumb navigation for Movies, TV and Music. Allows quick navigation between Seasons/Episodes and Albums/Songs.' }, { key: 'playlist', label: 'Playlist UX', desc: 'Improved Playlist page navigation: Items only play when the Play button is pressed. Clicking an item navigates to the item\'s page.' }, { key: 'itemDetailsCollections', label: 'Collections on Details Page', desc: 'Displays collections on item details pages (Included In section)' }, { key: 'flattenSingleSeasonShows', label: 'Flatten Single Season Shows', desc: 'Flattens single-season shows to display episodes directly on series page' }, { key: 'collections', label: 'Collection Sorting', desc: 'Collection sorting functionality on the Collection page' }, { key: 'subtitleSearch', label: 'Subtitle Search', desc: 'Search and download subtitles directly from the video OSD' }, { key: 'exclusiveElsewhere', label: 'Exclusive Elsewhere', desc: 'Custom branding when items aren\'t available on streaming services' }, { key: 'backdropLeakFix', label: 'Backdrop Leak Fix', desc: 'Fixes memory leaks from backdrop images when tab isn\'t focused' }, { key: 'dashboardButtonFix', label: 'Dashboard Button Fix', desc: 'Improved back button behavior on dashboard - prevents navigating back to the new tab browser page' } ]; return scriptNames.map(script => { const isEnabled = scripts[script.key] !== false; // Default to true if not set return `
${script.label}
${buildJellyfinCheckbox(`script_${script.key}`, isEnabled, '', { 'data-script-key': script.key })}
${script.desc}
`; }).join(''); } // Helper function to build Include Item Types badge field function buildIncludeItemTypesField(prefix, sectionIndex, sanitizedPrefix, currentTypes, sourceType) { // Available item types (excluding Collections and Playlists unless source type is Parent) const availableTypes = ['Movie', 'Series', 'Season', 'Episode', 'MusicArtist', 'MusicAlbum', 'Audio', 'MusicVideo', 'Book']; const parentOnlyTypes = ['BoxSet', 'Playlist']; // Only available when source type is Parent // All available types for this source type const allAvailableTypes = sourceType === 'Parent' ? [...availableTypes, ...parentOnlyTypes] : availableTypes; const selectionLabel = currentTypes.length ? `${currentTypes.length} selected` : 'Select item types'; // Current types as badges const badgesHtml = currentTypes.map(typeName => ` ${typeName} `).join(''); const dropdownOptions = allAvailableTypes.map(typeName => { const isChecked = currentTypes.includes(typeName); return ` `; }).join(''); return `
Include Item Types
No item types selected ${badgesHtml}
`; } // Helper function to build Jellyfin-style checkbox function buildJellyfinCheckbox(id, checked, label, dataAttributes = {}) { const dataAttrs = Object.entries(dataAttributes).map(([key, value]) => `${key}="${value}"`).join(' '); const checkedAttr = checked ? 'checked' : ''; return `
`; } // Helper function to build a section UI (for nested sections in seasonal and custom sections) function buildSectionUI(prefix, section, sectionIndex, isSeasonalNested = false) { const sectionId = section.id || `${prefix}_section_${sectionIndex}`; const enabled = section.enabled !== false; const name = section.name || ''; const type = section.type || 'Genre'; const source = section.source || ''; const itemLimit = section.itemLimit || 16; const sortOrder = section.sortOrder || 'Random'; const sortOrderDirection = section.sortOrderDirection || 'Ascending'; const cardFormat = section.cardFormat || 'Poster'; const order = section.order || 100; const spotlightEnabled = section.spotlight === true; const discoveryEnabled = section.discoveryEnabled === true; const searchTerm = section.searchTerm || ''; const includeItemTypes = Array.isArray(section.includeItemTypes) ? section.includeItemTypes : (section.includeItemTypes ? section.includeItemTypes.split(',').map(s => s.trim()).filter(Boolean) : (type === 'Parent' ? [] : ['Movie'])); // Determine source field based on type let sourceFieldHtml = ''; if (type === 'Parent') { // Parent type uses simple text input for parent IDs (comma-separated) const parentIds = source || ''; sourceFieldHtml = `
Parent IDs (comma-separated, leave empty for "Any")
`; } else if (type === 'Tag' || type === 'Genre' || type === 'Collection' || type === 'Playlist') { // Parse existing source (comma-separated) into array const sourceArray = source ? source.split(',').map(s => s.trim()).filter(Boolean) : []; // For Collections/Playlists, we'll show IDs initially and load names after // For Tags/Genres, show names directly let badgesHtml = ''; if (type === 'Tag' || type === 'Genre') { badgesHtml = sourceArray.map(val => ` ${val} `).join(''); } else { // Collections/Playlists: display IDs initially, will be replaced with names after fetch badgesHtml = sourceArray.map(id => ` ${id} `).join(''); } sourceFieldHtml = `
${type}
${badgesHtml}
`; } // Build section fields HTML for right column const sanitizedSectionPrefix = `${prefix}_section_${sectionIndex.toString().replace(/[^a-zA-Z0-9]/g, '_')}`; const spotlightCheckboxId = `${sanitizedSectionPrefix}_spotlight`; const discoveryCheckboxId = `${sanitizedSectionPrefix}_discovery`; const sectionFieldsHtml = createSectionConfiguration( sanitizedSectionPrefix, section, { includeName: true, defaultName: name || 'Unnamed Section', nameInputAttributes: { class: `${prefix}_section_name`, 'data-section-index': sectionIndex, 'data-prefix': prefix } } ); // For custom sections and seasonal nested sections, use the improved layout const useImprovedLayout = prefix === 'customSection' || isSeasonalNested; // Build section content - improved layout for custom sections and seasonal nested sections let sectionContent; if (useImprovedLayout) { // Custom sections: Row 1 (checkboxes + type), Row 2 (source), Row 3+ (remaining fields in 3 columns) sectionContent = `
Enabled
${buildJellyfinCheckbox(`${prefix}_section_enabled_${sectionIndex}`, enabled, '', { 'data-section-index': sectionIndex, 'data-prefix': prefix, 'class': `${prefix}_section_enabled` })}
Spotlight
${buildJellyfinCheckbox(spotlightCheckboxId, spotlightEnabled, 'Enable Spotlight', { 'data-section-index': sectionIndex, 'data-prefix': prefix, 'class': `${prefix}_section_spotlight` })}
Discovery
${buildJellyfinCheckbox(discoveryCheckboxId, discoveryEnabled, 'Enable as Discovery', { 'data-section-index': sectionIndex, 'data-prefix': prefix, 'class': `${prefix}_section_discovery` })}
Type
${sourceFieldHtml}
${sectionFieldsHtml}
Search Term
${buildIncludeItemTypesField(prefix, sectionIndex, sanitizedSectionPrefix, includeItemTypes, type)}
`; } // Wrap sections in collapsible details for both custom sections and seasonal nested sections if (useImprovedLayout) { // Determine summary class and name class based on prefix const summaryClass = prefix === 'customSection' ? 'custom-section-summary' : 'seasonal-section-summary'; const nameClass = prefix === 'customSection' ? 'custom-section-name' : 'seasonal-section-name'; const enabledClass = prefix === 'customSection' ? 'custom-section-enabled-display' : 'seasonal-section-enabled-display'; const orderClass = prefix === 'customSection' ? 'custom-section-order' : 'seasonal-section-order'; const showPreviewButton = prefix === 'customSection' || prefix === 'seasonal_season'; const previewButtonHtml = showPreviewButton ? `` : ''; return `
chevron_right ${name || 'Unnamed Section'} (${enabled ? 'Enabled' : 'Disabled'}, Order: ${order})
${previewButtonHtml}
${sectionContent}
`; } else { // Fallback for any other section types (shouldn't happen in current code) const showPreviewButton = prefix === 'customSection' || prefix === 'seasonal_season'; const previewButtonHtml = showPreviewButton ? `` : ''; return `
${name || 'Unnamed Section'}
${previewButtonHtml}
${sectionContent}
`; } } function mergeAttributes(defaultAttrs = {}, customAttrs = {}) { const merged = { ...defaultAttrs }; if (customAttrs && typeof customAttrs === 'object') { Object.entries(customAttrs).forEach(([key, value]) => { if (value === undefined || value === null) { return; } if (key === 'class' && merged.class) { merged.class = `${merged.class} ${value}`.trim(); } else { merged[key] = value; } }); } return merged; } function attributesToString(attrs = {}) { return Object.entries(attrs) .map(([key, value]) => { if (value === undefined || value === null) return ''; return `${key}="${value}"`; }) .filter(Boolean) .join(' '); } function parseNumberOrFallback(value, fallback) { if (value === null || value === undefined || value === '') { return fallback; } const parsed = parseInt(value, 10); return Number.isFinite(parsed) ? parsed : fallback; } function normalizeDiscoverySectionConfigEntry(rawValue, definition, discovery, legacyName = '') { const defaultItemLimit = discovery.defaultItemLimit ?? 16; const defaultSortOrder = discovery.defaultSortOrder ?? 'Random'; const defaultCardFormat = discovery.defaultCardFormat ?? 'Poster'; const defaults = { enabled: true, name: legacyName || definition.defaultName || '', itemLimit: defaultItemLimit, sortOrder: defaultSortOrder, sortOrderDirection: 'Ascending', cardFormat: defaultCardFormat }; if (definition.extras?.minimumItems !== undefined) { defaults.minimumItems = definition.extras.minimumItems; } let normalized = { ...defaults }; if (rawValue === false) { normalized.enabled = false; } else if (rawValue && typeof rawValue === 'object') { normalized = { ...normalized, ...rawValue }; } else if (rawValue === true) { normalized.enabled = true; } normalized.itemLimit = parseNumberOrFallback(normalized.itemLimit, defaultItemLimit); normalized.sortOrder = normalized.sortOrder || defaultSortOrder; normalized.sortOrderDirection = normalized.sortOrderDirection || 'Ascending'; normalized.cardFormat = normalized.cardFormat || defaultCardFormat; normalized.name = normalized.name || definition.defaultName || ''; if (definition.extras?.minimumItems !== undefined) { normalized.minimumItems = parseNumberOrFallback( normalized.minimumItems, definition.extras.minimumItems ); } return normalized; } function getNormalizedDiscoverySectionConfigs(discovery = {}) { const sectionTypes = discovery.sectionTypes || {}; const legacyNames = discovery.sectionNames || {}; const normalized = {}; DISCOVERY_SECTION_DEFINITIONS.forEach(def => { normalized[def.key] = normalizeDiscoverySectionConfigEntry( sectionTypes[def.key], def, discovery, legacyNames[def.key] ); }); return normalized; } // Helper function to build section configuration fields (Name, Item Limit, Sort Order, Card Format, Order) function createSectionConfiguration(prefix, config = {}, options = {}) { const { includeSortOrder = true, includeOrder = true, includeName = true, defaultName = '', nameLabel = 'Section Name', nameInputAttributes = {}, includeCardFormat = true, includeItemLimit = true } = options; const nameValue = config.name ?? defaultName ?? ''; const itemLimit = config.itemLimit ?? 16; const sortOrder = config.sortOrder ?? 'Random'; const sortOrderDirection = config.sortOrderDirection ?? 'Ascending'; const cardFormat = config.cardFormat ?? 'Poster'; const order = config.order ?? 100; let html = ''; if (includeName) { const nameAttrs = mergeAttributes( { id: `${prefix}_name`, class: 'fld emby-input' }, nameInputAttributes ); html += `
${nameLabel}
`; } if (includeCardFormat) { html += `
Card Format
`; } if (includeSortOrder) { html += `
Sort Order
Sort Order Direction
`; } if (includeOrder) { html += `
Order
`; } if (includeItemLimit) { html += `
Item Limit
`; } return html; } // Build home screen configuration function buildHomeScreenConfig(homeScreen) { const recentlyReleased = homeScreen.recentlyReleased || {}; const trending = homeScreen.trending || {}; const popularTVNetworks = homeScreen.popularTVNetworks || {}; const watchlist = homeScreen.watchlist || {}; const upcoming = homeScreen.upcoming || {}; const imdbTop250 = homeScreen.imdbTop250 || {}; const seasonal = homeScreen.seasonal || {}; const watchAgain = homeScreen.watchAgain || {}; const discovery = homeScreen.discovery || {}; const customSections = homeScreen.customSections || []; const normalizedDiscoverySections = getNormalizedDiscoverySectionConfigs(discovery); // Build seasonal sections HTML const seasonalSectionsHtml = (seasonal.seasons || []).map((season, seasonIndex) => { const sections = season.sections || []; const sectionsHtml = sections.map((section, sectionIndex) => { return buildSectionUI('seasonal_season', section, `${seasonIndex}_${sectionIndex}`, true); }).join(''); const seasonOrder = season.order || 100; return `
chevron_right ${season.name || 'Unnamed Season'} (${season.enabled !== false ? 'Enabled' : 'Disabled'}, Order: ${seasonOrder})
Enabled
${buildJellyfinCheckbox(`seasonal-season-enabled-${seasonIndex}`, season.enabled !== false, 'Enabled', { 'data-index': seasonIndex, 'class': 'seasonal-season-enabled' })}
Name
Start Date (MM-DD)
End Date (MM-DD)
Order
Sections
${sectionsHtml}
`; }).join(''); return `
${buildJellyfinCheckbox('homeScreen_recentlyReleased_enabled', recentlyReleased.enabled !== false, 'Recently Released Sections')}
chevron_right Recently Released Movies (${(recentlyReleased.movies || {}).enabled !== false ? 'Enabled' : 'Disabled'}, Order: ${(recentlyReleased.movies || {}).order || 30})
${buildJellyfinCheckbox('homeScreen_recentlyReleased_movies_enabled', (recentlyReleased.movies || {}).enabled !== false, 'Enabled')}
${createSectionConfiguration('homeScreen_recentlyReleased_movies', recentlyReleased.movies || {}, { includeName: true, defaultName: 'Recently Released Movies', includeSortOrder: false, includeOrder: true })}
chevron_right Recently Aired Episodes (${(recentlyReleased.episodes || {}).enabled !== false ? 'Enabled' : 'Disabled'}, Order: ${(recentlyReleased.episodes || {}).order || 31})
${buildJellyfinCheckbox('homeScreen_recentlyReleased_episodes_enabled', (recentlyReleased.episodes || {}).enabled !== false, 'Enabled')}
${createSectionConfiguration('homeScreen_recentlyReleased_episodes', recentlyReleased.episodes || {}, { includeName: true, defaultName: 'Recently Aired Episodes', includeSortOrder: false, includeOrder: true })}
${buildJellyfinCheckbox('homeScreen_trending_enabled', trending.enabled === true, 'Trending Sections', { disabled: 'true' })} (Order: ${trending.order || 100}) Under development
${buildJellyfinCheckbox('homeScreen_popularTVNetworks_enabled', popularTVNetworks.enabled === true, 'Popular TV Networks Sections')} (Order: ${popularTVNetworks.order || 100})
${createSectionConfiguration('homeScreen_popularTVNetworks', popularTVNetworks, { includeName: true, defaultName: 'Popular TV Networks' })}
Minimum Shows for Network to Appear
${buildJellyfinCheckbox('homeScreen_watchlist_enabled', watchlist.enabled === true, 'Watchlist')} (Order: ${watchlist.order || 100})
${createSectionConfiguration('homeScreen_watchlist', watchlist, { includeName: true, defaultName: 'Watchlist' })}
${buildJellyfinCheckbox('homeScreen_upcoming_enabled', upcoming.enabled !== false, 'Upcoming')} (Order: ${upcoming.order || 100})
${createSectionConfiguration('homeScreen_upcoming', upcoming, { includeName: true, defaultName: 'Upcoming', includeSortOrder: false })}
${buildJellyfinCheckbox('homeScreen_imdbTop250_enabled', imdbTop250.enabled !== false, 'IMDb Top 250')} (Order: ${imdbTop250.order || 100})
${createSectionConfiguration('homeScreen_imdbTop250', imdbTop250, { includeName: true, defaultName: 'IMDb Top 250' })}
${buildJellyfinCheckbox('homeScreen_seasonal_enabled', seasonal.enabled !== false, 'Seasonal Sections')}
${seasonalSectionsHtml}
${buildJellyfinCheckbox('homeScreen_watchAgain_enabled', watchAgain.enabled === true, 'Watch Again')} (Order: ${watchAgain.order || 100})
${createSectionConfiguration('homeScreen_watchAgain', watchAgain, { includeName: true, defaultName: 'Watch Again' })}
${buildJellyfinCheckbox('homeScreen_discovery_enabled', discovery.enabled !== false, 'Discovery Sections')}
Infinite Scroll / Load More Button
${buildJellyfinCheckbox('homeScreen_discovery_infiniteScroll', discovery.infiniteScroll !== false, 'Infinite Scroll')}
Randomize Section Order
${buildJellyfinCheckbox('homeScreen_discovery_randomizeOrder', discovery.randomizeOrder === true, 'Randomize Order')}
Minimum Appearances for Top People
Minimum Movie count for Genres
Spotlight & Collection Spawn Chance
0.0 = never, 1.0 = always
${createSectionConfiguration('homeScreen_discovery', discovery, { includeName: false, includeOrder: false, includeCardFormat: false, includeSortOrder: false, includeItemLimit: false })}
Discovery Sections
Section names support placeholders such as [Genre], [Director], [Writer], [Actor], [Movie], [Studio], [Collection Name]
${DISCOVERY_SECTION_DEFINITIONS.map(section => { const sectionConfig = normalizedDiscoverySections[section.key]; const prefix = `homeScreen_discovery_sectionTypes_${section.key}`; const configHtml = createSectionConfiguration(prefix, sectionConfig, { includeName: true, includeOrder: true, includeSortOrder: false, defaultName: section.defaultName }); const extraFields = section.extras?.minimumItems !== undefined ? `
Minimum Items
` : ''; const discoveryOrder = sectionConfig.order || 100; return `
chevron_right ${section.label} (${sectionConfig.enabled !== false ? 'Enabled' : 'Disabled'}, Order: ${discoveryOrder})
${buildJellyfinCheckbox(`${prefix}_enabled`, sectionConfig.enabled !== false, 'Enabled')}
${configHtml} ${extraFields}
`; }).join('')}
Custom Sections
Sections
${(customSections || []).map((section, index) => { return buildSectionUI('customSection', section, index, false); }).join('')}
`; } // Build exclusive elsewhere configuration function buildExclusiveElsewhereConfig(exclusiveElsewhere) { return `
Hide Server Name
Set to true to hide server name, useful when you want to only show a logo or icon via CSS
${buildJellyfinCheckbox('exclusiveElsewhere_hideServerName', exclusiveElsewhere.hideServerName === true, 'Enabled')}
`; } // Build search configuration function buildSearchConfig(search) { return `
Enable Jellyseerr
Enable Jellyseerr integration for request functionality
${buildJellyfinCheckbox('search_enableJellyseerr', search.enableJellyseerr === true, 'Enabled')}
`; } // Open configuration modal async function openConfigurationModal() { console.log('[KefinTweaks Configuration] Opening configuration modal...'); // Inject CSS if not already injected injectConfigModalCSS(); // Load configuration first let config; try { config = await getKefinTweaksConfig(); } catch (error) { console.error('[KefinTweaks Configuration] Error loading config:', error); alert('Error loading configuration. Please try again.'); return; } currentLoadedConfig = config; window.KefinTweaksCurrentConfig = config; // Build the content (without title, as ModalSystem adds it) const content = document.createElement('div'); content.className = 'modal-content-wrapper'; content.id = MODAL_ID; content.innerHTML = `
${buildConfigPageContent(config)}
`; // Create footer with save, export, and import buttons const footer = document.createElement('div'); footer.style.display = 'flex'; footer.style.gap = '0.75em'; footer.style.alignItems = 'center'; footer.innerHTML = ` `; // Create modal using ModalSystem if (!window.ModalSystem) { console.error('[KefinTweaks Configuration] ModalSystem not available'); alert('Modal system not available. Please ensure modal.js is loaded.'); return; } const modal = window.ModalSystem.create({ id: MODAL_ID, title: 'KefinTweaks Configuration', content: content, footer: footer, closeOnBackdrop: true, closeOnEscape: true, onOpen: (modalInstance) => { // Update modal dialog styling for large size if (modalInstance && modalInstance.dialog) { modalInstance.dialog.style.maxWidth = '90vw'; modalInstance.dialog.style.width = '1400px'; modalInstance.dialog.style.maxHeight = '90vh'; } // Add event handlers setupConfigModalHandlers(modalInstance, config); } }); } // Set up event handlers for configuration modal function setupConfigModalHandlers(modalInstance, config) { // Enabled checkbox handler const enabledCheckbox = modalInstance.dialogContent.querySelector('#kefinTweaksEnabled'); if (enabledCheckbox) { enabledCheckbox.addEventListener('change', async (e) => { const isEnabled = e.target.checked; try { // Update the config's enabled field config.enabled = isEnabled; // Save the updated config to the injector await saveConfigToJavaScriptInjector(config); window.KefinTweaksConfigEnabled = isEnabled; console.log('[KefinTweaks Configuration] KefinTweaks', isEnabled ? 'enabled' : 'disabled'); if (window.KefinTweaksToaster && window.KefinTweaksToaster.toast) { window.KefinTweaksToaster.toast(`KefinTweaks ${isEnabled ? 'enabled' : 'disabled'}. Page refresh required.`); } } catch (error) { console.error('[KefinTweaks Configuration] Error toggling KefinTweaks:', error); // Revert checkbox on error enabledCheckbox.checked = !isEnabled; alert(`Failed to ${isEnabled ? 'enable' : 'disable'} KefinTweaks: ${error.message}`); } }); } // Show Advanced Settings checkbox handler const advancedCheckbox = modalInstance.dialogContent.querySelector('#showAdvancedSettings'); if (advancedCheckbox) { advancedCheckbox.addEventListener('change', (e) => { const showAdvanced = e.target.checked; const advancedSection = modalInstance.dialogContent.querySelector('.kefinTweaks-advanced-section'); if (advancedSection) { advancedSection.style.display = showAdvanced ? '' : 'none'; } }); } // Edit script root button handler const editBtn = modalInstance.dialogContent.querySelector('#editScriptRootBtn'); if (editBtn) { editBtn.addEventListener('click', async () => { const confirmed = await showScriptRootEditConfirmation(); if (confirmed) { const contentDiv = modalInstance.dialogContent.querySelector('#scriptRootConfigContent'); if (contentDiv) { contentDiv.style.display = 'block'; } } }); } // No validation needed for default skin dropdown - it only allows valid options // Helper function to toggle container visibility function setupToggleVisibility(checkboxId, containerId) { const checkbox = modalInstance.dialogContent.querySelector(checkboxId); const container = modalInstance.dialogContent.querySelector(containerId); if (checkbox && container) { const toggle = () => { container.style.display = checkbox.checked ? '' : 'none'; }; checkbox.addEventListener('change', toggle); // Prevent details from toggling when clicking checkbox checkbox.addEventListener('click', (e) => { e.stopPropagation(); }); toggle(); // Set initial state } } // Home Screen: Setup all visibility toggles setupToggleVisibility('#homeScreen_recentlyReleased_enabled', '#homeScreen_recentlyReleased_container'); setupToggleVisibility('#homeScreen_trending_enabled', '#homeScreen_trending_container'); setupToggleVisibility('#homeScreen_popularTVNetworks_enabled', '#homeScreen_popularTVNetworks_container'); setupToggleVisibility('#homeScreen_watchlist_enabled', '#homeScreen_watchlist_container'); setupToggleVisibility('#homeScreen_upcoming_enabled', '#homeScreen_upcoming_container'); setupToggleVisibility('#homeScreen_imdbTop250_enabled', '#homeScreen_imdbTop250_container'); setupToggleVisibility('#homeScreen_seasonal_enabled', '#homeScreen_seasonal_container'); setupToggleVisibility('#homeScreen_watchAgain_enabled', '#homeScreen_watchAgain_container'); setupToggleVisibility('#homeScreen_discovery_enabled', '#homeScreen_discovery_container'); // Setup event listeners for section management // Add section to seasonal season modalInstance.dialogContent.addEventListener('click', (e) => { const addBtn = e.target.closest('.add-section-to-seasonal-btn'); if (addBtn) { const seasonIndex = parseInt(addBtn.getAttribute('data-season-index')); addSectionToSeasonalSeason(seasonIndex); } }); // Add custom section modalInstance.dialogContent.addEventListener('click', (e) => { const addBtn = e.target.closest('.add-custom-section-btn'); if (addBtn) { addCustomSection(); } }); // Delete section modalInstance.dialogContent.addEventListener('click', (e) => { const deleteBtn = e.target.closest('.delete-section-btn'); if (deleteBtn) { e.preventDefault(); e.stopPropagation(); const prefix = deleteBtn.getAttribute('data-prefix'); const sectionIndexRaw = deleteBtn.getAttribute('data-section-index'); const isSeasonal = deleteBtn.getAttribute('data-is-seasonal') === 'true'; if (prefix && sectionIndexRaw !== null) { // For seasonal sections, sectionIndex is a compound string like "0_1", don't parse it const sectionIndex = isSeasonal || sectionIndexRaw.includes('_') ? sectionIndexRaw : parseInt(sectionIndexRaw); deleteSection(prefix, sectionIndex, isSeasonal); } } }); // Preview section modalInstance.dialogContent.addEventListener('click', (e) => { const previewBtn = e.target.closest('.preview-section-btn'); if (previewBtn) { e.preventDefault(); e.stopPropagation(); const prefix = previewBtn.getAttribute('data-prefix'); const sectionIndexRaw = previewBtn.getAttribute('data-section-index'); if (prefix && sectionIndexRaw !== null) { // For seasonal sections, sectionIndex is a compound string like "0_1", don't parse it const isSeasonal = prefix === 'seasonal_season' || sectionIndexRaw.includes('_'); const sectionIndex = isSeasonal ? sectionIndexRaw : parseInt(sectionIndexRaw, 10); previewSection(prefix, sectionIndex); } } }); // Type dropdown change modalInstance.dialogContent.addEventListener('change', (e) => { const typeSelect = e.target.closest(`[class*="_section_type"]`); if (typeSelect && typeSelect.hasAttribute('data-prefix')) { const prefix = typeSelect.getAttribute('data-prefix'); const sectionIndex = typeSelect.getAttribute('data-section-index'); const isSeasonal = typeSelect.getAttribute('data-is-seasonal') === 'true'; updateSectionSourceField(prefix, sectionIndex, isSeasonal); } }); // Initialize autocomplete for all badge-based sections setTimeout(async () => { const badgeContainers = modalInstance.dialogContent.querySelectorAll('.tag-badge-container:not(.includeItemTypes-badge-container)'); for (const container of badgeContainers) { const prefix = container.getAttribute('data-prefix'); const sectionIndex = container.getAttribute('data-section-index'); const type = container.getAttribute('data-type'); if (prefix && sectionIndex && type) { await setupBadgeAutocomplete(prefix, sectionIndex, type); if (type === 'Collection' || type === 'Playlist') { await loadBadgeNames(prefix, sectionIndex, type); } } } // Initialize autocomplete for Include Item Types fields const includeItemTypesContainers = modalInstance.dialogContent.querySelectorAll('.includeItemTypes-badge-container'); for (const container of includeItemTypesContainers) { const prefix = container.getAttribute('data-prefix'); const sectionIndex = container.getAttribute('data-section-index'); const availableTypes = container.getAttribute('data-available-types')?.split(',').filter(Boolean) || []; if (prefix && sectionIndex) { setupIncludeItemTypesDropdown(prefix, sectionIndex, availableTypes); } } // Setup summary update listeners for existing custom sections // Setup summary listeners for custom sections const customSectionItems = modalInstance.dialogContent.querySelectorAll('.customSection_section_item'); customSectionItems.forEach(sectionItem => { const sectionIndex = sectionItem.getAttribute('data-section-index'); if (sectionIndex !== null) { setupCustomSectionSummaryListeners(sectionItem, sectionIndex); } }); // Setup summary listeners for seasonal nested sections const seasonalSectionItems = modalInstance.dialogContent.querySelectorAll('.seasonal_season_section_item'); seasonalSectionItems.forEach(sectionItem => { const sectionIndex = sectionItem.getAttribute('data-section-index'); if (sectionIndex !== null) { setupCustomSectionSummaryListeners(sectionItem, sectionIndex); } }); // Setup order update listeners for home screen sections setupHomeSectionOrderListeners(); // Setup order update listeners for recently released subsections setupRecentlyReleasedOrderListeners(); // Setup order update listeners for seasonal seasons setupSeasonalSeasonOrderListeners(); // Setup order update listeners for discovery section types setupDiscoverySectionTypeOrderListeners(); // Setup name update listeners for seasonal seasons setupSeasonalSeasonNameListeners(); }, 100); // Setup event listeners to update home section order displays function setupHomeSectionOrderListeners() { const orderSpans = modalInstance.dialogContent.querySelectorAll('.home-section-order'); orderSpans.forEach(span => { const prefix = span.getAttribute('data-prefix'); if (prefix) { const orderInput = modalInstance.dialogContent.querySelector(`#${prefix}_order`); if (orderInput) { orderInput.addEventListener('input', () => { span.textContent = orderInput.value || '100'; }); } } }); } // Setup event listeners to update recently released subsection order displays function setupRecentlyReleasedOrderListeners() { const moviesOrderSpan = modalInstance.dialogContent.querySelector('.recently-released-movies-order'); const moviesOrderInput = modalInstance.dialogContent.querySelector('#homeScreen_recentlyReleased_movies_order'); if (moviesOrderSpan && moviesOrderInput) { moviesOrderInput.addEventListener('input', () => { moviesOrderSpan.textContent = moviesOrderInput.value || '30'; }); } const episodesOrderSpan = modalInstance.dialogContent.querySelector('.recently-released-episodes-order'); const episodesOrderInput = modalInstance.dialogContent.querySelector('#homeScreen_recentlyReleased_episodes_order'); if (episodesOrderSpan && episodesOrderInput) { episodesOrderInput.addEventListener('input', () => { episodesOrderSpan.textContent = episodesOrderInput.value || '31'; }); } // Setup enabled status listeners const moviesEnabledSpan = modalInstance.dialogContent.querySelector('.recently-released-movies-enabled'); const moviesEnabledCheckbox = modalInstance.dialogContent.querySelector('#homeScreen_recentlyReleased_movies_enabled'); if (moviesEnabledSpan && moviesEnabledCheckbox) { moviesEnabledCheckbox.addEventListener('change', () => { moviesEnabledSpan.textContent = moviesEnabledCheckbox.checked ? 'Enabled' : 'Disabled'; }); } const episodesEnabledSpan = modalInstance.dialogContent.querySelector('.recently-released-episodes-enabled'); const episodesEnabledCheckbox = modalInstance.dialogContent.querySelector('#homeScreen_recentlyReleased_episodes_enabled'); if (episodesEnabledSpan && episodesEnabledCheckbox) { episodesEnabledCheckbox.addEventListener('change', () => { episodesEnabledSpan.textContent = episodesEnabledCheckbox.checked ? 'Enabled' : 'Disabled'; }); } } // Setup event listeners to update seasonal season order displays function setupSeasonalSeasonOrderListeners() { const orderInputs = modalInstance.dialogContent.querySelectorAll('.seasonal-season-order-input'); orderInputs.forEach(input => { const seasonIndex = input.getAttribute('data-index'); const orderSpan = modalInstance.dialogContent.querySelector(`.seasonal-season-order[data-season-index="${seasonIndex}"]`); if (orderSpan) { input.addEventListener('input', () => { orderSpan.textContent = input.value || '100'; }); } }); // Setup enabled status listeners const enabledCheckboxes = modalInstance.dialogContent.querySelectorAll('.seasonal-season-enabled'); enabledCheckboxes.forEach(checkbox => { const seasonIndex = checkbox.getAttribute('data-index'); const enabledSpan = modalInstance.dialogContent.querySelector(`.seasonal-season-enabled-display[data-season-index="${seasonIndex}"]`); if (enabledSpan) { checkbox.addEventListener('change', () => { enabledSpan.textContent = checkbox.checked ? 'Enabled' : 'Disabled'; }); } }); } // Setup event listeners to update discovery section type order displays function setupDiscoverySectionTypeOrderListeners() { DISCOVERY_SECTION_DEFINITIONS.forEach(section => { const prefix = `homeScreen_discovery_sectionTypes_${section.key}`; const orderInput = modalInstance.dialogContent.querySelector(`#${prefix}_order`); const orderSpan = modalInstance.dialogContent.querySelector(`.discovery-section-type-order[data-section-key="${section.key}"]`); if (orderInput && orderSpan) { orderInput.addEventListener('input', () => { orderSpan.textContent = orderInput.value || '100'; }); } // Setup enabled status listeners const enabledCheckbox = modalInstance.dialogContent.querySelector(`#${prefix}_enabled`); const enabledSpan = modalInstance.dialogContent.querySelector(`.discovery-section-type-enabled[data-section-key="${section.key}"]`); if (enabledCheckbox && enabledSpan) { enabledCheckbox.addEventListener('change', () => { enabledSpan.textContent = enabledCheckbox.checked ? 'Enabled' : 'Disabled'; }); } }); } // Setup event listeners to update seasonal season name displays function setupSeasonalSeasonNameListeners() { const nameInputs = modalInstance.dialogContent.querySelectorAll('.seasonal-season-name'); nameInputs.forEach(input => { const seasonIndex = input.getAttribute('data-index'); const nameSpan = modalInstance.dialogContent.querySelector(`.seasonal-season-name-display[data-season-index="${seasonIndex}"]`); if (nameSpan) { input.addEventListener('input', () => { nameSpan.textContent = input.value || 'Unnamed Season'; }); } }); } // Section management functions async function addSectionToSeasonalSeason(seasonIndex) { const sectionsList = modalInstance.dialogContent.querySelector(`.seasonal_season_sections_list[data-season-index="${seasonIndex}"]`); if (!sectionsList) return; const sectionIndex = sectionsList.querySelectorAll('.seasonal_season_section_item').length; const fullIndex = `${seasonIndex}_${sectionIndex}`; const newSection = { id: `seasonal-${seasonIndex}-section-${sectionIndex}`, enabled: true, name: 'New Section', type: 'Genre', source: '', itemLimit: 16, sortOrder: 'Random', sortOrderDirection: 'Ascending', cardFormat: 'Poster', order: 100 }; const sectionHtml = buildSectionUI('seasonal_season', newSection, fullIndex, true); sectionsList.insertAdjacentHTML('beforeend', sectionHtml); // Initialize the new section's source field const newSectionItem = sectionsList.querySelector(`.seasonal_season_section_item[data-section-index="${fullIndex}"]`); if (newSectionItem) { // Setup summary listeners for the new section setupCustomSectionSummaryListeners(newSectionItem, fullIndex); const typeSelect = newSectionItem.querySelector('.seasonal_season_section_type'); if (typeSelect) { const type = typeSelect.value; if (type === 'Parent') { // Setup Parent type input sync const parentInput = newSectionItem.querySelector(`.seasonal_season_section_source[data-section-index="${fullIndex}"]`); const parentHidden = newSectionItem.querySelector(`.seasonal_season_section_source_hidden[data-section-index="${fullIndex}"]`); if (parentInput && parentHidden) { parentInput.addEventListener('input', () => { parentHidden.value = parentInput.value; }); } } else { await setupBadgeAutocomplete('seasonal_season', fullIndex, type); if (type === 'Collection' || type === 'Playlist') { await loadBadgeNames('seasonal_season', fullIndex, type); } } } // Initialize Include Item Types autocomplete const includeItemTypesContainer = newSectionItem.querySelector(`.includeItemTypes-badge-container[data-section-index="${fullIndex}"]`); if (includeItemTypesContainer) { const availableTypes = includeItemTypesContainer.getAttribute('data-available-types')?.split(',').filter(Boolean) || []; setupIncludeItemTypesDropdown('seasonal_season', fullIndex, availableTypes); } } }; async function addCustomSection() { const sectionsList = modalInstance.dialogContent.querySelector('#customSections_list'); if (!sectionsList) return; const sectionIndex = sectionsList.querySelectorAll('.customSection_section_item').length; const newSection = { id: `custom-section-${sectionIndex}`, enabled: true, name: 'New Custom Section', type: 'Collection', source: '', itemLimit: 16, sortOrder: 'Random', sortOrderDirection: 'Ascending', cardFormat: 'Poster', order: 100, spotlight: false, discoveryEnabled: false }; const sectionHtml = buildSectionUI('customSection', newSection, sectionIndex, false); sectionsList.insertAdjacentHTML('beforeend', sectionHtml); // Initialize the new section's source field const newSectionItem = sectionsList.querySelector(`.customSection_section_item[data-section-index="${sectionIndex}"]`); if (newSectionItem) { const typeSelect = newSectionItem.querySelector('.customSection_section_type'); if (typeSelect) { const type = typeSelect.value; if (type === 'Parent') { // Setup Parent type input sync const parentInput = newSectionItem.querySelector(`.customSection_section_source[data-section-index="${sectionIndex}"]`); const parentHidden = newSectionItem.querySelector(`.customSection_section_source_hidden[data-section-index="${sectionIndex}"]`); if (parentInput && parentHidden) { parentInput.addEventListener('input', () => { parentHidden.value = parentInput.value; }); } } else { await setupBadgeAutocomplete('customSection', sectionIndex, type); if (type === 'Collection' || type === 'Playlist') { await loadBadgeNames('customSection', sectionIndex, type); } } } // Setup summary update listeners for custom sections setupCustomSectionSummaryListeners(newSectionItem, sectionIndex); // Initialize Include Item Types autocomplete const includeItemTypesContainer = newSectionItem.querySelector(`.includeItemTypes-badge-container[data-section-index="${sectionIndex}"]`); if (includeItemTypesContainer) { const availableTypes = includeItemTypesContainer.getAttribute('data-available-types')?.split(',').filter(Boolean) || []; setupIncludeItemTypesDropdown('customSection', sectionIndex, availableTypes); } } }; // Setup event listeners to update section summary when name/order changes // Works for both custom sections and seasonal nested sections function setupCustomSectionSummaryListeners(sectionItem, sectionIndex) { const prefix = sectionItem.classList.contains('customSection_section_item') ? 'customSection' : 'seasonal_season'; const sanitizedIndex = sectionIndex.toString().replace(/[^a-zA-Z0-9]/g, '_'); // Find inputs based on prefix const nameInput = sectionItem.querySelector(`.${prefix}_section_name[data-section-index="${sectionIndex}"]`); const orderInput = sectionItem.querySelector(`#${prefix}_section_${sanitizedIndex}_order`); const enabledCheckbox = sectionItem.querySelector(`#${prefix}_section_enabled_${sanitizedIndex}`) || sectionItem.querySelector(`.${prefix}_section_enabled[data-section-index="${sectionIndex}"]`); // Find summary display spans based on prefix const nameClass = prefix === 'customSection' ? 'custom-section-name' : 'seasonal-section-name'; const orderClass = prefix === 'customSection' ? 'custom-section-order' : 'seasonal-section-order'; const enabledClass = prefix === 'customSection' ? 'custom-section-enabled-display' : 'seasonal-section-enabled-display'; const nameSpan = sectionItem.querySelector(`.${nameClass}[data-section-index="${sectionIndex}"]`); const orderSpan = sectionItem.querySelector(`.${orderClass}[data-section-index="${sectionIndex}"]`); const enabledSpan = sectionItem.querySelector(`.${enabledClass}[data-section-index="${sectionIndex}"]`); if (nameInput && nameSpan) { nameInput.addEventListener('input', () => { nameSpan.textContent = nameInput.value || 'Unnamed Section'; }); } if (orderInput && orderSpan) { orderInput.addEventListener('input', () => { orderSpan.textContent = orderInput.value || '100'; }); } if (enabledCheckbox && enabledSpan) { enabledCheckbox.addEventListener('change', () => { enabledSpan.textContent = enabledCheckbox.checked ? 'Enabled' : 'Disabled'; }); } } function deleteSection(prefix, sectionIndex, isSeasonalNested) { // Try both string and number comparison for data-section-index const sectionItem = modalInstance.dialogContent.querySelector( `.${prefix}_section_item[data-section-index="${sectionIndex}"], .${prefix}_section_item[data-section-index='${sectionIndex}']` ); if (sectionItem && confirm('Are you sure you want to delete this section?')) { sectionItem.remove(); // For seasonal sections, sectionIndex is compound (e.g., "0_1"), need special handling if (isSeasonalNested && typeof sectionIndex === 'string' && sectionIndex.includes('_')) { const [seasonIndex, deletedSectionIndex] = sectionIndex.split('_'); const sectionsList = modalInstance.dialogContent.querySelector(`.seasonal_season_sections_list[data-season-index="${seasonIndex}"]`); if (sectionsList) { // Re-index only sections within the same season const remainingItems = Array.from(sectionsList.querySelectorAll(`.${prefix}_section_item`)) .sort((a, b) => { const aIdx = a.getAttribute('data-section-index'); const bIdx = b.getAttribute('data-section-index'); if (!aIdx || !bIdx) return 0; // Extract section index part (after underscore) const aSectionIdx = aIdx.includes('_') ? parseInt(aIdx.split('_')[1]) : parseInt(aIdx); const bSectionIdx = bIdx.includes('_') ? parseInt(bIdx.split('_')[1]) : parseInt(bIdx); return aSectionIdx - bSectionIdx; }); remainingItems.forEach((item, newSectionIndex) => { const newFullIndex = `${seasonIndex}_${newSectionIndex}`; const oldIndex = item.getAttribute('data-section-index'); item.setAttribute('data-section-index', newFullIndex); // Update all inputs within this section item.querySelectorAll(`[data-section-index="${oldIndex}"]`).forEach(el => { el.setAttribute('data-section-index', newFullIndex); }); // Update summary displays const summaryName = item.querySelector(`.seasonal-section-name[data-section-index="${oldIndex}"]`); if (summaryName) { summaryName.setAttribute('data-section-index', newFullIndex); } const summaryEnabled = item.querySelector(`.seasonal-section-enabled-display[data-section-index="${oldIndex}"]`); if (summaryEnabled) { summaryEnabled.setAttribute('data-section-index', newFullIndex); } const summaryOrder = item.querySelector(`.seasonal-section-order[data-section-index="${oldIndex}"]`); if (summaryOrder) { summaryOrder.setAttribute('data-section-index', newFullIndex); } // Update delete and preview button data attributes const deleteBtn = item.querySelector('.delete-section-btn'); if (deleteBtn) { deleteBtn.setAttribute('data-section-index', newFullIndex); } const previewBtn = item.querySelector('.preview-section-btn'); if (previewBtn) { previewBtn.setAttribute('data-section-index', newFullIndex); } }); } } else { // Regular custom sections - simple re-indexing const remainingItems = Array.from(modalInstance.dialogContent.querySelectorAll(`.${prefix}_section_item`)) .sort((a, b) => { const aIndex = parseInt(a.getAttribute('data-section-index')) || 0; const bIndex = parseInt(b.getAttribute('data-section-index')) || 0; return aIndex - bIndex; }); remainingItems.forEach((item, newIndex) => { const oldIndex = item.getAttribute('data-section-index'); item.setAttribute('data-section-index', newIndex); // Update all inputs within this section item.querySelectorAll(`[data-section-index="${oldIndex}"]`).forEach(el => { el.setAttribute('data-section-index', newIndex); }); // Update summary displays that reference section index const summaryName = item.querySelector(`.custom-section-name[data-section-index="${oldIndex}"]`); if (summaryName) { summaryName.setAttribute('data-section-index', newIndex); } const summaryEnabled = item.querySelector(`.custom-section-enabled-display[data-section-index="${oldIndex}"]`); if (summaryEnabled) { summaryEnabled.setAttribute('data-section-index', newIndex); } const summaryOrder = item.querySelector(`.custom-section-order[data-section-index="${oldIndex}"]`); if (summaryOrder) { summaryOrder.setAttribute('data-section-index', newIndex); } // Update delete button data attribute const deleteBtn = item.querySelector('.delete-section-btn'); if (deleteBtn) { deleteBtn.setAttribute('data-section-index', newIndex); } const previewBtn = item.querySelector('.preview-section-btn'); if (previewBtn) { previewBtn.setAttribute('data-section-index', newIndex); } }); } } }; async function previewSection(prefix, sectionIndex) { if (!window.ModalSystem) { alert('Modal system not available. Please ensure modal.js is loaded.'); return; } const sectionConfig = getSectionConfigFromUI(modalInstance.dialogContent, prefix, sectionIndex); if (!sectionConfig) { alert('Unable to build preview for this section. Please check the configuration values.'); return; } const modalId = `sectionPreview_${prefix}_${sectionIndex}_${Date.now()}`; const contentId = `${modalId}_content`; const previewModal = window.ModalSystem.create({ id: modalId, title: `Preview: ${sectionConfig.name || 'Custom Section'}`, content: `
Preparing preview...
`, footer: ` `, closeOnBackdrop: true, closeOnEscape: true, size: 'large', onOpen: async (previewInstance) => { previewInstance.dialogContent.style.width = '1400px'; const closeBtn = previewInstance.dialogFooter?.querySelector(`#${modalId}_closeBtn`); if (closeBtn) { closeBtn.addEventListener('click', () => previewInstance.close()); } const container = previewInstance.dialogContent.querySelector(`#${contentId}`); if (!container) { return; } container.innerHTML = `
Loading preview...
`; try { const items = await fetchItemsForSectionPreview(sectionConfig); if (!items || items.length === 0) { container.innerHTML = `
No items match this configuration yet.
`; return; } if (!window.cardBuilder) { container.innerHTML = `
Card builder utilities are not available.
`; return; } let previewElement = null; if (sectionConfig.spotlight && typeof window.cardBuilder.renderSpotlightSection === 'function') { previewElement = window.cardBuilder.renderSpotlightSection(items, sectionConfig.name || 'Preview', { autoPlay: false, showDots: true, showNavButtons: true, viewMoreUrl: null }); } else if (typeof window.cardBuilder.renderCards === 'function') { previewElement = window.cardBuilder.renderCards( items, sectionConfig.name || 'Preview', null, true, sectionConfig.cardFormat || 'Poster', sectionConfig.sortOrder || 'Random', sectionConfig.sortOrderDirection || 'Ascending' ); } container.innerHTML = ''; if (previewElement) { container.appendChild(previewElement); } else { container.innerHTML = `
Unable to render preview with the current configuration.
`; } } catch (error) { console.error('[KefinTweaks Configuration] Error rendering preview:', error); container.innerHTML = `
Failed to load preview: ${error?.message || error}
`; } } }); previewModal.open(); } async function updateSectionSourceField(prefix, sectionIndex, isSeasonalNested) { const sectionItem = modalInstance.dialogContent.querySelector(`.${prefix}_section_item[data-section-index="${sectionIndex}"]`); if (!sectionItem) { console.warn(`[KefinTweaks Configuration] Section item not found for prefix: ${prefix}, index: ${sectionIndex}`); return; } const typeSelect = sectionItem.querySelector(`.${prefix}_section_type[data-section-index="${sectionIndex}"]`); if (!typeSelect) { console.warn(`[KefinTweaks Configuration] Type select not found for prefix: ${prefix}, index: ${sectionIndex}`); return; } const type = typeSelect.value || 'Genre'; // Find the source field container using the specific class const sourceContainer = sectionItem.querySelector(`.${prefix}_section_source_container[data-section-index="${sectionIndex}"]`); if (!sourceContainer) { console.warn(`[KefinTweaks Configuration] Source container not found for prefix: ${prefix}, index: ${sectionIndex}`); return; } // Get current source value const currentSourceInput = sectionItem.querySelector(`.${prefix}_section_source[data-section-index="${sectionIndex}"]`); const badgeContainer = sourceContainer?.querySelector(`.tag-badge-container[data-section-index="${sectionIndex}"][data-type]`) || null; let currentSource = ''; if (badgeContainer) { // Extract from existing badges const badges = badgeContainer.querySelectorAll('.tag-badge'); currentSource = Array.from(badges).map(badge => badge.getAttribute('data-value')).filter(Boolean).join(', '); } else if (currentSourceInput) { // Extract from dropdown/input currentSource = currentSourceInput.value || ''; } // Clear badges whenever the source type changes // This ensures a clean state when switching between any types const currentType = currentSourceInput?.dataset?.type || badgeContainer?.dataset?.type; if (currentType && currentType !== type) { currentSource = ''; } let newSourceHtml = ''; if (type === 'Parent') { // Parent type uses simple text input newSourceHtml = `
Parent IDs (comma-separated, leave empty for "Any")
`; } else { // Build new badge-based UI for other types const sourceArray = currentSource ? currentSource.split(',').map(s => s.trim()).filter(Boolean) : []; const badgesHtml = sourceArray.map(val => { if (type === 'Tag' || type === 'Genre') { return ` ${val} `; } else { return ` ${val} `; } }).join(''); newSourceHtml = `
${type}
${badgesHtml}
`; } sourceContainer.innerHTML = newSourceHtml; // Setup event listener for Parent type to sync input with hidden field if (type === 'Parent') { const parentInput = sourceContainer.querySelector(`.${prefix}_section_source[data-section-index="${sectionIndex}"]`); const parentHidden = sourceContainer.querySelector(`.${prefix}_section_source_hidden[data-section-index="${sectionIndex}"]`); if (parentInput && parentHidden) { parentInput.addEventListener('input', () => { parentHidden.value = parentInput.value; }); } } else { // Initialize autocomplete for other types await setupBadgeAutocomplete(prefix, sectionIndex, type); // Load names for Collections/Playlists if (type === 'Collection' || type === 'Playlist') { await loadBadgeNames(prefix, sectionIndex, type); } } // Update Include Item Types field to reflect available types based on source type const includeItemTypesContainer = sectionItem.querySelector(`.${prefix}_section_includeItemTypes_container[data-section-index="${sectionIndex}"]`); if (includeItemTypesContainer) { const currentBadges = includeItemTypesContainer.querySelectorAll('.tag-badge'); const currentTypes = Array.from(currentBadges).map(badge => badge.getAttribute('data-value')).filter(Boolean); const availableTypes = type === 'Parent' ? ['Movie', 'Series', 'Season', 'Episode', 'MusicArtist', 'MusicAlbum', 'Audio', 'MusicVideo', 'Book', 'BoxSet', 'Playlist'] : ['Movie', 'Series', 'Season', 'Episode', 'MusicArtist', 'MusicAlbum', 'Audio', 'MusicVideo', 'Book']; // Remove invalid types (types not available for current source type) const validTypes = currentTypes.filter(t => availableTypes.includes(t)); // Rebuild the Include Item Types field const sanitizedPrefix = `${prefix}_section_${sectionIndex.toString().replace(/[^a-zA-Z0-9]/g, '_')}`; const newIncludeItemTypesHtml = buildIncludeItemTypesField(prefix, sectionIndex, sanitizedPrefix, validTypes, type); includeItemTypesContainer.outerHTML = newIncludeItemTypesHtml; // Re-initialize autocomplete for Include Item Types const newContainer = sectionItem.querySelector(`.includeItemTypes-badge-container[data-section-index="${sectionIndex}"]`); if (newContainer) { setupIncludeItemTypesDropdown(prefix, sectionIndex, availableTypes); } } } // Generic badge management system const BadgeSystem = { /** * Creates a badge element * @param {string} value - The value to store (ID for collections/playlists, name for tags/genres) * @param {string} displayText - The text to display * @returns {HTMLElement} Badge element */ createBadge(value, displayText) { const badge = document.createElement('span'); badge.className = 'tag-badge'; badge.setAttribute('data-value', value); badge.style.cssText = 'display: inline-flex; align-items: center; gap: 0.25em; background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2); border-radius: 4px; padding: 0.25em 0.5em; margin: 0.25em; font-size: 0.9em;'; badge.innerHTML = `${displayText}`; return badge; }, /** * Adds a badge to the container */ addBadge(prefix, sectionIndex, value, displayText, badgeContainer, input, hiddenInput) { // Check if badge already exists const existingBadges = badgeContainer.querySelectorAll('.tag-badge'); const alreadyExists = Array.from(existingBadges).some(badge => badge.getAttribute('data-value') === value ); if (alreadyExists) return; // Find the badges wrapper div (sibling of the input in new layout, or container in old layout) const badgesWrapper = input.nextElementSibling && input.nextElementSibling.matches('div') ? input.nextElementSibling : badgeContainer; const badge = this.createBadge(value, displayText); badgesWrapper.appendChild(badge); input.value = ''; this.updateHiddenInput(prefix, sectionIndex, badgeContainer, hiddenInput); }, /** * Removes a badge from the container */ removeBadge(prefix, sectionIndex, badge, badgeContainer, hiddenInput) { badge.remove(); this.updateHiddenInput(prefix, sectionIndex, badgeContainer, hiddenInput); }, /** * Removes all badges from the container */ clearAll(prefix, sectionIndex, badgeContainer, hiddenInput) { const badges = badgeContainer.querySelectorAll('.tag-badge'); badges.forEach(badge => badge.remove()); this.updateHiddenInput(prefix, sectionIndex, badgeContainer, hiddenInput); }, /** * Updates hidden input from badges */ updateHiddenInput(prefix, sectionIndex, badgeContainer, hiddenInput) { const badges = badgeContainer.querySelectorAll('.tag-badge'); const values = Array.from(badges).map(badge => badge.getAttribute('data-value')).filter(Boolean); if (hiddenInput) { hiddenInput.value = values.join(', '); } }, /** * Gets existing badge values (for deduplication) */ getExistingBadges(badgeContainer) { const badges = badgeContainer.querySelectorAll('.tag-badge'); return Array.from(badges).map(badge => badge.getAttribute('data-value').toLowerCase()); } }; // Generic autocomplete setup for badge-based inputs // Supports: Tag, Genre, Collection, Playlist async function setupBadgeAutocomplete(prefix, sectionIndex, type) { const badgeContainer = modalInstance.dialogContent.querySelector( `.tag-badge-container[data-section-index="${sectionIndex}"][data-type="${type}"]` ); const input = modalInstance.dialogContent.querySelector( `.${prefix}_section_source.autocomplete-input[data-section-index="${sectionIndex}"]` ); const suggestionsDiv = modalInstance.dialogContent.querySelector( `.autocomplete-suggestions[data-section-index="${sectionIndex}"]` ); const hiddenInput = modalInstance.dialogContent.querySelector( `.${prefix}_section_source_hidden[data-section-index="${sectionIndex}"]` ); const clearAllBtn = modalInstance.dialogContent.querySelector( `.badge-clear-all[data-section-index="${sectionIndex}"]` ); if (!badgeContainer || !input || !suggestionsDiv) return; // Setup badge remove handlers badgeContainer.addEventListener('click', (e) => { if (e.target.classList.contains('tag-badge-remove') || e.target.closest('.tag-badge-remove')) { const badge = e.target.closest('.tag-badge'); if (badge) { BadgeSystem.removeBadge(prefix, sectionIndex, badge, badgeContainer, hiddenInput); } } }); // Setup clear all button if (clearAllBtn) { clearAllBtn.addEventListener('click', () => { BadgeSystem.clearAll(prefix, sectionIndex, badgeContainer, hiddenInput); }); } // Fetch available options based on type let options = []; try { const userId = window.ApiClient.getCurrentUserId(); const serverAddress = window.ApiClient.serverAddress(); if (type === 'Tag' || type === 'Genre') { const url = `${serverAddress}/Items/Filters?UserId=${userId}&IncludeItemTypes=Movie`; const data = await window.apiHelper.getData(url, true); options = type === 'Tag' ? (data.Tags || []) : (data.Genres || []); } else if (type === 'Collection' || type === 'Playlist') { // Fetch Collections/Playlists using getItems with caching const itemType = type === 'Playlist' ? 'Playlist' : 'BoxSet,CollectionFolder'; const data = await window.apiHelper.getItems( { IncludeItemTypes: itemType, Recursive: true, Fields: 'ItemCounts' }, true, 300000 ); options = (data.Items || []).map(item => ({ id: item.Id, name: item.Name })); } } catch (err) { console.error('[KefinTweaks Configuration] Error fetching options:', err); } let currentSuggestions = []; let selectedIndex = -1; const getExistingBadges = () => BadgeSystem.getExistingBadges(badgeContainer); input.addEventListener('input', (e) => { const value = e.target.value.trim(); if (value.length === 0) { suggestionsDiv.style.display = 'none'; return; } const existing = getExistingBadges(); // Filter options based on type if (type === 'Tag' || type === 'Genre') { currentSuggestions = options.filter(opt => opt.toLowerCase().includes(value.toLowerCase()) && !existing.includes(opt.toLowerCase()) ).slice(0, 10); } else { // Collections/Playlists: search by name, exclude by ID currentSuggestions = options.filter(opt => opt.name.toLowerCase().includes(value.toLowerCase()) && !existing.includes(opt.id.toLowerCase()) ).slice(0, 10); } if (currentSuggestions.length > 0) { suggestionsDiv.innerHTML = currentSuggestions.map((opt, idx) => { const display = type === 'Tag' || type === 'Genre' ? opt : opt.name; const dataValue = type === 'Tag' || type === 'Genre' ? opt : opt.id; return `
${display}
`; }).join(''); suggestionsDiv.style.display = 'block'; selectedIndex = -1; // Set up mouse event handlers for each suggestion const suggestionItems = suggestionsDiv.querySelectorAll('.autocomplete-suggestion'); suggestionItems.forEach((item, idx) => { item.addEventListener('mouseenter', () => { // Clear keyboard selection selectedIndex = -1; updateSuggestionHighlight(); // Highlight hovered item item.style.background = 'rgba(255,255,255,0.1)'; }); item.addEventListener('mouseleave', () => { item.style.background = ''; }); }); } else { suggestionsDiv.style.display = 'none'; } }); // Handle suggestion clicks suggestionsDiv.addEventListener('click', (e) => { const suggestion = e.target.closest('.autocomplete-suggestion'); if (!suggestion) return; const selectedValue = suggestion.getAttribute('data-value'); const displayText = suggestion.getAttribute('data-display') || selectedValue; BadgeSystem.addBadge(prefix, sectionIndex, selectedValue, displayText, badgeContainer, input, hiddenInput); suggestionsDiv.style.display = 'none'; selectedIndex = -1; input.focus(); }); // Function to show all available suggestions (excluding already selected) function showAllSuggestions() { const existing = getExistingBadges(); // Filter options based on type, excluding already selected if (type === 'Tag' || type === 'Genre') { currentSuggestions = options.filter(opt => !existing.includes(opt.toLowerCase()) ).slice(0, 30); } else { // Collections/Playlists: exclude by ID currentSuggestions = options.filter(opt => !existing.includes(opt.id.toLowerCase()) ).slice(0, 30); } if (currentSuggestions.length > 0) { suggestionsDiv.innerHTML = currentSuggestions.map((opt, idx) => { const display = type === 'Tag' || type === 'Genre' ? opt : opt.name; const dataValue = type === 'Tag' || type === 'Genre' ? opt : opt.id; return `
${display}
`; }).join(''); suggestionsDiv.style.display = 'block'; selectedIndex = 0; updateSuggestionHighlight(); // Set up mouse event handlers for each suggestion const suggestionItems = suggestionsDiv.querySelectorAll('.autocomplete-suggestion'); suggestionItems.forEach((item, idx) => { item.addEventListener('mouseenter', () => { // Clear keyboard selection selectedIndex = -1; updateSuggestionHighlight(); // Highlight hovered item item.style.background = 'rgba(255,255,255,0.1)'; }); item.addEventListener('mouseleave', () => { item.style.background = ''; }); }); } else { suggestionsDiv.style.display = 'none'; } } // Handle keyboard navigation input.addEventListener('keydown', (e) => { if (e.key === 'ArrowDown') { e.preventDefault(); // If input is empty and no suggestions shown, show all suggestions if (input.value.trim().length === 0 && suggestionsDiv.style.display === 'none') { showAllSuggestions(); return; } // If suggestions are shown, navigate if (currentSuggestions.length > 0) { selectedIndex = Math.min(selectedIndex + 1, currentSuggestions.length - 1); updateSuggestionHighlight(); } } else if (e.key === 'ArrowUp') { e.preventDefault(); if (currentSuggestions.length > 0) { selectedIndex = Math.max(selectedIndex - 1, -1); updateSuggestionHighlight(); // If we go above the first item, hide suggestions if (selectedIndex < 0) { suggestionsDiv.style.display = 'none'; } } } else if (e.key === 'Enter') { e.preventDefault(); if (selectedIndex >= 0 && currentSuggestions[selectedIndex]) { const selected = currentSuggestions[selectedIndex]; const value = type === 'Tag' || type === 'Genre' ? selected : selected.id; const display = type === 'Tag' || type === 'Genre' ? selected : selected.name; BadgeSystem.addBadge(prefix, sectionIndex, value, display, badgeContainer, input, hiddenInput); suggestionsDiv.style.display = 'none'; selectedIndex = -1; } // No free-form entry - require autocomplete selection } else if (e.key === 'Escape') { suggestionsDiv.style.display = 'none'; selectedIndex = -1; } else if (e.key === 'Backspace' && input.value === '') { const badges = badgeContainer.querySelectorAll('.tag-badge'); if (badges.length > 0) { const lastBadge = badges[badges.length - 1]; BadgeSystem.removeBadge(prefix, sectionIndex, lastBadge, badgeContainer, hiddenInput); } } }); function updateSuggestionHighlight() { const items = suggestionsDiv.querySelectorAll('.autocomplete-suggestion'); items.forEach((item, idx) => { if (idx === selectedIndex) { item.style.background = 'rgba(0, 122, 255, 0.3)'; item.style.borderLeft = '3px solid rgba(0, 122, 255, 0.8)'; item.style.fontWeight = '500'; // Scroll into view if needed item.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); } else { item.style.background = ''; item.style.borderLeft = '3px solid transparent'; item.style.fontWeight = ''; } }); } // Hide suggestions when clicking outside document.addEventListener('click', (e) => { if (!badgeContainer.contains(e.target) && !suggestionsDiv.contains(e.target)) { suggestionsDiv.style.display = 'none'; } }); } // Loads and updates badge display text for Collections/Playlists // Replaces IDs with names after fetching from API async function loadBadgeNames(prefix, sectionIndex, type) { if (type !== 'Collection' && type !== 'Playlist') return; const badgeContainer = modalInstance.dialogContent.querySelector( `.tag-badge-container[data-section-index="${sectionIndex}"][data-type="${type}"]` ); if (!badgeContainer) return; const badges = badgeContainer.querySelectorAll('.tag-badge[data-loading="true"]'); if (badges.length === 0) return; try { const itemType = type === 'Playlist' ? 'Playlist' : 'BoxSet,CollectionFolder'; const data = await window.apiHelper.getItems( { IncludeItemTypes: itemType, Recursive: true, Fields: 'ItemCounts' }, true, 300000 ); const items = data.Items || []; const itemMap = new Map(items.map(item => [item.Id, item])); badges.forEach(badge => { const id = badge.getAttribute('data-value'); const item = itemMap.get(id); if (item) { const displayText = item.Name; badge.innerHTML = `${displayText}`; badge.removeAttribute('data-loading'); } else { // Item not found, keep ID display badge.removeAttribute('data-loading'); } }); } catch (err) { console.error('[KefinTweaks Configuration] Error loading badge names:', err); badges.forEach(badge => badge.removeAttribute('data-loading')); } } // Setup dropdown for Include Item Types field function setupIncludeItemTypesDropdown(prefix, sectionIndex, availableTypes) { const badgeContainer = modalInstance.dialogContent.querySelector( `.includeItemTypes-badge-container[data-section-index="${sectionIndex}"]` ); const toggleButton = badgeContainer?.querySelector('.includeItemTypes-dropdown-toggle'); const dropdown = badgeContainer?.querySelector('.includeItemTypes-dropdown'); const checkboxNodes = badgeContainer ? Array.from(badgeContainer.querySelectorAll('.includeItemTypes-option')) : []; const proxyInput = modalInstance.dialogContent.querySelector( `.${prefix}_section_includeItemTypes[data-section-index="${sectionIndex}"]` ); const hiddenInput = modalInstance.dialogContent.querySelector( `.${prefix}_section_includeItemTypes_hidden[data-section-index="${sectionIndex}"]` ); const badgesWrapper = badgeContainer?.querySelector('.includeItemTypes-badges'); const emptyState = badgeContainer?.querySelector('.includeItemTypes-empty'); const clearAllBtn = modalInstance.dialogContent.querySelector( `.badge-clear-all[data-section-index="${sectionIndex}"][data-field="includeItemTypes"]` ); const allowedTypeSet = new Set((availableTypes || []).map(type => type.toLowerCase())); if (!badgeContainer || !dropdown || !proxyInput || !hiddenInput || !badgesWrapper) return; const closeDropdown = () => { dropdown.style.display = 'none'; toggleButton?.setAttribute('aria-expanded', 'false'); }; const openDropdown = () => { dropdown.style.display = 'block'; toggleButton?.setAttribute('aria-expanded', 'true'); }; toggleButton?.addEventListener('click', (e) => { e.stopPropagation(); const isOpen = dropdown.style.display === 'block'; if (isOpen) { closeDropdown(); } else { openDropdown(); } }); document.addEventListener('click', (e) => { if (!badgeContainer.contains(e.target)) { closeDropdown(); } }); const updateEmptyState = () => { const hasBadges = badgesWrapper.querySelector('.tag-badge'); if (hasBadges) { emptyState?.setAttribute('hidden', 'true'); } else { emptyState?.removeAttribute('hidden'); } }; // Setup badge remove handlers badgeContainer.addEventListener('click', (e) => { if (e.target.classList.contains('tag-badge-remove') || e.target.closest('.tag-badge-remove')) { const badge = e.target.closest('.tag-badge'); if (badge) { const value = badge.getAttribute('data-value'); const checkbox = checkboxNodes.find(cb => cb.value === value); if (checkbox) { checkbox.checked = false; } BadgeSystem.removeBadge(prefix, sectionIndex, badge, badgeContainer, hiddenInput); updateEmptyState(); syncToggleLabel(); } } }); const syncToggleLabel = () => { const count = badgesWrapper.querySelectorAll('.tag-badge').length; if (toggleButton) { const textSpan = toggleButton.querySelector('.includeItemTypes-toggle-label'); if (textSpan) { textSpan.textContent = count > 0 ? `${count} selected` : 'Select item types'; } } }; const handleCheckboxChange = (checkbox) => { const value = checkbox.value; if (!value || (allowedTypeSet.size && !allowedTypeSet.has(value.toLowerCase()))) return; if (checkbox.checked) { BadgeSystem.addBadge(prefix, sectionIndex, value, value, badgeContainer, proxyInput, hiddenInput); } else { const badge = badgesWrapper.querySelector(`.tag-badge[data-value="${value}"]`); if (badge) { BadgeSystem.removeBadge(prefix, sectionIndex, badge, badgeContainer, hiddenInput); } else { BadgeSystem.updateHiddenInput(prefix, sectionIndex, badgeContainer, hiddenInput); } } updateEmptyState(); syncToggleLabel(); }; checkboxNodes.forEach(checkbox => { checkbox.addEventListener('change', () => handleCheckboxChange(checkbox)); }); // Setup clear all button if (clearAllBtn) { clearAllBtn.addEventListener('click', () => { checkboxNodes.forEach(cb => { cb.checked = false; }); BadgeSystem.clearAll(prefix, sectionIndex, badgeContainer, hiddenInput); updateEmptyState(); syncToggleLabel(); }); } // Ensure badges match checked state on init checkboxNodes.forEach(cb => { if (cb.checked && !badgesWrapper.querySelector(`.tag-badge[data-value="${cb.value}"]`)) { BadgeSystem.addBadge(prefix, sectionIndex, cb.value, cb.value, badgeContainer, proxyInput, hiddenInput); } }); updateEmptyState(); syncToggleLabel(); } // Seasonal season management functions (exposed globally for onclick handlers) window.addNewSeasonalSeason = function() { const seasonsList = modalInstance.dialogContent.querySelector('#homeScreen_seasonal_seasons_list'); if (!seasonsList) return; const newIndex = seasonsList.querySelectorAll('.seasonal-season-item').length; const newSeason = { id: `season-${newIndex}`, enabled: true, name: 'New Season', startDate: '', endDate: '', order: 100, sections: [] }; const newSeasonHtml = `
chevron_right New Season (Enabled, Order: 100)
Enabled
${buildJellyfinCheckbox(`seasonal-season-enabled-${newIndex}`, true, 'Enabled', { 'data-index': newIndex, 'class': 'seasonal-season-enabled' })}
Name
Start Date (MM-DD)
End Date (MM-DD)
Order
Sections
`; seasonsList.insertAdjacentHTML('beforeend', newSeasonHtml); // Setup listeners for the new season const newSeasonItem = seasonsList.querySelector(`.seasonal-season-item[data-season-index="${newIndex}"]`); if (newSeasonItem) { const nameInput = newSeasonItem.querySelector(`.seasonal-season-name[data-index="${newIndex}"]`); const nameSpan = newSeasonItem.querySelector(`.seasonal-season-name-display[data-season-index="${newIndex}"]`); const orderInput = newSeasonItem.querySelector(`.seasonal-season-order-input[data-index="${newIndex}"]`); const orderSpan = newSeasonItem.querySelector(`.seasonal-season-order[data-season-index="${newIndex}"]`); const enabledCheckbox = newSeasonItem.querySelector(`#seasonal-season-enabled-${newIndex}`) || newSeasonItem.querySelector(`.seasonal-season-enabled[data-index="${newIndex}"]`); const enabledSpan = newSeasonItem.querySelector(`.seasonal-season-enabled-display[data-season-index="${newIndex}"]`); if (nameInput && nameSpan) { nameInput.addEventListener('input', () => { nameSpan.textContent = nameInput.value || 'Unnamed Season'; }); } if (orderInput && orderSpan) { orderInput.addEventListener('input', () => { orderSpan.textContent = orderInput.value || '100'; }); } if (enabledCheckbox && enabledSpan) { enabledCheckbox.addEventListener('change', () => { enabledSpan.textContent = enabledCheckbox.checked ? 'Enabled' : 'Disabled'; }); } } }; // Collection and Playlist picker functions window.openCollectionPicker = async function(seasonIndex) { if (!window.ModalSystem) { alert('Modal system not available'); return; } try { // Fetch collections from server const userId = window.ApiClient.getCurrentUserId(); const serverAddress = window.ApiClient.serverAddress(); const token = window.ApiClient.accessToken(); const response = await fetch(`${serverAddress}/Users/${userId}/Items?IncludeItemTypes=BoxSet,CollectionFolder&Recursive=true&Fields=ItemCounts`, { headers: { 'X-Emby-Token': token } }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const data = await response.json(); const collections = data.Items || []; // Get currently selected collections const hiddenInput = modalInstance.dialogContent.querySelector(`.seasonal-season-collections[data-index="${seasonIndex}"]`); const selectedIds = hiddenInput ? JSON.parse(hiddenInput.value || '[]') : []; // Create picker modal let pickerModalInstanceRef = null; const pickerModal = window.ModalSystem.create({ id: 'collectionPickerModal', title: 'Select Collections', content: `
${collections.map(collection => { const isSelected = selectedIds.includes(collection.Id); return ` `; }).join('')}
`, footer: ` `, closeOnBackdrop: true, closeOnEscape: true, onOpen: (pickerModalInstance) => { pickerModalInstanceRef = pickerModalInstance; // Set up search filter const searchInput = pickerModalInstance.dialogContent.querySelector('#collectionPickerSearch'); if (searchInput) { searchInput.addEventListener('input', (e) => { const list = pickerModalInstance.dialogContent.querySelector('#collectionPickerList'); const items = list.querySelectorAll('label'); const term = e.target.value.toLowerCase(); items.forEach(item => { const name = item.querySelector('span').textContent.toLowerCase(); item.style.display = name.includes(term) ? '' : 'none'; }); }); } const confirmBtn = pickerModalInstance.dialogFooter?.querySelector('#collectionPickerConfirm'); const cancelBtn = pickerModalInstance.dialogFooter?.querySelector('#collectionPickerCancel'); if (confirmBtn) { confirmBtn.addEventListener('click', () => { const checkboxes = pickerModalInstance.dialogContent.querySelectorAll('#collectionPickerList input[type="checkbox"]:checked'); const selectedIds = Array.from(checkboxes).map(cb => cb.value); // Update hidden input if (hiddenInput) { hiddenInput.value = JSON.stringify(selectedIds); // Update button text and selected count const button = modalInstance.dialogContent.querySelector(`button[onclick="openCollectionPicker(${seasonIndex})"]`); const selectedDiv = modalInstance.dialogContent.querySelector(`.seasonal-season-collections-selected[data-index="${seasonIndex}"]`); if (button) { button.querySelector('span').textContent = `Select Collections (${selectedIds.length})`; } if (selectedDiv) { selectedDiv.textContent = selectedIds.length > 0 ? `Selected: ${selectedIds.length} collection(s)` : 'No collections selected'; } } pickerModalInstance.close(); }); } if (cancelBtn) { cancelBtn.addEventListener('click', () => { pickerModalInstance.close(); }); } } }); } catch (error) { console.error('[KefinTweaks Configuration] Error opening collection picker:', error); alert('Error loading collections. Please try again.'); } }; window.openPlaylistPicker = async function(seasonIndex) { if (!window.ModalSystem) { alert('Modal system not available'); return; } try { // Fetch playlists from server const userId = window.ApiClient.getCurrentUserId(); const serverAddress = window.ApiClient.serverAddress(); const token = window.ApiClient.accessToken(); const response = await fetch(`${serverAddress}/Users/${userId}/Items?IncludeItemTypes=Playlist&Recursive=true&Fields=ItemCounts`, { headers: { 'X-Emby-Token': token } }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const data = await response.json(); const playlists = data.Items || []; // Get currently selected playlists const hiddenInput = modalInstance.dialogContent.querySelector(`.seasonal-season-playlists[data-index="${seasonIndex}"]`); const selectedIds = hiddenInput ? JSON.parse(hiddenInput.value || '[]') : []; // Create picker modal let pickerModalInstanceRef = null; const pickerModal = window.ModalSystem.create({ id: 'playlistPickerModal', title: 'Select Playlists', content: `
${playlists.map(playlist => { const isSelected = selectedIds.includes(playlist.Id); return ` `; }).join('')}
`, footer: ` `, closeOnBackdrop: true, closeOnEscape: true, onOpen: (pickerModalInstance) => { pickerModalInstanceRef = pickerModalInstance; // Set up search filter const searchInput = pickerModalInstance.dialogContent.querySelector('#playlistPickerSearch'); if (searchInput) { searchInput.addEventListener('input', (e) => { const list = pickerModalInstance.dialogContent.querySelector('#playlistPickerList'); const items = list.querySelectorAll('label'); const term = e.target.value.toLowerCase(); items.forEach(item => { const name = item.querySelector('span').textContent.toLowerCase(); item.style.display = name.includes(term) ? '' : 'none'; }); }); } const confirmBtn = pickerModalInstance.dialogFooter?.querySelector('#playlistPickerConfirm'); const cancelBtn = pickerModalInstance.dialogFooter?.querySelector('#playlistPickerCancel'); if (confirmBtn) { confirmBtn.addEventListener('click', () => { const checkboxes = pickerModalInstance.dialogContent.querySelectorAll('#playlistPickerList input[type="checkbox"]:checked'); const selectedIds = Array.from(checkboxes).map(cb => cb.value); // Update hidden input if (hiddenInput) { hiddenInput.value = JSON.stringify(selectedIds); // Update button text and selected count const button = modalInstance.dialogContent.querySelector(`button[onclick="openPlaylistPicker(${seasonIndex})"]`); const selectedDiv = modalInstance.dialogContent.querySelector(`.seasonal-season-playlists-selected[data-index="${seasonIndex}"]`); if (button) { button.querySelector('span').textContent = `Select Playlists (${selectedIds.length})`; } if (selectedDiv) { selectedDiv.textContent = selectedIds.length > 0 ? `Selected: ${selectedIds.length} playlist(s)` : 'No playlists selected'; } } pickerModalInstance.close(); }); } if (cancelBtn) { cancelBtn.addEventListener('click', () => { pickerModalInstance.close(); }); } } }); } catch (error) { console.error('[KefinTweaks Configuration] Error opening playlist picker:', error); alert('Error loading playlists. Please try again.'); } }; // Picker functions for sections (used in nested sections) async function openCollectionPickerForSection(prefix, sectionIndex, isSeasonalNested) { if (!window.ModalSystem) { alert('Modal system not available'); return; } try { const userId = window.ApiClient.getCurrentUserId(); const serverAddress = window.ApiClient.serverAddress(); const token = window.ApiClient.accessToken(); const response = await fetch(`${serverAddress}/Users/${userId}/Items?IncludeItemTypes=BoxSet,CollectionFolder&Recursive=true&Fields=ItemCounts`, { headers: { 'X-Emby-Token': token } }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const data = await response.json(); const collections = data.Items || []; const sectionItem = modalInstance.dialogContent.querySelector(`.${prefix}_section_item[data-section-index="${sectionIndex}"]`); const sourceInput = sectionItem?.querySelector(`.${prefix}_section_source[data-section-index="${sectionIndex}"]`); const currentSource = sourceInput ? sourceInput.value : ''; const selectedId = currentSource || null; const pickerModal = window.ModalSystem.create({ id: 'collectionPickerForSectionModal', title: 'Select Collection', content: `
${collections.map(collection => { const isSelected = collection.Id === selectedId; return ` `; }).join('')}
`, footer: ` `, closeOnBackdrop: true, closeOnEscape: true, onOpen: (pickerModalInstance) => { const searchInput = pickerModalInstance.dialogContent.querySelector('#collectionPickerForSectionSearch'); if (searchInput) { searchInput.addEventListener('input', (e) => { const list = pickerModalInstance.dialogContent.querySelector('#collectionPickerForSectionList'); const items = list.querySelectorAll('label'); const term = e.target.value.toLowerCase(); items.forEach(item => { const name = item.querySelector('span').textContent.toLowerCase(); item.style.display = name.includes(term) ? '' : 'none'; }); }); } const confirmBtn = pickerModalInstance.dialogFooter?.querySelector('#collectionPickerForSectionConfirm'); const clearBtn = pickerModalInstance.dialogFooter?.querySelector('#collectionPickerForSectionClear'); const cancelBtn = pickerModalInstance.dialogFooter?.querySelector('#collectionPickerForSectionCancel'); if (confirmBtn) { confirmBtn.addEventListener('click', () => { const selected = pickerModalInstance.dialogContent.querySelector('#collectionPickerForSectionList input[type="radio"]:checked'); const selectedId = selected ? selected.value : ''; if (sourceInput) { sourceInput.value = selectedId; const button = sectionItem?.querySelector(`button[onclick*="openCollectionPickerForSection"]`); const selectedDiv = sectionItem?.querySelector(`.${prefix}_section_collection_selected[data-section-index="${sectionIndex}"]`); if (button) { button.querySelector('span').textContent = `Select Collection ${selectedId ? '(1)' : ''}`; } if (selectedDiv) { selectedDiv.textContent = selectedId ? `Selected: 1 collection` : 'No collection selected'; } } pickerModalInstance.close(); }); } if (clearBtn) { clearBtn.addEventListener('click', () => { const radios = pickerModalInstance.dialogContent.querySelectorAll('#collectionPickerForSectionList input[type="radio"]'); radios.forEach(radio => radio.checked = false); if (sourceInput) { sourceInput.value = ''; const button = sectionItem?.querySelector(`button[onclick*="openCollectionPickerForSection"]`); const selectedDiv = sectionItem?.querySelector(`.${prefix}_section_collection_selected[data-section-index="${sectionIndex}"]`); if (button) { button.querySelector('span').textContent = 'Select Collection'; } if (selectedDiv) { selectedDiv.textContent = 'No collection selected'; } } pickerModalInstance.close(); }); } if (cancelBtn) { cancelBtn.addEventListener('click', () => { pickerModalInstance.close(); }); } } }); } catch (error) { console.error('[KefinTweaks Configuration] Error opening collection picker for section:', error); alert('Error loading collections. Please try again.'); } }; async function openPlaylistPickerForSection(prefix, sectionIndex, isSeasonalNested) { if (!window.ModalSystem) { alert('Modal system not available'); return; } try { const userId = window.ApiClient.getCurrentUserId(); const serverAddress = window.ApiClient.serverAddress(); const token = window.ApiClient.accessToken(); const response = await fetch(`${serverAddress}/Users/${userId}/Items?IncludeItemTypes=Playlist&Recursive=true&Fields=ItemCounts`, { headers: { 'X-Emby-Token': token } }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const data = await response.json(); const playlists = data.Items || []; const sectionItem = modalInstance.dialogContent.querySelector(`.${prefix}_section_item[data-section-index="${sectionIndex}"]`); const sourceInput = sectionItem?.querySelector(`.${prefix}_section_source[data-section-index="${sectionIndex}"]`); const currentSource = sourceInput ? sourceInput.value : ''; const selectedId = currentSource || null; const pickerModal = window.ModalSystem.create({ id: 'playlistPickerForSectionModal', title: 'Select Playlist', content: `
${playlists.map(playlist => { const isSelected = playlist.Id === selectedId; return ` `; }).join('')}
`, footer: ` `, closeOnBackdrop: true, closeOnEscape: true, onOpen: (pickerModalInstance) => { const searchInput = pickerModalInstance.dialogContent.querySelector('#playlistPickerForSectionSearch'); if (searchInput) { searchInput.addEventListener('input', (e) => { const list = pickerModalInstance.dialogContent.querySelector('#playlistPickerForSectionList'); const items = list.querySelectorAll('label'); const term = e.target.value.toLowerCase(); items.forEach(item => { const name = item.querySelector('span').textContent.toLowerCase(); item.style.display = name.includes(term) ? '' : 'none'; }); }); } const confirmBtn = pickerModalInstance.dialogFooter?.querySelector('#playlistPickerForSectionConfirm'); const clearBtn = pickerModalInstance.dialogFooter?.querySelector('#playlistPickerForSectionClear'); const cancelBtn = pickerModalInstance.dialogFooter?.querySelector('#playlistPickerForSectionCancel'); if (confirmBtn) { confirmBtn.addEventListener('click', () => { const selected = pickerModalInstance.dialogContent.querySelector('#playlistPickerForSectionList input[type="radio"]:checked'); const selectedId = selected ? selected.value : ''; if (sourceInput) { sourceInput.value = selectedId; const button = sectionItem?.querySelector(`button[onclick*="openPlaylistPickerForSection"]`); const selectedDiv = sectionItem?.querySelector(`.${prefix}_section_playlist_selected[data-section-index="${sectionIndex}"]`); if (button) { button.querySelector('span').textContent = `Select Playlist ${selectedId ? '(1)' : ''}`; } if (selectedDiv) { selectedDiv.textContent = selectedId ? `Selected: 1 playlist` : 'No playlist selected'; } } pickerModalInstance.close(); }); } if (clearBtn) { clearBtn.addEventListener('click', () => { const radios = pickerModalInstance.dialogContent.querySelectorAll('#playlistPickerForSectionList input[type="radio"]'); radios.forEach(radio => radio.checked = false); if (sourceInput) { sourceInput.value = ''; const button = sectionItem?.querySelector(`button[onclick*="openPlaylistPickerForSection"]`); const selectedDiv = sectionItem?.querySelector(`.${prefix}_section_playlist_selected[data-section-index="${sectionIndex}"]`); if (button) { button.querySelector('span').textContent = 'Select Playlist'; } if (selectedDiv) { selectedDiv.textContent = 'No playlist selected'; } } pickerModalInstance.close(); }); } if (cancelBtn) { cancelBtn.addEventListener('click', () => { pickerModalInstance.close(); }); } } }); } catch (error) { console.error('[KefinTweaks Configuration] Error opening playlist picker for section:', error); alert('Error loading playlists. Please try again.'); } }; window.editSeasonalSeason = function(index) { // For now, editing is done inline - this could open a modal in the future console.log('Edit seasonal season', index); }; window.deleteSeasonalSeason = function(index) { const seasonsList = modalInstance.dialogContent.querySelector('#homeScreen_seasonal_seasons_list'); if (!seasonsList) return; const seasonItem = seasonsList.querySelector(`.seasonal-season-item[data-season-index="${index}"]`); if (seasonItem && confirm('Are you sure you want to delete this season?')) { seasonItem.remove(); // Re-index remaining items const remainingItems = seasonsList.querySelectorAll('.seasonal-season-item'); remainingItems.forEach((item, newIndex) => { item.setAttribute('data-season-index', newIndex); item.querySelectorAll('[data-index]').forEach(el => { el.setAttribute('data-index', newIndex); }); const editBtn = item.querySelector('button[onclick*="editSeasonalSeason"]'); const deleteBtn = item.querySelector('button[onclick*="deleteSeasonalSeason"]'); if (editBtn) editBtn.setAttribute('onclick', `editSeasonalSeason(${newIndex})`); if (deleteBtn) deleteBtn.setAttribute('onclick', `deleteSeasonalSeason(${newIndex})`); }); } }; // Toggle visibility of configuration sections based on script enable state const scriptCheckboxes = { search: modalInstance.dialogContent.querySelector('#script_search'), exclusiveElsewhere: modalInstance.dialogContent.querySelector('#script_exclusiveElsewhere'), skinManager: modalInstance.dialogContent.querySelector('#script_skinManager'), customMenuLinks: modalInstance.dialogContent.querySelector('#script_customMenuLinks') }; const configSections = { search: modalInstance.dialogContent.querySelector('#configSection_search'), exclusiveElsewhere: modalInstance.dialogContent.querySelector('#configSection_exclusiveElsewhere'), skin: modalInstance.dialogContent.querySelector('#configSection_skin'), theme: modalInstance.dialogContent.querySelector('#configSection_theme'), customMenuLinks: modalInstance.dialogContent.querySelector('#configSection_customMenuLinks') }; // Function to toggle section visibility const toggleSectionVisibility = (scriptKey, sectionKey) => { const checkbox = scriptCheckboxes[scriptKey]; const section = configSections[sectionKey]; if (checkbox && section) { const isEnabled = checkbox.checked; section.style.display = isEnabled ? '' : 'none'; } }; // Set up event listeners for each script checkbox if (scriptCheckboxes.search) { scriptCheckboxes.search.addEventListener('change', () => toggleSectionVisibility('search', 'search')); } if (scriptCheckboxes.exclusiveElsewhere) { scriptCheckboxes.exclusiveElsewhere.addEventListener('change', () => toggleSectionVisibility('exclusiveElsewhere', 'exclusiveElsewhere')); } if (scriptCheckboxes.skinManager) { scriptCheckboxes.skinManager.addEventListener('change', () => { toggleSectionVisibility('skinManager', 'skin'); toggleSectionVisibility('skinManager', 'theme'); }); } if (scriptCheckboxes.customMenuLinks) { scriptCheckboxes.customMenuLinks.addEventListener('change', () => toggleSectionVisibility('customMenuLinks', 'customMenuLinks')); } // Save button handler const saveBtn = modalInstance.dialogFooter?.querySelector('#saveConfigBtn'); if (saveBtn) { saveBtn.addEventListener('click', () => handleSaveConfig(modalInstance)); } const resetBtn = modalInstance.dialogFooter?.querySelector('#resetConfigBtn'); if (resetBtn) { resetBtn.addEventListener('click', () => handleResetConfig(modalInstance)); } // Export button handler const exportBtn = modalInstance.dialogFooter?.querySelector('#exportConfigBtn'); if (exportBtn) { exportBtn.addEventListener('click', () => handleExportConfig(config)); } // Import button handler const importBtn = modalInstance.dialogFooter?.querySelector('#importConfigBtn'); if (importBtn) { importBtn.addEventListener('click', () => handleImportConfig(modalInstance)); } } // Export configuration to clipboard async function handleExportConfig(config) { try { const configJson = JSON.stringify(config, null, 2); await navigator.clipboard.writeText(configJson); if (window.KefinTweaksToaster && window.KefinTweaksToaster.toast) { window.KefinTweaksToaster.toast('Configuration exported to clipboard!'); } else { alert('Configuration exported to clipboard!'); } } catch (error) { console.error('[KefinTweaks Configuration] Error exporting config:', error); if (window.KefinTweaksToaster && window.KefinTweaksToaster.toast) { window.KefinTweaksToaster.toast('Error exporting configuration to clipboard', '5'); } else { alert('Error exporting configuration to clipboard'); } } } // Import configuration from clipboard async function handleImportConfig(modalInstance) { if (!window.ModalSystem) { alert('Modal system not available'); return; } // Show import modal with textarea const importModal = window.ModalSystem.create({ id: 'importConfigModal', title: 'Import Configuration', content: `
Paste your configuration JSON below. This will completely replace your current configuration.
`, footer: ` `, closeOnBackdrop: true, closeOnEscape: true, onOpen: (importModalInstance) => { const confirmBtn = importModalInstance.dialogFooter?.querySelector('#confirmImportBtn'); const cancelBtn = importModalInstance.dialogFooter?.querySelector('#cancelImportBtn'); const textarea = importModalInstance.dialogContent.querySelector('#importConfigTextarea'); // Focus textarea if (textarea) { setTimeout(() => textarea.focus(), 100); } if (confirmBtn) { confirmBtn.addEventListener('click', async () => { const jsonText = textarea?.value.trim() || ''; if (!jsonText) { if (window.KefinTweaksToaster && window.KefinTweaksToaster.toast) { window.KefinTweaksToaster.toast('Please paste configuration JSON', '3'); } else { alert('Please paste configuration JSON'); } return; } // Validate JSON let importedConfig; try { importedConfig = JSON.parse(jsonText); } catch (parseError) { console.error('[KefinTweaks Configuration] Invalid JSON:', parseError); if (window.KefinTweaksToaster && window.KefinTweaksToaster.toast) { window.KefinTweaksToaster.toast(`Invalid JSON: ${parseError.message}`, '5'); } else { alert(`Invalid JSON: ${parseError.message}`); } return; } // Validate config structure (basic check) if (typeof importedConfig !== 'object' || importedConfig === null) { if (window.KefinTweaksToaster && window.KefinTweaksToaster.toast) { window.KefinTweaksToaster.toast('Invalid configuration format', '5'); } else { alert('Invalid configuration format'); } return; } // Show confirmation dialog const confirmed = await showImportConfirmation(); if (!confirmed) { return; } // Close import modal importModalInstance.close(); // Apply imported config try { await applyImportedConfig(importedConfig, modalInstance); } catch (error) { console.error('[KefinTweaks Configuration] Error applying imported config:', error); if (window.KefinTweaksToaster && window.KefinTweaksToaster.toast) { window.KefinTweaksToaster.toast(`Error applying configuration: ${error.message}`, '5'); } else { alert(`Error applying configuration: ${error.message}`); } } }); } if (cancelBtn) { cancelBtn.addEventListener('click', () => { importModalInstance.close(); }); } } }); } // Show confirmation dialog for import function showImportConfirmation() { return new Promise((resolve) => { if (!window.ModalSystem) { resolve(false); return; } const modal = window.ModalSystem.create({ id: 'importConfirmation', title: 'Confirm Import', content: `
This will completely overwrite your current configuration. All existing settings will be replaced with the imported configuration. This action cannot be undone.
`, footer: ` `, closeOnBackdrop: true, closeOnEscape: true, onOpen: (modalInstance) => { const confirmBtn = modalInstance.dialogFooter?.querySelector('#confirmImportConfirmBtn'); const cancelBtn = modalInstance.dialogFooter?.querySelector('#cancelImportConfirmBtn'); if (confirmBtn) { confirmBtn.addEventListener('click', () => { modalInstance.close(); resolve(true); }); } if (cancelBtn) { cancelBtn.addEventListener('click', () => { modalInstance.close(); resolve(false); }); } } }); }); } // Apply imported configuration async function applyImportedConfig(importedConfig, modalInstance) { // Save to JavaScript Injector await saveConfigToJavaScriptInjector(importedConfig); // Reload the modal with new config modalInstance.close(); // Show success message if (window.KefinTweaksToaster && window.KefinTweaksToaster.toast) { window.KefinTweaksToaster.toast('Configuration imported successfully! Reloading...'); } // Reopen modal with new config after a short delay setTimeout(() => { openConfigurationModal(); }, 500); } // Find JavaScript Injector plugin async function findJavaScriptInjectorPlugin() { try { if (!window.ApiClient || !window.ApiClient._serverAddress || !window.ApiClient.accessToken) { throw new Error('ApiClient not available'); } const server = ApiClient._serverAddress; const token = ApiClient.accessToken(); const response = await fetch(`${server}/Plugins`, { headers: { 'X-Emby-Token': token } }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const plugins = await response.json(); console.log('[KefinTweaks Configuration] Active Plugins:', plugins); // Handle both array and object with Items property const pluginsList = Array.isArray(plugins) ? plugins : (plugins.Items || []); // Find JavaScript Injector plugin const injectorPlugin = pluginsList.find(plugin => plugin.Name === 'JavaScript Injector' || plugin.Name === 'JS Injector' ); if (!injectorPlugin) { throw new Error('JavaScript Injector plugin not found. Please ensure it is installed.'); } console.log('[KefinTweaks Configuration] Found JavaScript Injector plugin:', injectorPlugin); return injectorPlugin.Id; } catch (error) { console.error('[KefinTweaks Configuration] Error finding JavaScript Injector plugin:', error); throw error; } } // Get current JavaScript Injector configuration async function getJavaScriptInjectorConfig(pluginId) { try { if (!window.ApiClient || !window.ApiClient._serverAddress || !window.ApiClient.accessToken) { throw new Error('ApiClient not available'); } const server = ApiClient._serverAddress; const token = ApiClient.accessToken(); const response = await fetch(`${server}/Plugins/${pluginId}/Configuration`, { headers: { 'X-Emby-Token': token } }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const config = await response.json(); console.log('[KefinTweaks Configuration] Current JS Injector config:', config); return config; } catch (error) { console.error('[KefinTweaks Configuration] Error getting JS Injector config:', error); throw error; } } // Save configuration to JavaScript Injector plugin async function saveConfigToJavaScriptInjector(config) { try { // Find the plugin const pluginId = await findJavaScriptInjectorPlugin(); // Get fresh configuration data const injectorConfig = await getJavaScriptInjectorConfig(pluginId); // Ensure CustomJavaScripts array exists if (!injectorConfig.CustomJavaScripts) { injectorConfig.CustomJavaScripts = []; } // Create the script content const scriptContent = `// KefinTweaks Configuration // This file is automatically generated by KefinTweaks Configuration UI // Do not edit manually unless you know what you're doing window.KefinTweaksConfig = ${JSON.stringify(config, null, 2)};`; // Check if KefinTweaks-Config already exists const existingScriptIndex = injectorConfig.CustomJavaScripts.findIndex( script => script.Name === 'KefinTweaks-Config' ); if (existingScriptIndex !== -1) { // Update existing script console.log('[KefinTweaks Configuration] Updating existing KefinTweaks-Config script'); injectorConfig.CustomJavaScripts[existingScriptIndex].Script = scriptContent; // Keep existing Enabled and RequiresAuthentication settings } else { // Add new script console.log('[KefinTweaks Configuration] Adding new KefinTweaks-Config script'); injectorConfig.CustomJavaScripts.push({ Name: 'KefinTweaks-Config', Script: scriptContent, Enabled: true, RequiresAuthentication: false }); } // POST the updated configuration back const server = ApiClient._serverAddress; const token = ApiClient.accessToken(); const response = await fetch(`${server}/Plugins/${pluginId}/Configuration`, { method: 'POST', headers: { 'X-Emby-Token': token, 'Content-Type': 'application/json' }, body: JSON.stringify(injectorConfig) }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } console.log('[KefinTweaks Configuration] Configuration saved successfully'); return true; } catch (error) { console.error('[KefinTweaks Configuration] Error saving configuration:', error); throw error; } } function getSectionConfigFromUI(rootElement, prefix, sectionIndex) { const scope = rootElement || document; const sectionItem = scope.querySelector(`.${prefix}_section_item[data-section-index="${sectionIndex}"]`); if (!sectionItem) return null; const sanitizedIndex = sectionIndex.toString().replace(/[^a-zA-Z0-9]/g, '_'); const sectionIdAttr = sectionItem.getAttribute('data-section-id') || `${prefix}-section-${sanitizedIndex}`; const enabledCheckbox = sectionItem.querySelector(`#${prefix}_section_enabled_${sanitizedIndex}`) || sectionItem.querySelector(`.${prefix}_section_enabled[data-section-index="${sectionIndex}"]`); const enabled = enabledCheckbox?.checked !== false; const name = sectionItem.querySelector(`.${prefix}_section_name[data-section-index="${sectionIndex}"]`)?.value || ''; const type = sectionItem.querySelector(`.${prefix}_section_type[data-section-index="${sectionIndex}"]`)?.value || 'Genre'; let source = ''; const sourceContainer = sectionItem.querySelector(`.${prefix}_section_source_container[data-section-index="${sectionIndex}"]`); const badgeContainer = sourceContainer?.querySelector(`.tag-badge-container[data-section-index="${sectionIndex}"][data-type]`) || null; if (badgeContainer) { const badges = badgeContainer.querySelectorAll('.tag-badge'); source = Array.from(badges).map(badge => badge.getAttribute('data-value')).filter(Boolean).join(', '); } else { const sourceInput = sectionItem.querySelector(`.${prefix}_section_source[data-section-index="${sectionIndex}"]`); source = sourceInput ? sourceInput.value : ''; } const itemLimit = parseInt(sectionItem.querySelector(`#${prefix}_section_${sanitizedIndex}_itemLimit`)?.value || '16', 10); const sortOrder = sectionItem.querySelector(`#${prefix}_section_${sanitizedIndex}_sortOrder`)?.value || 'Random'; const sortOrderDirection = sectionItem.querySelector(`#${prefix}_section_${sanitizedIndex}_sortOrderDirection`)?.value || 'Ascending'; const cardFormat = sectionItem.querySelector(`#${prefix}_section_${sanitizedIndex}_cardFormat`)?.value || 'Poster'; const order = parseInt(sectionItem.querySelector(`#${prefix}_section_${sanitizedIndex}_order`)?.value || '100', 10); const spotlightCheckbox = sectionItem.querySelector(`#${prefix}_section_${sanitizedIndex}_spotlight`) || sectionItem.querySelector(`.${prefix}_section_spotlight[data-section-index="${sectionIndex}"]`); const discoveryCheckbox = sectionItem.querySelector(`#${prefix}_section_${sanitizedIndex}_discovery`) || sectionItem.querySelector(`.${prefix}_section_discovery[data-section-index="${sectionIndex}"]`); const spotlight = spotlightCheckbox?.checked === true; const discoveryEnabled = discoveryCheckbox?.checked === true; const searchTerm = sectionItem.querySelector(`#${prefix}_section_${sanitizedIndex}_searchTerm`)?.value?.trim() || ''; let includeItemTypes = []; const includeItemTypesContainer = sectionItem.querySelector(`.includeItemTypes-badge-container[data-section-index="${sectionIndex}"]`); if (includeItemTypesContainer) { const badges = includeItemTypesContainer.querySelectorAll('.tag-badge'); includeItemTypes = Array.from(badges).map(badge => badge.getAttribute('data-value')).filter(Boolean); } if (includeItemTypes.length === 0 && type !== 'Parent') { includeItemTypes = ['Movie']; } return { id: sectionIdAttr, enabled: enabled, name: name, type: type, source: source, itemLimit: itemLimit, sortOrder: sortOrder, sortOrderDirection: sortOrderDirection, cardFormat: cardFormat, order: order, spotlight: spotlight, discoveryEnabled: discoveryEnabled, searchTerm: searchTerm, includeItemTypes: includeItemTypes }; } async function fetchItemsForSectionPreview(sectionConfig) { const apiClient = window.ApiClient; if (!apiClient) { throw new Error('ApiClient is not available'); } const userId = apiClient.getCurrentUserId(); const serverAddress = apiClient.serverAddress(); const token = apiClient.accessToken(); const type = sectionConfig.type || 'Genre'; const searchTerm = sectionConfig.searchTerm?.trim() || ''; const includeItemTypes = Array.isArray(sectionConfig.includeItemTypes) && sectionConfig.includeItemTypes.length > 0 ? sectionConfig.includeItemTypes.join(',') : (sectionConfig.includeItemTypes || 'Movie'); const sortOrder = sectionConfig.sortOrder || 'Random'; const sortOrderDirection = sectionConfig.sortOrderDirection || 'Ascending'; const itemLimit = parseInt(sectionConfig.itemLimit, 10) || 16; const sources = (sectionConfig.source || '').split(',').map(s => s.trim()).filter(Boolean); const fields = 'PrimaryImageAspectRatio,DateCreated,Overview,ProductionYear,ImageTags,BackdropImageTags,ParentBackdropImageTags,ParentThumbImageTag,SeriesPrimaryImageTag'; const headers = { 'Authorization': `MediaBrowser Token="${token}"` }; const dedupeAndLimit = (items = []) => { let working = Array.isArray(items) ? [...items] : []; if (sortOrder === 'Random') { working.sort(() => Math.random() - 0.5); } else if (window.cardBuilder?.sortItems) { working = window.cardBuilder.sortItems(working, sortOrder, sortOrderDirection); } const seen = new Set(); const limited = []; for (const item of working) { if (!item || !item.Id || seen.has(item.Id)) continue; seen.add(item.Id); limited.push(item); if (limited.length >= itemLimit) break; } return limited; }; const fetchJson = async (url) => { const response = await fetch(url, { headers }); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } return response.json(); }; try { if (type === 'Genre' || type === 'Tag') { if (sources.length === 0) { return []; } const paramName = type === 'Genre' ? 'Genres' : 'Tags'; const valueParam = sources.map(s => encodeURIComponent(s)).join('|'); const url = `${serverAddress}/Items?userId=${userId}&${paramName}=${valueParam}` + `&IncludeItemTypes=${encodeURIComponent(includeItemTypes)}` + `&Recursive=true&Fields=${encodeURIComponent(fields)}` + `&Limit=${itemLimit}&SortBy=${encodeURIComponent(sortOrder)}&SortOrder=${encodeURIComponent(sortOrderDirection)}` + (searchTerm ? `&SearchTerm=${encodeURIComponent(searchTerm)}` : ''); const data = await fetchJson(url); return dedupeAndLimit(data.Items || []); } if (type === 'Collection' || type === 'Playlist' || type === 'Parent') { const existingIds = new Set(); let collected = []; const queryBase = { IncludeItemTypes: includeItemTypes, Recursive: true, Fields: fields, SortBy: sortOrder, SortOrder: sortOrderDirection }; const runQuery = async (params) => { const response = await apiClient.getItems(userId, params); if (response?.Items?.length) { response.Items.forEach(item => { if (item && item.Id && !existingIds.has(item.Id)) { existingIds.add(item.Id); collected.push(item); } }); } }; if (type === 'Parent' && sources.length === 0) { const params = { ...queryBase, Limit: itemLimit * 2 }; if (searchTerm) params.SearchTerm = searchTerm; await runQuery(params); } else { const multiplier = Math.max(1, sources.length); for (const parentId of sources) { const params = { ...queryBase, ParentId: parentId, Limit: itemLimit * multiplier }; if (searchTerm) params.SearchTerm = searchTerm; await runQuery(params); } } return dedupeAndLimit(collected); } return []; } catch (error) { console.warn('[KefinTweaks Configuration] Preview fetch failed:', error); throw error; } } // Handle save configuration async function handleSaveConfig(modalInstance) { // Verify admin status before saving const userIsAdmin = await isAdmin(); if (!userIsAdmin) { alert('You must be an administrator to save configuration.'); return; } console.log('[KefinTweaks Configuration] Saving configuration...'); // Collect all form values const config = { kefinTweaksRoot: document.getElementById('kefinTweaksRoot')?.value || '', scripts: {}, homeScreen: {}, exclusiveElsewhere: {}, search: {}, defaultSkin: document.getElementById('defaultSkin')?.value || null, skins: [], themes: [], customMenuLinks: [] }; config.enabled = modalInstance.dialogContent.querySelector('#kefinTweaksEnabled')?.checked !== false; // Remove scriptRoot if it exists (legacy field, no longer used) if (config.scriptRoot) { delete config.scriptRoot; } // Collect script toggles document.querySelectorAll('[data-script-key]').forEach(checkbox => { const key = checkbox.getAttribute('data-script-key'); config.scripts[key] = checkbox.checked; }); // Helper function to get section config function getSectionConfig(prefix, includeSortOrderOrOptions = true, includeOrderFlag = true) { let includeSortOrder = true; let includeOrder = true; let includeName = false; let defaultName = ''; if (typeof includeSortOrderOrOptions === 'object') { const opts = includeSortOrderOrOptions || {}; includeSortOrder = opts.includeSortOrder !== undefined ? opts.includeSortOrder : true; includeOrder = opts.includeOrder !== undefined ? opts.includeOrder : true; includeName = opts.includeName === true; defaultName = opts.defaultName || ''; } else { includeSortOrder = includeSortOrderOrOptions !== false; includeOrder = includeOrderFlag !== false; } const config = { itemLimit: parseInt(document.getElementById(`${prefix}_itemLimit`)?.value || '16', 10) }; if (includeName) { config.name = document.getElementById(`${prefix}_name`)?.value || defaultName || ''; } if (includeSortOrder) { config.sortOrder = document.getElementById(`${prefix}_sortOrder`)?.value || 'Random'; config.sortOrderDirection = document.getElementById(`${prefix}_sortOrderDirection`)?.value || 'Ascending'; } config.cardFormat = document.getElementById(`${prefix}_cardFormat`)?.value || 'Poster'; if (includeOrder) { config.order = parseInt(document.getElementById(`${prefix}_order`)?.value || '100', 10); } return config; } // Collect seasonal seasons function getSeasonalSeasons() { const seasons = []; const seasonItems = modalInstance.dialogContent.querySelectorAll('.seasonal-season-item'); seasonItems.forEach((item, seasonIndex) => { // Try to find checkbox by ID first, then fall back to class selector const enabledCheckbox = item.querySelector(`#seasonal-season-enabled-${seasonIndex}`) || item.querySelector('.seasonal-season-enabled[data-index="${seasonIndex}"]'); const enabled = enabledCheckbox?.checked !== false; const name = item.querySelector('.seasonal-season-name')?.value || ''; const startDate = item.querySelector('.seasonal-season-startDate')?.value || ''; const endDate = item.querySelector('.seasonal-season-endDate')?.value || ''; const orderInput = item.querySelector(`.seasonal-season-order-input[data-index="${seasonIndex}"]`); const order = orderInput ? parseInt(orderInput.value || '100', 10) : 100; // Collect nested sections const sectionsList = item.querySelector(`.seasonal_season_sections_list[data-season-index="${seasonIndex}"]`); const sections = []; if (sectionsList) { const sectionItems = sectionsList.querySelectorAll('.seasonal_season_section_item'); sectionItems.forEach((sectionItem, sectionItemIndex) => { const fullIndex = `${seasonIndex}_${sectionItemIndex}`; const sectionConfig = getSectionConfigFromUI(modalInstance.dialogContent, 'seasonal_season', fullIndex); if (sectionConfig) { sections.push(sectionConfig); } }); } const seasonConfig = { id: name.toLowerCase().replace(/\s+/g, '-') || `season-${seasonIndex}`, name: name, enabled: enabled, startDate: startDate, endDate: endDate, order: order, sections: sections }; seasons.push(seasonConfig); }); return seasons; } // Collect custom sections function getCustomSections() { const sectionsList = modalInstance.dialogContent.querySelector('#customSections_list'); const sections = []; if (!sectionsList) { return sections; } const sectionItems = sectionsList.querySelectorAll('.customSection_section_item'); sectionItems.forEach((sectionItem, index) => { const sectionIndex = sectionItem.getAttribute('data-section-index') ?? index; const sectionConfig = getSectionConfigFromUI(modalInstance.dialogContent, 'customSection', sectionIndex); if (sectionConfig) { sections.push(sectionConfig); } }); return sections; } // Collect home screen config config.homeScreen = { defaultItemLimit: 16, defaultSortOrder: 'Random', defaultCardFormat: 'Poster', recentlyReleased: { enabled: document.getElementById('homeScreen_recentlyReleased_enabled')?.checked !== false, movies: { enabled: document.getElementById('homeScreen_recentlyReleased_movies_enabled')?.checked !== false, ...getSectionConfig('homeScreen_recentlyReleased_movies', { includeName: true, defaultName: 'Recently Released Movies', includeSortOrder: false, includeOrder: true }) }, episodes: { enabled: document.getElementById('homeScreen_recentlyReleased_episodes_enabled')?.checked !== false, ...getSectionConfig('homeScreen_recentlyReleased_episodes', { includeName: true, defaultName: 'Recently Aired Episodes', includeSortOrder: false, includeOrder: true }) } }, trending: { enabled: document.getElementById('homeScreen_trending_enabled')?.checked === true, ...getSectionConfig('homeScreen_trending', { includeName: true, defaultName: 'Trending' }) }, popularTVNetworks: { enabled: document.getElementById('homeScreen_popularTVNetworks_enabled')?.checked === true, minimumShowsForNetwork: parseInt(document.getElementById('homeScreen_popularTVNetworks_minimumShowsForNetwork')?.value || '5'), ...getSectionConfig('homeScreen_popularTVNetworks', { includeName: true, defaultName: 'Popular TV Networks' }) }, watchlist: { enabled: document.getElementById('homeScreen_watchlist_enabled')?.checked === true, ...getSectionConfig('homeScreen_watchlist', { includeName: true, defaultName: 'Watchlist' }) }, watchAgain: { enabled: document.getElementById('homeScreen_watchAgain_enabled')?.checked === true, ...getSectionConfig('homeScreen_watchAgain', { includeName: true, defaultName: 'Watch Again' }) }, upcoming: { enabled: document.getElementById('homeScreen_upcoming_enabled')?.checked !== false, ...getSectionConfig('homeScreen_upcoming', { includeSortOrder: false, includeName: true, defaultName: 'Upcoming' }) }, imdbTop250: { enabled: document.getElementById('homeScreen_imdbTop250_enabled')?.checked !== false, ...getSectionConfig('homeScreen_imdbTop250', { includeName: true, defaultName: 'IMDb Top 250' }) }, seasonal: { enabled: document.getElementById('homeScreen_seasonal_enabled')?.checked !== false, defaultItemLimit: 16, defaultSortOrder: 'Random', defaultCardFormat: 'Poster', seasons: getSeasonalSeasons() }, discovery: { enabled: document.getElementById('homeScreen_discovery_enabled')?.checked !== false, infiniteScroll: document.getElementById('homeScreen_discovery_infiniteScroll')?.checked !== false, randomizeOrder: document.getElementById('homeScreen_discovery_randomizeOrder')?.checked === true, minPeopleAppearances: parseInt(document.getElementById('homeScreen_discovery_minPeopleAppearances')?.value || '10'), minGenreMovieCount: parseInt(document.getElementById('homeScreen_discovery_minGenreMovieCount')?.value || '50'), spotlightDiscoveryChance: parseFloat(document.getElementById('homeScreen_discovery_spotlightDiscoveryChance')?.value || '0.5'), defaultItemLimit: parseInt(document.getElementById('homeScreen_discovery_itemLimit')?.value || '16'), defaultSortOrder: document.getElementById('homeScreen_discovery_sortOrder')?.value || 'Random', defaultCardFormat: document.getElementById('homeScreen_discovery_cardFormat')?.value || 'Poster', sectionTypes: (() => { const sectionConfigs = {}; DISCOVERY_SECTION_DEFINITIONS.forEach(section => { const prefix = `homeScreen_discovery_sectionTypes_${section.key}`; const collectedConfig = getSectionConfig(prefix, { includeName: true, includeOrder: true, includeSortOrder: false, defaultName: section.defaultName }); collectedConfig.enabled = document.getElementById(`${prefix}_enabled`)?.checked !== false; if (section.extras?.minimumItems !== undefined) { const minimumValue = parseInt(document.getElementById(`${prefix}_minimumItems`)?.value || `${section.extras.minimumItems}`, 10); collectedConfig.minimumItems = Number.isFinite(minimumValue) ? minimumValue : section.extras.minimumItems; } sectionConfigs[section.key] = collectedConfig; }); return sectionConfigs; })() }, customSections: getCustomSections() }; // Collect exclusive elsewhere config config.exclusiveElsewhere = { hideServerName: document.getElementById('exclusiveElsewhere_hideServerName')?.checked === true }; // Collect search config config.search = { enableJellyseerr: document.getElementById('search_enableJellyseerr')?.checked === true }; // Parse JSON fields const skinsFromJson = parseJSONField('skinsJson', []); config.themes = parseJSONField('themesJson', []); config.customMenuLinks = parseJSONField('customMenuLinksJson', []); // Collect skin enabled toggles and merge with JSON skins // First, get the original config to preserve hidden skins const originalConfig = await getKefinTweaksConfig(); const originalSkins = originalConfig.skins || []; const hiddenSkins = originalSkins.filter(skin => skin.hidden === true); // Collect enabled states from toggles const skinEnabledStates = {}; modalInstance.dialogContent.querySelectorAll('[data-skin-name]').forEach(checkbox => { const skinName = checkbox.getAttribute('data-skin-name'); skinEnabledStates[skinName] = checkbox.checked; }); // Merge: start with hidden skins (preserve them), then add/update from JSON config.skins = [...hiddenSkins]; // Add/update skins from JSON textarea skinsFromJson.forEach(skin => { const existingIndex = config.skins.findIndex(s => s.name === skin.name); if (existingIndex !== -1) { // Update existing skin (shouldn't happen for hidden, but just in case) config.skins[existingIndex] = { ...config.skins[existingIndex], ...skin, enabled: skinEnabledStates[skin.name] !== false // Default to true if not set }; } else { // Add new skin config.skins.push({ ...skin, enabled: skinEnabledStates[skin.name] !== false, hidden: false // Explicitly set for new skins }); } }); // Update enabled states for all skins (including hidden ones) config.skins.forEach(skin => { if (skinEnabledStates.hasOwnProperty(skin.name)) { skin.enabled = skinEnabledStates[skin.name]; } }); // Handle defaultSkin if (config.defaultSkin === '') { config.defaultSkin = null; } console.log('[KefinTweaks Configuration] Configuration collected:', config); // Save to JavaScript Injector plugin try { await saveConfigToJavaScriptInjector(config); // Show success toast if (window.KefinTweaksToaster && window.KefinTweaksToaster.toast) { window.KefinTweaksToaster.toast('KefinTweaks saved!'); } } catch (error) { console.error('[KefinTweaks Configuration] Error saving configuration:', error); // Show error toast if (window.KefinTweaksToaster && window.KefinTweaksToaster.toast) { window.KefinTweaksToaster.toast(`Error saving configuration: ${error.message}. Please ensure the JavaScript Injector plugin is installed and you have administrator permissions.`, '5'); } else { // Fallback to alert if toaster is not available alert(`Error saving configuration: ${error.message}\n\nPlease ensure the JavaScript Injector plugin is installed and you have administrator permissions.`); } } } async function handleResetConfig(modalInstance) { const userIsAdmin = await isAdmin(); if (!userIsAdmin) { alert('You must be an administrator to reset configuration.'); return; } const confirmed = confirm('This will restore the KefinTweaks configuration to its defaults. It cannot be undone. Are you sure you want to continue?'); if (!confirmed) { return; } try { const defaultConfig = await loadDefaultConfig(); // Retain kefinTweaksRoot from existing config const existingConfig = await getKefinTweaksConfig(); defaultConfig.kefinTweaksRoot = existingConfig.kefinTweaksRoot; // Note: scriptRoot is no longer used - scripts are loaded from kefinTweaksRoot + '/scripts/' await saveConfigToJavaScriptInjector(defaultConfig); if (window.KefinTweaksToaster && window.KefinTweaksToaster.toast) { window.KefinTweaksToaster.toast('Configuration reset to defaults.'); } else { alert('Configuration reset to defaults.'); } if (modalInstance && typeof modalInstance.close === 'function') { modalInstance.close(); } openConfigurationModal(); } catch (error) { console.error('[KefinTweaks Configuration] Error resetting config:', error); if (window.KefinTweaksToaster && window.KefinTweaksToaster.toast) { window.KefinTweaksToaster.toast(`Error resetting configuration: ${error.message}`, '5'); } else { alert(`Error resetting configuration: ${error.message}`); } } } // Helper to parse JSON fields safely function parseJSONField(fieldId, defaultValue) { try { const field = document.getElementById(fieldId); if (!field || !field.value.trim()) { return defaultValue; } return JSON.parse(field.value); } catch (error) { console.error(`[KefinTweaks Configuration] Error parsing JSON field ${fieldId}:`, error); alert(`Error parsing JSON in ${fieldId}: ${error.message}`); return defaultValue; } } // Create configuration button for Administration section function createConfigButton() { const button = document.createElement('div'); button.style.display = 'block'; button.style.padding = '0'; button.style.margin = '0'; button.className = 'listItem-border emby-button kefin-config-button'; button.setAttribute('data-kefintweaks-config-button', 'true'); button.onclick = (e) => { e.preventDefault(); openConfigurationModal(); }; button.innerHTML = `
Configure KefinTweaks
`; return button; } // Create dashboard side menu button function createDashboardConfigButton() { // Check if button already exists if (document.querySelector('[data-kefintweaks-dashboard-config-button]')) { return null; } const div = document.createElement('div'); div.className = 'MuiButtonBase-root MuiListItemButton-root MuiListItemButton-gutters MuiListItemButton-root MuiListItemButton-gutters kefin-config-button'; div.setAttribute('tabindex', '0'); div.setAttribute('data-kefintweaks-dashboard-config-button', 'true'); div.onclick = () => { openConfigurationModal(); }; // Create icon with Material icon const icon = document.createElement('div'); icon.className = 'MuiListItemIcon-root css-37qkju'; const iconSpan = document.createElement('span'); iconSpan.className = 'material-icons build MuiSvgIcon-root MuiSvgIcon-fontSizeMedium'; iconSpan.style.marginRight = '12px'; iconSpan.setAttribute('aria-hidden', 'true'); icon.appendChild(iconSpan); // Create text const text = document.createElement('div'); text.className = 'MuiListItemText-root css-f696uz'; const span = document.createElement('span'); span.className = 'MuiTypography-root MuiTypography-body1 MuiListItemText-primary css-hlxkyz'; span.textContent = 'KefinTweaks'; text.appendChild(span); // Create ripple effect span const ripple = document.createElement('span'); ripple.className = 'MuiTouchRipple-root css-w0pj6f'; div.appendChild(icon); div.appendChild(text); div.appendChild(ripple); return div; } // Add configuration button to dashboard side menu function addConfigButtonToDashboard() { // Check if button already exists if (document.querySelector('[data-kefintweaks-dashboard-config-button]')) { return; } // Find the plugins section const pluginsSection = document.querySelector('ul[aria-labelledby="plugins-subheader"]'); if (!pluginsSection) { console.log('[KefinTweaks Configuration] Plugins section not found, retrying...'); setTimeout(addConfigButtonToDashboard, 500); return; } // Create the button const button = createDashboardConfigButton(); if (!button) { return; } // Add button to the plugins section pluginsSection.appendChild(button); console.log('[KefinTweaks Configuration] Configuration button added to dashboard side menu'); } // Add configuration button to Administration section function addConfigButtonToAdminSection() { // Check if button already exists (check for admin section button specifically) if (document.querySelector('.adminSection [data-kefintweaks-config-button]')) { return; } // Find the Administration section const adminSection = document.querySelector('.adminSection.verticalSection'); if (!adminSection) { console.log('[KefinTweaks Configuration] Administration section not found, retrying...'); setTimeout(addConfigButtonToAdminSection, 500); return; } // Create and add the button const button = createConfigButton(); adminSection.appendChild(button); console.log('[KefinTweaks Configuration] Configuration button added to Administration section'); } // Register onViewPage handler for mypreferencesmenu page and dashboard function registerViewPageHandler() { if (!window.KefinTweaksUtils || !window.KefinTweaksUtils.onViewPage) { console.log('[KefinTweaks Configuration] KefinTweaksUtils.onViewPage not available, retrying...'); setTimeout(registerViewPageHandler, 1000); return; } // Handler for dashboard and preferences pages window.KefinTweaksUtils.onViewPage(async (view, element, hash) => { // Check if user is admin before adding buttons const userIsAdmin = await isAdmin(); if (!userIsAdmin) { console.log('[KefinTweaks Configuration] User is not admin, not adding buttons'); return; } // Check if we're on the mypreferencesmenu page if (hash && (hash.includes('mypreferencesmenu') || hash.includes('userpreferences') || hash.includes('preferences'))) { console.log('[KefinTweaks Configuration] Preferences page detected'); // Wait a bit for the page to fully load setTimeout(() => { addConfigButtonToAdminSection(); }, 500); } // Check if we're on the dashboard page if (view === 'dashboard' || view === 'configurationpage' || hash.includes('dashboard') || hash.includes('configurationpage')) { console.log('[KefinTweaks Configuration] Dashboard page detected'); // Wait a bit for the page to fully load setTimeout(() => { addConfigButtonToDashboard(); }, 500); } }); console.log('[KefinTweaks Configuration] Registered onViewPage handler'); } // Add configuration link to custom menu async function addConfigLinkToCustomMenu() { // Check if user is admin const userIsAdmin = await isAdmin(); if (!userIsAdmin) { console.log('[KefinTweaks Configuration] User is not admin, not adding menu link'); return; } // Check if utils is available if (!window.KefinTweaksUtils || !window.KefinTweaksUtils.addCustomMenuLink) { console.log('[KefinTweaks Configuration] KefinTweaksUtils.addCustomMenuLink not available, retrying...'); setTimeout(addConfigLinkToCustomMenu, 1000); return; } // Use a special URL that we can intercept const configUrl = '#'; // Add the menu link const success = await window.KefinTweaksUtils.addCustomMenuLink( 'Configure', 'build', configUrl, false, '.adminMenuOptions' ); if (success) { console.log('[KefinTweaks Configuration] Configuration link added to custom menu'); // Set up click handler to intercept navigation and open modal instead setupConfigLinkClickHandler(); } } // Set up click handler for configuration menu link function setupConfigLinkClickHandler() { // Find the config button const configButton = document.querySelector('.navMenuOption[data-name="configure"]'); if (!configButton) { console.log('[KefinTweaks Configuration] Configuration button not found, retrying...'); setTimeout(setupConfigLinkClickHandler, 1000); return; } // Add click handler to the config button configButton.addEventListener('click', (e) => { e.preventDefault(); openConfigurationModal(); }); } // Handle direct navigation to config URL function handleDirectConfigNavigation() { if (window.location.hash === '#kefintweaks-config') { console.log('[KefinTweaks Configuration] Direct navigation to config URL detected'); // Remove the hash to prevent navigation window.history.replaceState(null, '', window.location.pathname + window.location.search); // Open modal openConfigurationModal(); } } // Set up hashchange listener for navigation after page load function setupHashChangeListener() { window.addEventListener('hashchange', () => { if (window.location.hash === '#kefintweaks-config') { console.log('[KefinTweaks Configuration] Hash change to config URL detected'); // Remove the hash to prevent navigation window.history.replaceState(null, '', window.location.pathname + window.location.search); // Open modal openConfigurationModal(); } }); } // Initialize when DOM is ready async function initialize() { if (!window.ApiClient || !window.ApiClient._loggedIn) { setTimeout(initialize, 1000); return; } // Register view page handler registerViewPageHandler(); // Add configuration link to custom menu addConfigLinkToCustomMenu(); // Set up hashchange listener setupHashChangeListener(); // Handle direct navigation to config URL handleDirectConfigNavigation(); // Also check current page on initial load const hash = window.location.hash; const userIsAdmin = await isAdmin(); if (userIsAdmin) { if (hash && (hash.includes('mypreferencesmenu') || hash.includes('userpreferences') || hash.includes('preferences'))) { setTimeout(() => { addConfigButtonToAdminSection(); }, 1000); } if (hash && hash.includes('dashboard')) { setTimeout(() => { addConfigButtonToDashboard(); }, 1000); } } } // Start initialization if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initialize); } else { initialize(); } console.log('[KefinTweaks Configuration] Script loaded'); })();