This commit is contained in:
Mateusz Gruszczyński
2026-09-16 09:04:43 +02:00
parent 3d69e74319
commit 0437ef7b6f
28 changed files with 1254 additions and 221 deletions
+70 -5
View File
@@ -66,29 +66,36 @@ function resetHistoryRangeControl(host) {
if (range && toolbar && range.parentElement === host) toolbar.insertBefore(range, refresh);
}
function configureHistoryRangeControl(tab, host) {
function configureHistoryRangeControl(tab, host, hasEnergyTargets = true) {
const range = $('#historyRangeControl');
if (!range) return;
const toolbar = range.closest('.chart-toolbar') || host?.closest('.chart-toolbar');
const toolbarPanel = toolbar?.closest('.history-toolbar-panel');
const refresh = $('#historyRefresh');
const label = range.querySelector('span');
const hint = $('#historyRangeHint');
const sixHours = range.querySelector('option[value="6"]');
const energy = tab === 'energy';
const energyUnavailable = energy && !hasEnergyTargets;
const rangeLabel = tr(energy ? 'energy.period' : 'history.range');
if (label) label.textContent = rangeLabel;
range.setAttribute('aria-label', rangeLabel);
if (hint) { hint.textContent = energy ? tr('energy.periodHint') : ''; hint.hidden = !energy; }
if (sixHours) { sixHours.hidden = energy; sixHours.disabled = energy; }
if (energy && $('#historyHours')?.value === '6') $('#historyHours').value = '24';
range.hidden = energyUnavailable;
if (refresh) refresh.hidden = energyUnavailable;
if (toolbarPanel) toolbarPanel.hidden = energyUnavailable;
range.classList.toggle('energy-period-control', energy);
if (toolbar) toolbar.classList.toggle('energy-toolbar', energy);
if (energy && host) host.appendChild(range);
if (energy && host && hasEnergyTargets) host.appendChild(range);
}
function renderHistoryNavigation() {
$$('#historyTabs [data-history-tab]').forEach(button => button.classList.toggle('active', button.dataset.historyTab === app.historyTab));
const energyPickerWasOpen = $('#historyEnergyTargetPicker')?.open === true;
const host = $('#historyContextControls'); if (!host) return;
let hasEnergyTargets = true;
resetHistoryRangeControl(host);
host.classList.toggle('energy-context-controls', app.historyTab === 'energy');
const options = historyEntityOptions();
@@ -100,10 +107,11 @@ function renderHistoryNavigation() {
const select = $('#historyDeviceSelect'); if ([...select.options].some(option => option.value === app.historyDevice)) select.value = app.historyDevice;
} else if (app.historyTab === 'energy') {
const targets = normalizeEnergyHistoryTargets();
hasEnergyTargets = targets.length > 0;
const targetOptions = targets.map(target => `<label class="history-energy-option"><input type="checkbox" data-history-energy-target="${esc(target.id)}" ${app.historyEnergyTargets.includes(target.id) ? 'checked' : ''}><span>${esc(target.label)}</span></label>`).join('');
host.innerHTML = targets.length
? `<div class="history-energy-targets"><span class="history-control-label">${esc(tr('energy.targets'))}</span><details class="history-energy-picker" id="historyEnergyTargetPicker"><summary><span>${esc(energyTargetPickerSummary(targets))}</span><b>${app.historyEnergyTargets.length}/8</b></summary><div class="history-energy-options">${targetOptions}</div></details><small>${esc(tr('energy.multiselectHint'))}</small></div><label><span>${esc(tr('history.bucket'))}</span><select id="historyEnergyInterval"><option value="hourly">${esc(tr('energy.hourly'))}</option><option value="daily">${esc(tr('energy.daily'))}</option><option value="weekly">${esc(tr('energy.weekly'))}</option><option value="monthly">${esc(tr('energy.monthly'))}</option></select></label><label><span>${esc(tr('energy.compare'))}</span><select id="historyEnergyCompare"><option value="none">${esc(tr('energy.compareNone'))}</option><option value="previous_day">${esc(tr('energy.comparePreviousDay'))}</option><option value="previous_period">${esc(tr('energy.comparePreviousPeriod'))}</option><option value="previous_year">${esc(tr('energy.comparePreviousYear'))}</option></select></label>`
: `<span class="history-context-hint">${esc(tr('energy.noData'))}</span>`;
: '';
const intervalSelect = $('#historyEnergyInterval'); if (intervalSelect) intervalSelect.value = app.historyEnergyInterval;
const compareSelect = $('#historyEnergyCompare'); if (compareSelect) compareSelect.value = app.historyEnergyCompare;
if (energyPickerWasOpen && $('#historyEnergyTargetPicker')) $('#historyEnergyTargetPicker').open = true;
@@ -121,7 +129,7 @@ function renderHistoryNavigation() {
} else {
host.innerHTML = `<span class="history-context-hint">${esc(tr('history.overviewHint'))}</span>`;
}
configureHistoryRangeControl(app.historyTab, host);
configureHistoryRangeControl(app.historyTab, host, hasEnergyTargets);
}
async function loadHistory() {
@@ -164,6 +172,7 @@ async function loadHistory() {
const HISTORY_COLORS = ['--accent', '--info', '--warning', '--purple', '--danger', '--teal', '--orange', '--blue'];
const MAX_CHART_ZOOM = 16;
const chartRuntime = new Map();
const chartFullscreenState = new WeakMap();
function chartSeriesKey(item, index) {
return item.key || `${index}:${item.label}`;
@@ -251,6 +260,28 @@ function updateChartFullscreenButton(card) {
button.setAttribute('aria-label', button.title);
}
function restoreChartPreviewLayout(card) {
const state = chartFullscreenState.get(card);
if (!state) return null;
const canvas = card.querySelector('canvas[id]');
const wrap = canvas?.parentElement;
if (canvas) {
if (state.canvasStyleWidth) canvas.style.width = state.canvasStyleWidth; else canvas.style.removeProperty('width');
if (state.canvasStyleHeight) canvas.style.height = state.canvasStyleHeight; else canvas.style.removeProperty('height');
canvas.width = state.canvasWidth;
canvas.height = state.canvasHeight;
}
if (wrap) {
if (state.wrapStyleHeight) wrap.style.height = state.wrapStyleHeight; else wrap.style.removeProperty('height');
if (state.wrapStyleMinHeight) wrap.style.minHeight = state.wrapStyleMinHeight; else wrap.style.removeProperty('min-height');
if (state.wrapStyleMaxHeight) wrap.style.maxHeight = state.wrapStyleMaxHeight; else wrap.style.removeProperty('max-height');
wrap.scrollLeft = state.scrollLeft;
wrap.scrollTop = state.scrollTop;
}
chartFullscreenState.delete(card);
return state;
}
function closeChartPreview(card) {
if (!card) return;
card.classList.remove('chart-fullscreen-fallback');
@@ -258,9 +289,31 @@ function closeChartPreview(card) {
card.removeAttribute('aria-modal');
card.removeAttribute('aria-label');
document.body.classList.remove('chart-fullscreen-open');
const state = restoreChartPreviewLayout(card);
updateChartFullscreenButton(card);
const canvas = card.querySelector('canvas[id]');
if (canvas?.id) requestAnimationFrame(() => redrawHistoryChart(canvas.id));
if (!canvas?.id) return;
// Force layout after dropping the fullscreen class before sizing the canvas again.
// This prevents a fullscreen-sized canvas from keeping a dialog artificially tall.
card.getBoundingClientRect();
requestAnimationFrame(() => {
redrawHistoryChart(canvas.id);
const wrap = canvas.parentElement;
if (wrap && state) {
wrap.scrollLeft = state.scrollLeft;
wrap.scrollTop = state.scrollTop;
}
const dialog = card.closest('dialog');
if (dialog?.open) {
dialog.style.removeProperty('height');
dialog.style.removeProperty('max-height');
requestAnimationFrame(() => {
dialog.style.removeProperty('height');
dialog.style.removeProperty('max-height');
});
}
});
}
function toggleChartFullscreen(id) {
@@ -278,6 +331,18 @@ function toggleChartFullscreen(id) {
return;
}
const wrap = canvas.parentElement;
chartFullscreenState.set(card, {
canvasStyleWidth: canvas.style.width,
canvasStyleHeight: canvas.style.height,
canvasWidth: canvas.width,
canvasHeight: canvas.height,
wrapStyleHeight: wrap?.style.height || '',
wrapStyleMinHeight: wrap?.style.minHeight || '',
wrapStyleMaxHeight: wrap?.style.maxHeight || '',
scrollLeft: wrap?.scrollLeft || 0,
scrollTop: wrap?.scrollTop || 0,
});
card.classList.add('chart-fullscreen-fallback');
card.setAttribute('role', 'dialog');
card.setAttribute('aria-modal', 'true');
+40 -15
View File
@@ -261,11 +261,36 @@ function applyTranslations() {
if (app.currentView === 'history' && app.zones.length) loadHistory();
}
function setLanguage(language) {
async function loadLanguagePack(language) {
if (app.translations[language]) return;
const item = app.languages.find(entry => entry.code === language);
if (!item) throw new Error(`Unknown language: ${language}`);
const response = await fetch(withBase(item.path || `/lang/${encodeURIComponent(item.code)}.json`));
if (!response.ok) throw new Error(`Language ${item.code} HTTP ${response.status}`);
const pack = await response.json();
app.translations[item.code] = pack.translations || {};
app.locales[item.code] = pack.meta?.locale || item.locale || item.code;
}
async function setLanguage(language) {
const available = app.languages.some(item => item.code === language);
app.language = available ? language : DEFAULT_LANGUAGE;
setCookie('gree_controller_language', app.language);
applyTranslations();
const nextLanguage = available ? language : DEFAULT_LANGUAGE;
const previousLanguage = app.language;
const select = $('#languageSelect');
if (nextLanguage === previousLanguage && app.translations[nextLanguage]) return;
if (select) select.disabled = true;
try {
await loadLanguagePack(nextLanguage);
app.language = nextLanguage;
setCookie('gree_controller_language', app.language);
applyTranslations();
} catch (error) {
console.error(`Unable to load language ${nextLanguage}:`, error);
if (select) select.value = previousLanguage;
toast(error.message, true);
} finally {
if (select) select.disabled = false;
}
}
function renderLanguageOptions() {
@@ -286,21 +311,21 @@ async function loadLanguages() {
const manifest = await response.json();
const languages = Array.isArray(manifest.languages) ? manifest.languages : [];
if (!languages.some(item => item.code === DEFAULT_LANGUAGE)) throw new Error('Default English language pack is missing');
const loaded = await Promise.all(languages.map(async item => {
const packResponse = await fetch(withBase(item.path || `/lang/${encodeURIComponent(item.code)}.json`));
if (!packResponse.ok) throw new Error(`Language ${item.code} HTTP ${packResponse.status}`);
const pack = await packResponse.json();
return { item, pack };
}));
app.languages = loaded.map(({ item }) => item);
app.translations = Object.fromEntries(loaded.map(({ item, pack }) => [item.code, pack.translations || {}]));
app.locales = Object.fromEntries(loaded.map(({ item, pack }) => [item.code, pack.meta?.locale || item.locale || item.code]));
app.languages = languages;
app.translations = {};
app.locales = Object.fromEntries(languages.map(item => [item.code, item.locale || item.code]));
app.language = app.languages.some(item => item.code === preferredLanguage)
? preferredLanguage
: (manifest.default || DEFAULT_LANGUAGE);
if (!app.languages.some(item => item.code === app.language)) app.language = DEFAULT_LANGUAGE;
try {
await loadLanguagePack(app.language);
} catch (error) {
if (app.language === DEFAULT_LANGUAGE) throw error;
console.error(`Unable to load preferred language ${app.language}:`, error);
app.language = DEFAULT_LANGUAGE;
await loadLanguagePack(DEFAULT_LANGUAGE);
}
renderLanguageOptions();
} catch (error) {
console.error('Unable to load language packs:', error);
+1 -1
View File
@@ -49,7 +49,7 @@ function renderHouseClimate() {
if (powerOn) { powerOn.classList.remove('active'); powerOn.removeAttribute('aria-pressed'); }
if (powerOff) { powerOff.classList.remove('active'); powerOff.removeAttribute('aria-pressed'); }
node.innerHTML = `<div class="house-climate-head"><div><span class="eyebrow">${esc(tr('house.seasonMode'))}</span><h3>${esc(tr('house.smartThermostat'))}</h3><p>${esc(tr('house.setpointStrategy'))}</p></div><div class="outside-pill"><small>${esc(tr('house.outdoor'))}</small><strong>${esc(outdoor)}</strong></div></div>
node.innerHTML = `<div class="house-climate-head"><div><span class="eyebrow">${esc(tr('house.seasonMode'))}</span><h3>${esc(tr('house.smartThermostat'))}</h3><p>${esc(tr('house.setpointStrategy'))}</p></div><button type="button" class="outside-pill" data-action="open-outdoor-history" title="${esc(tr('house.outdoorHistoryOpen'))}" aria-label="${esc(tr('house.outdoorHistoryOpen'))}"><small>${esc(tr('house.outdoor'))}</small><strong>${esc(outdoor)}</strong></button></div>
<div class="house-mode-row">
<button class="${mode === 'cool' ? 'active' : ''}" data-action="house-mode" data-value="cool" aria-pressed="${mode === 'cool'}">${esc(tr('mode.cool'))}</button>
<button class="${mode === 'heat' ? 'active' : ''}" data-action="house-mode" data-value="heat" aria-pressed="${mode === 'heat'}">${esc(tr('mode.heat'))}</button>
+14
View File
@@ -11,6 +11,19 @@ document.addEventListener('keydown', event => {
document.addEventListener('click', async event => {
const inlineTarget = event.target.closest('[data-temperature-kind]');
if (inlineTarget && !event.target.closest('button')) { beginInlineTemperatureEdit(inlineTarget); return; }
const historyRoute = event.target.closest('a[data-history-route]');
if (historyRoute) {
event.preventDefault();
const hours = historyRoute.dataset.historyHours;
if (hours && $('#historyHours')) $('#historyHours').value = hours;
else if ($('#historyHours')) $('#historyHours').value = '24';
const dialog = historyRoute.closest('dialog');
closeChartPreview(dialog?.querySelector('.history-chart-card.chart-fullscreen-fallback'));
if (dialog?.open) dialog.close();
app.historyTab = 'overview';
showView('history');
return;
}
const button = event.target.closest('button'); if (!button) return;
if (button.dataset.settingsTab) { setSettingsTab(button.dataset.settingsTab); return; }
if (button.dataset.debugFilter) { app.debugFilter = button.dataset.debugFilter; renderDebugOverlay(); return; }
@@ -73,6 +86,7 @@ document.addEventListener('click', async event => {
return;
}
const action = button.dataset.action; if (!action) return;
if (action === 'open-outdoor-history') { await openOutdoorHistory(); return; }
if (action === 'add-cloud-device') {
const cloudId = button.dataset.cloudId; if (!cloudId) return;
button.disabled = true;
+5 -5
View File
@@ -816,16 +816,16 @@ function flowPresetRequirements(preset) {
const haEntities = [...new Set(nodes.map(node => node.config?.entity_id).filter(value => typeof value === 'string' && value && !value.startsWith('$')))];
const requirements = [];
const missing = [];
const addCount = (kind, count, available, key) => {
const addCount = (count, available, key) => {
if (!count) return;
const label = tr(key, { count });
requirements.push({ label, ok: available >= count });
if (available < count) missing.push(label);
};
addCount('zone', placeholders.zone.size, (app.zones || []).length, 'flow.templateRequiresZone');
addCount('device', placeholders.device.size, (app.devices || []).length, 'flow.templateRequiresDevice');
addCount('group', placeholders.group.size, (app.groups || []).length, 'flow.templateRequiresGroup');
addCount('shared', placeholders.shared.size, (app.flowSharedInputs || []).length, 'flow.templateRequiresShared');
addCount(placeholders.zone.size, (app.zones || []).length, 'flow.templateRequiresZone');
addCount(placeholders.device.size, (app.devices || []).length, 'flow.templateRequiresDevice');
addCount(placeholders.group.size, (app.groups || []).length, 'flow.templateRequiresGroup');
addCount(placeholders.shared.size, (app.flowSharedInputs || []).length, 'flow.templateRequiresShared');
if (hasHa) {
const ready = Boolean(app.settings?.home_assistant?.url && app.settings?.home_assistant?.token_configured);
requirements.push({ label: tr('flow.templateRequiresHa'), ok: ready });
+1
View File
@@ -273,6 +273,7 @@ function requestDialogClose(dialog) {
if (!dialog) return true;
const form = $('form', dialog);
if (form && !confirmDiscardForm(form)) return false;
closeChartPreview(dialog.querySelector?.('.history-chart-card.chart-fullscreen-fallback'));
dialog.close();
return true;
}
+37
View File
@@ -26,6 +26,43 @@ function outdoorHistorySeries(devices, rows) {
}));
}
async function openOutdoorHistory() {
const host = $('#outdoorHistoryChartHost');
const current = $('#outdoorHistoryCurrent');
if (!host || !current) return;
current.textContent = app.outdoorTemperature == null ? tr('common.unavailable') : fmtTemp(app.outdoorTemperature);
host.innerHTML = `<div class="panel outdoor-history-loading">${esc(tr('common.loading'))}</div>`;
$$('#outdoorHistoryDialog [data-history-route]').forEach(link => {
const hours = link.dataset.historyHours;
link.href = withBase(`/history/overview${hours ? `?hours=${encodeURIComponent(hours)}` : ''}`);
});
openDialog('outdoorHistoryDialog');
try {
const data = await api('/api/history?scope=overview&hours=24&limit=20000');
const deviceRows = data.devices || [];
const outdoorDeviceSeries = outdoorHistorySeries(app.devices, deviceRows).map(item => ({
...item,
label: item.label.includes(' · ') ? item.label : `${item.label} · ${tr('history.greeOutdoor')}`,
}));
const sensorRows = (data.sensors || []).filter(row => row.kind === 'outdoor');
const outdoorEntities = [...new Set(sensorRows.map(row => row.entity_id))];
const outdoorHaSeries = outdoorEntities.map((entity, index) => ({
label: `HA · ${haSensorLabel(entity)}`,
color: historySeriesColor(index + outdoorDeviceSeries.length),
dash: [6, 4],
value: row => row.entity_id === entity ? historyNumber(row.temperature) : NaN,
}));
const series = [...outdoorDeviceSeries, ...outdoorHaSeries];
const rows = [...deviceRows, ...sensorRows];
host.innerHTML = historyChartMarkup('outdoorHistoryModalChart', tr('history.allOutdoor'), tr('house.outdoorHistoryHint'));
drawLineChart($('#outdoorHistoryModalChart'), series, rows, { height: 350 });
renderLegend($('#outdoorHistoryModalChartLegend'), series);
} catch (error) {
host.innerHTML = `<div class="empty"><strong>${esc(tr('history.noData'))}</strong><span>${esc(error.message)}</span></div>`;
toast(error.message, true);
}
}
function renderHistorySummary() {
const host = $('#historySummary'); if (!host) return;
if (app.historyTab === 'energy') { renderEnergyHistorySummary(); return; }
+30 -24
View File
@@ -738,18 +738,21 @@ async function openDeviceDetails(id) {
const sensorSelect = form.ha_energy_entity_id;
sensorSelect.disabled = groupOwnsEnergy;
sensorSelect.innerHTML = '<option value="">—</option>';
try {
const response = await api('/api/integrations/home-assistant/energy-sensors');
for (const sensor of (response.sensors || [])) {
const option = document.createElement('option');
option.value = sensor.entity_id;
option.textContent = `${sensor.name || sensor.entity_id} · ${sensor.unit || ''}`;
option.dataset.unit = sensor.unit || '';
option.dataset.deviceClass = sensor.device_class || '';
option.dataset.stateClass = sensor.state_class || '';
sensorSelect.append(option);
}
} catch (_) { }
const haConfigured = Boolean(String(app.settings?.home_assistant?.url || '').trim() && app.settings?.home_assistant?.token_configured);
if (haConfigured) {
try {
const response = await api('/api/integrations/home-assistant/energy-sensors');
for (const sensor of (response.sensors || [])) {
const option = document.createElement('option');
option.value = sensor.entity_id;
option.textContent = `${sensor.name || sensor.entity_id} · ${sensor.unit || ''}`;
option.dataset.unit = sensor.unit || '';
option.dataset.deviceClass = sensor.device_class || '';
option.dataset.stateClass = sensor.state_class || '';
sensorSelect.append(option);
}
} catch (_) { }
}
const energyEntity = groupOwnsEnergy ? installation.ha_energy_entity_id : device.ha_energy_entity_id;
const energyUnit = groupOwnsEnergy ? installation.ha_energy_unit : device.ha_energy_unit;
const energyDeviceClass = groupOwnsEnergy ? installation.ha_energy_device_class : device.ha_energy_device_class;
@@ -822,18 +825,21 @@ async function loadDeviceGroupEnergySensors(group = null) {
const form = $('#deviceGroupForm'); if (!form) return;
const select = form.ha_energy_entity_id;
select.innerHTML = '<option value="">—</option>';
try {
const response = await api('/api/integrations/home-assistant/energy-sensors');
for (const sensor of (response.sensors || [])) {
const option = document.createElement('option');
option.value = sensor.entity_id;
option.textContent = `${sensor.name || sensor.entity_id} · ${sensor.unit || ''}`;
option.dataset.unit = sensor.unit || '';
option.dataset.deviceClass = sensor.device_class || '';
option.dataset.stateClass = sensor.state_class || '';
select.append(option);
}
} catch (_) { }
const haConfigured = Boolean(String(app.settings?.home_assistant?.url || '').trim() && app.settings?.home_assistant?.token_configured);
if (haConfigured) {
try {
const response = await api('/api/integrations/home-assistant/energy-sensors');
for (const sensor of (response.sensors || [])) {
const option = document.createElement('option');
option.value = sensor.entity_id;
option.textContent = `${sensor.name || sensor.entity_id} · ${sensor.unit || ''}`;
option.dataset.unit = sensor.unit || '';
option.dataset.deviceClass = sensor.device_class || '';
option.dataset.stateClass = sensor.state_class || '';
select.append(option);
}
} catch (_) { }
}
if (group?.ha_energy_entity_id && ![...select.options].some(option => option.value === group.ha_energy_entity_id)) {
const option = document.createElement('option');
option.value = group.ha_energy_entity_id;
+461
View File
@@ -0,0 +1,461 @@
'use strict';
const customSelectRegistry = new WeakMap();
let customSelectOpenState = null;
let customSelectSequence = 0;
let customSelectObserver = null;
let customSelectPropertiesPatched = false;
function patchCustomSelectProperties() {
if (customSelectPropertiesPatched) return;
customSelectPropertiesPatched = true;
['value', 'selectedIndex'].forEach(property => {
const descriptor = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, property);
if (!descriptor?.get || !descriptor?.set || descriptor.configurable === false) return;
try {
Object.defineProperty(HTMLSelectElement.prototype, property, {
configurable: descriptor.configurable,
enumerable: descriptor.enumerable,
get: descriptor.get,
set(nextValue) {
descriptor.set.call(this, nextValue);
queueMicrotask(() => refreshCustomSelect(this));
},
});
} catch (_) { }
});
}
function customSelectSelectedOption(select) {
return select.options?.[select.selectedIndex] || null;
}
function customSelectLabel(select) {
const explicit = select.getAttribute('aria-label');
if (explicit) return explicit;
const labelledBy = select.getAttribute('aria-labelledby');
if (labelledBy) {
const text = labelledBy.split(/\s+/).map(id => document.getElementById(id)?.textContent?.trim()).filter(Boolean).join(' ');
if (text) return text;
}
const label = select.closest('label');
const labelSpan = label?.querySelector(':scope > span');
return labelSpan?.textContent?.trim() || select.name || select.id || '';
}
function customSelectOptionRows(select) {
const rows = [];
[...select.children].forEach(child => {
if (child instanceof HTMLOptGroupElement) {
rows.push({ type: 'group', label: child.label });
[...child.children].forEach(option => {
if (option instanceof HTMLOptionElement) rows.push({ type: 'option', option, index: [...select.options].indexOf(option) });
});
} else if (child instanceof HTMLOptionElement) {
rows.push({ type: 'option', option: child, index: [...select.options].indexOf(child) });
}
});
return rows;
}
function positionCustomSelectMenu(state) {
if (!state?.open || !state.trigger?.isConnected || !state.menu?.isConnected) return;
const rect = state.trigger.getBoundingClientRect();
const margin = 8;
const gap = 6;
const toolbar = state.toolbar;
const viewportWidth = document.documentElement.clientWidth || window.innerWidth;
const viewportHeight = document.documentElement.clientHeight || window.innerHeight;
const width = Math.min(Math.max(rect.width, toolbar ? 210 : 180), Math.max(180, viewportWidth - margin * 2));
const below = Math.max(0, viewportHeight - rect.bottom - gap - margin);
const above = Math.max(0, rect.top - gap - margin);
state.menu.style.width = `${Math.round(width)}px`;
state.menu.style.maxHeight = '320px';
// Once the popover is visible, scrollHeight is the natural menu height.
// Use that height to choose the side and, especially, to place short menus
// directly above the trigger instead of at the top of a 320px allowance.
const naturalHeight = Math.min(320, Math.max(0, state.menu.scrollHeight || state.menu.getBoundingClientRect().height || 0));
const desiredHeight = naturalHeight || 180;
const useBelow = below >= desiredHeight || (below >= above && above < desiredHeight);
const available = Math.max(1, Math.min(320, useBelow ? below : above));
state.menu.style.maxHeight = `${Math.round(available)}px`;
const renderedHeight = naturalHeight ? Math.min(naturalHeight, available) : available;
const left = Math.min(Math.max(margin, rect.left), Math.max(margin, viewportWidth - width - margin));
const rawTop = useBelow ? rect.bottom + gap : rect.top - gap - renderedHeight;
const maxTop = Math.max(margin, viewportHeight - renderedHeight - margin);
const top = Math.min(Math.max(margin, rawTop), maxTop);
state.menu.style.left = `${Math.round(left)}px`;
state.menu.style.top = `${Math.round(top)}px`;
state.menu.dataset.placement = useBelow ? 'bottom' : 'top';
}
function rebuildCustomSelectMenu(select, state) {
const rows = customSelectOptionRows(select);
state.menu.replaceChildren();
if (!rows.length) {
const empty = document.createElement('div');
empty.className = 'custom-select-empty';
empty.textContent = '—';
state.menu.appendChild(empty);
return;
}
rows.forEach(row => {
if (row.type === 'group') {
const group = document.createElement('div');
group.className = 'custom-select-group';
group.textContent = row.label;
state.menu.appendChild(group);
return;
}
const { option, index } = row;
const button = document.createElement('button');
button.type = 'button';
button.className = 'custom-select-option';
button.dataset.index = String(index);
button.setAttribute('role', 'option');
button.setAttribute('aria-selected', option.selected ? 'true' : 'false');
button.disabled = option.disabled || option.parentElement?.disabled || select.disabled;
const text = document.createElement('span');
text.textContent = option.textContent || option.label || option.value || '—';
const check = document.createElement('b');
check.setAttribute('aria-hidden', 'true');
check.textContent = option.selected ? '✓' : '';
button.append(text, check);
button.addEventListener('click', event => {
event.preventDefault();
event.stopPropagation();
if (button.disabled) return;
const nextIndex = Number(button.dataset.index);
if (!Number.isInteger(nextIndex) || !select.options[nextIndex]) return;
const changed = select.selectedIndex !== nextIndex;
select.selectedIndex = nextIndex;
refreshCustomSelect(select);
closeCustomSelect();
if (changed) {
select.dispatchEvent(new Event('input', { bubbles: true }));
select.dispatchEvent(new Event('change', { bubbles: true }));
}
state.trigger.focus({ preventScroll: true });
});
state.menu.appendChild(button);
});
}
function refreshCustomSelect(select) {
const state = customSelectRegistry.get(select);
if (!state) return;
const selected = customSelectSelectedOption(select);
const text = selected?.textContent?.trim() || selected?.label || selected?.value || '—';
const label = customSelectLabel(select);
const disabled = !!select.disabled;
if (state.toolbar) {
state.trigger.classList.toggle('custom-select-disabled', disabled);
state.trigger.setAttribute('aria-disabled', disabled ? 'true' : 'false');
state.trigger.setAttribute('aria-label', label ? `${label}: ${text}` : text);
state.trigger.tabIndex = disabled ? -1 : 0;
} else {
state.value.textContent = text;
state.trigger.disabled = disabled;
state.trigger.setAttribute('aria-label', label ? `${label}: ${text}` : text);
state.wrapper.hidden = !!select.hidden;
}
if (state.open) {
rebuildCustomSelectMenu(select, state);
requestAnimationFrame(() => positionCustomSelectMenu(state));
}
}
function closeCustomSelect(state = customSelectOpenState) {
if (!state?.open) return;
state.open = false;
state.trigger.setAttribute('aria-expanded', 'false');
state.trigger.classList.remove('custom-select-open');
state.wrapper?.classList.remove('custom-select-open');
if (typeof state.menu.hidePopover === 'function') {
try {
if (state.menu.matches(':popover-open')) state.menu.hidePopover();
} catch (_) { }
}
state.menu.classList.remove('custom-select-menu-fallback-open');
state.menu.hidden = true;
if (customSelectOpenState === state) customSelectOpenState = null;
}
function openCustomSelect(select) {
const state = customSelectRegistry.get(select);
if (!state || select.disabled) return;
if (customSelectOpenState === state && state.open) {
closeCustomSelect(state);
return;
}
closeCustomSelect();
refreshCustomSelect(select);
rebuildCustomSelectMenu(select, state);
state.open = true;
customSelectOpenState = state;
state.trigger.setAttribute('aria-expanded', 'true');
state.trigger.classList.add('custom-select-open');
state.wrapper?.classList.add('custom-select-open');
state.menu.hidden = false;
positionCustomSelectMenu(state);
if (typeof state.menu.showPopover === 'function') {
try { state.menu.showPopover(); }
catch (_) { state.menu.classList.add('custom-select-menu-fallback-open'); }
} else {
state.menu.classList.add('custom-select-menu-fallback-open');
}
positionCustomSelectMenu(state);
requestAnimationFrame(() => {
positionCustomSelectMenu(state);
state.menu.querySelector('.custom-select-option[aria-selected="true"]')?.scrollIntoView({ block: 'nearest' });
});
}
function customSelectKeyboard(event, select) {
if (select.disabled) return;
const state = customSelectRegistry.get(select);
if (!state) return;
if (event.key === 'Enter' || event.key === ' ' || event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
if (!state.open) {
openCustomSelect(select);
return;
}
const enabled = [...state.menu.querySelectorAll('.custom-select-option:not(:disabled)')];
if (!enabled.length) return;
const active = document.activeElement;
const current = enabled.indexOf(active);
const delta = event.key === 'ArrowUp' ? -1 : 1;
enabled[(current + delta + enabled.length) % enabled.length].focus();
} else if (event.key === 'Escape' && state.open) {
event.preventDefault();
closeCustomSelect(state);
state.trigger.focus({ preventScroll: true });
} else if (event.key === 'Home' && state.open) {
event.preventDefault();
state.menu.querySelector('.custom-select-option:not(:disabled)')?.focus();
} else if (event.key === 'End' && state.open) {
event.preventDefault();
[...state.menu.querySelectorAll('.custom-select-option:not(:disabled)')].at(-1)?.focus();
}
}
function enhanceCustomSelect(select) {
if (!(select instanceof HTMLSelectElement) || customSelectRegistry.has(select) || select.multiple || select.size > 1 || select.dataset.nativeSelect === 'true') return;
const toolbarHost = select.classList.contains('toolbar-picker-select') ? select.closest('.toolbar-picker') : null;
const originalSelectState = {
tabIndex: select.getAttribute('tabindex'),
ariaHidden: select.getAttribute('aria-hidden'),
};
const originalToolbarState = toolbarHost ? {
role: toolbarHost.getAttribute('role'),
ariaHaspopup: toolbarHost.getAttribute('aria-haspopup'),
ariaControls: toolbarHost.getAttribute('aria-controls'),
ariaExpanded: toolbarHost.getAttribute('aria-expanded'),
ariaDisabled: toolbarHost.getAttribute('aria-disabled'),
} : null;
const menu = document.createElement('div');
const menuId = `customSelectMenu${++customSelectSequence}`;
menu.id = menuId;
menu.className = 'custom-select-menu';
menu.setAttribute('role', 'listbox');
menu.setAttribute('popover', 'manual');
menu.hidden = true;
document.body.appendChild(menu);
let wrapper = null;
let trigger = toolbarHost;
let value = null;
select.classList.add('select-native-proxy');
select.tabIndex = -1;
select.setAttribute('aria-hidden', 'true');
if (toolbarHost) {
toolbarHost.classList.add('custom-select-toolbar');
toolbarHost.setAttribute('role', 'button');
toolbarHost.setAttribute('aria-haspopup', 'listbox');
toolbarHost.setAttribute('aria-controls', menuId);
toolbarHost.setAttribute('aria-expanded', 'false');
} else {
wrapper = document.createElement('div');
wrapper.className = 'custom-select';
trigger = document.createElement('button');
trigger.type = 'button';
trigger.className = 'custom-select-trigger';
trigger.setAttribute('aria-haspopup', 'listbox');
trigger.setAttribute('aria-controls', menuId);
trigger.setAttribute('aria-expanded', 'false');
value = document.createElement('span');
value.className = 'custom-select-value';
const chevron = document.createElement('span');
chevron.className = 'custom-select-chevron';
chevron.setAttribute('aria-hidden', 'true');
chevron.textContent = '⌄';
trigger.append(value, chevron);
wrapper.appendChild(trigger);
select.insertAdjacentElement('afterend', wrapper);
}
const state = {
select,
wrapper,
trigger,
value,
menu,
toolbar: !!toolbarHost,
open: false,
originalSelectState,
originalToolbarState,
};
customSelectRegistry.set(select, state);
trigger.addEventListener('click', event => {
event.preventDefault();
event.stopPropagation();
openCustomSelect(select);
});
trigger.addEventListener('keydown', event => customSelectKeyboard(event, select));
menu.addEventListener('keydown', event => customSelectKeyboard(event, select));
// Clicking an implicit <label> may synthesize a click on the original select.
// Redirect that trusted interaction to the custom popup instead of opening the OS picker.
select.addEventListener('click', event => {
if (!event.isTrusted) return;
event.preventDefault();
event.stopPropagation();
openCustomSelect(select);
});
select.addEventListener('change', () => refreshCustomSelect(select));
select.addEventListener('input', () => refreshCustomSelect(select));
refreshCustomSelect(select);
}
function cleanupCustomSelect(select) {
const state = customSelectRegistry.get(select);
if (!state) return;
if (state.open) closeCustomSelect(state);
state.menu.remove();
state.wrapper?.remove();
select.classList.remove('select-native-proxy');
if (state.originalSelectState.tabIndex == null) select.removeAttribute('tabindex');
else select.setAttribute('tabindex', state.originalSelectState.tabIndex);
if (state.originalSelectState.ariaHidden == null) select.removeAttribute('aria-hidden');
else select.setAttribute('aria-hidden', state.originalSelectState.ariaHidden);
if (state.toolbar && state.trigger) {
state.trigger.classList.remove('custom-select-toolbar', 'custom-select-open', 'custom-select-disabled');
const restoreAttribute = (name, value) => value == null ? state.trigger.removeAttribute(name) : state.trigger.setAttribute(name, value);
restoreAttribute('role', state.originalToolbarState?.role);
restoreAttribute('aria-haspopup', state.originalToolbarState?.ariaHaspopup);
restoreAttribute('aria-controls', state.originalToolbarState?.ariaControls);
restoreAttribute('aria-expanded', state.originalToolbarState?.ariaExpanded);
restoreAttribute('aria-disabled', state.originalToolbarState?.ariaDisabled);
}
customSelectRegistry.delete(select);
}
function refreshCustomSelects(root = document) {
if (root instanceof HTMLSelectElement) refreshCustomSelect(root);
root.querySelectorAll?.('select').forEach(select => refreshCustomSelect(select));
}
function enhanceCustomSelects(root = document) {
if (root instanceof HTMLSelectElement) enhanceCustomSelect(root);
root.querySelectorAll?.('select').forEach(enhanceCustomSelect);
}
function initCustomSelects() {
patchCustomSelectProperties();
enhanceCustomSelects(document);
if (customSelectObserver) return;
customSelectObserver = new MutationObserver(records => {
const toRefresh = new Set();
records.forEach(record => {
record.addedNodes.forEach(node => {
if (node.nodeType !== Node.ELEMENT_NODE) return;
enhanceCustomSelects(node);
const select = node.closest?.('select');
if (select) toRefresh.add(select);
});
record.removedNodes.forEach(node => {
if (node.nodeType !== Node.ELEMENT_NODE) return;
if (node instanceof HTMLSelectElement && !node.isConnected) cleanupCustomSelect(node);
node.querySelectorAll?.('select').forEach(select => {
// A DOM move is reported as a removal followed by an addition. Keep
// the existing custom-select state when the select is still attached
// to the document; otherwise every move would leave an old wrapper
// behind and create another one on the next enhancement pass.
if (!select.isConnected) cleanupCustomSelect(select);
});
});
const targetElement = record.target.nodeType === Node.ELEMENT_NODE ? record.target : record.target.parentElement;
const select = targetElement?.closest?.('select');
if (select) toRefresh.add(select);
});
toRefresh.forEach(select => {
if (!select.isConnected) {
cleanupCustomSelect(select);
return;
}
if (!customSelectRegistry.has(select)) enhanceCustomSelect(select);
refreshCustomSelect(select);
});
});
customSelectObserver.observe(document.documentElement, {
childList: true,
subtree: true,
characterData: true,
attributes: true,
attributeFilter: ['disabled', 'hidden', 'selected', 'label', 'value', 'aria-label', 'aria-labelledby'],
});
document.addEventListener('pointerdown', event => {
const state = customSelectOpenState;
if (!state?.open) return;
if (state.menu.contains(event.target) || state.trigger.contains(event.target)) return;
closeCustomSelect(state);
}, true);
document.addEventListener('reset', event => {
requestAnimationFrame(() => refreshCustomSelects(event.target));
}, true);
document.addEventListener('invalid', event => {
const select = event.target;
if (!(select instanceof HTMLSelectElement)) return;
const state = customSelectRegistry.get(select);
if (!state) return;
requestAnimationFrame(() => state.trigger.focus({ preventScroll: true }));
}, true);
window.addEventListener('resize', () => positionCustomSelectMenu(customSelectOpenState));
document.addEventListener('scroll', event => {
const state = customSelectOpenState;
if (!state?.open || state.menu.contains(event.target)) return;
closeCustomSelect(state);
}, true);
}
initCustomSelects();