Compare commits

...
Author SHA1 Message Date
dependabot[bot] 54d89b3253 Bump happy-dom from 20.14.5 to 21.0.4
Bumps [happy-dom](https://github.com/capricorn86/happy-dom) from 20.14.5 to 21.0.4.
- [Release notes](https://github.com/capricorn86/happy-dom/releases)
- [Commits](https://github.com/capricorn86/happy-dom/compare/v20.14.5...v21.0.4)

---
updated-dependencies:
- dependency-name: happy-dom
  dependency-version: 21.0.4
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-31 19:21:16 +00:00
GeorgeSG 44cb92bba4 Merge pull request #68 from AcMetelka/master
Feature to accept Time HA entity.
2026-10-05 09:01:19 +03:00
Jindrich.Stepan 326c195dfd Use generic alarm entity and consistent time domain labels 2026-10-05 00:52:32 +02:00
Jindrich.Stepan 81ca4cfb53 Feature: accepts time entity, not only input_datetime. 2026-10-05 00:31:27 +02:00
GeorgeSG e7aade9647 Merge pull request #67 from bramkragten/entity-name-followup
Keep an empty name meaning Home Assistant's own name
2026-09-30 11:18:19 +03:00
Bram KragtenandClaude Opus 5 769176243f Reflow the name union after dropping parent_device
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-29 23:36:54 +02:00
Bram KragtenandClaude Opus 5 7fc93eecea Keep an empty name meaning "use Home Assistant's name"
formatEntityName returns any string it is given verbatim, the empty one
included, so `name: ''` blanked the label where it previously fell through
to the friendly name. It now reaches the formatter as undefined.

Also drops `parent_device` from the accepted name parts. It only landed in
the frontend on 2026-09-10 and is in no release yet, so under the 2026.4
gate it was silently ignored.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 12:48:36 +01:00
Georgi Gardev 349c0aecf6 Modernize tech stack 2026-09-15 21:19:58 +03:00
GeorgeSG 8477d69bfe Merge pull request #66 from bramkragten/ha-entity-names
Resolve entity names via hass.formatEntityName
2026-09-15 14:47:20 +03:00
Bram KragtenandClaude Opus 5 64b83101dd Guard against a hass without formatEntityName
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 12:33:10 +02:00
Bram KragtenandClaude Opus 5 547b34e85a Add explicit return types to schema helpers
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 15:15:03 +02:00
Bram KragtenandClaude Opus 5 1069a8e7e4 Resolve entity names via hass.formatEntityName
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 15:08:51 +02:00
31 changed files with 2996 additions and 4361 deletions
-18
View File
@@ -1,18 +0,0 @@
{
"parser": "@typescript-eslint/parser", // Specifies the ESLint parser
"extends": [
"plugin:@typescript-eslint/recommended", // Uses the recommended rules from the @typescript-eslint/eslint-plugin
],
"parserOptions": {
"ecmaVersion": 2018, // Allows for the parsing of modern ECMAScript features
"sourceType": "module", // Allows for the use of imports
"experimentalDecorators": true
},
"rules": {
"@typescript-eslint/camelcase": 0,
"@typescript-eslint/no-non-null-assertion": 0,
"@typescript-eslint/explicit-function-return-type": [1, { "allowExpressions": true }],
"@typescript-eslint/no-namespace": 0,
},
"ignorePatterns": ["dist/", "node_modules/", "*.js"]
}
+17 -7
View File
@@ -1,4 +1,4 @@
name: 'CI'
name: CI
on:
push:
@@ -12,10 +12,20 @@ jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build
run: |
npm install
npm run build
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
cache: npm
- name: Install
run: npm ci
- name: Lint
run: npm run lint
- name: Format
run: npm run format:check
- name: Typecheck
run: npm run typecheck
- name: Test
run: npm run test
run: npm test
- name: Build
run: npm run rollup
+12 -9
View File
@@ -4,21 +4,24 @@ on:
release:
types: [published]
permissions:
contents: write
jobs:
release:
name: Build and upload
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
cache: npm
- name: Build time-picker-card.js
run: |
npm install
npm ci
npm run build
- name: Upload to release
uses: shopify/upload-to-release@1.0.0
with:
name: time-picker-card.js
path: dist/time-picker-card.js
repo-token: ${{ secrets.GITHUB_TOKEN }}
run: gh release upload "${{ github.event.release.tag_name }}" dist/time-picker-card.js --clobber
env:
GH_TOKEN: ${{ github.token }}
+1
View File
@@ -4,3 +4,4 @@ dist/
devtools/homeassistant/*
!devtools/homeassistant/configuration.yaml
!devtools/homeassistant/ui-lovelace.yaml
!devtools/homeassistant/packages/
+1
View File
@@ -0,0 +1 @@
24
+53 -18
View File
@@ -11,7 +11,7 @@
This is a Time Picker Card for [Home Assistant](https://www.home-assistant.io/)'s [Lovelace UI](https://www.home-assistant.io/lovelace).
Requires an [Input Datetime](https://www.home-assistant.io/integrations/input_datetime/) that has time (`has_time: true`).
Supports a [Time](https://www.home-assistant.io/integrations/time/) entity or an [Input Datetime](https://www.home-assistant.io/integrations/input_datetime/) entity that has time (`has_time: true`).
## Installation
@@ -66,6 +66,16 @@ hide:
name: true
```
### `time` entity
```yaml
type: custom:time-picker-card
entity: time.alarm_time
minute_step: 5
```
The card reads the time entity's `HH:MM:SS` state and updates it using `time.set_value`.
### Custom config - hidden card name, 12 hour mode with a "single" hour mode picker
![Default theme with single hour mode](https://raw.githubusercontent.com/GeorgeSG/lovelace-time-picker-card/master/examples/single_hour_mode.png)
@@ -107,21 +117,22 @@ layout:
## Options
| Name | Type | Requirement | Description | Default |
| ----------------- | ------------ | ------------ | --------------------------------------------------------------------------------------------------------- | ------------------------ |
| type | string | **Required** | `custom:time-picker-card` | |
| entity | string | **Required** | [Input Datetime](https://www.home-assistant.io/integrations/input_datetime/) entity with `has_time: true` | |
| name | string | **Optional** | Card name | Entity's `friendly_name` |
| link_values | boolean | **Optional** | If enabled, will change hour when minutes overflow. E.g. will go from 11:55 to 12:00, instead of 11:00 | `false` |
| hour_mode | `12` or `24` | **Optional** | Hour format. If `12`, card will show AM/PM picker | `24` |
| hour_step | number | **Optional** | Hour change when clicking arrows | `1` |
| minute_step | number | **Optional** | Minute change when clicking arrows | `5` |
| delay | number | **Optional** | Delay in ms before updating entity | `0` |
| layout | object | **Optional** | Card Layout configuration | `none` |
| hide | object | **Optional** | Hide object | `none` |
| tap_action | action | **Optional** | Home assistant action to perform on tap | `more-info` |
| double_tap_action | action | **Optional** | Home assistant action to perform on tap | `more-info` |
| hold_action | action | **Optional** | Home assistant action to perform on tap | `more-info` |
| Name | Type | Requirement | Description | Default |
| ----------------- | ------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| type | string | **Required** | `custom:time-picker-card` | |
| entity | string | **Required** | [Time](https://www.home-assistant.io/integrations/time/) entity or [Input Datetime](https://www.home-assistant.io/integrations/input_datetime/) entity with `has_time: true` | |
| name | string / list | **Optional** | Card name. Accepts a [structured name](#structured-names) on Home Assistant 2026.4 and later. | Entity's name |
| link_values | boolean | **Optional** | If enabled, will change hour when minutes overflow. E.g. will go from 11:55 to 12:00, instead of 11:00 | `false` |
| hour_mode | `12` or `24` | **Optional** | Hour format. If `12`, card will show AM/PM picker | `24` |
| hour_step | number | **Optional** | Hour change when clicking arrows | `1` |
| minute_step | number | **Optional** | Minute change when clicking arrows | `5` |
| second_step | number | **Optional** | Second change when clicking arrows (only with `hide.seconds: false`) | `5` |
| delay | number | **Optional** | Delay in ms before updating entity | `0` |
| layout | object | **Optional** | Card Layout configuration | `none` |
| hide | object | **Optional** | Hide object | `none` |
| tap_action | action | **Optional** | Home assistant action to perform on tap | `more-info` |
| double_tap_action | action | **Optional** | Home assistant action to perform on tap | `more-info` |
| hold_action | action | **Optional** | Home assistant action to perform on tap | `more-info` |
### Layout Object
@@ -156,6 +167,30 @@ you can use the following variables in your theme's config file:
| time-picker-border-radius | `var(--ha-card-border-radius)` | Border radius of the card |
| time-picker-control-padding | `8px` | Padding for interactive elements. Increase for larger hitboxes of the controls. Example: `10px 12px` |
### Structured names
_Requires Home Assistant 2026.4 or later. On earlier versions a structured `name` falls back to the entity's friendly name._
Home Assistant composes an entity's display name out of its registry context
(entity, device, area, floor) rather than one `friendly_name` string. `name` can
be a list of those parts instead of a plain string, so it keeps following renames
and matches what the built-in cards show:
```yaml
type: custom:time-picker-card
entity: input_datetime.alarm
name:
- type: area
- type: entity
```
Available part types are `entity`, `device`, `area`, `floor`, and
`text` (a literal, written as `{type: text, text: 'Alarm'}`). Parts that resolve to
nothing are dropped. A plain string `name` keeps working exactly as before, and the
visual editor offers both modes on Home Assistant 2025.11 and later.
See the [Home Assistant developer documentation](https://developers.home-assistant.io/docs/frontend/data#hassformatentitynamestateobj-name-options) for details.
## Meta
**Georgi Gardev**
@@ -170,9 +205,9 @@ you can use the following variables in your theme's config file:
[downloads-link]: https://github.com/GeorgeSG/lovelace-time-picker-card/releases
[releases-shield]: https://img.shields.io/github/release/GeorgeSG/lovelace-time-picker-card.svg
[releases-link]: https://github.com/GeorgeSG/lovelace-time-picker-card/releases
[ci-shield]: https://img.shields.io/github/workflow/status/GeorgeSG/lovelace-time-picker-card/CI?label=CI&logo=github&
[ci-shield]: https://img.shields.io/github/actions/workflow/status/GeorgeSG/lovelace-time-picker-card/ci.yaml?branch=master&label=CI&logo=github
[ci-link]: https://github.com/GeorgeSG/lovelace-time-picker-card/actions?query=workflow%3ACI
[maintenance-shield]: https://img.shields.io/maintenance/yes/2022.svg
[maintenance-shield]: https://img.shields.io/maintenance/yes/2026.svg
[maintenance-link]: https://github.com/GeorgeSG/lovelace-time-picker-card
[license-shield]: https://img.shields.io/github/license/GeorgeSG/lovelace-time-picker-card?color=brightgreen
[license-link]: https://github.com/GeorgeSG/lovelace-time-picker-card/blob/master/LICENSE
+2 -8
View File
@@ -6,18 +6,12 @@ homeassistant:
logger:
default: info
logs:
hacs: debug
lovelace:
mode: yaml
resource_mode: yaml
resources:
- type: module
url: /hacsfiles/button-card/button-card.js
- type: module
url: /hacsfiles/lovelace-state-switch/state-switch.js
- type: module
url: http://127.0.0.1:5000/time-picker-card.js
url: http://127.0.0.1:5100/time-picker-card.js
dashboards:
lovelace-home:
mode: yaml
@@ -0,0 +1,12 @@
# Test entities for the Time Picker Card dev dashboard (ui-lovelace.yaml).
input_datetime:
test_date_time:
name: Test date time
has_date: true
has_time: true
initial: '2026-01-01 07:30:00'
test_date:
name: Test date (no time)
has_date: true
has_time: false
initial: '2026-01-01'
+8 -9
View File
@@ -6,7 +6,7 @@ views:
- type: vertical-stack
cards:
- type: markdown
content: "# 🕰 Time Picker Card dev"
content: '# 🕰 Time Picker Card dev'
- type: entities
entities:
- input_datetime.test_date_time
@@ -21,20 +21,20 @@ views:
action: call-service
service: logbook.log
service_data:
name: "Time picker card · Tap Action"
message: "Debug"
name: 'Time picker card · Tap Action'
message: 'Debug'
double_tap_action:
action: call-service
service: logbook.log
service_data:
name: "Time picker card · Double Tap Action"
message: "Debug"
name: 'Time picker card · Double Tap Action'
message: 'Debug'
hold_action:
action: call-service
service: logbook.log
service_data:
name: "Time picker card · Hold action"
message: "Debug"
name: 'Time picker card · Hold action'
message: 'Debug'
- type: custom:time-picker-card
name: Hour mode 12, thin, single, hidden name
entity: input_datetime.test_date_time
@@ -60,7 +60,7 @@ views:
thin: true
- type: custom:time-picker-card
entity: input_datetime.test_date_time
name: Hidden seconds
name: Shown seconds
hide:
seconds: false
@@ -120,7 +120,6 @@ views:
cards:
- type: vertical-stack
cards:
- type: entities
entities:
- input_datetime.test_date_time
+31
View File
@@ -0,0 +1,31 @@
import js from '@eslint/js';
import { defineConfig, globalIgnores } from 'eslint/config';
import prettier from 'eslint-config-prettier';
import lit from 'eslint-plugin-lit';
import wc from 'eslint-plugin-wc';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default defineConfig([
globalIgnores(['dist/', 'node_modules/', 'devtools/']),
js.configs.recommended,
tseslint.configs.recommended,
lit.configs['flat/recommended'],
wc.configs['flat/recommended'],
{
languageOptions: {
globals: globals.browser,
parserOptions: { experimentalDecorators: true },
},
rules: {
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-namespace': 'off',
'@typescript-eslint/explicit-function-return-type': ['warn', { allowExpressions: true }],
},
},
{
files: ['*.config.{js,ts}'],
languageOptions: { globals: globals.node },
},
prettier,
]);
-8
View File
@@ -1,8 +0,0 @@
module.exports = {
preset: 'ts-jest/presets/js-with-babel',
testRegex: '/test/.*\\.test?\\.ts$',
transformIgnorePatterns: [
'node_modules/(?!(testing-library__dom|@open-wc|lit-html|lit-element|pure-lit|lit-element-state-decoupler)/)',
],
moduleFileExtensions: ['ts', 'js'],
};
+2240 -4187
View File
File diff suppressed because it is too large Load Diff
+35 -23
View File
@@ -13,38 +13,50 @@
"lovelace-custom-card"
],
"license": "MIT",
"type": "module",
"repository": "git@github.com:GeorgeSG/lovelace-time-picker-card.git",
"engines": {
"node": ">=24",
"npm": ">=11"
},
"scripts": {
"start": "rollup -c --watch --bundleConfigAsCjs",
"build": "npm run lint && npm run rollup",
"lint": "eslint src/*.ts",
"rollup": "rollup -c --bundleConfigAsCjs",
"test": "jest",
"start": "rollup -c --watch",
"build": "npm run lint && npm run typecheck && npm run rollup",
"lint": "eslint .",
"rollup": "rollup -c",
"test": "vitest run",
"release-patch": "npm version patch && git push origin master --tags",
"release-minor": "npm version minor && git push origin master --tags",
"release-major": "npm version major && git push origin master --tags",
"start:ha": "docker run --rm -p8124:8123 -v $(pwd)/devtools/homeassistant:/config homeassistant/home-assistant:latest"
"start:ha": "docker run --rm -p8124:8123 -v $(pwd)/devtools/homeassistant:/config homeassistant/home-assistant:latest",
"test:watch": "vitest",
"typecheck": "tsc --noEmit",
"format": "prettier --write .",
"format:check": "prettier --check ."
},
"dependencies": {
"custom-card-helpers": "^1.9.0",
"home-assistant-js-websocket": "^8.0.0",
"lit": "^2.8.0"
"custom-card-helpers": "^2.0.0",
"home-assistant-js-websocket": "^9.7.0",
"lit": "^3.3.3"
},
"devDependencies": {
"@el3um4s/rollup-plugin-terser": "^1.0.2",
"@rollup/plugin-babel": "^6.0.2",
"@rollup/plugin-commonjs": "^28.0.1",
"@eslint/js": "^10.0.1",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^15.0.1",
"@rollup/plugin-typescript": "^12.1.1",
"@types/jest": "^29.2.1",
"@typescript-eslint/eslint-plugin": "^8.13.0",
"eslint": "^8.26.0",
"jest": "^29.2.2",
"prettier": "^3.3.3",
"rollup": "^4.24.4",
"rollup-plugin-serve": "^2.0.1",
"ts-jest": "^29.0.3",
"typescript": "^5.6.3"
"@rollup/plugin-node-resolve": "^16.0.3",
"@rollup/plugin-terser": "^1.0.0",
"@rollup/plugin-typescript": "^12.3.0",
"eslint": "^10.10.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-lit": "^2.3.1",
"eslint-plugin-wc": "^3.1.0",
"globals": "^17.12.0",
"happy-dom": "^21.0.4",
"prettier": "^3.9.6",
"rollup": "^4.63.3",
"rollup-plugin-serve": "^3.0.0",
"tslib": "^2.8.1",
"typescript": "~6.0.3",
"typescript-eslint": "^8.70.0",
"vitest": "^5.0.1"
}
}
+3 -7
View File
@@ -1,16 +1,15 @@
import nodeResolve from '@rollup/plugin-node-resolve';
import json from '@rollup/plugin-json';
import typescript from '@rollup/plugin-typescript';
import { terser } from '@el3um4s/rollup-plugin-terser';
import babel from '@rollup/plugin-babel';
import terser from '@rollup/plugin-terser';
import serve from 'rollup-plugin-serve';
const dev = process.env.ROLLUP_WATCH;
const serveOptions = {
contentBase: ['./dist'],
host: 'localhost',
port: 5000,
host: '127.0.0.1', // 'localhost' resolves to ::1 on Node 17+, but HA loads the card from 127.0.0.1
port: 5100, // 5000 is taken by the macOS AirPlay Receiver
allowCrossOrigin: true,
headers: {
'Access-Control-Allow-Origin': '*',
@@ -27,9 +26,6 @@ export default {
typescript({ exclude: ['test/**/*'] }),
nodeResolve(),
json(),
babel({
exclude: 'node_modules/**',
}),
dev && serve(serveOptions),
!dev && terser(),
],
+4 -5
View File
@@ -1,8 +1,7 @@
import { noChange } from 'lit';
import { AttributePart, directive, Directive, DirectiveParameters } from 'lit/directive.js';
import { fireEvent } from 'custom-card-helpers';
import { ActionHandlerDetail, ActionHandlerOptions } from 'custom-card-helpers/dist/types';
import { ActionHandlerDetail, ActionHandlerOptions, fireEvent } from 'custom-card-helpers';
const isTouch =
'ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.maxTouchPoints > 0;
@@ -10,7 +9,7 @@ const isTouch =
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
interface ActionHandler extends HTMLElement {
holdTime: number;
bind(element: Element, options): void;
bind(element: Element, options?: ActionHandlerOptions): void;
}
interface ActionHandlerElement extends HTMLElement {
@@ -69,7 +68,7 @@ class ActionHandler extends HTMLElement implements ActionHandler {
);
}
public bind(element: ActionHandlerElement, options): void {
public bind(element: ActionHandlerElement, options: ActionHandlerOptions = {}): void {
if (element.actionHandler) {
return;
}
@@ -201,7 +200,7 @@ export const actionHandler = directive(
return noChange;
}
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars, @typescript-eslint/explicit-function-return-type
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/explicit-function-return-type
render(_options?: ActionHandlerOptions) {}
},
);
+1
View File
@@ -5,6 +5,7 @@ export const CARD_VERSION = pkg.version;
export const CARD_SIZE = 3;
export const ENTITY_DOMAIN = 'input_datetime';
export const TIME_ENTITY_DOMAIN = 'time';
// Config defaults
export const DEFAULT_HOUR_STEP = 1;
+18 -11
View File
@@ -1,10 +1,11 @@
import { HomeAssistant, LovelaceCardEditor } from 'custom-card-helpers';
import { supportsEntityNameSelector } from './entity-name';
import { html, LitElement, TemplateResult } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { TimePickerCardConfig } from './types';
const NAME_TO_LABEL_MAP = {
entity: 'input_datetime entity id',
const NAME_TO_LABEL_MAP: Record<string, string> = {
entity: 'time or input_datetime entity id',
name: 'Name',
hour_step: 'Hour step',
minute_step: 'Minute step',
@@ -17,12 +18,18 @@ const NAME_TO_LABEL_MAP = {
seconds: 'Seconds',
};
const SCHEMA = [
{ name: 'entity', selector: { entity: { domain: 'input_datetime' } } },
{
name: 'name',
selector: { text: {} },
},
type FormSchemaEntry = Record<string, unknown>;
// The entity_name selector, which lets users compose a name out of registry
// parts, was added in HA 2025.11. Older versions fall back to a plain text field.
const nameSchema = (hass: HomeAssistant): FormSchemaEntry =>
supportsEntityNameSelector(hass)
? { name: 'name', selector: { entity_name: {} }, context: { entity: 'entity' } }
: { name: 'name', selector: { text: {} } };
const schema = (hass: HomeAssistant): FormSchemaEntry[] => [
{ name: 'entity', selector: { entity: { domain: ['input_datetime', 'time'] } } },
nameSchema(hass),
{
type: 'grid',
schema: [
@@ -121,7 +128,7 @@ export class TimePickerCardEditor extends LitElement implements LovelaceCardEdit
@property({ type: Object }) hass!: HomeAssistant;
@property() private config!: TimePickerCardConfig;
private computeLabel({ name }): string {
private computeLabel({ name }: { name: string }): string {
return NAME_TO_LABEL_MAP[name] || name;
}
@@ -135,14 +142,14 @@ export class TimePickerCardEditor extends LitElement implements LovelaceCardEdit
<ha-form
.hass=${this.hass}
.data=${this.config}
.schema=${SCHEMA}
.schema=${schema(this.hass)}
.computeLabel=${this.computeLabel}
@value-changed=${this.valueChanged}
></ha-form>
`;
}
setConfig(config): void {
setConfig(config: TimePickerCardConfig): void {
this.config = config;
}
+60
View File
@@ -0,0 +1,60 @@
import { HomeAssistant } from 'custom-card-helpers';
import { HassEntity } from 'home-assistant-js-websocket';
import { EntityName } from './types';
// hass.formatEntityName only accepts a card's `name` option (a user string, a
// structured name, or undefined) from HA 2026.4. Earlier versions expose the
// same helper with an incompatible signature, so feature detection is not
// enough - the version has to be checked.
function atLeastVersion(hass: HomeAssistant, major: number, minor: number): boolean {
const [haMajor, haMinor] = (hass.config?.version ?? '').split('.', 2);
return Number(haMajor) > major || (Number(haMajor) === major && Number(haMinor) >= minor);
}
function supportsEntityNames(hass: HomeAssistant): boolean {
// A hass can report a recent version without carrying the helper (a test
// harness, or a hass that has not finished initialising), and calling it
// then throws - so the version gate alone is not enough.
if (!hass || typeof (hass as { formatEntityName?: unknown }).formatEntityName !== 'function') {
return false;
}
return atLeastVersion(hass, 2026, 4);
}
/**
* The `entity_name` selector, which lets users compose a name out of registry
* parts in the visual editor, was added in HA 2025.11.
*/
export function supportsEntityNameSelector(hass: HomeAssistant): boolean {
return atLeastVersion(hass, 2025, 11);
}
type HassWithEntityNames = HomeAssistant & {
formatEntityName: (stateObj: HassEntity, name: EntityName | undefined) => string;
};
/**
* Resolves a `name` option against the entity's registry context (entity,
* device, area, floor). Falls back to the friendly name on Home Assistant
* versions that cannot resolve a structured name.
*/
export function computeEntityName(
hass: HomeAssistant,
stateObj: HassEntity | undefined,
name: EntityName | undefined,
): string | undefined {
// A configured empty name has always meant "use Home Assistant's name", but
// formatEntityName returns any string verbatim - including the empty one, which
// would blank the label. Normalise it to undefined so the formatter composes.
if (name === '') name = undefined;
const configuredName = typeof name === 'string' ? name : undefined;
if (!stateObj) {
return configuredName;
}
if (supportsEntityNames(hass)) {
return (hass as HassWithEntityNames).formatEntityName(stateObj, name);
}
return configuredName ?? stateObj.attributes.friendly_name;
}
+5 -1
View File
@@ -8,7 +8,11 @@ import { TimeUnit } from './time-unit';
export class Hour extends TimeUnit {
private static readonly VALUE_LIMIT = 24;
constructor(value: number, step = DEFAULT_HOUR_STEP, private hourMode?: HourMode) {
constructor(
value: number,
step = DEFAULT_HOUR_STEP,
private hourMode?: HourMode,
) {
super(value, step, Hour.VALUE_LIMIT);
}
+10 -2
View File
@@ -19,7 +19,11 @@ export abstract class TimeUnit {
* @param _step how much to increase / decrease the value when step-changing
* @param _limit value upper limit
*/
constructor(private _value: number, protected _step: number, protected _limit: number) {}
constructor(
private _value: number,
protected _step: number,
protected _limit: number,
) {}
get value(): number {
return this._value;
@@ -40,7 +44,11 @@ export abstract class TimeUnit {
* @param direction
*/
stepUpdate(direction: Direction, step: number = this._step): void {
direction === Direction.UP ? this.increment(step) : this.decrement(step);
if (direction === Direction.UP) {
this.increment(step);
} else {
this.decrement(step);
}
}
toString(): string {
+1 -1
View File
@@ -8,7 +8,7 @@ export class Time {
public hour: Hour,
public minute: Minute,
public second: Second,
private _linkValues: boolean = false
private _linkValues: boolean = false,
) {}
hourStep(direction: Direction): void {
+75 -38
View File
@@ -11,6 +11,7 @@ import { css, CSSResult, html, LitElement, TemplateResult } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { ClassInfo, classMap } from 'lit/directives/class-map.js';
import { actionHandler } from './action-handler-directive';
import { computeEntityName } from './entity-name';
import './components/time-period.component';
import './components/time-unit.component';
import {
@@ -23,6 +24,7 @@ import {
DEFAULT_LAYOUT_NAME,
DEFAULT_MINUTE_STEP,
ENTITY_DOMAIN,
TIME_ENTITY_DOMAIN,
} from './const';
import './editor';
import { Hour } from './models/hour';
@@ -35,14 +37,14 @@ import { Layout, Period, TimePickerCardConfig, TimePickerHideConfig } from './ty
console.info(
`%c TIME-PICKER-CARD \n%c Version ${CARD_VERSION} `,
'color: orange; font-weight: bold; background: black',
'color: white; font-weight: bold; background: dimgray'
'color: white; font-weight: bold; background: dimgray',
);
window.customCards = window.customCards || [];
window.customCards.push({
type: 'time-picker-card',
name: 'Time Picker Card',
description: 'A Time Picker card for setting the time value of Input Datetime entities.',
description: 'A Time Picker card for input_datetime and time entities.',
});
@customElement('time-picker-card')
@@ -79,7 +81,7 @@ export class TimePickerCard extends LitElement implements LovelaceCard {
}
private get name(): string | undefined {
return this.config.name || this.entity?.attributes.friendly_name;
return computeEntityName(this.hass, this.entity, this.config.name);
}
private get shouldShowPeriod(): boolean {
@@ -132,7 +134,7 @@ export class TimePickerCard extends LitElement implements LovelaceCard {
private renderNestedName(
name: string,
entity: HassEntity,
hide?: TimePickerHideConfig
hide?: TimePickerHideConfig,
): TemplateResult {
const icon = html`<state-badge
class="entity-icon"
@@ -169,18 +171,33 @@ export class TimePickerCard extends LitElement implements LovelaceCard {
return Partial.error('Entity not found', this.config);
}
if (computeDomain(this.entity.entity_id) !== ENTITY_DOMAIN) {
return Partial.error(`You must set an ${ENTITY_DOMAIN} entity`, this.config);
}
if (!this.entity.attributes.has_time) {
const domain = computeDomain(this.entity.entity_id);
if (domain !== ENTITY_DOMAIN && domain !== TIME_ENTITY_DOMAIN) {
return Partial.error(
`You must set an ${ENTITY_DOMAIN} entity that sets has_time: true`,
this.config
`You must set an ${ENTITY_DOMAIN} or ${TIME_ENTITY_DOMAIN} entity`,
this.config,
);
}
const { hour, minute, second } = this.entity!.attributes;
if (domain === ENTITY_DOMAIN && !this.entity.attributes.has_time) {
return Partial.error(
`You must set an ${ENTITY_DOMAIN} entity that sets has_time: true`,
this.config,
);
}
let hour: number;
let minute: number;
let second: number;
if (domain === TIME_ENTITY_DOMAIN) {
const match = /^(\d{2}):(\d{2}):(\d{2})$/.exec(this.entity.state);
if (!match || Number(match[1]) > 23 || Number(match[2]) > 59 || Number(match[3]) > 59) {
return Partial.error('The time entity has no valid HH:MM:SS value', this.config);
}
[hour, minute, second] = match.slice(1).map(Number);
} else {
({ hour, minute, second } = this.entity.attributes);
}
const hourInstance = new Hour(hour, this.config.hour_step, this.config.hour_mode);
const minuteInstance = new Minute(minute, this.config.minute_step);
const secondInstance = new Second(second, this.config.second_step);
@@ -191,9 +208,11 @@ export class TimePickerCard extends LitElement implements LovelaceCard {
<ha-card class=${classMap(this.haCardClass)}>
${this.hasNameInHeader ? this.renderHeaderName(this.name!) : ''}
<div class=${classMap(this.rowClass)}>
${this.hasNameInside
? this.renderNestedName(this.name!, this.entity, this.config.hide)
: ''}
${
this.hasNameInside
? this.renderNestedName(this.name!, this.entity, this.config.hide)
: ''
}
<div class=${classMap(this.contentClass)}>
<time-unit
@@ -207,28 +226,32 @@ export class TimePickerCard extends LitElement implements LovelaceCard {
@stepChange=${this.onMinuteStepChange}
@update=${this.debouncedCallHassService}
></time-unit>
${this.config.hide?.seconds === false
? html`<div class="time-separator">:</div>
<time-unit
.unit=${this.time.second}
@stepChange=${this.onSecondStepChange}
@update=${this.debouncedCallHassService}
></time-unit>`
: ''}
${this.shouldShowPeriod
? html`<time-period
.period=${this.period}
.mode=${this.config.layout?.hour_mode ?? DEFAULT_LAYOUT_HOUR_MODE}
@toggle=${this.onPeriodToggle}
></time-period>`
: ''}
${
this.config.hide?.seconds === false
? html`<div class="time-separator">:</div>
<time-unit
.unit=${this.time.second}
@stepChange=${this.onSecondStepChange}
@update=${this.debouncedCallHassService}
></time-unit>`
: ''
}
${
this.shouldShowPeriod
? html`<time-period
.period=${this.period}
.mode=${this.config.layout?.hour_mode ?? DEFAULT_LAYOUT_HOUR_MODE}
@toggle=${this.onPeriodToggle}
></time-period>`
: ''
}
</div>
</div>
</ha-card>
`;
}
setConfig(config): void {
setConfig(config: TimePickerCardConfig): void {
if (!config) {
throw new Error('Invalid configuration');
}
@@ -279,13 +302,25 @@ export class TimePickerCard extends LitElement implements LovelaceCard {
private callHassService(): Promise<void> {
if (!this.hass) {
throw new Error('Unable to update datetime');
throw new Error('Unable to update time');
}
return this.hass.callService(ENTITY_DOMAIN, 'set_datetime', {
entity_id: this.entity!.entity_id,
time: this.time.value,
});
const domain = computeDomain(this.entity!.entity_id);
const time =
domain === TIME_ENTITY_DOMAIN
? [this.time.hour.value, this.time.minute.value, this.time.second.value]
.map((value) => String(value).padStart(2, '0'))
.join(':')
: this.time.value;
return this.hass.callService(
domain,
domain === TIME_ENTITY_DOMAIN ? 'set_value' : 'set_datetime',
{
entity_id: this.entity!.entity_id,
time,
},
);
}
static get styles(): CSSResult {
@@ -381,9 +416,11 @@ export class TimePickerCard extends LitElement implements LovelaceCard {
static getStubConfig(
_: HomeAssistant,
entities: Array<string>
entities: Array<string>,
): Omit<TimePickerCardConfig, 'type'> {
const datetimeEntity = entities.find((entityId) => computeDomain(entityId) === ENTITY_DOMAIN);
const datetimeEntity = entities.find((entityId) =>
[ENTITY_DOMAIN, TIME_ENTITY_DOMAIN].includes(computeDomain(entityId)),
);
return {
entity: datetimeEntity || '',
+7 -1
View File
@@ -2,7 +2,7 @@ import { ActionConfig, LovelaceCardConfig } from 'custom-card-helpers';
export interface TimePickerCardConfig extends LovelaceCardConfig {
entity: string;
name?: string;
name?: EntityName;
link_values?: boolean;
hour_mode?: HourMode;
hour_step?: number;
@@ -16,6 +16,12 @@ export interface TimePickerCardConfig extends LovelaceCardConfig {
hold_action?: ActionConfig;
}
/** A `name` option: a plain string, or name parts resolved from the registry. */
export type EntityName = string | EntityNameItem | EntityNameItem[];
export type EntityNameItem =
{ type: 'entity' | 'device' | 'area' | 'floor' } | { type: 'text'; text: string };
export type HourMode = 12 | 24 | undefined;
export interface TimePickerLayoutConfig {
+78
View File
@@ -0,0 +1,78 @@
import { describe, it, expect, vi } from 'vitest';
import { HomeAssistant } from 'custom-card-helpers';
import { HassEntity } from 'home-assistant-js-websocket';
import { computeEntityName, supportsEntityNameSelector } from '../src/entity-name';
const entity: HassEntity = {
entity_id: 'input_datetime.alarm',
state: '07:30:00',
attributes: { friendly_name: 'Alarm' },
last_changed: '',
last_updated: '',
context: { id: '', user_id: null, parent_id: null },
};
const hassWithVersion = (
version: string | undefined,
extra: Record<string, unknown> = {},
): HomeAssistant =>
({ config: version ? { version } : undefined, ...extra }) as unknown as HomeAssistant;
describe('supportsEntityNameSelector', () => {
it('is false before Home Assistant 2025.11', () => {
expect(supportsEntityNameSelector(hassWithVersion('2025.10.3'))).toBe(false);
expect(supportsEntityNameSelector(hassWithVersion('2024.12.0'))).toBe(false);
});
it('is true from Home Assistant 2025.11', () => {
expect(supportsEntityNameSelector(hassWithVersion('2025.11.0'))).toBe(true);
expect(supportsEntityNameSelector(hassWithVersion('2026.1.0'))).toBe(true);
});
it('is false when the version is unknown', () => {
expect(supportsEntityNameSelector(hassWithVersion(undefined))).toBe(false);
});
});
describe('computeEntityName', () => {
it('returns the configured string when there is no entity', () => {
expect(computeEntityName(hassWithVersion('2026.9.0'), undefined, 'Wake up')).toEqual('Wake up');
expect(computeEntityName(hassWithVersion('2026.9.0'), undefined, undefined)).toBeUndefined();
expect(
computeEntityName(hassWithVersion('2026.9.0'), undefined, [{ type: 'area' }]),
).toBeUndefined();
});
it('delegates to hass.formatEntityName from Home Assistant 2026.4', () => {
const formatEntityName = vi.fn().mockReturnValue('Bedroom Alarm');
const hass = hassWithVersion('2026.4.0', { formatEntityName });
const name = [{ type: 'area' as const }, { type: 'entity' as const }];
expect(computeEntityName(hass, entity, name)).toEqual('Bedroom Alarm');
expect(formatEntityName).toHaveBeenCalledWith(entity, name);
});
it('passes an undefined name through to hass.formatEntityName', () => {
const formatEntityName = vi.fn().mockReturnValue('Alarm');
computeEntityName(hassWithVersion('2026.4.0', { formatEntityName }), entity, undefined);
expect(formatEntityName).toHaveBeenCalledWith(entity, undefined);
});
it('falls back to the friendly name before Home Assistant 2026.4', () => {
const formatEntityName = vi.fn();
const hass = hassWithVersion('2026.3.2', { formatEntityName });
expect(computeEntityName(hass, entity, [{ type: 'area' }])).toEqual('Alarm');
expect(computeEntityName(hass, entity, undefined)).toEqual('Alarm');
expect(formatEntityName).not.toHaveBeenCalled();
});
it('prefers a configured string over the friendly name on older versions', () => {
expect(computeEntityName(hassWithVersion('2026.3.2'), entity, 'Wake up')).toEqual('Wake up');
});
it('falls back when a recent hass does not carry formatEntityName', () => {
expect(computeEntityName(hassWithVersion('2026.9.0'), entity, 'Wake up')).toEqual('Wake up');
expect(computeEntityName(hassWithVersion('2026.9.0'), entity, undefined)).toEqual('Alarm');
});
});
+1
View File
@@ -1,3 +1,4 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { Hour } from '../../src/models/hour';
import { Direction } from '../../src/types';
import { DEFAULT_HOUR_STEP } from '../../src/const';
+1
View File
@@ -1,3 +1,4 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { Minute } from '../../src/models/minute';
import { Direction } from '../../src/types';
+1
View File
@@ -1,3 +1,4 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { Second } from '../../src/models/second';
import { Direction } from '../../src/types';
+77
View File
@@ -0,0 +1,77 @@
import { describe, it, expect } from 'vitest';
import { Hour } from '../../src/models/hour';
import { Minute } from '../../src/models/minute';
import { Second } from '../../src/models/second';
import { Time } from '../../src/models/time';
import { Direction } from '../../src/types';
const time = (h: number, m: number, s: number, linkValues = false): Time =>
new Time(new Hour(h), new Minute(m, 5), new Second(s, 5), linkValues);
describe('Time', () => {
describe('value', () => {
it('joins the units with colons', () => {
expect(time(7, 5, 0).value).toEqual('7:5:0');
});
});
describe('hourStep', () => {
it('steps the hour without touching minutes', () => {
const t = time(23, 30, 0);
t.hourStep(Direction.UP);
expect([t.hour.value, t.minute.value]).toEqual([0, 30]);
});
});
describe('minuteStep', () => {
it('does not change the hour when values are not linked', () => {
const t = time(11, 55, 0);
t.minuteStep(Direction.UP);
expect([t.hour.value, t.minute.value]).toEqual([11, 0]);
});
it('carries an overflow into the next hour when values are linked', () => {
const t = time(11, 55, 0, true);
t.minuteStep(Direction.UP);
expect([t.hour.value, t.minute.value]).toEqual([12, 0]);
});
it('borrows from the previous hour when values are linked', () => {
const t = time(0, 0, 0, true);
t.minuteStep(Direction.DOWN);
expect([t.hour.value, t.minute.value]).toEqual([23, 55]);
});
it('carries by one hour regardless of the hour step', () => {
const t = new Time(new Hour(10, 3), new Minute(55, 5), new Second(0), true);
t.minuteStep(Direction.UP);
expect(t.hour.value).toEqual(11);
});
it('does not carry when the step stays within the hour', () => {
const t = time(10, 30, 0, true);
t.minuteStep(Direction.UP);
expect([t.hour.value, t.minute.value]).toEqual([10, 35]);
});
});
describe('secondStep', () => {
it('does not change the minute when values are not linked', () => {
const t = time(10, 30, 55);
t.secondStep(Direction.UP);
expect([t.minute.value, t.second.value]).toEqual([30, 0]);
});
it('carries an overflow into the next minute when values are linked', () => {
const t = time(10, 30, 55, true);
t.secondStep(Direction.UP);
expect([t.minute.value, t.second.value]).toEqual([31, 0]);
});
it('borrows from the previous minute when values are linked', () => {
const t = time(10, 30, 0, true);
t.secondStep(Direction.DOWN);
expect([t.minute.value, t.second.value]).toEqual([29, 55]);
});
});
});
+219
View File
@@ -0,0 +1,219 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { LitElement } from 'lit';
import { HomeAssistant } from 'custom-card-helpers';
import { HassEntity } from 'home-assistant-js-websocket';
import '../src/time-picker-card';
import { TimePickerCard } from '../src/time-picker-card';
import { TimePickerCardConfig } from '../src/types';
// The card renders Home Assistant's error card for invalid configs; stub the
// element so the test can read the error it was given.
class ErrorCardStub extends HTMLElement {
config?: { error: string };
setConfig(config: { error: string }): void {
this.config = config;
}
}
customElements.define('hui-error-card', ErrorCardStub);
const ENTITY_ID = 'input_datetime.alarm';
const TIME_ENTITY_ID = 'time.alarm_time';
/** YAML is untyped at runtime, so setConfig has to cope with shapes the type forbids. */
const invalidConfig = (config: Record<string, unknown>): TimePickerCardConfig =>
config as unknown as TimePickerCardConfig;
const alarm = (hour: number, minute = 30, second = 0): HassEntity => ({
entity_id: ENTITY_ID,
state: `${hour}:${minute}:${second}`,
attributes: { friendly_name: 'Alarm', has_time: true, has_date: false, hour, minute, second },
last_changed: '',
last_updated: '',
context: { id: '', user_id: null, parent_id: null },
});
const timeEntity = (state = '07:30:00'): HassEntity => ({
...alarm(7),
entity_id: TIME_ENTITY_ID,
state,
attributes: { friendly_name: 'Alarm time' },
});
const createHass = (entity: HassEntity = alarm(7)): HomeAssistant =>
({
states: { [entity.entity_id]: entity },
config: { version: '2026.9.2' },
callService: vi.fn().mockResolvedValue(undefined),
}) as unknown as HomeAssistant;
const renderCard = async (
config: Partial<TimePickerCardConfig>,
hass: HomeAssistant = createHass(),
): Promise<TimePickerCard> => {
const card = document.createElement('time-picker-card') as TimePickerCard;
card.setConfig({ type: 'custom:time-picker-card', entity: ENTITY_ID, ...config });
card.hass = hass;
document.body.appendChild(card);
await settle(card);
return card;
};
/** Waits for the card and its nested Lit children to finish rendering. */
const settle = async (card: TimePickerCard): Promise<void> => {
await card.updateComplete;
const children = card.shadowRoot!.querySelectorAll('time-unit, time-period');
await Promise.all(Array.from(children).map((el) => (el as LitElement).updateComplete));
};
const inputValues = (card: TimePickerCard): string[] =>
Array.from(card.shadowRoot!.querySelectorAll('time-unit')).map(
(unit) => unit.shadowRoot!.querySelector<HTMLInputElement>('input')!.value,
);
describe('time-picker-card', () => {
let card: TimePickerCard;
afterEach(() => {
card?.remove();
});
describe('setConfig', () => {
beforeEach(() => {
card = document.createElement('time-picker-card') as TimePickerCard;
});
it('rejects a missing entity', () => {
expect(() => card.setConfig(invalidConfig({ type: 'custom:time-picker-card' }))).toThrow(
'You must set an entity',
);
});
it('rejects an unknown hour mode', () => {
expect(() =>
card.setConfig(
invalidConfig({ type: 'custom:time-picker-card', entity: ENTITY_ID, hour_mode: 10 }),
),
).toThrow('Invalid hour_mode');
});
});
describe('rendering', () => {
it('shows hour and minute inputs with the entity time', async () => {
card = await renderCard({});
expect(inputValues(card)).toEqual(['07', '30']);
expect(card.shadowRoot!.querySelector('time-period')).toBeNull();
});
it('shows the entity name in the header by default', async () => {
card = await renderCard({});
expect(card.shadowRoot!.querySelector('.time-picker-header')!.textContent!.trim()).toEqual(
'Alarm',
);
});
it('shows seconds and an AM/PM toggle when configured', async () => {
card = await renderCard({ hour_mode: 12, hide: { seconds: false } });
expect(inputValues(card)).toEqual(['07', '30', '00']);
expect(card.shadowRoot!.querySelector('time-period')).not.toBeNull();
});
it('re-renders when hass delivers a new entity state', async () => {
card = await renderCard({});
card.hass = createHass(alarm(9, 45));
await settle(card);
expect(inputValues(card)).toEqual(['09', '45']);
});
it('reads a time entity from its state and follows state updates', async () => {
card = await renderCard({ entity: TIME_ENTITY_ID }, createHass(timeEntity()));
expect(inputValues(card)).toEqual(['07', '30']);
card.hass = createHass(timeEntity('09:45:06'));
await settle(card);
expect(inputValues(card)).toEqual(['09', '45']);
});
it('rejects an unavailable time entity instead of rendering invalid numbers', async () => {
card = await renderCard({ entity: TIME_ENTITY_ID }, createHass(timeEntity('unavailable')));
const error = card.shadowRoot!.querySelector('hui-error-card') as ErrorCardStub;
expect(error.config?.error).toContain('HH:MM:SS');
});
it('rejects entities from other domains', async () => {
const entity = { ...alarm(7), entity_id: 'sensor.alarm' };
card = await renderCard({ entity: entity.entity_id }, createHass(entity));
const error = card.shadowRoot!.querySelector('hui-error-card') as ErrorCardStub;
expect(error.config?.error).toContain('input_datetime or time');
});
it('renders an error card when the entity is missing', async () => {
card = await renderCard({ entity: 'input_datetime.missing' });
const error = card.shadowRoot!.querySelector('hui-error-card') as ErrorCardStub;
expect(error.config?.error).toEqual('Entity not found');
});
it('renders an error card when the entity has no time', async () => {
const dateOnly = { ...alarm(7), attributes: { friendly_name: 'Date', has_time: false } };
card = await renderCard({}, createHass(dateOnly));
const error = card.shadowRoot!.querySelector('hui-error-card') as ErrorCardStub;
expect(error.config?.error).toContain('has_time: true');
});
});
describe('interaction', () => {
it('calls set_datetime when an hour arrow is clicked', async () => {
const hass = createHass();
card = await renderCard({}, hass);
const hourUnit = card.shadowRoot!.querySelector('time-unit')!;
hourUnit.shadowRoot!.querySelector<HTMLElement>('.time-picker-icon')!.click();
expect(hass.callService).toHaveBeenCalledWith('input_datetime', 'set_datetime', {
entity_id: ENTITY_ID,
time: '8:30:0',
});
});
it('calls time.set_value with a zero-padded time for time entities', async () => {
const hass = createHass(timeEntity());
card = await renderCard({ entity: TIME_ENTITY_ID }, hass);
const hourUnit = card.shadowRoot!.querySelector('time-unit')!;
hourUnit.shadowRoot!.querySelector<HTMLElement>('.time-picker-icon')!.click();
expect(hass.callService).toHaveBeenCalledWith('time', 'set_value', {
entity_id: TIME_ENTITY_ID,
time: '08:30:00',
});
});
it('debounces the service call when a delay is configured', async () => {
vi.useFakeTimers();
try {
const hass = createHass();
card = await renderCard({ delay: 500 }, hass);
const [up] = Array.from(
card
.shadowRoot!.querySelector('time-unit')!
.shadowRoot!.querySelectorAll<HTMLElement>('.time-picker-icon'),
);
up.click();
up.click();
expect(hass.callService).not.toHaveBeenCalled();
vi.advanceTimersByTime(500);
expect(hass.callService).toHaveBeenCalledTimes(1);
expect(hass.callService).toHaveBeenCalledWith('input_datetime', 'set_datetime', {
entity_id: ENTITY_ID,
time: '9:30:0',
});
} finally {
vi.useRealTimers();
}
});
});
it('offers time entities in the generated configuration', () => {
expect(
TimePickerCard.getStubConfig(createHass(), ['sensor.unknown', TIME_ENTITY_ID]).entity,
).toBe(TIME_ENTITY_ID);
});
});
+15 -8
View File
@@ -1,18 +1,25 @@
{
// TypeScript stays on the 6.0 line: typescript-eslint declares a peer range of
// >=4.8.4 <6.1.0, and @rollup/plugin-typescript needs the JS compiler API
// that the native (7.x) compiler does not expose yet.
"compilerOptions": {
"target": "es2017",
"module": "esnext",
"moduleResolution": "node",
"lib": ["es2017", "dom", "dom.iterable"],
"target": "ES2021",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2021", "DOM", "DOM.Iterable"],
"noEmit": true,
"strict": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"strict": true,
"noImplicitAny": false,
"skipLibCheck": true,
"resolveJsonModule": true,
"isolatedModules": true,
// Lit reactive properties rely on TypeScript's legacy decorators. Keep
// useDefineForClassFields off: it defaults to true for target >= ES2022 and
// then class fields silently shadow the accessors that @property() installs.
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true // for importing sinon in tests
}
"useDefineForClassFields": false
},
"include": ["src", "test", "vitest.config.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['test/**/*.test.ts'],
environment: 'happy-dom',
},
});