diff --git a/.claude/hooks/block-docs-raster.sh b/.claude/hooks/block-docs-raster.sh new file mode 100755 index 0000000..f12ace1 --- /dev/null +++ b/.claude/hooks/block-docs-raster.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# Claude Code PreToolUse hook: deny Bash git add/commit/rm/mv of marketing PNG/GIF/JPEG +# under assets/ or docs/assets/. Twin of .cursor/hooks/block-docs-raster.sh. +set -euo pipefail + +input=$(cat) +command=$( + printf '%s' "$input" | python3 -c ' +import json, sys +try: + data = json.load(sys.stdin) +except Exception: + print("") + raise SystemExit(0) +# PreToolUse payload: tool_input.command for Bash +tool_input = data.get("tool_input") or {} +print(tool_input.get("command") or data.get("command") or "") +' 2>/dev/null || true +) + +# Fail open if we cannot parse +if [[ -z "$command" ]]; then + exit 0 +fi + +deny() { + local reason="$1" + python3 -c " +import json +print(json.dumps({ + 'hookSpecificOutput': { + 'hookEventName': 'PreToolUse', + 'permissionDecision': 'deny', + 'permissionDecisionReason': '''$reason''' + } +})) +" + exit 0 +} + +# Only care about git staging/commit-ish commands +if ! printf '%s' "$command" | grep -Eq '(^|[[:space:];|&])git[[:space:]]+(add|commit|rm|mv)\b'; then + exit 0 +fi + +# Look for raster paths under marketing dirs in the command string +if printf '%s' "$command" | grep -Eqi '(^|[[:space:]=])((\.\/)?(assets|docs\/assets)\/[^[:space:]]+\.(png|gif|jpe?g))\b'; then + deny 'Marketing docs images must be WebP. Do not commit PNG/GIF/JPEG under assets/ or docs/assets/. Run ./scripts/convert-docs-images.sh (convert-docs-images skill), update refs, then stage .webp files.' +fi + +# Catch git commit when staged index already has marketing rasters +if printf '%s' "$command" | grep -Eq 'git[[:space:]]+commit\b'; then + if command -v git >/dev/null 2>&1 && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then + staged=$(git diff --cached --name-only --diff-filter=ACMR 2>/dev/null || true) + if printf '%s\n' "$staged" | grep -Eqi '^(assets|docs/assets)/.+\.(png|gif|jpe?g)$'; then + deny 'Staged PNG/GIF/JPEG under assets/ or docs/assets/. Unstage them, run ./scripts/convert-docs-images.sh, stage .webp files, then commit.' + fi + fi +fi + +exit 0 diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..093d647 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-docs-raster.sh" + } + ] + } + ] + } +} diff --git a/.claude/skills/convert-docs-images/SKILL.md b/.claude/skills/convert-docs-images/SKILL.md new file mode 100644 index 0000000..a135cc2 --- /dev/null +++ b/.claude/skills/convert-docs-images/SKILL.md @@ -0,0 +1,52 @@ +--- +name: convert-docs-images +description: >- + Convert marketing/docs PNG/JPG/GIF under assets/ or docs/assets/ to WebP, + rewrite markdown/yml/html refs, and remove originals. Use when adding or + updating README/docs screenshots, or when a hook blocked a png/gif commit. +--- + +# Convert docs images to WebP + +Cross-agent policy also lives in root [`AGENTS.md`](../../../AGENTS.md) (Claude Code + Cursor). This skill is mirrored under `.claude/skills/convert-docs-images/` and `.cursor/skills/convert-docs-images/`. + +Enforcement hooks (block committing PNG/GIF under marketing asset dirs): +- Cursor: `.cursor/hooks.json` + `.cursor/hooks/block-docs-raster.sh` +- Claude Code: `.claude/settings.json` + `.claude/hooks/block-docs-raster.sh` + +## When to use + +- Adding or replacing screenshots in `assets/` or `docs/assets/` +- A Cursor hook blocked `git add`/`git commit` of `.png`/`.gif` under those dirs +- Migrating leftover rasters after a docs update + +## Do not convert + +- Runtime card art under `src/assets/` (e.g. Whisker AVIF litter robots) +- `coverage/`, `test-results/`, `node_modules/`, `dist/` + +## Steps + +1. Prefer writing new screenshots as `.webp` directly when the capture tool allows it. +2. If you only have PNG/JPG/GIF, put them under `assets/` or `docs/assets/`, then run from the **repo root**: + +```bash +./scripts/convert-docs-images.sh +``` + +Dry-run: + +```bash +./scripts/convert-docs-images.sh --dry-run +``` + +3. Requires `cwebp` and `gif2webp` (`brew install webp`). +4. Confirm refs in `README.md`, `docs/**`, and `mkdocs.yml` point at `.webp`. +5. Do not leave the original `.png`/`.gif` in the tree under marketing asset dirs. + +## Defaults + +| Source | Encoder | Flags | +|--------|---------|-------| +| PNG/JPG | `cwebp` | `-near_lossless 40 -metadata icc -m 6` | +| GIF | `gif2webp` | `-q 80 -m 4 -mt -mixed` (animated WebP) | diff --git a/.cursor/hooks.json b/.cursor/hooks.json new file mode 100644 index 0000000..e2e14ed --- /dev/null +++ b/.cursor/hooks.json @@ -0,0 +1,12 @@ +{ + "version": 1, + "hooks": { + "beforeShellExecution": [ + { + "command": ".cursor/hooks/block-docs-raster.sh", + "matcher": "git\\s+(add|commit|rm|mv)", + "failClosed": false + } + ] + } +} diff --git a/.cursor/hooks/block-docs-raster.sh b/.cursor/hooks/block-docs-raster.sh new file mode 100755 index 0000000..5292242 --- /dev/null +++ b/.cursor/hooks/block-docs-raster.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Deny git add/commit/rm/mv that stages marketing PNG/GIF/JPEG under assets/ or docs/assets/. +set -euo pipefail + +input=$(cat) +command=$(printf '%s' "$input" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("command",""))' 2>/dev/null || true) + +# Fail open if we cannot parse +if [[ -z "$command" ]]; then + echo '{ "permission": "allow" }' + exit 0 +fi + +# Only care about git staging/commit-ish commands +if ! printf '%s' "$command" | grep -Eq '(^|[[:space:];|&])git[[:space:]]+(add|commit|rm|mv)\b'; then + echo '{ "permission": "allow" }' + exit 0 +fi + +# Look for raster paths under marketing dirs in the command string +if printf '%s' "$command" | grep -Eqi '(^|[[:space:]=])((\.\/)?(assets|docs\/assets)\/[^[:space:]]+\.(png|gif|jpe?g))\b'; then + python3 - <<'PY' +import json +print(json.dumps({ + "permission": "deny", + "user_message": "Blocked: do not commit PNG/GIF/JPEG under assets/ or docs/assets/. Convert with ./scripts/convert-docs-images.sh (convert-docs-images skill) and use .webp.", + "agent_message": "Marketing docs images must be WebP. Run ./scripts/convert-docs-images.sh (see convert-docs-images skill), update refs, then stage the .webp files instead." +})) +PY + exit 0 +fi + +# Also catch bare globs like `git add assets/` when staged index would include rasters — best-effort via git status if available +if printf '%s' "$command" | grep -Eq 'git[[:space:]]+commit\b'; then + if command -v git >/dev/null 2>&1 && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then + staged=$(git diff --cached --name-only --diff-filter=ACMR 2>/dev/null || true) + if printf '%s\n' "$staged" | grep -Eqi '^(assets|docs/assets)/.+\.(png|gif|jpe?g)$'; then + python3 - <<'PY' +import json +print(json.dumps({ + "permission": "deny", + "user_message": "Blocked: staged PNG/GIF/JPEG under assets/ or docs/assets/. Convert with ./scripts/convert-docs-images.sh first.", + "agent_message": "Staged marketing rasters found. Unstage them, run ./scripts/convert-docs-images.sh, stage .webp files, then commit." +})) +PY + exit 0 + fi + fi +fi + +echo '{ "permission": "allow" }' +exit 0 diff --git a/.cursor/rules/docs-images-webp.mdc b/.cursor/rules/docs-images-webp.mdc new file mode 100644 index 0000000..956384d --- /dev/null +++ b/.cursor/rules/docs-images-webp.mdc @@ -0,0 +1,13 @@ +--- +description: Marketing/docs images must be WebP; never commit PNG/GIF under assets or docs/assets +alwaysApply: true +--- + +# Docs images must be WebP + +Marketing and documentation screenshots live under `assets/` and `docs/assets/`. + +- Store new docs/marketing images as **`.webp` only** (animated WebP for former GIFs). +- Do **not** add or commit `.png`, `.jpg`, `.jpeg`, or `.gif` under `assets/` or `docs/assets/`. +- When replacing an existing raster, convert with `scripts/convert-docs-images.sh` (see the `convert-docs-images` skill) and update all markdown/yml/html refs. +- **Exempt:** runtime card art under `src/assets/` (e.g. Whisker AVIF litter robots) and generated junk (`coverage/`, `test-results/`, `node_modules/`, `dist/`). diff --git a/.cursor/skills/convert-docs-images/SKILL.md b/.cursor/skills/convert-docs-images/SKILL.md new file mode 100644 index 0000000..2ae7a66 --- /dev/null +++ b/.cursor/skills/convert-docs-images/SKILL.md @@ -0,0 +1,53 @@ +--- +name: convert-docs-images +description: >- + Convert marketing/docs PNG/JPG/GIF under assets/ or docs/assets/ to WebP, + rewrite markdown/yml/html refs, and remove originals. Use when adding or + updating README/docs screenshots, or when a hook blocked a png/gif commit. +--- + +# Convert docs images to WebP + +Cross-agent policy also lives in root [`AGENTS.md`](../../../AGENTS.md) (Claude Code + Cursor). This skill is mirrored under `.claude/skills/convert-docs-images/` and `.cursor/skills/convert-docs-images/`. + +Enforcement hooks (block committing PNG/GIF under marketing asset dirs): + +- Cursor: `.cursor/hooks.json` + `.cursor/hooks/block-docs-raster.sh` +- Claude Code: `.claude/settings.json` + `.claude/hooks/block-docs-raster.sh` + +## When to use + +- Adding or replacing screenshots in `assets/` or `docs/assets/` +- A Cursor hook blocked `git add`/`git commit` of `.png`/`.gif` under those dirs +- Migrating leftover rasters after a docs update + +## Do not convert + +- Runtime card art under `src/assets/` (e.g. Whisker AVIF litter robots) +- `coverage/`, `test-results/`, `node_modules/`, `dist/` + +## Steps + +1. Prefer writing new screenshots as `.webp` directly when the capture tool allows it. +2. If you only have PNG/JPG/GIF, put them under `assets/` or `docs/assets/`, then run from the **repo root**: + +```bash +./scripts/convert-docs-images.sh +``` + +Dry-run: + +```bash +./scripts/convert-docs-images.sh --dry-run +``` + +3. Requires `cwebp` and `gif2webp` (`brew install webp`). +4. Confirm refs in `README.md`, `docs/**`, and `mkdocs.yml` point at `.webp`. +5. Do not leave the original `.png`/`.gif` in the tree under marketing asset dirs. + +## Defaults + +| Source | Encoder | Flags | +| ------- | ---------- | --------------------------------------- | +| PNG/JPG | `cwebp` | `-q 90 -m 6` | +| GIF | `gif2webp` | `-q 80 -m 4 -mt -mixed` (animated WebP) | diff --git a/.gitignore b/.gitignore index 1416e2c..47e925c 100644 --- a/.gitignore +++ b/.gitignore @@ -23,6 +23,18 @@ !examples/** !yarn.lock +!scripts/ +!scripts/** +!*.sh +!*.mdc +!.cursor/hooks.json +!.cursor/rules/** +!.cursor/skills/** +!.cursor/hooks/** +!.claude/skills/** + +!.claude/hooks/** +!.claude/settings.json # Ignore folders. node_modules dist diff --git a/.mocharc.json b/.mocharc.json index 0d5e10a..8ee212a 100644 --- a/.mocharc.json +++ b/.mocharc.json @@ -2,7 +2,8 @@ "require": [ "ts-node/register", "tsconfig-paths/register", - "@homeassistant-extras/config/mocha/setup.card" + "@homeassistant-extras/config/mocha/setup.card", + "./test/setup.ts" ], "extensions": ["ts"], "spec": ["test/**/*.spec.ts"], diff --git a/AGENTS.md b/AGENTS.md index 0059d7c..63fef90 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,3 +7,9 @@ Run `yarn pass` (format + typecheck + lint + test) before shipping changes. Use ## Scoped Guidance Read the nearest `AGENTS.md` before changing files in a subdirectory. Scoped files exist under `test/`, `src/cards/`, `src/common/`, `src/config/`, `src/delegates/`, `src/hass/`, `src/helpers/`, `src/html/`, `src/localize/`, `src/translations/`, and `src/types/`. + +## Docs images (WebP) + +Marketing/docs screenshots live under `assets/` and `docs/assets/`. Store them as **`.webp` only** (animated WebP for former GIFs). Do not add `.png` / `.gif` / `.jpg` there. Runtime card art under `src/assets/` is exempt (e.g. Whisker AVIF). + +If you only have a PNG/GIF, run `./scripts/convert-docs-images.sh` from the repo root (needs `cwebp` / `gif2webp` from `brew install webp`). See `.claude/skills/convert-docs-images/SKILL.md` and `.cursor/skills/convert-docs-images/SKILL.md`. diff --git a/README.md b/README.md index a09b677..e466d91 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ _A comprehensive card to display and organize your Home Assistant device entities_ -![Device Card](docs/assets/cards.png) +![Device Card](docs/assets/cards.webp) ![Home Assistant](https://img.shields.io/badge/home%20assistant-%2341BDF5.svg?style=for-the-badge&logo=home-assistant&logoColor=white) [![hacs_badge](https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge)](https://github.com/hacs/integration) @@ -50,6 +50,8 @@ integration: zwave_js ## Installation +Requires Home Assistant **2026.11.0** or newer. + ### HACS (Recommended) [![HACS](https://my.home-assistant.io/badges/hacs_repository.svg)](https://my.home-assistant.io/redirect/hacs_repository/?owner=homeassistant-extras&repository=device-card&category=dashboard) diff --git a/docs/assets/attributes.png b/docs/assets/attributes.png deleted file mode 100644 index b4f67bc..0000000 Binary files a/docs/assets/attributes.png and /dev/null differ diff --git a/docs/assets/attributes.webp b/docs/assets/attributes.webp new file mode 100644 index 0000000..b560e4b Binary files /dev/null and b/docs/assets/attributes.webp differ diff --git a/docs/assets/cards.png b/docs/assets/cards.png deleted file mode 100644 index 98b1eb6..0000000 Binary files a/docs/assets/cards.png and /dev/null differ diff --git a/docs/assets/cards.webp b/docs/assets/cards.webp new file mode 100644 index 0000000..7831b85 Binary files /dev/null and b/docs/assets/cards.webp differ diff --git a/docs/assets/collapsible-card.png b/docs/assets/collapsible-card.png deleted file mode 100644 index 8774c53..0000000 Binary files a/docs/assets/collapsible-card.png and /dev/null differ diff --git a/docs/assets/collapsible-card.webp b/docs/assets/collapsible-card.webp new file mode 100644 index 0000000..f843b76 Binary files /dev/null and b/docs/assets/collapsible-card.webp differ diff --git a/docs/assets/compact-mode.png b/docs/assets/compact-mode.png deleted file mode 100644 index 3352b31..0000000 Binary files a/docs/assets/compact-mode.png and /dev/null differ diff --git a/docs/assets/compact-mode.webp b/docs/assets/compact-mode.webp new file mode 100644 index 0000000..3167795 Binary files /dev/null and b/docs/assets/compact-mode.webp differ diff --git a/docs/assets/editor.png b/docs/assets/editor.png deleted file mode 100644 index 88275a7..0000000 Binary files a/docs/assets/editor.png and /dev/null differ diff --git a/docs/assets/editor.webp b/docs/assets/editor.webp new file mode 100644 index 0000000..17853b4 Binary files /dev/null and b/docs/assets/editor.webp differ diff --git a/docs/assets/expanded.png b/docs/assets/expanded.png deleted file mode 100644 index 04ab534..0000000 Binary files a/docs/assets/expanded.png and /dev/null differ diff --git a/docs/assets/expanded.webp b/docs/assets/expanded.webp new file mode 100644 index 0000000..65152bf Binary files /dev/null and b/docs/assets/expanded.webp differ diff --git a/docs/assets/icon.png b/docs/assets/icon.png deleted file mode 100644 index aeda013..0000000 Binary files a/docs/assets/icon.png and /dev/null differ diff --git a/docs/assets/icon.webp b/docs/assets/icon.webp new file mode 100644 index 0000000..5de5e04 Binary files /dev/null and b/docs/assets/icon.webp differ diff --git a/docs/assets/integration-card.png b/docs/assets/integration-card.png deleted file mode 100644 index cae9aa9..0000000 Binary files a/docs/assets/integration-card.png and /dev/null differ diff --git a/docs/assets/integration-card.webp b/docs/assets/integration-card.webp new file mode 100644 index 0000000..8a77f2a Binary files /dev/null and b/docs/assets/integration-card.webp differ diff --git a/docs/assets/integration-picker.png b/docs/assets/integration-picker.png deleted file mode 100644 index f9160ab..0000000 Binary files a/docs/assets/integration-picker.png and /dev/null differ diff --git a/docs/assets/integration-picker.webp b/docs/assets/integration-picker.webp new file mode 100644 index 0000000..7ed82fc Binary files /dev/null and b/docs/assets/integration-picker.webp differ diff --git a/docs/assets/percent-colors.png b/docs/assets/percent-colors.png deleted file mode 100644 index 07b82bb..0000000 Binary files a/docs/assets/percent-colors.png and /dev/null differ diff --git a/docs/assets/percent-colors.webp b/docs/assets/percent-colors.webp new file mode 100644 index 0000000..84df638 Binary files /dev/null and b/docs/assets/percent-colors.webp differ diff --git a/docs/assets/percent-gauges.png b/docs/assets/percent-gauges.png deleted file mode 100644 index f3464b8..0000000 Binary files a/docs/assets/percent-gauges.png and /dev/null differ diff --git a/docs/assets/percent-gauges.webp b/docs/assets/percent-gauges.webp new file mode 100644 index 0000000..6975146 Binary files /dev/null and b/docs/assets/percent-gauges.webp differ diff --git a/docs/assets/pinned-entity-state.png b/docs/assets/pinned-entity-state.png deleted file mode 100644 index a1bb81e..0000000 Binary files a/docs/assets/pinned-entity-state.png and /dev/null differ diff --git a/docs/assets/pinned-entity-state.webp b/docs/assets/pinned-entity-state.webp new file mode 100644 index 0000000..6ca010d Binary files /dev/null and b/docs/assets/pinned-entity-state.webp differ diff --git a/docs/assets/portraits.png b/docs/assets/portraits.png deleted file mode 100644 index c1ef73e..0000000 Binary files a/docs/assets/portraits.png and /dev/null differ diff --git a/docs/assets/portraits.webp b/docs/assets/portraits.webp new file mode 100644 index 0000000..44887be Binary files /dev/null and b/docs/assets/portraits.webp differ diff --git a/docs/assets/problems.png b/docs/assets/problems.png deleted file mode 100644 index 3ba4790..0000000 Binary files a/docs/assets/problems.png and /dev/null differ diff --git a/docs/assets/problems.webp b/docs/assets/problems.webp new file mode 100644 index 0000000..ed3bb2e Binary files /dev/null and b/docs/assets/problems.webp differ diff --git a/docs/device-card/index.md b/docs/device-card/index.md index 87a127f..38e6de2 100644 --- a/docs/device-card/index.md +++ b/docs/device-card/index.md @@ -2,7 +2,7 @@ A custom card for Home Assistant that provides a comprehensive overview of any device in your system. The card organizes device information into expandable sections, displaying sensors, controls, configuration options, and diagnostic data in a clean, user-friendly interface. -![Device sections](../assets/cards.png) +![Device sections](../assets/cards.webp) ## Features @@ -21,13 +21,13 @@ A custom card for Home Assistant that provides a comprehensive overview of any d - Visual indication when problems are detected (card border turns red) - Problem entities show a green or red indicator to their left -![Problem detection](../assets/problems.png) +![Problem detection](../assets/problems.webp) ### Entity Pictures With an optional flag, you can showcase entity pictures when available. There must exist an entity with an `entity_picture` attribute. -![Entity pictures](../assets/portraits.png) +![Entity pictures](../assets/portraits.webp) ### Expandable Sections @@ -35,7 +35,7 @@ With an optional flag, you can showcase entity pictures when available. There mu - Preview counts for sensors to reduce visual clutter - Ability to expand sections to see all entities -![Expanded](../assets/expanded.png) +![Expanded](../assets/expanded.webp) ### Entity Attributes @@ -44,41 +44,45 @@ With an optional flag, you can showcase entity pictures when available. There mu - Click anywhere in the expanded attribute list to open Home Assistant's [more-info dialog](https://www.home-assistant.io/dashboards/more-info-dialog/) for that entity - This behavior can be disabled by setting `tap_action` to "none" -![Attributes](../assets/attributes.png) +![Attributes](../assets/attributes.webp) ### Pinned Entity State Display a specific entity's state prominently in the card header, providing instant visibility for your most important information. Perfect for temperature sensors, battery levels, or any critical value you want to monitor at a glance. -![Pinned entity state](../assets/pinned-entity-state.png) +![Pinned entity state](../assets/pinned-entity-state.webp) ### Heading Icon An icon appears next to the card heading. When `entity_id` or `entity` is configured, the entity's icon is shown (reflecting its current state). You can also set a custom `icon` in the config (e.g. `mdi:thermometer`) to override the entity icon or display an icon when no entity is configured. Use the `hide_icon` feature flag to hide the icon if you prefer a cleaner look. -![Icon](../assets/icon.png) +![Icon](../assets/icon.webp) + +### Device Page Shortcut + +Long-press (hold) the card header to open the device's page in Home Assistant settings (**Settings → Devices & services → Devices**). A normal tap still collapses or expands the card. Requires Home Assistant 2026.11 or newer. ### Percent Gauges Visual percentage indicators for entities with percentage values. Gauges automatically change color based on the value (red for low, yellow for medium, green for high). -![Percent gauges](../assets/percent-gauges.png) +![Percent gauges](../assets/percent-gauges.webp) Don't want the red / yellow / green scale for every entity? `percent_colors` lets you pick a single color or your own thresholds per entity or pattern. Below, all three values are 45%: the top bar uses the default scale, humidity uses custom comfort bands, and disk usage uses a solid theme color. See [Percent Bar Colors](configuration.md#percent-bar-colors). -![Custom percent colors](../assets/percent-colors.png) +![Custom percent colors](../assets/percent-colors.webp) ### Collapsible Card Cards can be configured to start in a collapsed state. Simply click the header to expand and reveal all sections. -![Collapsible card](../assets/collapsible-card.png) +![Collapsible card](../assets/collapsible-card.webp) ### Compact Mode A space-efficient layout option that reduces padding and margins, ideal for information-dense dashboards or smaller screens. -![Compact mode](../assets/compact-mode.png) +![Compact mode](../assets/compact-mode.webp) ### Advanced Sorting @@ -102,7 +106,7 @@ The card is fully configurable in the UI editor. Simply select "Custom: Device C !!! caution The editor may delete advanced settings, such as regex or wildcards. Make a copy of the card config prior to using the UI editor. -![Editor](../assets/editor.png) +![Editor](../assets/editor.webp) ## Quick Start diff --git a/docs/index.md b/docs/index.md index b4a34f1..cee60a5 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,5 +1,5 @@

- +

Device Card

diff --git a/docs/installation.md b/docs/installation.md index 3c3e6a0..7bad476 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -1,5 +1,7 @@ # Installation +Requires Home Assistant **2026.11.0** or newer. + ## HACS (Recommended) 1. Open HACS in your Home Assistant instance diff --git a/docs/integration-card/index.md b/docs/integration-card/index.md index a9e3b5a..30c3aad 100644 --- a/docs/integration-card/index.md +++ b/docs/integration-card/index.md @@ -6,7 +6,7 @@ The Integration Card automatically finds and displays all devices from a selecte - Creating dedicated dashboards for specific systems in your home - Monitoring the status of all devices in an integration at once -![Integration picker](../assets/integration-picker.png) +![Integration picker](../assets/integration-picker.webp) ## Quick Start diff --git a/hacs.json b/hacs.json index f79848b..743a864 100644 --- a/hacs.json +++ b/hacs.json @@ -1,4 +1,5 @@ { "name": "Device Card", - "render_readme": true + "render_readme": true, + "homeassistant": "2026.11.0" } diff --git a/mkdocs.yml b/mkdocs.yml index e2d344b..2b50988 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -47,8 +47,8 @@ theme: - content.code.copy icon: repo: fontawesome/brands/github - logo: assets/cards.png - favicon: assets/cards.png + logo: assets/cards.webp + favicon: assets/cards.webp plugins: - search diff --git a/package.json b/package.json index 5bf1fcb..1744a25 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "device-card", - "version": "1.2.0", + "version": "2.0.0", "author": { "name": "Patrick Masters", "url": "https://curiouscat.consulting/projects/ha-device-card?utm_source=github-device-card&utm_medium=package-metadata&utm_campaign=oss-presence&utm_content=author-url" diff --git a/scripts/convert-docs-images.sh b/scripts/convert-docs-images.sh new file mode 100755 index 0000000..a121729 --- /dev/null +++ b/scripts/convert-docs-images.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# Convert marketing/docs PNG/JPG/GIF under assets/ and docs/assets/ to WebP, +# rewrite refs in markdown/yml/html, and remove originals. +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" + +if ! command -v cwebp >/dev/null 2>&1; then + echo "error: cwebp not found (install webp / brew install webp)" >&2 + exit 1 +fi +if ! command -v gif2webp >/dev/null 2>&1; then + echo "error: gif2webp not found (install webp / brew install webp)" >&2 + exit 1 +fi + +DRY_RUN=0 +if [[ "${1:-}" == "--dry-run" ]]; then + DRY_RUN=1 +fi + +DIRS="" +[[ -d assets ]] && DIRS="$DIRS assets" +[[ -d docs/assets ]] && DIRS="$DIRS docs/assets" + +if [[ -z "$DIRS" ]]; then + echo "No assets/ or docs/assets/ directory found; nothing to do." + exit 0 +fi + +# shellcheck disable=SC2086 +IMAGES=$(find $DIRS \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.gif' \) \ + ! -path '*/coverage/*' ! -path '*/test-results/*' ! -path '*/node_modules/*' ! -path '*/dist/*' \ + -type f | sort) + +if [[ -z "$IMAGES" ]]; then + echo "No PNG/JPG/GIF under assets/ or docs/assets/; nothing to do." + exit 0 +fi + +before_bytes=0 +after_bytes=0 +converted=0 +skipped=0 + +rewrite_refs() { + local basename_no_ext="$1" + local old_ext="$2" + + find . \( -name '*.md' -o -name '*.yml' -o -name '*.yaml' -o -name '*.html' \) \ + ! -path '*/node_modules/*' ! -path '*/coverage/*' ! -path '*/dist/*' ! -path '*/.git/*' \ + -type f -print0 2>/dev/null | + while IFS= read -r -d '' f; do + if grep -qE "${basename_no_ext}\\.${old_ext}" "$f" 2>/dev/null; then + if [[ $DRY_RUN -eq 1 ]]; then + echo " would rewrite refs in $f" + else + perl -i -pe "s/${basename_no_ext}\\.${old_ext}/${basename_no_ext}.webp/gi" "$f" + echo " rewrote refs in $f" + fi + fi + done +} + +human() { + local b=$1 + if [[ $b -ge 1048576 ]]; then + awk -v b="$b" 'BEGIN { printf "%.1f MB", b/1048576 }' + elif [[ $b -ge 1024 ]]; then + awk -v b="$b" 'BEGIN { printf "%.1f KB", b/1024 }' + else + echo "${b} B" + fi +} + +while IFS= read -r src; do + [[ -z "$src" ]] && continue + ext="${src##*.}" + ext_lc=$(printf '%s' "$ext" | tr '[:upper:]' '[:lower:]') + dest="${src%.*}.webp" + base=$(basename "$src") + base_no_ext="${base%.*}" + size_src=$(stat -f%z "$src" 2>/dev/null || stat -c%s "$src") + before_bytes=$((before_bytes + size_src)) + + size_dest=0 + if [[ -f "$dest" && "$dest" -nt "$src" ]]; then + echo "reuse existing: $dest" + skipped=$((skipped + 1)) + size_dest=$(stat -f%z "$dest" 2>/dev/null || stat -c%s "$dest") + else + echo "convert: $src -> $dest" + if [[ $DRY_RUN -eq 1 ]]; then + rewrite_refs "$base_no_ext" "$ext_lc" + converted=$((converted + 1)) + continue + fi + + case "$ext_lc" in + gif) + # -mt multithread; -m 4 is much faster than 6 on large animated GIFs + gif2webp -q 80 -m 4 -mt -mixed "$src" -o "$dest" >/dev/null 2>&1 + ;; + png|jpg|jpeg) + cwebp -near_lossless 40 -metadata icc -m 6 "$src" -o "$dest" >/dev/null 2>&1 + ;; + *) + echo " unsupported extension: $ext_lc" >&2 + continue + ;; + esac + size_dest=$(stat -f%z "$dest" 2>/dev/null || stat -c%s "$dest") + converted=$((converted + 1)) + fi + + after_bytes=$((after_bytes + size_dest)) + + if [[ $DRY_RUN -eq 1 ]]; then + continue + fi + + rewrite_refs "$base_no_ext" "$ext_lc" + + remaining=$( + grep -rE --include='*.md' --include='*.yml' --include='*.yaml' --include='*.html' \ + -l "${base_no_ext}\\.${ext_lc}" . 2>/dev/null | + grep -v node_modules | grep -v coverage | grep -v '/\.git/' || true + ) + if [[ -z "$remaining" ]]; then + rm -f "$src" + echo " removed $src" + else + echo " kept $src (still referenced):" + echo "$remaining" | sed 's/^/ /' + fi +done <<< "$IMAGES" + +echo +echo "Done. converted=$converted skipped=$skipped dry_run=$DRY_RUN" +if [[ $DRY_RUN -eq 0 ]]; then + echo "Size: $(human "$before_bytes") -> $(human "$after_bytes")" + if [[ $before_bytes -gt 0 ]]; then + saved=$((before_bytes - after_bytes)) + pct=$(awk -v s="$saved" -v b="$before_bytes" 'BEGIN { printf "%.0f", (s/b)*100 }') + echo "Saved: $(human "$saved") (${pct}%)" + fi +fi diff --git a/scripts/rewrite-release-image-urls.sh b/scripts/rewrite-release-image-urls.sh new file mode 100755 index 0000000..27b9db3 --- /dev/null +++ b/scripts/rewrite-release-image-urls.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash +# Rewrite GitHub release note image URLs after docs PNG/GIF → WebP migration. +# - *.png|gif|jpeg → *.webp for marketing assets +# - /assets/foo.webp → /docs/assets/foo.webp when the file only lives under docs/assets/ +# - Never touches src/assets/ (runtime card art) +# +# Usage (from a card repo root): +# ./scripts/rewrite-release-image-urls.sh # dry-run +# ./scripts/rewrite-release-image-urls.sh --apply # edit releases +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" + +APPLY=0 +if [[ "${1:-}" == "--apply" ]]; then + APPLY=1 +fi + +if ! command -v gh >/dev/null 2>&1; then + echo "error: gh CLI required" >&2 + exit 1 +fi +if ! command -v python3 >/dev/null 2>&1; then + echo "error: python3 required" >&2 + exit 1 +fi + +REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner) +echo "repo=$REPO apply=$APPLY" + +python3 - "$REPO" "$APPLY" <<'PY' +import json, os, re, subprocess, sys +from pathlib import Path + +repo, apply_s = sys.argv[1], sys.argv[2] +apply = apply_s == "1" +root = Path.cwd() + +docs_webps = {p.name for p in (root / "docs" / "assets").glob("*.webp")} if (root / "docs" / "assets").is_dir() else set() +root_webps = {p.name for p in (root / "assets").glob("*.webp")} if (root / "assets").is_dir() else set() + +print(f"docs/assets webps: {len(docs_webps)}") +print(f"assets/ webps: {len(root_webps)}") + +# Match github blob / raw URLs pointing at this repo's asset images +# Groups: prefix, path_before_file, filename_stem, ext, suffix(?raw= etc) +url_re = re.compile( + rf"(https://(?:github\.com/{re.escape(repo)}/blob/[^/\s)\"]+/|raw\.githubusercontent\.com/{re.escape(repo)}/(?:refs/heads/)?[^/\s)\"]+/))" + rf"((?:docs/)?assets/)" + rf"([^/\s)\"?]+)\." + rf"(png|gif|jpe?g|webp)" + rf"([^)\s\"]*)", + re.IGNORECASE, +) + +def rewrite_url(m: re.Match) -> str: + prefix, folder, stem, ext, suffix = m.group(1), m.group(2), m.group(3), m.group(4), m.group(5) + name_webp = f"{stem}.webp" + # Prefer docs/assets when the webp lives there (handles assets/ → docs/assets/ moves) + if name_webp in docs_webps: + new_folder = "docs/assets/" + new_ext = "webp" + elif name_webp in root_webps: + new_folder = "assets/" + new_ext = "webp" + else: + # Unknown file: still flip raster ext → webp, keep folder (best effort) + if ext.lower() in ("png", "gif", "jpg", "jpeg"): + new_folder = folder + new_ext = "webp" + else: + return m.group(0) + return f"{prefix}{new_folder}{stem}.{new_ext}{suffix}" + +tags = json.loads( + subprocess.check_output( + ["gh", "release", "list", "--limit", "100", "--json", "tagName"], + text=True, + ) +) + +changed_releases = 0 +for item in tags: + tag = item["tagName"] + body = json.loads( + subprocess.check_output( + ["gh", "release", "view", tag, "--json", "body"], + text=True, + ) + )["body"] or "" + + new_body, n = url_re.subn(rewrite_url, body) + if n == 0 or new_body == body: + continue + + changed_releases += 1 + print(f"\n=== {tag} ({n} url rewrite(s)) ===") + # Show only changed lines for dry-run readability + old_urls = url_re.findall(body) + # Print before → after for each match in original + for m in url_re.finditer(body): + before = m.group(0) + after = rewrite_url(m) + if before != after: + print(f" - {before}") + print(f" + {after}") + + if apply: + # notes-file via stdin + proc = subprocess.run( + ["gh", "release", "edit", tag, "--notes-file", "-"], + input=new_body, + text=True, + capture_output=True, + ) + if proc.returncode != 0: + print(f"FAILED {tag}: {proc.stderr}", file=sys.stderr) + sys.exit(proc.returncode) + print(f" applied {tag}") + +print(f"\nDone. releases_needing_update={changed_releases} apply={apply}") +if not apply and changed_releases: + print("Re-run with --apply to write changes.") +PY diff --git a/src/cards/components/AGENTS.md b/src/cards/components/AGENTS.md index a01e636..e82f354 100644 --- a/src/cards/components/AGENTS.md +++ b/src/cards/components/AGENTS.md @@ -3,7 +3,7 @@ Reusable Lit sub-components used inside ``. Each subfolder defines its own custom element with co-located styles. - **`section/`** — ``: one collapsible section (controls, sensors, configuration, diagnostic, …). Owns its own expand/collapse state so toggling does not re-render sibling sections. Defaults to `hasFeature(config, 'expanded')`. -- **`row/`** — ``: one entity row. Owns its own attribute-detail expansion state. Listens for `ll-custom` events with `detail.device_card.expand` and `entity_id` matching this row to toggle. Resolves HA `loadCardHelpers` once before rendering. +- **`row/`** — ``: one entity row. Owns its own attribute-detail expansion state. Binds `@ll-custom` on the row wrapper; toggles when `detail.device_card.expand` and `entity_id` match this row. Card helpers are preloaded from `src/index.ts` (`entityRow` returns `nothing` until ready). ## Conventions diff --git a/src/cards/components/row/row.ts b/src/cards/components/row/row.ts index dd2acb2..ccc8119 100644 --- a/src/cards/components/row/row.ts +++ b/src/cards/components/row/row.ts @@ -1,8 +1,4 @@ import type { Config } from '@device/types'; -import { - resolvePoatCardHelpers, - type CardHelpers, -} from '@homeassistant-extras/hass/helpers/card-helpers'; import { entityRow } from '@homeassistant-extras/hass/html/entity-row'; import { HassConfigMixin } from '@homeassistant-extras/hass/mixins/hass-config-mixin'; import { attributes } from '@html/attributes'; @@ -29,19 +25,13 @@ export class DeviceCardRow extends HassConfigMixin( @state() private _expanded = false; - /** - * Resolved once from {@link globalThis.loadCardHelpers}; used via global helper accessor. - */ - @state() - private _cardHelpers?: CardHelpers; - /** * Handles the ll-custom expand event to toggle entity attribute visibility. * Entity ID comes from ev.detail.device_card.entity_id. * * @param ev - The CustomEvent with detail.device_card.expand and detail.device_card.entity_id */ - private readonly _onLlCustom = (ev: Event): void => { + private readonly _handleLLCustomEvent = (ev: Event): void => { const ce = ev as CustomEvent<{ device_card?: { expand?: boolean; entity_id?: string }; }>; @@ -53,20 +43,6 @@ export class DeviceCardRow extends HassConfigMixin( this._expanded = !this._expanded; }; - override connectedCallback(): void { - super.connectedCallback(); - this.addEventListener('ll-custom', this._onLlCustom); - - void resolvePoatCardHelpers(globalThis.loadCardHelpers).then((helpers) => { - this._cardHelpers = helpers; - }); - } - - override disconnectedCallback(): void { - this.removeEventListener('ll-custom', this._onLlCustom); - super.disconnectedCallback(); - } - /** * Returns the component's styles */ @@ -79,11 +55,6 @@ export class DeviceCardRow extends HassConfigMixin( * @returns {TemplateResult} The rendered HTML template */ override render(): TemplateResult | typeof nothing { - // Avoid rendering sections until helpers are resolved; this keeps all downstream rendering sync. - if (!this._cardHelpers) { - return nothing; - } - let statusClassName: string | undefined; if (this.entity.isProblemEntity) { @@ -104,6 +75,7 @@ export class DeviceCardRow extends HassConfigMixin( statusClassName, this._expanded ? 'expanded-row' : '', ].join(' ')}" + @ll-custom=${this._handleLLCustomEvent} >

${entityRow( diff --git a/src/cards/components/row/styles.ts b/src/cards/components/row/styles.ts index d39d46f..265144e 100644 --- a/src/cards/components/row/styles.ts +++ b/src/cards/components/row/styles.ts @@ -14,13 +14,27 @@ export const styles = css` /* Container for a row */ .row { position: relative; - border-radius: 3px; + isolation: isolate; cursor: pointer; - transition: background-color 0.2s ease; } - .row:hover { - background-color: var(--secondary-background-color); + /* Hover highlight: rounded, bleeds slightly past the row so it isn't flush */ + .row::before { + content: ''; + position: absolute; + inset: 0 -8px; + border-radius: 8px; + background-color: var(--primary-text-color); + opacity: 0; + transition: opacity 0.2s ease; + pointer-events: none; + z-index: -1; + } + + @media (hover: hover) { + .row:hover::before { + opacity: 0.06; + } } .row.expanded-row { diff --git a/src/cards/device-card/AGENTS.md b/src/cards/device-card/AGENTS.md index 688c05b..3897724 100644 --- a/src/cards/device-card/AGENTS.md +++ b/src/cards/device-card/AGENTS.md @@ -13,4 +13,5 @@ The `custom:device-card` Lovelace card: a single-device view that groups the dev - The `_config` setter does a `fast-deep-equal` check before reassigning to avoid spurious re-renders. - `_hass` is **not** a Lit `@state` — updates flow through the mixin and are dispatched manually in `shouldUpdate`. +- Header gestures go through HA, not local click handlers: the header binds `actionHandler` and forwards each gesture as a `hass-action` with configs from `@delegates/utils/header-actions` (tap → `fire-dom-event` `device_card.collapse`, hold → navigate to `/config/devices/device/`). HA re-fires the tap as `ll-custom` from the header (HA 2026.11+ only, hence the `hacs.json` minimum), which `` handles with `@ll-custom` to toggle `collapse`. - Don't move section/row expansion state into the top-level card; it lives in the child components so toggling one row doesn't re-render the whole device. diff --git a/src/cards/device-card/card.ts b/src/cards/device-card/card.ts index b690c1b..181fe50 100644 --- a/src/cards/device-card/card.ts +++ b/src/cards/device-card/card.ts @@ -2,6 +2,7 @@ import { getOrderedSections } from '@/helpers/device-section'; import '@cards/components/section/section'; import { getDevice } from '@delegates/utils/get-device'; import { hasProblem } from '@delegates/utils/has-problem'; +import type { HeaderCollapseDetail } from '@delegates/utils/header-actions'; import { styles } from '@device/styles'; import { hasFeature } from '@homeassistant-extras/hass/common/config/feature'; import { HassConfigMixin } from '@homeassistant-extras/hass/mixins/hass-config-mixin'; @@ -47,6 +48,19 @@ export class DeviceCard extends HassUpdateMixin(HassConfigMixin(LitElement)) { @state() private collapse = false; + /** + * Toggles collapse when the header's `fire-dom-event` tap action comes + * back from Home Assistant as `ll-custom`. + */ + private readonly _handleLLCustomEvent = (ev: Event): void => { + const detail = (ev as CustomEvent).detail; + if (!detail?.device_card?.collapse) { + return; + } + ev.stopPropagation(); + this.collapse = !this.collapse; + }; + /** * Returns the component's styles */ @@ -124,12 +138,14 @@ export class DeviceCard extends HassUpdateMixin(HassConfigMixin(LitElement)) { device: this._device, hass: this._hass, collapse: this.collapse, - onCollapseToggle: () => (this.collapse = !this.collapse), entity, }); return html` - + ${headerContent} ${ this.collapse diff --git a/src/cards/device-card/styles.ts b/src/cards/device-card/styles.ts index 41b40e9..24d3d39 100644 --- a/src/cards/device-card/styles.ts +++ b/src/cards/device-card/styles.ts @@ -18,15 +18,19 @@ export const styles = css` } .card-header { + position: relative; + isolation: isolate; padding: 0px 0px 10px 16px; line-height: 35px; border-bottom: 1px solid var(--divider-color); margin-bottom: 8px; cursor: pointer; - transition: background-color 0.2s ease; display: flex; justify-content: space-between; align-items: center; + /* long-press opens the device page; don't select text on hold */ + user-select: none; + -webkit-user-select: none; } /* Remove bottom border when collapsed */ @@ -35,8 +39,26 @@ export const styles = css` margin-bottom: 0; } - .card-header:hover { - background-color: var(--secondary-background-color); + /* + * Hover highlight: a rounded layer that bleeds a little past the header's + * edges so it doesn't hug the text, and stops short of the divider. + */ + .card-header::before { + content: ''; + position: absolute; + inset: -6px -8px 4px -8px; + border-radius: 10px; + background-color: var(--primary-text-color); + opacity: 0; + transition: opacity 0.2s ease; + pointer-events: none; + z-index: -1; + } + + @media (hover: hover) { + .card-header:hover::before { + opacity: 0.06; + } } .title { diff --git a/src/delegates/utils/get-device.ts b/src/delegates/utils/get-device.ts index 0c29802..f7883d4 100644 --- a/src/delegates/utils/get-device.ts +++ b/src/delegates/utils/get-device.ts @@ -41,6 +41,7 @@ export const getDevice = ( return undefined; } + device.id = hassDevice.id; device.name = hassDevice.name_by_user ?? hassDevice.name ?? 'Device'; device.model = [ hassDevice.manufacturer, diff --git a/src/delegates/utils/header-actions.ts b/src/delegates/utils/header-actions.ts new file mode 100644 index 0000000..29bd180 --- /dev/null +++ b/src/delegates/utils/header-actions.ts @@ -0,0 +1,42 @@ +import type { ActionConfig } from '@homeassistant-extras/hass/data/lovelace/config/action'; +import type { ActionConfigParams } from '@homeassistant-extras/hass/panels/lovelace/common/handle-action'; + +/** `ll-custom` detail fired by the header tap action. */ +export interface HeaderCollapseDetail { + device_card?: { collapse?: boolean }; +} + +/** + * Path to a device's page in the Home Assistant settings UI. + */ +export const devicePagePath = (deviceId: string): string => + `/config/devices/device/${deviceId}`; + +/** + * Tap action for the header: a `fire-dom-event` that HA re-fires as + * `ll-custom` from the header, which the device card handles to toggle + * collapse. Requires HA 2026.11+ (frontend 20261028), where `hass-action` + * fires `ll-custom` from the originating element instead of the app root. + */ +export const collapseAction = (): ActionConfig => + ({ + action: 'fire-dom-event', + device_card: { collapse: true }, + }) as unknown as ActionConfig; + +/** + * Navigate action to the device page. + */ +export const deviceNavigateAction = (deviceId: string): ActionConfig => ({ + action: 'navigate', + navigation_path: devicePagePath(deviceId), +}); + +/** + * Action configs for the card header, handed to HA via `hass-action`. + * Tap toggles collapse; hold opens the device page (when the device is known). + */ +export const headerActions = (deviceId?: string): ActionConfigParams => ({ + tap_action: collapseAction(), + ...(deviceId ? { hold_action: deviceNavigateAction(deviceId) } : {}), +}); diff --git a/src/html/device-card-header.ts b/src/html/device-card-header.ts index 8e917b5..d5d1d59 100644 --- a/src/html/device-card-header.ts +++ b/src/html/device-card-header.ts @@ -1,5 +1,9 @@ +import { headerActions } from '@delegates/utils/header-actions'; import type { Config } from '@device/types'; import { hasFeature } from '@homeassistant-extras/hass/common/config/feature'; +import { fireEvent } from '@homeassistant-extras/hass/common/dom/fire_event'; +import type { ActionHandlerEvent } from '@homeassistant-extras/hass/data/lovelace/action_handler'; +import { actionHandler } from '@homeassistant-extras/hass/panels/lovelace/common/directives/action-handler-directive'; import type { HomeAssistant } from '@homeassistant-extras/hass/types'; import { localize } from '@localize/localize'; import type { Device } from '@type/config'; @@ -10,10 +14,19 @@ export interface DeviceCardHeaderParams { device: Device; hass: HomeAssistant; collapse: boolean; - onCollapseToggle: () => void; entity: TemplateResult | typeof nothing; } +/** + * Forwards an action-handler gesture to Home Assistant as a `hass-action`. + */ +const handleHeaderAction = (ev: ActionHandlerEvent, deviceId?: string) => { + fireEvent(ev.currentTarget as HTMLElement, 'hass-action', { + config: headerActions(deviceId), + action: ev.detail.action, + }); +}; + /** * Renders the device card header (title, model, icon, pinned entity). * Returns nothing when both title and model are hidden and no entity to show. @@ -21,7 +34,7 @@ export interface DeviceCardHeaderParams { export const deviceCardHeader = ( params: DeviceCardHeaderParams, ): TemplateResult | typeof nothing => { - const { config, device, hass, collapse, onCollapseToggle, entity } = params; + const { config, device, hass, collapse, entity } = params; const hideTitle = hasFeature(config, 'hide_title'); const hideDeviceModel = hasFeature(config, 'hide_device_model'); const hideHeader = hideTitle && hideDeviceModel; @@ -32,7 +45,6 @@ export const deviceCardHeader = ( device, hass, collapse, - onCollapseToggle, entity, hideTitle, hideDeviceModel, @@ -59,13 +71,14 @@ function renderFullHeader( device, hass, collapse, - onCollapseToggle, entity, hideTitle, hideDeviceModel, hideIcon, } = params; + const deviceId = device.id; + const titleContent = hideTitle ? nothing : html`${config.title ?? device.name}`; @@ -92,12 +105,17 @@ function renderFullHeader( const collapseLabel = collapse ? localize(hass, 'card.expand') : localize(hass, 'card.collapse'); + // second tooltip line hints at the hold gesture when it's available + const tooltip = deviceId + ? `${collapseLabel}\n${localize(hass, 'card.hold_for_device')}` + : collapseLabel; return html`
handleHeaderAction(ev, deviceId)} + .actionHandler=${actionHandler({ hasHold: !!deviceId })} + title="${tooltip}" >
${iconContent} diff --git a/src/translations/en.json b/src/translations/en.json index 1d9555e..c377b3b 100644 --- a/src/translations/en.json +++ b/src/translations/en.json @@ -8,7 +8,8 @@ "device_card_name": "Device Card", "device_card_description": "A card to summarize the status of a Device.", "integration_card_name": "Integration Card", - "integration_card_description": "A card to display all devices from a specific integration." + "integration_card_description": "A card to display all devices from a specific integration.", + "hold_for_device": "Hold to open device page" }, "sections": { "controls": "Controls", diff --git a/src/translations/fr.json b/src/translations/fr.json index 477c753..dad1975 100644 --- a/src/translations/fr.json +++ b/src/translations/fr.json @@ -8,7 +8,8 @@ "device_card_name": "Carte d'Appareil", "device_card_description": "Une carte pour résumer le statut d'un Appareil.", "integration_card_name": "Carte d'Intégration", - "integration_card_description": "Une carte pour afficher tous les appareils d'une intégration spécifique." + "integration_card_description": "Une carte pour afficher tous les appareils d'une intégration spécifique.", + "hold_for_device": "Maintenir pour ouvrir la page de l'appareil" }, "sections": { "controls": "Contrôles", diff --git a/src/translations/pt.json b/src/translations/pt.json index 98073c4..d53673b 100644 --- a/src/translations/pt.json +++ b/src/translations/pt.json @@ -8,7 +8,8 @@ "device_card_name": "Cartão de Dispositivo", "device_card_description": "Um cartão para resumir o status de um Dispositivo.", "integration_card_name": "Cartão de Integração", - "integration_card_description": "Um cartão para exibir todos os dispositivos de uma integração específica." + "integration_card_description": "Um cartão para exibir todos os dispositivos de uma integração específica.", + "hold_for_device": "Segure para abrir a página do dispositivo" }, "sections": { "controls": "Controles", diff --git a/src/translations/ru.json b/src/translations/ru.json index ee02008..22a1fc3 100644 --- a/src/translations/ru.json +++ b/src/translations/ru.json @@ -8,7 +8,8 @@ "device_card_name": "Карточка устройства", "device_card_description": "Карточка для обобщения состояния устройства.", "integration_card_name": "Карточка интеграции", - "integration_card_description": "Карточка для отображения всех устройств из определенной интеграции." + "integration_card_description": "Карточка для отображения всех устройств из определенной интеграции.", + "hold_for_device": "Удерживайте, чтобы открыть страницу устройства" }, "sections": { "controls": "Управление", diff --git a/src/types/config.ts b/src/types/config.ts index c51c193..89fd9fd 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -101,6 +101,9 @@ export interface DeviceSortConfig { * Represents the states of various sensors in a Z-Wave device */ export interface Device { + /** The Home Assistant device registry ID */ + id?: string; + /** The name of the device */ name?: string; diff --git a/test/AGENTS.md b/test/AGENTS.md index b08ee5a..f9621da 100644 --- a/test/AGENTS.md +++ b/test/AGENTS.md @@ -16,6 +16,10 @@ To run a specific test file, prefer the repo's Mocha setup and test TypeScript c TS_NODE_PROJECT='./tsconfig.test.json' npx mocha test/path/to/specific.spec.ts ``` +## Shared setup + +`test/setup.ts` (loaded via `.mocharc.json`) stubs Home Assistant's global `` element so the `actionHandler` directive can bind under JSDOM. The stub records bound options on `element.actionHandler.options`; simulate gestures by dispatching an `action` event (`{ detail: { action: 'tap' | 'hold' } }`) built with `window.CustomEvent`. There is no HA `hass-action` handler under test, so assert on the `hass-action` payload, and dispatch `ll-custom` directly to test what the card does with a `fire-dom-event`. + ## `yarn test` failing with `ERR_MODULE_NOT_FOUND` If `yarn test` fails with an error like: diff --git a/test/cards/components/row/row.spec.ts b/test/cards/components/row/row.spec.ts index 7dc12c7..87787a8 100644 --- a/test/cards/components/row/row.spec.ts +++ b/test/cards/components/row/row.spec.ts @@ -1,7 +1,5 @@ import { DeviceCardRow } from '@cards/components/row/row'; import type { Config } from '@device/types'; -import type { CardHelpers } from '@homeassistant-extras/hass/helpers/card-helpers'; -import * as cardHelpersModule from '@homeassistant-extras/hass/helpers/card-helpers'; import * as entityRowModule from '@homeassistant-extras/hass/html/entity-row'; import type { HomeAssistant } from '@homeassistant-extras/hass/types'; import * as attributesModule from '@html/attributes'; @@ -9,7 +7,7 @@ import * as percentBarModule from '@html/percent'; import { fixture } from '@open-wc/testing-helpers'; import type { EntityInformation } from '@type/config'; import { expect } from 'chai'; -import { html, nothing, type TemplateResult } from 'lit'; +import { html, type TemplateResult } from 'lit'; import { stub } from 'sinon'; describe('device-card-row.ts', () => { @@ -18,17 +16,11 @@ describe('device-card-row.ts', () => { let config: Config; let entity: EntityInformation; - let resolvePoatCardHelpersStub: sinon.SinonStub; let entityRowStub: sinon.SinonStub; let percentBarStub: sinon.SinonStub; let attributesStub: sinon.SinonStub; beforeEach(() => { - resolvePoatCardHelpersStub = stub( - cardHelpersModule, - 'resolvePoatCardHelpers', - ); - entityRowStub = stub(entityRowModule, 'entityRow'); entityRowStub.returns(html`
`); @@ -57,37 +49,13 @@ describe('device-card-row.ts', () => { }); afterEach(() => { - resolvePoatCardHelpersStub.restore(); entityRowStub.restore(); percentBarStub.restore(); attributesStub.restore(); }); - describe('connectedCallback', () => { - it('should resolve and store card helpers', async () => { - (el as any)._cardHelpers = undefined; - const helpers = {} as CardHelpers; - resolvePoatCardHelpersStub.resolves(helpers); - (globalThis as any).loadCardHelpers = () => Promise.resolve(helpers); - - // Avoid Lit style adoption in jsdom; test only helper resolution. - (el as any).createRenderRoot = () => document.createElement('div'); - el.connectedCallback(); - await Promise.resolve(); - - expect(resolvePoatCardHelpersStub.calledOnce).to.be.true; - expect((el as any)._cardHelpers).to.equal(helpers); - }); - }); - describe('render()', () => { - it('should render nothing if card helpers are not resolved yet', () => { - (el as any)._cardHelpers = undefined; - expect(el.render()).to.equal(nothing); - }); - it('should render row content and percent bar', async () => { - (el as any)._cardHelpers = {} as CardHelpers; const root = await fixture(el.render() as TemplateResult); expect(root.classList.contains('row')).to.be.true; @@ -97,7 +65,6 @@ describe('device-card-row.ts', () => { }); it('should render a percentage bar for entities with % unit variations like "% available"', async () => { - (el as any)._cardHelpers = {} as CardHelpers; el.entity = { ...entity, attributes: { @@ -114,7 +81,6 @@ describe('device-card-row.ts', () => { }); it('should not render a percentage bar for non-percentage entities', async () => { - (el as any)._cardHelpers = {} as CardHelpers; el.entity = { ...entity, attributes: { ...entity.attributes, unit_of_measurement: '°C' }, @@ -126,7 +92,6 @@ describe('device-card-row.ts', () => { }); it('should not render a percentage bar for entities with % unit but non-numeric state', async () => { - (el as any)._cardHelpers = {} as CardHelpers; el.entity = { ...entity, state: 'unknown', @@ -139,7 +104,6 @@ describe('device-card-row.ts', () => { }); it('should apply status-error class for active problem entities', async () => { - (el as any)._cardHelpers = {} as CardHelpers; el.entity = { ...entity, isProblemEntity: true, isActive: true }; const root = await fixture(el.render() as TemplateResult); @@ -150,7 +114,6 @@ describe('device-card-row.ts', () => { }); it('should apply status-ok class for inactive problem entities', async () => { - (el as any)._cardHelpers = {} as CardHelpers; el.entity = { ...entity, isProblemEntity: true, isActive: false }; const root = await fixture(el.render() as TemplateResult); @@ -161,7 +124,6 @@ describe('device-card-row.ts', () => { }); it('should pass inverse_percent and percent_colors to percentBar when configured', async () => { - (el as any)._cardHelpers = {} as CardHelpers; const percentColors = { 'sensor.*': 'blue' }; el.config = { ...config, @@ -181,8 +143,6 @@ describe('device-card-row.ts', () => { }); it('should pass empty array to percentBar when inverse_percent is not configured', async () => { - (el as any)._cardHelpers = {} as CardHelpers; - await fixture(el.render() as TemplateResult); expect(percentBarStub.calledOnce).to.be.true; @@ -190,7 +150,6 @@ describe('device-card-row.ts', () => { }); it('should not show attributes when entity is collapsed', async () => { - (el as any)._cardHelpers = {} as CardHelpers; (el as any)._expanded = false; await fixture(el.render() as TemplateResult); @@ -199,7 +158,6 @@ describe('device-card-row.ts', () => { }); it('should show attributes when entity is expanded', async () => { - (el as any)._cardHelpers = {} as CardHelpers; (el as any)._expanded = true; const root = await fixture(el.render() as TemplateResult); @@ -209,4 +167,43 @@ describe('device-card-row.ts', () => { expect(attributesStub.firstCall.args[0]).to.equal(entity); }); }); + + describe('_handleLLCustomEvent', () => { + it('should toggle expanded for matching entity_id', () => { + (el as any)._expanded = false; + + const ev = new CustomEvent('ll-custom', { + detail: { + device_card: { expand: true, entity_id: 'sensor.test' }, + }, + cancelable: true, + }); + const stopStub = stub(ev, 'stopPropagation'); + + (el as any)._handleLLCustomEvent(ev); + + expect((el as any)._expanded).to.be.true; + expect(stopStub.calledOnce).to.be.true; + }); + + it('should ignore events for other entities or without expand', () => { + (el as any)._expanded = false; + + (el as any)._handleLLCustomEvent( + new CustomEvent('ll-custom', { + detail: { + device_card: { expand: true, entity_id: 'sensor.other' }, + }, + }), + ); + expect((el as any)._expanded).to.be.false; + + (el as any)._handleLLCustomEvent( + new CustomEvent('ll-custom', { + detail: { device_card: { expand: false, entity_id: 'sensor.test' } }, + }), + ); + expect((el as any)._expanded).to.be.false; + }); + }); }); diff --git a/test/cards/device-card/card.spec.ts b/test/cards/device-card/card.spec.ts index 0d0940b..315f8c2 100644 --- a/test/cards/device-card/card.spec.ts +++ b/test/cards/device-card/card.spec.ts @@ -272,6 +272,59 @@ describe('card.ts', () => { deviceStub.restore(); }); + it('should toggle collapse when the header is tapped', async () => { + // Stand-in for HA 2026.11's hass-action listener: fire-dom-event is + // re-fired as ll-custom from the element that sent the action. + const haRoot = (ev: Event) => { + const { config, action } = (ev as CustomEvent).detail; + const actionConfig = config[`${action}_action`]; + if (actionConfig?.action === 'fire-dom-event') { + ev.composedPath()[0]!.dispatchEvent( + new window.CustomEvent('ll-custom', { + detail: actionConfig, + bubbles: true, + composed: true, + }), + ); + } + }; + document.addEventListener('hass-action', haRoot); + try { + const el = await fixture(card.render() as TemplateResult); + el.querySelector('.card-header')!.dispatchEvent( + new window.CustomEvent('action', { + detail: { action: 'tap' }, + bubbles: true, + composed: true, + }), + ); + expect((card as any).collapse).to.be.true; + } finally { + document.removeEventListener('hass-action', haRoot); + } + }); + + it('should toggle collapse on ll-custom collapse event', async () => { + const el = await fixture(card.render() as TemplateResult); + const outer = new window.CustomEvent('ll-custom', { bubbles: true }); + let escaped = false; + el.parentElement!.addEventListener('ll-custom', () => (escaped = true)); + + el.querySelector('.card-header')!.dispatchEvent( + new window.CustomEvent('ll-custom', { + detail: { device_card: { collapse: true } }, + bubbles: true, + composed: true, + }), + ); + expect((card as any).collapse).to.be.true; + expect(escaped).to.be.false; + + el.dispatchEvent(outer); + expect((card as any).collapse).to.be.true; + expect(escaped).to.be.true; + }); + it('should not render sections when collapsed', async () => { card.setConfig({ device_id: 'device_1', diff --git a/test/delegates/utils/header-actions.spec.ts b/test/delegates/utils/header-actions.spec.ts new file mode 100644 index 0000000..b171b34 --- /dev/null +++ b/test/delegates/utils/header-actions.spec.ts @@ -0,0 +1,38 @@ +import { + collapseAction, + deviceNavigateAction, + devicePagePath, + headerActions, +} from '@delegates/utils/header-actions'; +import { expect } from 'chai'; + +describe('header-actions.ts', () => { + it('should build the device page path', () => { + expect(devicePagePath('abc')).to.equal('/config/devices/device/abc'); + }); + + it('should build a fire-dom-event collapse action', () => { + expect(collapseAction()).to.deep.equal({ + action: 'fire-dom-event', + device_card: { collapse: true }, + }); + }); + + it('should build a navigate action to the device page', () => { + expect(deviceNavigateAction('abc')).to.deep.equal({ + action: 'navigate', + navigation_path: '/config/devices/device/abc', + }); + }); + + it('should tap to collapse and hold to navigate', () => { + expect(headerActions('abc')).to.deep.equal({ + tap_action: collapseAction(), + hold_action: deviceNavigateAction('abc'), + }); + }); + + it('should omit hold_action without a device id', () => { + expect(headerActions()).to.deep.equal({ tap_action: collapseAction() }); + }); +}); diff --git a/test/html/device-card-header.spec.ts b/test/html/device-card-header.spec.ts index 4e42644..fcaab02 100644 --- a/test/html/device-card-header.spec.ts +++ b/test/html/device-card-header.spec.ts @@ -9,6 +9,13 @@ import { expect } from 'chai'; import { html, nothing, type TemplateResult } from 'lit'; import { stub } from 'sinon'; +const tapOrHold = (action: 'tap' | 'hold') => + new window.CustomEvent('action', { + detail: { action }, + bubbles: true, + composed: true, + }); + describe('device-card-header.ts', () => { let mockHass: HomeAssistant; let mockDevice: Device; @@ -21,7 +28,6 @@ describe('device-card-header.ts', () => { device: mockDevice, hass: mockHass, collapse: false, - onCollapseToggle: () => {}, entity: nothing as TemplateResult | typeof nothing, }); @@ -40,8 +46,13 @@ describe('device-card-header.ts', () => { hasFeatureStub = stub(featureModule, 'hasFeature'); localizeStub = stub(localizeModule, 'localize'); hasFeatureStub.returns(false); - localizeStub.callsFake((_, key: string) => - key === 'card.expand' ? 'Expand' : 'Collapse', + localizeStub.callsFake( + (_, key: string) => + ({ + 'card.expand': 'Expand', + 'card.collapse': 'Collapse', + 'card.hold_for_device': 'Hold to open device page', + })[key] ?? key, ); }); @@ -166,6 +177,29 @@ describe('device-card-header.ts', () => { expect(el.getAttribute('title')).to.equal('Expand'); }); + it('should add the hold hint to the tooltip when device has an id', async () => { + mockDevice = { ...mockDevice, id: 'device_1' }; + const el = await fixture( + deviceCardHeader(defaultParams()) as TemplateResult, + ); + expect(el.getAttribute('title')).to.equal( + 'Collapse\nHold to open device page', + ); + }); + + it('should add the hold hint under Expand when collapsed', async () => { + mockDevice = { ...mockDevice, id: 'device_1' }; + const el = await fixture( + deviceCardHeader({ + ...defaultParams(), + collapse: true, + }) as TemplateResult, + ); + expect(el.getAttribute('title')).to.equal( + 'Expand\nHold to open device page', + ); + }); + it('should add collapsed class when collapse is true', async () => { const result = deviceCardHeader({ ...defaultParams(), @@ -175,17 +209,6 @@ describe('device-card-header.ts', () => { expect(el.classList.contains('collapsed')).to.be.true; }); - it('should call onCollapseToggle when header is clicked', async () => { - let toggled = false; - const result = deviceCardHeader({ - ...defaultParams(), - onCollapseToggle: () => (toggled = true), - }); - const el = await fixture(result as TemplateResult); - (el as HTMLElement).click(); - expect(toggled).to.be.true; - }); - it('should include entity in header', async () => { const entityContent = html`75%`; const result = deviceCardHeader({ @@ -198,6 +221,83 @@ describe('device-card-header.ts', () => { }); }); + describe('actions', () => { + const hassActions = (el: Element) => { + const events: CustomEvent[] = []; + el.addEventListener('hass-action', (e) => events.push(e as CustomEvent)); + return events; + }; + + const collapseTap = { + action: 'fire-dom-event', + device_card: { collapse: true }, + }; + const navigate = { + action: 'navigate', + navigation_path: '/config/devices/device/device_1', + }; + + beforeEach(() => { + mockDevice = { ...mockDevice, id: 'device_1' }; + }); + + it('should bind the action handler with hold when device has an id', async () => { + const el = await fixture( + deviceCardHeader(defaultParams()) as TemplateResult, + ); + expect((el as any).actionHandler.options).to.deep.equal({ + hasHold: true, + }); + }); + + it('should bind the action handler without hold when device has no id', async () => { + mockDevice = { ...mockDevice, id: undefined }; + const el = await fixture( + deviceCardHeader(defaultParams()) as TemplateResult, + ); + expect((el as any).actionHandler.options).to.deep.equal({ + hasHold: false, + }); + }); + + it('should forward a tap as hass-action with the header configs', async () => { + const el = await fixture( + deviceCardHeader(defaultParams()) as TemplateResult, + ); + const events = hassActions(el); + el.dispatchEvent(tapOrHold('tap')); + expect(events).to.have.length(1); + expect(events[0]!.detail).to.deep.equal({ + config: { tap_action: collapseTap, hold_action: navigate }, + action: 'tap', + }); + }); + + it('should forward a hold as hass-action with the header configs', async () => { + const el = await fixture( + deviceCardHeader(defaultParams()) as TemplateResult, + ); + const events = hassActions(el); + el.dispatchEvent(tapOrHold('hold')); + expect(events[0]!.detail).to.deep.equal({ + config: { tap_action: collapseTap, hold_action: navigate }, + action: 'hold', + }); + }); + + it('should omit hold_action when device has no id', async () => { + mockDevice = { ...mockDevice, id: undefined }; + const el = await fixture( + deviceCardHeader(defaultParams()) as TemplateResult, + ); + const events = hassActions(el); + el.dispatchEvent(tapOrHold('hold')); + expect(events[0]!.detail.config).to.deep.equal({ + tap_action: collapseTap, + }); + }); + }); + describe('entity-state-only (header hidden)', () => { it('should render entity-state-only when both hide_title and hide_device_model', async () => { hasFeatureStub.withArgs(mockConfig, 'hide_title').returns(true); diff --git a/test/setup.ts b/test/setup.ts new file mode 100644 index 0000000..c74af9a --- /dev/null +++ b/test/setup.ts @@ -0,0 +1,17 @@ +/** + * Shared test setup, loaded after the JSDOM globals (see .mocharc.json). + * + * Home Assistant defines `` globally; the `actionHandler` + * directive looks it up and calls `bind()`. Provide a stub that records the + * bound options so specs can assert on them and dispatch `action` events. + */ +if (!customElements.get('action-handler')) { + customElements.define( + 'action-handler', + class extends HTMLElement { + bind(element: HTMLElement & { actionHandler?: unknown }, options = {}) { + element.actionHandler = { options }; + } + }, + ); +}