mirror of
https://github.com/Matysh/houseplan-card
synced 2026-09-29 03:09:36 +00:00
§7 SPEC.md референса. Пять карточек #598 остались, менялось содержимое; все ключи _markerDialog и все записи в них прежние (§7.2): - Basics — баннеры привязки стали callout'ами; Name с подсказкой «Shown on the plan»; привязка — сегмент [Virtual | From the HA list] (те же радио bmode) и кнопка выбора #marker-binding с панелью в потоке (sourcePicker набора), чекбокс «Show entities» — внутри панели рядом с поиском (решение владельца Q8); Room селектом с подсказкой «по зоне / переопределяет»; секции радара и пылесоса — своими модулями без изменений; - Tap action — селект с подсказкой Target/Now, «Ask for confirmation» — строка-тумблер только при toggle/run (Q8), Entity to toggle и What to run теми же условиями (список целей — панель набора), «Controls other light sources» — чипы набора и поиск с панелью в потоке; - Light and glow — «Include the device temperature…» строкой-тумблером; роль — сегмент [Auto | Always | Never] с подсказкой результата Auto; Leading light entity по условиям; блок свечения (.hpf-block): подзаголовок с «?», сегмент [From source | Set colour | Colour and brightness] с отключёнными вариантами и aria-describedby на объяснение, плашка цвета вокруг прежнего hp-color-opacity (Q5), яркость и радиус строками с числом и единицей, при Never блок неактивен целиком (aria-disabled) с callout'ом причины; - Appearance — поле иконки с превью, очисткой и ссылкой Pin в подсказке; Display селектом с подсказкой режима; пульс — плашка цвета и строка размера; Value source по условиям; подраздел Value badge — компактный тумблер, Value селектом с техническим идентификатором, Position сегментом [Above | Right | Below | Left]; предупреждения бейджа — заметки и callout'ы; Display preview — прежний hp-device-preview целиком в блоке на тинте с тегом Now (решение владельца Q3); «Icon size and rotation» — две строки range-line в сетке; - Details — Model и Link в ряд, Description textarea набора, Manuals чипами и строкой действий Attach…, «Additional actions» подзаголовком набора. Футер: Hide и Delete слева, статус, Cancel и Save справа. К10: снимок черновика при _openMarkerDialog (marker-form-state.ts поверх dialog-baseline; транзиентные ключи — раскрытие и фильтры списков, busy, объявление подсказки, autoIcon, uploadId); в edit Save только при изменениях, закрытие с изменениями спрашивает через _confirmDanger. Прежние запреты Save (busy, калибровка радара, привязка не выбрана/не подтверждена) остались; привязка и радиус свечения названы словами под полем (marker.error_binding, marker.error_glow_radius), «Review N fields» ведёт к полю. Тумблеры диалога — строки набора (нативный чекбокс, К7), а не ha-switch; слайдеры — прежний _rangeInput (ha-slider в HA). Набор: sourcePicker получил toolbar и disabled; сегмент — value у радио, disabled и describedBy у варианта; callout — role note и id; unitInput — describedBy; rangeLine — id; новые классы .hpf-block/.hpf-disabled, .hpf-toolbar/.hpf-check, .hpf-iconfield/.hpf-iconpreview, .hpf-mono, .hpf-note, .hpf-hint-line, textarea.hpf-input. settingsCopy вынесен в editors/settings-copy.ts (общий для пространства, комнаты, устройства). Смоки переписаны осознанно, с пометкой #600: binding_ui (#marker-binding, .hpf-panel, #marker-show-entities), tap_run (панель набора, #marker-tap- confirm), value_face_source (.hpf-cand.sel), static_icon (callout'ы), climate_temp (#marker-use-climate-temp), help_affordance (#marker-name, .hpf-block.hpf-disabled вместо fieldset[disabled]; второй Escape в грязном диалоге спрашивает — К10), size_angle_parity (сетка Appearance), color_picker_consumers (подписи полей), device_preview_parity (сегмент стороны), ha_controls (тумблеры набора — нативные чекбоксы по К7, ha-slider прежний). Golden-harness device — .hpf-field/.hpf-block, скроллер .content. Новый фокусный свидетель demo/smoke_device_settings_form.mjs: пять карточек без старой разметки, оболочка, привязка/панель/Show entities, Q8, сегменты и блок свечения, плашки, иконка, бейдж, превью на тинте, размеры, Details, цели 44, Save/dirty/вопрос при закрытии, create-режим, семь полос экранов. Мутанты: marker-save-enabled-without-changes, marker-discard-without-asking, marker-confirm-row-shown-for-do-nothing, marker-never-keeps-glow-block-live, marker-badge-position-forgets-touch; якоря same-binding-click-resets-source, state-callout-hidden-under-help, form-kit-segment-drops-radio-semantics переставлены на новую разметку. Контрактные тесты: color-picker (два поля набора вместо flex-строк), native-select-contract (сторона бейджа — сегмент), i18n dead-keys (34 → 38 подсказок), German=English (marker.name_label). Словарь i18n/settings: 21 ключ marker.* на четыре локали; в основном каталоге marker.name_label «Name», marker.size_label «Icon size and rotation», удалены мёртвые marker.room_override, marker.light_role_always/never. Фикстуры листа диалогов набора пересняты намеренно (панель — байт в байт, AC11). Бюджет: стартовый граф 290 489 (потолок 291 600 без изменений); ленивый редакторский 243 173 — потолок 240 100 → 243 900 с разбором в bundle-budget.mjs; старые стили диалога устройства снимаются в финале. Гейты: typecheck, build, bundle:sync (три копии байт в байт), npm test 2790+ pass по четырём частям, mutation-gate --check, 39 смоков диалога устройства + новый + три формы серий 1–3. Issue: #600 User-Visible: no
203 lines
9.3 KiB
JavaScript
203 lines
9.3 KiB
JavaScript
// Shared face parity for the same live light on the full plan, the marker
|
|
// editor preview and houseplan-space-card.
|
|
import { launch, checkAll, finish } from './serve.mjs';
|
|
|
|
const { page, browser } = await launch({ width: 1100, height: 900 }, 1);
|
|
const res = await page.evaluate(async () => {
|
|
const c = window.__card;
|
|
const sr = () => c.shadowRoot || c.renderRoot;
|
|
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
const face = (node) => {
|
|
if (!node) return null;
|
|
const semantic = ['on', 'open', 'alarm', 'unavail', 'valonly', 'activity-running', 'activity-event', 'activity-presence', 'activity-transition'];
|
|
return {
|
|
classes: semantic.filter((name) => node.classList.contains(name)),
|
|
icon: node.querySelector('.device-core > ha-icon')?.getAttribute('icon') || '',
|
|
value: node.querySelector('.valtext')?.textContent?.trim() || '',
|
|
badge: node.querySelector('.value-badge')?.textContent?.trim() || '',
|
|
badgePosition: [...(node.querySelector('.value-badge')?.classList || [])]
|
|
.find((name) => name.startsWith('pos-')) || '',
|
|
scale: node.style.getPropertyValue('--dev-scale'),
|
|
rippleScale: node.style.getPropertyValue('--ripple-scale'),
|
|
rippleColor: node.style.getPropertyValue('--ripple-color'),
|
|
pulse: [...(node.querySelector('.device-pulse')?.classList || [])]
|
|
.filter((name) => ['alarm', 'short', 'continuous', 'event', 'presence', 'transition', 'running'].includes(name)),
|
|
reducedMotionDot: !!node.querySelector('.activity-dot'),
|
|
};
|
|
};
|
|
|
|
c._setMode('view');
|
|
c.requestUpdate();
|
|
await c.updateComplete;
|
|
const planFace = face(sr().querySelector('.dev[data-id="d_light1"]'));
|
|
|
|
c._setMode('devices');
|
|
const device = c._devices.find((item) => item.id === 'd_light1');
|
|
c._openMarkerDialog(device);
|
|
await c.updateComplete;
|
|
const preview = sr().querySelector('hp-device-preview');
|
|
await preview?.updateComplete;
|
|
preview?.dispatchEvent(new PointerEvent('pointerover', {
|
|
pointerType: 'mouse', bubbles: true, composed: true,
|
|
}));
|
|
const previewHoverGatePropagates = c.hasAttribute('data-pointer-hover')
|
|
&& preview?.hasAttribute('data-pointer-hover');
|
|
const previewFace = face(preview?.renderRoot?.querySelector('.dev'));
|
|
const providerShown = /demo/i.test(preview?.renderRoot?.querySelector('.previewfacts')?.textContent || '');
|
|
|
|
// Dynamic option creation must not leave a freshly mounted native select on
|
|
// its first row when a different display/room/badge choice is persisted.
|
|
// Unmount the dialog first: replacing one open marker can leave old option
|
|
// nodes around and would miss the real first-open regression.
|
|
c._markerDialog = null;
|
|
await c.updateComplete;
|
|
const badgeDevice = c._devices.find((item) => item.id === 'd_temp');
|
|
c._openMarkerDialog({
|
|
...badgeDevice,
|
|
marker: {
|
|
...(badgeDevice.marker || {}),
|
|
display: 'value',
|
|
value_badge: {
|
|
enabled: true,
|
|
source: { kind: 'derived_lqi' },
|
|
position: 'left',
|
|
},
|
|
},
|
|
});
|
|
await c.updateComplete;
|
|
const displaySelect = sr().querySelector('#marker-display');
|
|
const roomSelect = sr().querySelector('#marker-room');
|
|
const badgeSourceSelect = sr().querySelector('#marker-value-badge-source');
|
|
// #600: сторона бейджа — сегмент набора (радио marker-value-badge-position), не select
|
|
const badgePositionSelect = (() => {
|
|
const checked = sr().querySelector('input[name="marker-value-badge-position"]:checked');
|
|
return checked ? { value: checked.value, selectedOptions: [{ value: checked.value }] } : null;
|
|
})();
|
|
const savedBadgePreview = sr().querySelector('hp-device-preview');
|
|
await savedBadgePreview?.updateComplete;
|
|
const savedDisplaySelected = displaySelect?.value === 'value'
|
|
&& displaySelect?.selectedOptions?.[0]?.value === 'value';
|
|
const expectedRoom = c._markerDialog?.room || '';
|
|
const savedRoomSelected = expectedRoom !== '' && roomSelect?.value === expectedRoom
|
|
&& roomSelect?.selectedOptions?.[0]?.value === expectedRoom;
|
|
const savedBadgeSourceSelected = badgeSourceSelect?.value === 'derived:lqi'
|
|
&& badgeSourceSelect?.selectedOptions?.[0]?.value === 'derived:lqi';
|
|
const savedBadgePositionSelected = badgePositionSelect?.value === 'left'
|
|
&& badgePositionSelect?.selectedOptions?.[0]?.value === 'left';
|
|
const savedBadgePreviewMatches = savedBadgePreview?.renderRoot
|
|
?.querySelector('.value-badge')?.textContent?.trim() === '154';
|
|
const savedBadgeUntouched = c._markerDialog?.valueBadgeTouched === false;
|
|
|
|
// Issue #90: every explicit anchor, including a long value and the largest
|
|
// activity ring, stays inside the preview safe area with a real measured gap.
|
|
c.hass.states['sensor.hp_preview_long'] = {
|
|
entity_id: 'sensor.hp_preview_long', state: '12345678901234567890', attributes: {},
|
|
};
|
|
let badgeBounds = true;
|
|
for (const position of ['right', 'bottom', 'left', 'top']) {
|
|
c._markerDialog = {
|
|
...c._markerDialog,
|
|
display: 'icon_ripple', rippleSize: 8,
|
|
valueBadgeEnabled: true, valueBadgeTouched: true,
|
|
valueBadgeSource: { kind: 'entity_state', entity_id: 'sensor.hp_preview_long' },
|
|
valueBadgePosition: position,
|
|
};
|
|
c.requestUpdate();
|
|
await c.updateComplete;
|
|
const currentPreview = sr().querySelector('hp-device-preview');
|
|
await currentPreview?.updateComplete;
|
|
const stage = currentPreview?.renderRoot?.querySelector('.previewstage')?.getBoundingClientRect();
|
|
const badge = currentPreview?.renderRoot?.querySelector('.value-badge')?.getBoundingClientRect();
|
|
const gap = 3;
|
|
badgeBounds &&= !!stage && !!badge
|
|
&& badge.left >= stage.left + gap && badge.right <= stage.right - gap
|
|
&& badge.top >= stage.top + gap && badge.bottom <= stage.bottom - gap;
|
|
}
|
|
|
|
// One persisted bottom badge is then projected through all three renderers.
|
|
// It intentionally coexists with LQI to guard the vertical stack contract.
|
|
const persistedBadge = {
|
|
id: 'd_temp', binding: 'device:d_temp',
|
|
value_badge: {
|
|
enabled: true,
|
|
source: { kind: 'entity_state', entity_id: 'sensor.living_temp' },
|
|
position: 'bottom',
|
|
},
|
|
};
|
|
c._serverCfg.markers = [
|
|
...(c._serverCfg.markers || []).filter((marker) => marker.id !== 'd_temp'),
|
|
persistedBadge,
|
|
];
|
|
c._regSignature = '';
|
|
c._maybeRebuildDevices();
|
|
c._setMode('view');
|
|
c.requestUpdate();
|
|
await c.updateComplete;
|
|
const planBadgeNode = sr().querySelector('.dev[data-id="d_temp"]');
|
|
const planBadgeFace = face(planBadgeNode);
|
|
const planBadgeRect = planBadgeNode?.querySelector('.value-badge')?.getBoundingClientRect();
|
|
const planLqiRect = planBadgeNode?.querySelector('.lqi')?.getBoundingClientRect();
|
|
const bottomBadgeLqiStacked = !!planBadgeRect && !!planLqiRect
|
|
&& planLqiRect.top >= planBadgeRect.bottom - 1;
|
|
|
|
c._openMarkerDialog(c._devices.find((item) => item.id === 'd_temp'));
|
|
await c.updateComplete;
|
|
const persistedPreview = sr().querySelector('hp-device-preview');
|
|
await persistedPreview?.updateComplete;
|
|
const persistedPreviewFace = face(persistedPreview?.renderRoot?.querySelector('.dev'));
|
|
|
|
await customElements.whenDefined('houseplan-space-card');
|
|
const card = document.createElement('houseplan-space-card');
|
|
card.setConfig({ type: 'custom:houseplan-space-card', space: 'f1' });
|
|
// A real static card reads the latest complete server/cache snapshot. Inject
|
|
// that same revision explicitly here so this smoke compares renderers, not
|
|
// the demo server's intentionally non-persistent websocket fixture.
|
|
card._snap = {
|
|
config: structuredClone(c._serverCfg),
|
|
rev: c._cfgRev,
|
|
configFingerprint: `fixture-${c._cfgRev}`,
|
|
layout: structuredClone(c._layout),
|
|
layoutRev: c._layoutRev,
|
|
layoutFingerprint: `fixture-${c._layoutRev}`,
|
|
};
|
|
card._loadedOnce = true;
|
|
card.hass = c.hass;
|
|
document.body.appendChild(card);
|
|
const started = Date.now();
|
|
while (!card.renderRoot?.querySelector('.hp-static-stage') && Date.now() - started < 6000) await wait(60);
|
|
await card.updateComplete;
|
|
const staticNode = card.renderRoot.querySelector('.dev[data-id="d_light1"]');
|
|
const staticFace = face(staticNode);
|
|
const staticBadgeFace = face(card.renderRoot.querySelector('.dev[data-id="d_temp"]'));
|
|
const resolvedBaseContract = [
|
|
sr().querySelector('.dev[data-id="d_light1"]'),
|
|
persistedPreview?.renderRoot?.querySelector('.dev'),
|
|
staticNode,
|
|
].every((node) => node
|
|
&& getComputedStyle(node).getPropertyValue('--device-visual-factor').trim() === ''
|
|
&& parseFloat(getComputedStyle(node).getPropertyValue('--device-base-size')) > 0);
|
|
|
|
return {
|
|
allFacesPresent: !!planFace && !!previewFace && !!staticFace,
|
|
previewHoverGatePropagates,
|
|
planPreviewEqual: JSON.stringify(planFace) === JSON.stringify(previewFace),
|
|
planStaticEqual: JSON.stringify(planFace) === JSON.stringify(staticFace),
|
|
providerShown,
|
|
savedDisplaySelected,
|
|
savedRoomSelected,
|
|
savedBadgeSourceSelected,
|
|
savedBadgePositionSelected,
|
|
savedBadgePreviewMatches,
|
|
savedBadgeUntouched,
|
|
badgeBounds,
|
|
valueBadgePlanPreviewParity: JSON.stringify(planBadgeFace) === JSON.stringify(persistedPreviewFace),
|
|
valueBadgePlanStaticParity: JSON.stringify(planBadgeFace) === JSON.stringify(staticBadgeFace),
|
|
resolvedBaseContract,
|
|
bottomBadgeLqiStacked,
|
|
staticBindingHook: staticNode?.getAttribute('data-binding-status') === 'active',
|
|
};
|
|
});
|
|
|
|
checkAll(res);
|
|
await finish(browser, res);
|