Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow customization of time format #22339

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 21 additions & 5 deletions src/common/datetime/relative_time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,40 @@ import memoizeOne from "memoize-one";
import type { FrontendLocaleData } from "../../data/translation";
import { selectUnit } from "../util/select-unit";

export enum RelativeTimeFormat {
relative = "long",
relative_short = "short",
relative_narrow = "narrow",
}

export type RelativeTimeStyle = `${RelativeTimeFormat}`;

export function isRelativeTimeFormat(
format: string
): format is RelativeTimeFormat {
return Object.keys(RelativeTimeFormat).includes(format as RelativeTimeFormat);
}

const formatRelTimeMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.RelativeTimeFormat(locale.language, { numeric: "auto" })
(locale: FrontendLocaleData, style: RelativeTimeStyle) =>
new Intl.RelativeTimeFormat(locale.language, { numeric: "auto", style })
);

export const relativeTime = (
from: Date,
locale: FrontendLocaleData,
to?: Date,
includeTense = true
includeTense = true,
format?: RelativeTimeFormat
): string => {
const diff = selectUnit(from, to, locale);
const style: RelativeTimeStyle = format ? RelativeTimeFormat[format] : "long";
if (includeTense) {
return formatRelTimeMem(locale).format(diff.value, diff.unit);
return formatRelTimeMem(locale, style).format(diff.value, diff.unit);
}
return Intl.NumberFormat(locale.language, {
style: "unit",
unit: diff.unit,
unitDisplay: "long",
unitDisplay: style,
}).format(Math.abs(diff.value));
};
15 changes: 13 additions & 2 deletions src/components/ha-relative-time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import { parseISO } from "date-fns";
import type { PropertyValues } from "lit";
import { ReactiveElement } from "lit";
import { customElement, property } from "lit/decorators";
import { relativeTime } from "../common/datetime/relative_time";
import {
relativeTime,
type RelativeTimeFormat,
} from "../common/datetime/relative_time";
import { capitalizeFirstLetter } from "../common/string/capitalize-first-letter";
import type { HomeAssistant } from "../types";

Expand All @@ -12,6 +15,8 @@ class HaRelativeTime extends ReactiveElement {

@property({ attribute: false }) public datetime?: string | Date;

@property({ attribute: false }) public format?: RelativeTimeFormat;

@property({ type: Boolean }) public capitalize = false;

private _interval?: number;
Expand Down Expand Up @@ -65,7 +70,13 @@ class HaRelativeTime extends ReactiveElement {
? parseISO(this.datetime)
: this.datetime;

const relTime = relativeTime(date, this.hass.locale);
const relTime = relativeTime(
date,
this.hass.locale,
undefined,
undefined,
this.format
);
this.innerHTML = this.capitalize
? capitalizeFirstLetter(relTime)
: relTime;
Expand Down
1 change: 1 addition & 0 deletions src/panels/lovelace/badges/hui-entity-badge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ export class HuiEntityBadge extends LitElement implements LovelaceBadge {
.hass=${this.hass}
.content=${this._config.state_content}
.name=${this._config.name}
.format=${this._config.format}
>
</state-display>
`;
Expand Down
2 changes: 2 additions & 0 deletions src/panels/lovelace/badges/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { ActionConfig } from "../../../data/lovelace/config/action";
import type { LovelaceBadgeConfig } from "../../../data/lovelace/config/badge";
import type { LegacyStateFilter } from "../common/evaluate-filter";
import type { Condition } from "../common/validate-condition";
import type { TimestampRenderingFormat } from "../components/types";
import type { EntityFilterEntityConfig } from "../entity-rows/types";
import type { DisplayType } from "./hui-entity-badge";

Expand Down Expand Up @@ -42,6 +43,7 @@ export interface EntityBadgeConfig extends LovelaceBadgeConfig {
tap_action?: ActionConfig;
hold_action?: ActionConfig;
double_tap_action?: ActionConfig;
format?: TimestampRenderingFormat;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should also add this to the struct in hui-entity-badge-editor

/**
* @deprecated use `show_state`, `show_name`, `icon_type`
*/
Expand Down
1 change: 1 addition & 0 deletions src/panels/lovelace/cards/hui-tile-card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ export class HuiTileCard extends LitElement implements LovelaceCard {
.hass=${this.hass}
.content=${this._config.state_content}
.name=${this._config.name}
.format=${this._config.format}
>
</state-display>
`;
Expand Down
1 change: 1 addition & 0 deletions src/panels/lovelace/cards/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,7 @@ export interface TileCardConfig extends LovelaceCardConfig {
icon_hold_action?: ActionConfig;
icon_double_tap_action?: ActionConfig;
features?: LovelaceCardFeatureConfig[];
format?: TimestampRenderingFormat;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should also add this to the struct in hui-tile-card-editor

}

export interface HeadingCardConfig extends LovelaceCardConfig {
Expand Down
21 changes: 15 additions & 6 deletions src/panels/lovelace/components/hui-timestamp-display.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import { customElement, property, state } from "lit/decorators";
import { formatDate } from "../../../common/datetime/format_date";
import { formatDateTime } from "../../../common/datetime/format_date_time";
import { formatTime } from "../../../common/datetime/format_time";
import { relativeTime } from "../../../common/datetime/relative_time";
import {
isRelativeTimeFormat,
RelativeTimeFormat,
relativeTime,
} from "../../../common/datetime/relative_time";
import { capitalizeFirstLetter } from "../../../common/string/capitalize-first-letter";
import type { FrontendLocaleData } from "../../../data/translation";
import type { HomeAssistant } from "../../../types";
Expand All @@ -22,7 +26,7 @@ const FORMATS: {
datetime: formatDateTime,
time: formatTime,
};
const INTERVAL_FORMAT = ["relative", "total"];
const INTERVAL_FORMAT = [...Object.keys(RelativeTimeFormat), "total"];

@customElement("hui-timestamp-display")
class HuiTimestampDisplay extends LitElement {
Expand Down Expand Up @@ -112,10 +116,15 @@ class HuiTimestampDisplay extends LitElement {

private _updateRelative(): void {
if (this.ts && this.hass?.localize) {
this._relative =
this._format === "relative"
? relativeTime(this.ts, this.hass!.locale)
: relativeTime(new Date(), this.hass!.locale, this.ts, false);
this._relative = isRelativeTimeFormat(this._format)
? relativeTime(
this.ts,
this.hass!.locale,
undefined,
undefined,
this._format
)
: relativeTime(new Date(), this.hass!.locale, this.ts, false);

this._relative = this.capitalize
? capitalizeFirstLetter(this._relative)
Expand Down
2 changes: 2 additions & 0 deletions src/panels/lovelace/components/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export interface ConditionalBaseConfig extends LovelaceCardConfig {

export const TIMESTAMP_RENDERING_FORMATS = [
"relative",
"relative_narrow",
"relative_short",
"total",
"date",
"time",
Expand Down
6 changes: 5 additions & 1 deletion src/state-display/state-display.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type { UpdateEntity } from "../data/update";
import { computeUpdateStateDisplay } from "../data/update";
import "../panels/lovelace/components/hui-timestamp-display";
import type { HomeAssistant } from "../types";
import type { TimestampRenderingFormat } from "../panels/lovelace/components/types";

const TIMESTAMP_STATE_DOMAINS = ["button", "input_button", "scene"];

Expand Down Expand Up @@ -59,6 +60,8 @@ class StateDisplay extends LitElement {

@property({ attribute: false }) public name?: string;

@property({ attribute: false }) public format?: TimestampRenderingFormat;

@property({ type: Boolean, attribute: "dash-unavailable" })
public dashUnavailable?: boolean;

Expand Down Expand Up @@ -90,7 +93,7 @@ class StateDisplay extends LitElement {
<hui-timestamp-display
.hass=${this.hass}
.ts=${new Date(stateObj.state)}
format="relative"
.format=${this.format}
capitalize
></hui-timestamp-display>
`;
Expand Down Expand Up @@ -133,6 +136,7 @@ class StateDisplay extends LitElement {
<ha-relative-time
.hass=${this.hass}
.datetime=${relativeDateTime}
.format=${this.format}
Copy link
Member

@bramkragten bramkragten Nov 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would not be used ever, as we already would have returned the content === state part?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have to check this, but I'm pretty sure I saw this being reached at some point during my testing. I'll investigate a bit more and provide any pertinent data.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is definitely being hit frequently in my intended use-case (binary motion sensors displaying the last changed time).

The original content === state part is only hit when we explicitly want to render the base/default state item (and it additionally has the "correct" device class or domain). When content === "last_changed" for example, the requested format needs to be respected still.

Note the new formats are opt-in; when format - a new prop - isn't passed, it defaults to relative (aka long in the Intl library) which is existing behavior for both ha-relative-time and hui-timestamp-display.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the removal of the code from the previous comment it does.

capitalize
></ha-relative-time>
`;
Expand Down
Loading