Compare commits

...
10 Commits
Author SHA1 Message Date
GeorgeSG fe93d385e9 1.0.0 2020-07-17 20:22:38 +03:00
GeorgeSG 05e0952624 Implements #5: Add link_values option 2020-07-17 20:20:42 +03:00
GeorgeSG 3c10a9ab44 Fixes #6: Inherit border-radius from theme. Add variable for border radius 2020-07-17 19:09:34 +03:00
GeorgeSG 9a2a57af5c Update README 2020-05-18 22:22:32 +03:00
GeorgeSG 74949a3df2 0.1.1 2020-05-10 00:22:45 +03:00
GeorgeSG 224ee3b043 Remove commit activity from README 2020-05-10 00:18:38 +03:00
GeorgeSG 2e604a66d6 Update README 2020-05-10 00:17:43 +03:00
GeorgeSG b7ad71d979 Rename CI task. Don't lint twice 2020-05-10 00:15:20 +03:00
GeorgeSG 79418592c9 Fix 12AM representation. Add model tests 2020-05-10 00:13:29 +03:00
GeorgeSG 0297c9aba4 Update README 2020-05-09 20:42:35 +03:00
18 changed files with 537 additions and 109 deletions
+1 -2
View File
@@ -9,14 +9,13 @@ on:
- master - master
jobs: jobs:
build: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Build - name: Build
run: | run: |
npm install npm install
npm run lint
npm run build npm run build
- name: Test - name: Test
run: npm run test run: npm run test
+5
View File
@@ -0,0 +1,5 @@
{
"files.exclude": {
"dist/**": true
}
}
+25 -27
View File
@@ -5,7 +5,6 @@
[![GitHub Release][releases-shield]][releases-link] [![GitHub Release][releases-shield]][releases-link]
[![CI][ci-shield]][ci-link] [![CI][ci-shield]][ci-link]
[![Project Maintenance][maintenance-shield]][maintenance-link] [![Project Maintenance][maintenance-shield]][maintenance-link]
[![GitHub Activity][commits-shield]][commits-link]
[![License][license-shield]][license-link] [![License][license-shield]][license-link]
## Overview ## Overview
@@ -16,7 +15,19 @@ Requires an [Input Datetime](https://www.home-assistant.io/integrations/input_da
## Installation ## Installation
Install using [HACS](https://hacs.xyz) or follow this [guide](https://github.com/thomasloven/hass-config/wiki/Lovelace-Plugins) ### HACS
Install using [HACS](https://hacs.xyz) and add the following to your config:
```yaml
resources:
- url: /hacsfiles/lovelace-time-picker-card/time-picker-card.js
type: module
```
### Manual
Download time-picker-card.js from the [latest realease](https://github.com/GeorgeSG/lovelace-time-picker-card/releases/latest) and place it in your `config/www` folder. Add the following to your config:
```yaml ```yaml
resources: resources:
@@ -32,19 +43,6 @@ Time Picker Card supports Lovelace's Visual Editor. Click the + button to add a
![Visual Editor](https://raw.githubusercontent.com/GeorgeSG/lovelace-time-picker-card/master/examples/visual_editor.png) ![Visual Editor](https://raw.githubusercontent.com/GeorgeSG/lovelace-time-picker-card/master/examples/visual_editor.png)
### YAML
```yaml
type: 'custom:time-picker-card'
entity: input_datetime.alarm_time
name: 'Choose a time'
hour_mode: 24
hour_step: 1
minute_step: 5
hide:
name: false
```
## Examples ## Examples
### Default config - card name shown, 24 hour mode ### Default config - card name shown, 24 hour mode
@@ -105,13 +103,14 @@ layout:
| type | string | **Required** | `custom:time-picker-card` | | | 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` | | | 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` | | 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_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` | | hour_step | number | **Optional** | Hour change when clicking arrows | `1` |
| minute_step | number | **Optional** | Minute change when clicking arrows | `5` | | minute_step | number | **Optional** | Minute change when clicking arrows | `5` |
| layout | object | **Optional** | Card Layout configuration | `none` | | layout | object | **Optional** | Card Layout configuration | `none` |
| hide | object | **Optional** | Hide object | `none` | | hide | object | **Optional** | Hide object | `none` |
## Layout Object ### Layout Object
| Name | Value | Requirement | Description | Default | | Name | Value | Requirement | Description | Default |
| -------------- | ------------------------- | ------------ | -------------------------------------------------------------------------------------------------- | -------- | | -------------- | ------------------------- | ------------ | -------------------------------------------------------------------------------------------------- | -------- |
@@ -119,24 +118,25 @@ layout:
| align_controls | `left`, `center`, `right` | **Optional** | Horizontal alignment of the controls | `center` | | align_controls | `left`, `center`, `right` | **Optional** | Horizontal alignment of the controls | `center` |
| name | `header`, `inside` | **Optional** | Whether to show the name as a header or inside the card | `header` | | name | `header`, `inside` | **Optional** | Whether to show the name as a header or inside the card | `header` |
## Hide Object ### Hide Object
| Name | Type | Requirement | Description | Default | | Name | Type | Requirement | Description | Default |
| ---- | ------- | ------------ | ------------------- | ------- | | ---- | ------- | ------------ | ------------------- | ------- |
| name | boolean | **Optional** | Hides the card name | `false` | | name | boolean | **Optional** | Hides the card name | `false` |
## Theme Variables ### Theme Variables
Time Picker Card will automatically pick up colors from your lovelace theme, but if you want to customize some of them, Time Picker Card will automatically pick up colors from your lovelace theme, but if you want to customize some of them,
you can use the following variables in your theme's config file: you can use the following variables in your theme's config file:
| Name | Default | Description | | Name | Default | Description |
| ------------------------------------- | ---------------------------- | -------------------------------------- | | ------------------------------------- | ------------------------------ | -------------------------------------- |
| time-picker-elements-background-color | `var(--primary-color)` | Background color for header and inputs | | time-picker-elements-background-color | `var(--primary-color)` | Background color for header and inputs |
| time-picker-icon-color | `var(--primary-text-color)` | Arrow color | | time-picker-icon-color | `var(--primary-text-color)` | Arrow color |
| time-picker-text-color | `white` | Text color | | time-picker-text-color | `white` | Text color |
| time-picker-accent-color | `var(--primary-color)` | AM / PM active color | | time-picker-accent-color | `var(--primary-color)` | AM / PM active color |
| time-picker-off-color | `var(--disabled-text-color)` | AM / PM inactive color | | time-picker-off-color | `var(--disabled-text-color)` | AM / PM inactive color |
| time-picker-border-radius | `var(--ha-card-border-radius)` | Border radius of the card |
## Meta ## Meta
@@ -156,8 +156,6 @@ you can use the following variables in your theme's config file:
[ci-link]: https://github.com/GeorgeSG/lovelace-time-picker-card/actions?query=workflow%3ACI [ci-link]: https://github.com/GeorgeSG/lovelace-time-picker-card/actions?query=workflow%3ACI
[maintenance-shield]: https://img.shields.io/maintenance/yes/2020.svg [maintenance-shield]: https://img.shields.io/maintenance/yes/2020.svg
[maintenance-link]: https://github.com/GeorgeSG/lovelace-time-picker-card [maintenance-link]: https://github.com/GeorgeSG/lovelace-time-picker-card
[commits-shield]: https://img.shields.io/github/commit-activity/y/GeorgeSG/lovelace-time-picker-card
[commits-link]: https://github.com/GeorgeSG/lovelace-time-picker-card/commits/master
[license-shield]: https://img.shields.io/github/license/GeorgeSG/lovelace-time-picker-card?color=brightgreen [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 [license-link]: https://github.com/GeorgeSG/lovelace-time-picker-card/blob/master/LICENSE
[github-icon]: http://i.imgur.com/9I6NRUm.png [github-icon]: http://i.imgur.com/9I6NRUm.png
+54 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "time-picker-card", "name": "time-picker-card",
"version": "0.1.0", "version": "1.0.0",
"lockfileVersion": 1, "lockfileVersion": 1,
"requires": true, "requires": true,
"dependencies": { "dependencies": {
@@ -423,6 +423,21 @@
"lit-html": "^1.0.0" "lit-html": "^1.0.0"
} }
}, },
"@rollup/plugin-commonjs": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-11.1.0.tgz",
"integrity": "sha512-Ycr12N3ZPN96Fw2STurD21jMqzKwL9QuFhms3SD7KKRK7oaXUsBU9Zt0jL/rOPHiPYisI21/rXGO3jr9BnLHUA==",
"dev": true,
"requires": {
"@rollup/pluginutils": "^3.0.8",
"commondir": "^1.0.1",
"estree-walker": "^1.0.1",
"glob": "^7.1.2",
"is-reference": "^1.1.2",
"magic-string": "^0.25.2",
"resolve": "^1.11.0"
}
},
"@rollup/plugin-json": { "@rollup/plugin-json": {
"version": "4.0.3", "version": "4.0.3",
"resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-4.0.3.tgz", "resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-4.0.3.tgz",
@@ -1086,6 +1101,12 @@
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
"dev": true "dev": true
}, },
"commondir": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz",
"integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=",
"dev": true
},
"component-bind": { "component-bind": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/component-bind/-/component-bind-1.0.0.tgz", "resolved": "https://registry.npmjs.org/component-bind/-/component-bind-1.0.0.tgz",
@@ -2167,6 +2188,23 @@
"integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
"dev": true "dev": true
}, },
"is-reference": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.1.4.tgz",
"integrity": "sha512-uJA/CDPO3Tao3GTrxYn6AwkM4nUPJiGGYu5+cB8qbC7WGFlrKZbiRo7SFKxUAEpFUfiHofWCXBUNhvYJMh+6zw==",
"dev": true,
"requires": {
"@types/estree": "0.0.39"
},
"dependencies": {
"@types/estree": {
"version": "0.0.39",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz",
"integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==",
"dev": true
}
}
},
"is-regex": { "is-regex": {
"version": "1.0.5", "version": "1.0.5",
"resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.5.tgz", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.5.tgz",
@@ -2541,6 +2579,15 @@
"streamroller": "^1.0.6" "streamroller": "^1.0.6"
} }
}, },
"magic-string": {
"version": "0.25.7",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.7.tgz",
"integrity": "sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA==",
"dev": true,
"requires": {
"sourcemap-codec": "^1.4.4"
}
},
"media-typer": { "media-typer": {
"version": "0.3.0", "version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
@@ -3421,6 +3468,12 @@
"source-map": "^0.6.0" "source-map": "^0.6.0"
} }
}, },
"sourcemap-codec": {
"version": "1.4.8",
"resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz",
"integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==",
"dev": true
},
"sprintf-js": { "sprintf-js": {
"version": "1.0.3", "version": "1.0.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
+3 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "time-picker-card", "name": "time-picker-card",
"version": "0.1.0", "version": "1.0.0",
"author": "Georgi Gardev <georgi@gardev.com>", "author": "Georgi Gardev <georgi@gardev.com>",
"description": "Lovelace time-picker-card", "description": "Lovelace time-picker-card",
"keywords": [ "keywords": [
@@ -19,7 +19,7 @@
"build": "npm run lint && npm run rollup", "build": "npm run lint && npm run rollup",
"lint": "eslint src/*.ts", "lint": "eslint src/*.ts",
"rollup": "rollup -c", "rollup": "rollup -c",
"test": "./node_modules/karma/bin/karma start", "test": "./node_modules/karma/bin/karma start ./test/karma.conf.js",
"release-patch": "npm version patch && git push origin master --tags", "release-patch": "npm version patch && git push origin master --tags",
"release-minor": "npm version minor && 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" "release-major": "npm version major && git push origin master --tags"
@@ -33,6 +33,7 @@
"devDependencies": { "devDependencies": {
"@babel/core": "^7.9.0", "@babel/core": "^7.9.0",
"@open-wc/testing": "^2.5.16", "@open-wc/testing": "^2.5.16",
"@rollup/plugin-commonjs": "^11.1.0",
"@rollup/plugin-json": "^4.0.3", "@rollup/plugin-json": "^4.0.3",
"@rollup/plugin-node-resolve": "^7.1.1", "@rollup/plugin-node-resolve": "^7.1.1",
"@rollup/plugin-typescript": "^4.0.0", "@rollup/plugin-typescript": "^4.0.0",
+5 -8
View File
@@ -16,6 +16,7 @@ import { Direction } from '../types';
@customElement('time-unit') @customElement('time-unit')
export class TimeUnitComponent extends LitElement { export class TimeUnitComponent extends LitElement {
static readonly EVENT_UPDATE = 'update'; static readonly EVENT_UPDATE = 'update';
static readonly EVENT_STEP_CHANGE = 'stepChange';
@property() private unit!: TimeUnit; @property() private unit!: TimeUnit;
@@ -27,7 +28,7 @@ export class TimeUnitComponent extends LitElement {
class="time-input" class="time-input"
type="number" type="number"
placeholder="MM" placeholder="MM"
min="0" min=${this.unit.minValue}
max=${this.unit.maxValue} max=${this.unit.maxValue}
.value="${this.unit.toString()}" .value="${this.unit.toString()}"
@change=${this.onInputChange} @change=${this.onInputChange}
@@ -39,16 +40,12 @@ export class TimeUnitComponent extends LitElement {
onInputChange({ target: { value } }: { target: HTMLInputElement }): void { onInputChange({ target: { value } }: { target: HTMLInputElement }): void {
this.unit.setStringValue(value); this.unit.setStringValue(value);
this.emitUpdate(); const event = new CustomEvent(TimeUnitComponent.EVENT_UPDATE);
this.dispatchEvent(event);
} }
onStepChangerClick(direction: Direction): void { onStepChangerClick(direction: Direction): void {
this.unit.stepUpdate(direction); const event = new CustomEvent(TimeUnitComponent.EVENT_STEP_CHANGE, { detail: { direction } });
this.emitUpdate();
}
private emitUpdate(): void {
const event = new CustomEvent(TimeUnitComponent.EVENT_UPDATE);
this.dispatchEvent(event); this.dispatchEvent(event);
} }
+39 -20
View File
@@ -61,14 +61,15 @@ export class TimePickerCardEditor extends LitElement implements LovelaceCardEdit
@value-changed=${this.onValueChange} @value-changed=${this.onValueChange}
></paper-input> ></paper-input>
<div class="side-by-side"> <div class="side-by-side">
<ha-switch <div>
style="margin-left: 10px" <ha-switch
.checked="${!Boolean(this.config.hide?.name)}" style="margin-left: 10px"
.configValue="${'hide_name'}" .checked="${!Boolean(this.config.hide?.name)}"
@change="${this.onHideNameChange}" .configValue="${'hide_name'}"
> @change="${this.onHideNameChange}"
></ha-switch>
Show name? Show name?
</ha-switch> </div>
<paper-dropdown-menu <paper-dropdown-menu
style="width: 100%" style="width: 100%"
label="Name Position (Optional)" label="Name Position (Optional)"
@@ -101,20 +102,24 @@ export class TimePickerCardEditor extends LitElement implements LovelaceCardEdit
></paper-input> ></paper-input>
</div> </div>
<div class="side-by-side"> <div class="side-by-side">
<ha-switch <div>
.checked="${this.config.hour_mode === 12}" <ha-switch
.configValue="${'hour_mode'}" .checked="${this.config.hour_mode === 12}"
@change="${this.onHourModeChange}" .configValue="${'hour_mode'}"
> @change="${this.onHourModeChange}"
></ha-switch>
12-Hour mode 12-Hour mode
</ha-switch> </div>
<ha-switch ${this.config.hour_mode === 12
.checked="${this.config.layout?.hour_mode === 'single'}" ? html`<div>
.configValue="${'hour_mode_layout'}" <ha-switch
@change="${this.onHourModeLayoutChange}" .checked="${this.config.layout?.hour_mode === 'single'}"
> .configValue="${'hour_mode_layout'}"
"Single" hour mode layout (in 12-Hour mode only) @change="${this.onHourModeLayoutChange}"
</ha-switch> ></ha-switch>
"Single" hour mode layout
</div>`
: ''}
</div> </div>
<div class="side-by-side"> <div class="side-by-side">
<paper-dropdown-menu <paper-dropdown-menu
@@ -131,6 +136,14 @@ export class TimePickerCardEditor extends LitElement implements LovelaceCardEdit
${Object.values(Layout.AlignControls).map((a) => html`<paper-item>${a}</paper-item>`)} ${Object.values(Layout.AlignControls).map((a) => html`<paper-item>${a}</paper-item>`)}
</paper-listbox> </paper-listbox>
</paper-dropdown-menu> </paper-dropdown-menu>
<div>
<ha-switch
.checked="${this.config.link_values}"
.configValue="${'link_values'}"
@change="${this.onLinkValuesChange}"
></ha-switch>
Link Values
</div>
</div> </div>
</div>`; </div>`;
} }
@@ -173,6 +186,11 @@ export class TimePickerCardEditor extends LitElement implements LovelaceCardEdit
this.dispatch(newConfig); this.dispatch(newConfig);
} }
private onLinkValuesChange({ target: { checked } }): void {
const newConfig = { ...this.config, link_values: checked };
this.dispatch(newConfig);
}
private onValueChange(e: CustomEvent): void { private onValueChange(e: CustomEvent): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const property = (e.target as any).configValue; const property = (e.target as any).configValue;
@@ -209,6 +227,7 @@ export class TimePickerCardEditor extends LitElement implements LovelaceCardEdit
return css` return css`
ha-switch { ha-switch {
padding: 16px 0; padding: 16px 0;
margin-right: 16px;
} }
.side-by-side { .side-by-side {
display: flex; display: flex;
+14 -10
View File
@@ -8,12 +8,16 @@ import { TimeUnit } from './time-unit';
export class Hour extends TimeUnit { export class Hour extends TimeUnit {
private static readonly VALUE_LIMIT = 24; 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); super(value, step, Hour.VALUE_LIMIT);
} }
get minValue(): number {
return this.hourMode === 12 ? 1 : 0; // there is no 00:00 AM -> it's 12:00 AM.
}
get maxValue(): number { get maxValue(): number {
return this.hourMode || Hour.VALUE_LIMIT; return this.hourMode === 12 ? 12 : Hour.VALUE_LIMIT - 1;
} }
togglePeriod(): void { togglePeriod(): void {
@@ -21,15 +25,15 @@ export class Hour extends TimeUnit {
} }
toString(): string { toString(): string {
const value = this.hourMode === 12 ? (this.value + 12) % 12 : this.value; let value;
if (this.hourMode === 12) {
value = (this.value + 12) % 12;
value = value === 0 ? 12 : value;
} else {
value = this.value;
}
return value < 10 ? `0${value}` : value.toString(); return value < 10 ? `0${value}` : value.toString();
} }
protected isValidString(valueStr: string): boolean {
const value = parseInt(valueStr);
const limit = this.hourMode || this._limit;
return !isNaN(value) && value >= 0 && value <= limit;
}
} }
+10 -4
View File
@@ -1,5 +1,6 @@
import { DEFAULT_MINUTE_STEP } from '../const'; import { DEFAULT_MINUTE_STEP } from '../const';
import { TimeUnit } from './time-unit'; import { TimeUnit } from './time-unit';
import { Direction } from '../types';
/** /**
* * Represents the minute value of a datetime. * * Represents the minute value of a datetime.
@@ -7,14 +8,19 @@ import { TimeUnit } from './time-unit';
export class Minute extends TimeUnit { export class Minute extends TimeUnit {
private static readonly VALUE_LIMIT = 60; private static readonly VALUE_LIMIT = 60;
maxValue = Minute.VALUE_LIMIT; minValue = 0;
maxValue = Minute.VALUE_LIMIT - 1;
constructor(value: number, step = DEFAULT_MINUTE_STEP) { constructor(value: number, step = DEFAULT_MINUTE_STEP) {
super(value, step, Minute.VALUE_LIMIT); super(value, step, Minute.VALUE_LIMIT);
} }
protected isValidString(valueStr: string): boolean { /**
const value = parseInt(valueStr); * Returns true if the minutes will overflow to a different hour when changed in {@param direction}.
return !isNaN(value) && value >= 0 && value <= this._limit; * @param direction
*/
willOverflow(direction: Direction): boolean {
const newValue = direction === Direction.UP ? this.value + this._step : this.value - this._step;
return newValue >= this._limit || newValue < 0;
} }
} }
+18 -10
View File
@@ -5,12 +5,11 @@ import { Direction } from '../types';
*/ */
export abstract class TimeUnit { export abstract class TimeUnit {
/** /**
* Whether {@param valueStr} can be set as a value of this instance. * The min allowed UI value for this instance.
*/ */
protected abstract isValidString(valueStr: string): boolean; abstract minValue: number;
/** /**
* The max allowed value for this instance. Used for UI validation. * The max allowed value for this instance.
*/ */
abstract maxValue: number; abstract maxValue: number;
@@ -40,27 +39,36 @@ export abstract class TimeUnit {
* Updates the value in {@param direction} by the step size specified in the constructoor. * Updates the value in {@param direction} by the step size specified in the constructoor.
* @param direction * @param direction
*/ */
stepUpdate(direction: Direction): void { stepUpdate(direction: Direction, step: number = this._step): void {
direction === Direction.UP ? this.increment() : this.decrement(); direction === Direction.UP ? this.increment(step) : this.decrement(step);
} }
toString(): string { toString(): string {
return this.value < 10 ? `0${this.value}` : this.value.toString(); return this.value < 10 ? `0${this.value}` : this.value.toString();
} }
private increment(): void { private increment(step: number = this._step): void {
this.setValue(this.value + this._step); this.setValue(this.value + step);
} }
private decrement(): void { private decrement(step: number = this._step): void {
this.setValue(this.value - this._step); this.setValue(this.value - step);
} }
protected setValue(newValue: number): void { protected setValue(newValue: number): void {
if (isNaN(newValue)) {
return;
}
if (newValue >= this._limit || newValue < 0) { if (newValue >= this._limit || newValue < 0) {
newValue = (newValue + this._limit) % this._limit; newValue = (newValue + this._limit) % this._limit;
} }
this._value = newValue; this._value = newValue;
} }
protected isValidString(valueStr: string): boolean {
const value = parseInt(valueStr);
return !isNaN(value) && value >= 0 && value < this._limit;
}
} }
+23
View File
@@ -0,0 +1,23 @@
import { Hour } from './hour';
import { Minute } from './minute';
import { Direction } from '../types';
export class Time {
constructor(public hour: Hour, public minute: Minute, private _linkValues: boolean = false) {}
hourStep(direction: Direction): void {
this.hour.stepUpdate(direction);
}
minuteStep(direction: Direction): void {
if (this._linkValues && this.minute.willOverflow(direction)) {
this.hour.stepUpdate(direction, 1);
}
this.minute.stepUpdate(direction);
}
get value(): string {
return `${this.hour.value}:${this.minute.value}`;
}
}
+32 -11
View File
@@ -19,6 +19,7 @@ import {
} from './const'; } from './const';
import { Hour } from './models/hour'; import { Hour } from './models/hour';
import { Minute } from './models/minute'; import { Minute } from './models/minute';
import { Time } from './models/time';
import { Partial } from './partials'; import { Partial } from './partials';
import { Period, TimePickerCardConfig, Layout } from './types'; import { Period, TimePickerCardConfig, Layout } from './types';
@@ -43,8 +44,7 @@ window.customCards.push({
export class TimePickerCard extends LitElement implements LovelaceCard { export class TimePickerCard extends LitElement implements LovelaceCard {
@property({ type: Object }) hass!: HomeAssistant; @property({ type: Object }) hass!: HomeAssistant;
@property() private config!: TimePickerCardConfig; @property() private config!: TimePickerCardConfig;
@property() private hour!: Hour; @property() private time!: Time;
@property() private minute!: Minute;
@property() private period!: Period; @property() private period!: Period;
private get entity(): HassEntity | undefined { private get entity(): HassEntity | undefined {
@@ -110,9 +110,10 @@ export class TimePickerCard extends LitElement implements LovelaceCard {
} }
const { hour, minute } = this.entity!.attributes; const { hour, minute } = this.entity!.attributes;
this.hour = new Hour(hour, this.config.hour_step, this.config.hour_mode); const hourInstance = new Hour(hour, this.config.hour_step, this.config.hour_mode);
this.minute = new Minute(minute, this.config.minute_step); const minuteInstance = new Minute(minute, this.config.minute_step);
this.period = this.hour.value >= 12 ? Period.PM : Period.AM; this.time = new Time(hourInstance, minuteInstance, this.config.link_values);
this.period = hourInstance.value >= 12 ? Period.PM : Period.AM;
return html` return html`
<ha-card> <ha-card>
@@ -121,9 +122,17 @@ export class TimePickerCard extends LitElement implements LovelaceCard {
${this.hasNameInside ? Partial.nestedName(this.name!, this.entity) : ''} ${this.hasNameInside ? Partial.nestedName(this.name!, this.entity) : ''}
<div class=${classMap(this.contentClass)}> <div class=${classMap(this.contentClass)}>
<time-unit .unit=${this.hour} @update=${this.callHassService}></time-unit> <time-unit
.unit=${this.time.hour}
@stepChange=${this.onHourStepChange}
@update=${this.callHassService}
></time-unit>
<div class="time-separator">:</div> <div class="time-separator">:</div>
<time-unit .unit=${this.minute} @update=${this.callHassService}></time-unit> <time-unit
.unit=${this.time.minute}
@stepChange=${this.onMinuteStepChange}
@update=${this.callHassService}
></time-unit>
${this.shouldShowPeriod ${this.shouldShowPeriod
? html`<time-period ? html`<time-period
@@ -159,7 +168,17 @@ export class TimePickerCard extends LitElement implements LovelaceCard {
} }
private onPeriodToggle(): void { private onPeriodToggle(): void {
this.hour.togglePeriod(); this.time.hour.togglePeriod();
this.callHassService();
}
private onHourStepChange(event: CustomEvent): void {
this.time.hourStep(event.detail.direction);
this.callHassService();
}
private onMinuteStepChange(event: CustomEvent): void {
this.time.minuteStep(event.detail.direction);
this.callHassService(); this.callHassService();
} }
@@ -168,11 +187,9 @@ export class TimePickerCard extends LitElement implements LovelaceCard {
throw new Error('Unable to update datetime'); throw new Error('Unable to update datetime');
} }
const time = `${this.hour.value}:${this.minute.value}:00`;
return this.hass.callService(ENTITY_DOMAIN, 'set_datetime', { return this.hass.callService(ENTITY_DOMAIN, 'set_datetime', {
entity_id: this.entity!.entity_id, entity_id: this.entity!.entity_id,
time, time: this.time.value,
}); });
} }
@@ -188,12 +205,16 @@ export class TimePickerCard extends LitElement implements LovelaceCard {
--tpc-text-color: var(--time-picker-text-color, #fff); --tpc-text-color: var(--time-picker-text-color, #fff);
--tpc-accent-color: var(--time-picker-accent-color, var(--primary-color)); --tpc-accent-color: var(--time-picker-accent-color, var(--primary-color));
--tpc-off-color: var(--time-picker-off-color, var(--disabled-text-color)); --tpc-off-color: var(--time-picker-off-color, var(--disabled-text-color));
--tpc-border-radius: var(--time-picker-border-radius, var(--ha-card-border-radius, 4px));
} }
.time-picker-header { .time-picker-header {
padding: 16px; padding: 16px;
color: var(--tpc-text-color); color: var(--tpc-text-color);
background-color: var(--tpc-elements-background-color); background-color: var(--tpc-elements-background-color);
border-top-left-radius: var(--tpc-border-radius);
border-top-right-radius: var(--tpc-border-radius);
font-size: 1em; font-size: 1em;
text-align: center; text-align: center;
} }
+1
View File
@@ -3,6 +3,7 @@ import { LovelaceCardConfig } from 'custom-card-helpers';
export interface TimePickerCardConfig extends LovelaceCardConfig { export interface TimePickerCardConfig extends LovelaceCardConfig {
entity: string; entity: string;
name?: string; name?: string;
link_values?: boolean;
hour_mode?: HourMode; hour_mode?: HourMode;
hour_step?: number; hour_step?: number;
minute_step?: number; minute_step?: number;
@@ -1,9 +1,9 @@
import { expect, fixture, html } from '@open-wc/testing'; import { expect, fixture, html } from '@open-wc/testing';
import { HomeAssistant } from 'custom-card-helpers'; import { HomeAssistant } from 'custom-card-helpers';
import { HassEntity } from 'home-assistant-js-websocket'; import { HassEntity } from 'home-assistant-js-websocket';
import '../src/time-picker-card'; import '../../src/time-picker-card';
import { TimePickerCard } from '../src/time-picker-card'; import { TimePickerCard } from '../../src/time-picker-card';
import { TimePickerCardConfig, HourMode } from '../src/types'; import { TimePickerCardConfig, HourMode } from '../../src/types';
import './test-error-card'; import './test-error-card';
async function render(config?: { async function render(config?: {
+19 -11
View File
@@ -1,10 +1,10 @@
module.exports = function (config) { module.exports = function (config) {
config.set({ return config.set({
basePath: 'test/', basePath: './',
frameworks: ['mocha', 'chai'], frameworks: ['mocha', 'chai'],
files: ['*.test.ts'], files: ['**/*.test.ts'],
preprocessors: { preprocessors: {
'*.test.ts': ['rollup'], '**/*.test.ts': ['rollup'],
}, },
rollupPreprocessor: { rollupPreprocessor: {
@@ -12,26 +12,34 @@ module.exports = function (config) {
require('@rollup/plugin-node-resolve')(), require('@rollup/plugin-node-resolve')(),
require('@rollup/plugin-json')(), require('@rollup/plugin-json')(),
require('@rollup/plugin-typescript')(), require('@rollup/plugin-typescript')(),
require('rollup-plugin-babel')(), require('@rollup/plugin-commonjs')({
namedExports: {
chai: ['expect'],
},
}),
], ],
output: { output: {
format: 'umd', format: 'umd',
sourcemap: 'inline', sourcemap: 'inline',
}, },
onwarn: function (message) {
if (/Circular dependency/.test(message)) return;
console.warn(message);
},
}, },
// possible values: 'dots', 'progress' reporters: ['dots'],
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
port: 9876, port: 9876,
colors: true, colors: true,
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
autoWatch: false, autoWatch: false,
singleRun: true, singleRun: true,
browsers: ['ChromeHeadless'],
concurrency: Infinity, concurrency: Infinity,
browsers: ['ChromeHeadless'],
client: {
captureConsole: false,
},
}); });
}; };
+166
View File
@@ -0,0 +1,166 @@
import { Hour } from '../../src/models/hour';
import { Direction } from '../../src/types';
import { DEFAULT_HOUR_STEP } from '../../src/const';
import { expect } from 'chai';
describe('Hour', () => {
let hour: Hour;
context('with default config', () => {
beforeEach(() => {
hour = new Hour(2);
});
it('returns value', () => {
expect(hour.value).to.equal(2);
});
it('has correct max value', () => {
expect(hour.maxValue).to.equal(23);
});
describe('toString', () => {
it('returns formatted string', () => {
expect(hour.toString()).to.equal('02');
});
it('renders values correctly', () => {
hour = new Hour(0);
expect(hour.toString()).to.equal('00');
hour = new Hour(6);
expect(hour.toString()).to.equal('06');
hour = new Hour(12);
expect(hour.toString()).to.equal('12');
hour = new Hour(18);
expect(hour.toString()).to.equal('18');
hour = new Hour(23);
expect(hour.toString()).to.equal('23');
});
});
describe('stepUpdate', () => {
it('updates up', () => {
hour.stepUpdate(Direction.UP);
expect(hour.value).to.equal(3);
});
it('updates down', () => {
hour.stepUpdate(Direction.DOWN);
expect(hour.value).to.equal(1);
});
it('goes up from 23 to 0', () => {
hour = new Hour(23);
hour.stepUpdate(Direction.UP);
expect(hour.value).to.equal(0);
});
it('goes down from 0 to 23', () => {
hour = new Hour(0);
hour.stepUpdate(Direction.DOWN);
expect(hour.value).to.equal(23);
});
});
describe('setStringValue', () => {
it('sets value from valid string', () => {
hour.setStringValue('3');
expect(hour.value).to.equal(3);
});
it("doesn't set value from invalid string", () => {
hour.setStringValue('test');
expect(hour.value).to.equal(2);
});
it("doesn't set value from outside of scope", () => {
hour.setStringValue('24');
expect(hour.value).to.equal(2);
});
});
});
context('with a different step size', () => {
beforeEach(() => {
hour = new Hour(2, 5);
});
it('goes up correctly', () => {
hour.stepUpdate(Direction.UP);
expect(hour.value).to.equal(7);
hour.stepUpdate(Direction.UP);
hour.stepUpdate(Direction.UP);
hour.stepUpdate(Direction.UP);
hour.stepUpdate(Direction.UP);
expect(hour.value).to.equal(3);
});
it('goes down correclty', () => {
hour.stepUpdate(Direction.DOWN);
expect(hour.value).to.equal(21);
});
});
context('in 12 hour mode', () => {
beforeEach(() => {
hour = new Hour(2, DEFAULT_HOUR_STEP, 12);
});
it('has correct max value', () => {
expect(hour.maxValue).to.equal(12);
});
describe('togglePeriod', () => {
it('changes values correclty', () => {
hour = new Hour(2, DEFAULT_HOUR_STEP, 12);
hour.togglePeriod();
expect(hour.value).to.equal(14);
hour = new Hour(0, DEFAULT_HOUR_STEP, 12);
hour.togglePeriod();
expect(hour.value).to.equal(12);
hour = new Hour(23, DEFAULT_HOUR_STEP, 12);
hour.togglePeriod();
expect(hour.value).to.equal(11);
});
it('has no side effects', () => {
const value = hour.value;
hour.togglePeriod();
hour.togglePeriod();
expect(hour.value).to.equal(value);
});
});
describe('toString', () => {
it('renders values above 12 orrectly', () => {
hour = new Hour(13, DEFAULT_HOUR_STEP, 12);
expect(hour.toString()).to.equal('01');
});
it('renders values correctly', () => {
hour = new Hour(0, DEFAULT_HOUR_STEP, 12);
expect(hour.toString()).to.equal('12');
hour = new Hour(6, DEFAULT_HOUR_STEP, 12);
expect(hour.toString()).to.equal('06');
hour = new Hour(12, DEFAULT_HOUR_STEP, 12);
expect(hour.toString()).to.equal('12');
hour = new Hour(18, DEFAULT_HOUR_STEP, 12);
expect(hour.toString()).to.equal('06');
hour = new Hour(23, DEFAULT_HOUR_STEP, 12);
expect(hour.toString()).to.equal('11');
});
});
});
});
+119
View File
@@ -0,0 +1,119 @@
import { Minute } from '../../src/models/minute';
import { Direction } from '../../src/types';
import { expect } from 'chai';
describe('Minute', () => {
let minute: Minute;
context('with default config', () => {
beforeEach(() => {
minute = new Minute(2);
});
it('returns value', () => {
expect(minute.value).to.equal(2);
});
it('has correct max value', () => {
expect(minute.maxValue).to.equal(59);
});
describe('toString', () => {
it('renders values correctly', () => {
minute = new Minute(0);
expect(minute.toString()).to.equal('00');
minute = new Minute(5);
expect(minute.toString()).to.equal('05');
minute = new Minute(59);
expect(minute.toString()).to.equal('59');
});
});
describe('stepUpdate', () => {
it('updates up', () => {
minute.stepUpdate(Direction.UP);
expect(minute.value).to.equal(7);
});
it('updates down', () => {
minute.stepUpdate(Direction.DOWN);
expect(minute.value).to.equal(57);
});
it('goes up from 59 to 4', () => {
minute = new Minute(59);
minute.stepUpdate(Direction.UP);
expect(minute.value).to.equal(4);
});
it('goes down from 0 to 55', () => {
minute = new Minute(0);
minute.stepUpdate(Direction.DOWN);
expect(minute.value).to.equal(55);
});
});
describe('setStringValue', () => {
it('sets value from valid string', () => {
minute.setStringValue('3');
expect(minute.value).to.equal(3);
});
it("doesn't set value from invalid string", () => {
minute.setStringValue('test');
expect(minute.value).to.equal(2);
});
it("doesn't set value from outside of scope", () => {
minute.setStringValue('60');
expect(minute.value).to.equal(2);
minute.setStringValue('65');
expect(minute.value).to.equal(2);
});
});
});
context('with a different step size', () => {
beforeEach(() => {
minute = new Minute(2, 15);
});
it('goes up correctly', () => {
minute.stepUpdate(Direction.UP);
expect(minute.value).to.equal(17);
minute.stepUpdate(Direction.UP);
minute.stepUpdate(Direction.UP);
minute.stepUpdate(Direction.UP);
expect(minute.value).to.equal(2);
minute.stepUpdate(Direction.UP);
expect(minute.value).to.equal(17);
});
it('goes down correclty', () => {
minute.stepUpdate(Direction.DOWN);
expect(minute.value).to.equal(47);
});
});
describe('will overflow', () => {
it('returns true if the minutes will overflow an hour up', () => {
minute.setStringValue('59');
expect(minute.willOverflow(Direction.UP)).to.be.true;
});
it('returns true if the minutes will overflow an hour down', () => {
minute.setStringValue('0');
expect(minute.willOverflow(Direction.DOWN)).to.be.true;
});
it('returns true if the minutes will not overflow', () => {
minute.setStringValue('55');
expect(minute.willOverflow(Direction.DOWN)).to.be.false;
});
});
});