Files
NextFloor/frontend/src/components/quick-menu.ts
T

537 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Quick menu at a device (long press in 3D): a ring of colours around a power button for lights,
// up/stop/down for blinds, on/off for switches, with a slider and a way to the full details.
import { css, html, LitElement, nothing } from "lit";
import { assumedCover, type CarState, entityName, isUnavailable, kindOf } from "../devices.ts";
import { translate, type I18nKey } from "../i18n.ts";
import { openMoreInfo, stateText } from "../markers.ts";
import { tokens } from "../styles.ts";
import type { HassEntity, HomeAssistant } from "../types.ts";
import { coverWithTilt } from "../entities/covers.ts";
const COLORS: [number, number, number][] = [
[255, 181, 71],
[255, 236, 210],
[55, 224, 255],
[91, 124, 255],
[190, 90, 255],
[255, 95, 210],
[255, 70, 70],
[120, 255, 150],
];
const KELVINS = [2200, 2700, 3200, 4000, 5000, 6500];
const COLOR_MODES = ["hs", "rgb", "rgbw", "rgbww", "xy"];
const COVER_SET_POSITION = 4;
const COVER_OPEN_TILT = 16;
const COVER_CLOSE_TILT = 32;
const COVER_SET_TILT = 128;
/** What a light can do, from its supported colour modes. */
export function lightAbilities(st: HassEntity): { dim: boolean; color: boolean; temp: boolean } {
const modes = (st.attributes.supported_color_modes as string[] | undefined) ?? [];
const color = modes.some((m) => COLOR_MODES.includes(m));
return { dim: modes.some((m) => m !== "onoff"), color, temp: modes.includes("color_temp") };
}
/** Whether a cover can be moved to a position. */
export function coverPositionable(st: HassEntity): boolean {
return (((st.attributes.supported_features as number) ?? 0) & COVER_SET_POSITION) !== 0 && typeof st.attributes.current_position === "number";
}
export class NfQuickMenu extends LitElement {
static properties = {
hass: { attribute: false },
entity: { attribute: false },
car: { attribute: false },
presets: { attribute: false },
confirmSwitch: { type: Boolean },
myPosition: { attribute: false },
tiltEntity: { attribute: false },
low: { type: Boolean, reflect: true },
};
declare hass: HomeAssistant;
declare entity: string;
/** Auto: the car behind a parking spot's pin – its menu replaces the entity's. */
declare car: CarState | null;
/** Klang: stations and playlists to start on a speaker. */
declare presets: { id: string; label: string; type: string; content: string }[];
/** Ask before the power button switches. */
declare confirmSwitch: boolean;
/** Blinds: the favourite position (Somfy's "My", %), a button in the ring moves there; null = none. */
declare myPosition: number | null;
declare tiltEntity: string | null;
/** Tablet level: no blur behind the menu. */
declare low: boolean;
private t(key: I18nKey, vars?: Record<string, string | number>): string {
return translate(this.hass, key, vars);
}
/** Ask before switching when the device is marked so (power and lock buttons; sliders and colours never ask). */
private ask(): boolean {
return !this.confirmSwitch || confirm(this.t("confirm_switch", { name: entityName(this.hass, this.entity) }));
}
private call(domain: string, service: string, data: Record<string, unknown> = {}): void {
void this.hass.callService(domain, service, { entity_id: this.entity, ...data });
}
private close(): void {
this.dispatchEvent(new CustomEvent("close", { bubbles: true, composed: true }));
}
private details(): void {
openMoreInfo(this, this.entity);
this.close();
}
/** Buttons spread on a ring around the centre. */
private ring(items: ReturnType<typeof html>[]) {
const n = items.length;
return items.map((item, i) => {
const a = (i / n) * Math.PI * 2 - Math.PI / 2;
return html`<div class="qm-at" style="left:${50 + Math.cos(a) * 39}%;top:${50 + Math.sin(a) * 39}%">${item}</div>`;
});
}
private renderLight(st: HassEntity) {
const can = lightAbilities(st);
const on = st.state === "on";
const pct = on && typeof st.attributes.brightness === "number" ? Math.round((st.attributes.brightness as number) / 2.55) : on ? 100 : 0;
const swatches = can.color
? COLORS.map(
(c) => html`<button class="qm-swatch" style="background:rgb(${c.join(",")})" aria-label=${`RGB ${c.join(", ")}`} @click=${() => this.call("light", "turn_on", { rgb_color: c })}></button>`,
)
: can.temp
? KELVINS.map(
(k) => html`<button class="qm-swatch" style="background:${kelvinCss(k)}" aria-label=${`${k} K`} @click=${() => this.call("light", "turn_on", { color_temp_kelvin: k })}></button>`,
)
: [];
return html`<div class="qm-ring ${swatches.length ? "" : "qm-ring-small"}">
${this.ring(swatches)}
<button class="qm-power ${on ? "qm-on" : ""}" aria-pressed=${on} @click=${() => this.ask() && this.call("light", "toggle")}>
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 3v8M6.3 6.8a8 8 0 1 0 11.4 0" /></svg>
<b>${on ? `${pct} %` : this.t("qm_off")}</b>
</button>
</div>
${can.dim
? html`<input
class="qm-slider"
type="range"
min="1"
max="100"
.value=${String(Math.max(1, pct))}
aria-label=${this.t("brightness")}
@change=${(e: Event) => this.call("light", "turn_on", { brightness_pct: Number((e.target as HTMLInputElement).value) })}
/>`
: nothing}`;
}
private renderCover(st: HassEntity) {
st = coverWithTilt(this.hass, st, this.tiltEntity);
const pos = typeof st.attributes.current_position === "number" ? (st.attributes.current_position as number) : null;
const moving = st.state === "opening" || st.state === "closing";
const setPos = coverPositionable(st);
// like the colour ring of lights: open and close, positions in between and stop around the blind
const slot = (label: string, aria: string, action: () => void, active = false) =>
html`<button class="qm-swatch qm-slot ${active ? "qm-slot-on" : ""}" aria-label=${aria} @click=${action}>${label}</button>`;
const at = (p: number) => pos !== null && Math.abs(pos - p) < 3;
const ring = [
// moving asks first when the blind is marked so; stopping never asks
slot("▲", this.t("cover_open"), () => this.ask() && this.call("cover", "open_cover"), at(100)),
...(setPos ? [75, 50].map((p) => slot(`${p}`, `${p} %`, () => this.ask() && this.call("cover", "set_cover_position", { position: p }), at(p))) : []),
slot("▼", this.t("cover_close"), () => this.ask() && this.call("cover", "close_cover"), at(0)),
...(setPos ? [25].map((p) => slot(`${p}`, `${p} %`, () => this.ask() && this.call("cover", "set_cover_position", { position: p }), at(p))) : []),
...(Number(st.attributes.supported_features ?? 0) & 8 ? [slot("■", this.t("cover_stop"), () => this.call("cover", "stop_cover"), moving)] : []),
// the favourite position: a cover that sets positions goes there; a Somfy RTS motor without feedback goes to its own "My" on stop
...(this.myPosition != null && (setPos || Number(st.attributes.supported_features ?? 0) & 8)
? [slot("My", this.t("cover_my_go", { p: this.myPosition }), () => this.ask() && (setPos ? this.call("cover", "set_cover_position", { position: this.myPosition }) : this.call("cover", "stop_cover")), at(this.myPosition))]
: []),
];
// the centre shows the blind: its closed part fills from the top
const closed = pos === null ? (st.state === "closed" ? 100 : 0) : 100 - pos;
// without a known state the centre cannot tell whether to open or close: only the arrows move it
const known = pos !== null || moving || st.state === "open" || st.state === "closed";
return html`<div class="qm-ring">
${this.ring(ring)}
<button
class="qm-power qm-blind ${known && closed < 100 ? "qm-on" : ""}"
style="--closed:${closed}%"
?disabled=${!known}
aria-label=${moving ? this.t("cover_stop") : closed > 50 ? this.t("cover_open") : this.t("cover_close")}
@click=${() => (moving ? this.call("cover", "stop_cover") : this.ask() && this.call("cover", closed > 50 ? "open_cover" : "close_cover"))}
>
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 4h16M5 4v15M19 4v15M7 8h10M7 12h10M7 16h10" /></svg>
<b>${pos !== null ? `${Math.round(pos)} %` : stateText(this.hass, st)}</b>
</button>
</div>
${setPos
? html`<input
class="qm-slider"
type="range"
min="0"
max="100"
.value=${String(pos ?? 0)}
aria-label=${this.t("position")}
@change=${(e: Event) => this.call("cover", "set_cover_position", { position: Number((e.target as HTMLInputElement).value) })}
/>`
: nothing}
${this.renderTilt(st)}`;
}
/** Slats of a venetian blind or a Raffstore: a tilt slider when the cover sets a tilt position, else open/close tilt buttons. */
private renderTilt(st: HassEntity) {
const features = ((st.attributes.supported_features as number) ?? 0) | 0;
const tilt = typeof st.attributes.current_tilt_position === "number" ? (st.attributes.current_tilt_position as number) : null;
if (features & COVER_SET_TILT && tilt !== null)
return html`<label class="qm-tilt"
><span>${this.t("cover_tilt")} · ${Math.round(tilt)} %</span>
<input
class="qm-slider"
type="range"
min="0"
max="100"
.value=${String(tilt)}
aria-label=${this.t("cover_tilt")}
@change=${(e: Event) => this.call("cover", "set_cover_tilt_position", { entity_id: st.attributes.nf_cover_control ? this.entity : this.tiltEntity || this.entity, tilt_position: Number((e.target as HTMLInputElement).value) })}
/></label>`;
if (features & (COVER_OPEN_TILT | COVER_CLOSE_TILT))
return html`<div class="qm-tilt-buttons">
${features & COVER_OPEN_TILT ? html`<button class="qm-swatch qm-slot" @click=${() => this.call("cover", "open_cover_tilt")}>${this.t("cover_tilt_open")}</button>` : nothing}
${features & COVER_CLOSE_TILT ? html`<button class="qm-swatch qm-slot" @click=${() => this.call("cover", "close_cover_tilt")}>${this.t("cover_tilt_close")}</button>` : nothing}
</div>`;
return nothing;
}
private renderToggle(st: HassEntity) {
const on = st.state === "on" || st.state === "unlocked" || st.state === "playing";
const domain = st.entity_id.split(".")[0];
return html`<div class="qm-ring qm-ring-small">
<button
class="qm-power ${on ? "qm-on" : ""}"
aria-pressed=${on}
@click=${() => this.ask() && (domain === "lock" ? this.call("lock", on ? "lock" : "unlock") : this.call("homeassistant", "toggle"))}
>
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 3v8M6.3 6.8a8 8 0 1 0 11.4 0" /></svg>
<b>${stateText(this.hass, st)}</b>
</button>
</div>`;
}
/** A speaker or TV: power, play/pause and skip, the volume, its sources, and the stations and playlists it may play. */
private renderMedia(st: HassEntity) {
const on = !["off", "standby", "unavailable", "unknown"].includes(st.state);
const playing = st.state === "playing";
const a = st.attributes as Record<string, unknown>;
const volume = typeof a.volume_level === "number" ? Math.round(a.volume_level * 100) : null;
const sources = Array.isArray(a.source_list) ? (a.source_list as string[]).slice(0, 24) : [];
const title = [a.media_title, a.media_artist].filter((v) => typeof v === "string" && v).join(" · ");
const icon = (d: string) => html`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d=${d} /></svg>`;
const slot = (label: ReturnType<typeof html>, aria: string, action: () => void, active = false) =>
html`<button class="qm-swatch qm-slot ${active ? "qm-slot-on" : ""}" aria-label=${aria} title=${aria} @click=${action}>${label}</button>`;
const ring = on
? [
slot(icon(playing ? "M6 5h4v14H6zM14 5h4v14h-4z" : "M8 5v14l11-7z"), this.t(playing ? "media_pause" : "media_play"), () => this.call("media_player", "media_play_pause"), playing),
slot(icon("M6 6h2v12H6zm3.5 6 8.5 6V6z"), this.t("media_previous"), () => this.call("media_player", "media_previous_track")),
slot(icon("M16 6h2v12h-2zM6 18l8.5-6L6 6z"), this.t("media_next"), () => this.call("media_player", "media_next_track")),
]
: [];
return html`<div class="qm-ring ${ring.length ? "" : "qm-ring-small"}">
${this.ring(ring)}
<button class="qm-power ${on ? "qm-on" : ""}" aria-pressed=${on} @click=${() => this.ask() && this.call("media_player", on ? "turn_off" : "turn_on")}>
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 3v8M6.3 6.8a8 8 0 1 0 11.4 0" /></svg>
<b>${volume !== null && on ? `${volume} %` : stateText(this.hass, st)}</b>
</button>
</div>
${title ? html`<div class="qm-media-title">${title}</div>` : nothing}
${volume !== null
? html`<input class="qm-slider" type="range" min="0" max="100" .value=${String(volume)} aria-label=${this.t("media_volume")} @change=${(e: Event) => this.call("media_player", "volume_set", { volume_level: Number((e.target as HTMLInputElement).value) / 100 })} />`
: nothing}
${sources.length
? html`<div class="qm-play-head">${this.t("media_sources")}</div>
<div class="qm-play">${sources.map((s) => html`<button class="qm-chip ${a.source === s ? "qm-chip-on" : ""}" @click=${() => this.call("media_player", "select_source", { source: s })}>${s}</button>`)}</div>`
: nothing}
${this.presets?.length
? html`<div class="qm-play-head">${this.t("presets")}</div>
<div class="qm-play">${this.presets.map((p) => html`<button class="qm-chip" @click=${() => this.call("media_player", "play_media", { media_content_type: p.type, media_content_id: p.content })}>${p.label}</button>`)}</div>`
: nothing}`;
}
protected render() {
const st = this.hass?.states[this.entity];
if (!st) return nothing;
const kind = kindOf(this.entity);
// a cover without feedback (a garage remote) stays unknown, but its buttons still work
const body = isUnavailable(st) && !assumedCover(st)
? html`<p class="qm-note">${stateText(this.hass, st)}</p>`
: kind === "light"
? this.renderLight(st)
: kind === "cover"
? this.renderCover(st)
: kind === "media"
? this.renderMedia(st)
: this.renderToggle(st);
return html`<div class="qm" role="dialog" aria-label=${entityName(this.hass, this.entity)}>
<div class="qm-title">${entityName(this.hass, this.entity)}</div>
${body}
<button class="qm-details" @click=${() => this.details()}>${this.t("details")} …</button>
</div>`;
}
static styles = [
tokens,
css`
.qm-play-head {
margin: 10px 0 4px;
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
opacity: 0.7;
}
.qm-play {
display: flex;
flex-wrap: wrap;
gap: 6px;
max-height: 110px;
overflow-y: auto;
}
.qm-chip {
border: 1px solid rgba(160, 240, 255, 0.35);
border-radius: 999px;
padding: 5px 10px;
background: rgba(8, 16, 34, 0.55);
color: inherit;
font: inherit;
font-size: 12.5px;
cursor: pointer;
}
.qm-chip-on {
border-color: var(--nf-accent, var(--nf-accent));
color: var(--nf-accent, var(--nf-accent));
}
.qm {
width: 232px;
padding: 12px 14px 10px;
border-radius: 22px;
background: var(--nf-chrome);
box-shadow: var(--nf-shadow), 0 0 0 1px var(--nf-line);
backdrop-filter: blur(10px);
}
:host([low]) .qm {
backdrop-filter: none;
box-shadow: 0 0 0 1px var(--nf-line);
animation: none;
color: var(--nf-text);
text-align: center;
animation: qm-in 140ms ease-out;
}
@keyframes qm-in {
from {
opacity: 0;
transform: scale(0.85);
}
}
.qm-title {
font: 700 14.5px var(--nf-title-font);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.qm-ring {
position: relative;
width: 196px;
height: 196px;
margin: 6px auto 4px;
display: grid;
place-items: center;
}
.qm-ring-small {
height: 110px;
}
.qm-at {
position: absolute;
transform: translate(-50%, -50%);
}
.qm-swatch {
width: 34px;
height: 34px;
border: 2px solid color-mix(in srgb, var(--nf-text) 25%, transparent);
border-radius: 50%;
cursor: pointer;
box-shadow: 0 0 12px rgba(0, 0, 0, 0.35);
}
.qm-swatch:active {
transform: scale(0.9);
}
.qm-power {
display: grid;
place-items: center;
gap: 2px;
width: 88px;
height: 88px;
border: 0;
border-radius: 50%;
background: var(--nf-bg2);
color: var(--nf-muted);
box-shadow: inset 0 0 0 2px var(--nf-line);
cursor: pointer;
font: inherit;
}
.qm-power:disabled {
opacity: 0.45;
cursor: default;
}
.qm-power b {
font: 700 15px var(--nf-title-font);
color: var(--nf-text);
}
.qm-power small {
font-size: 11px;
}
.qm-on {
color: #1a1204;
background: var(--nf-warm);
box-shadow: 0 0 24px rgba(255, 181, 71, 0.55);
}
.qm-on b {
color: #1a1204;
}
.qm-slot {
display: grid;
place-items: center;
border-color: var(--nf-line);
background: var(--nf-bg2);
color: var(--nf-text);
font: 700 12px var(--nf-title-font);
}
.qm-slot-on {
background: var(--nf-accent);
color: var(--nf-accent-text);
border-color: transparent;
box-shadow: var(--nf-shadow);
}
/* the blind: its closed part covers the circle from the top, the open part glows like daylight */
.qm-blind.qm-on {
background: linear-gradient(to bottom, #1e2c4c var(--closed), #9fd9ff var(--closed));
box-shadow: 0 0 22px rgba(120, 200, 255, 0.4);
color: #06101f;
}
.qm-blind b {
text-shadow: 0 0 6px rgba(0, 0, 0, 0.6);
color: #fff;
}
.qm-round {
width: 46px;
height: 46px;
border: 0;
border-radius: 50%;
background: var(--nf-accent);
color: var(--nf-accent-text);
font-size: 17px;
cursor: pointer;
}
.qm-car-line {
margin: 2px 0 8px;
text-align: center;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.qm-car {
display: grid;
gap: 6px;
justify-items: stretch;
}
.qm-car .qm-slot {
width: auto;
padding: 6px 10px;
font-size: 13px;
}
.qm-media {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
margin: 6px 0;
}
.qm-media-main {
width: 64px;
height: 64px;
border-radius: 50%;
background-size: cover;
background-position: center;
position: relative;
}
.qm-media-main span {
position: absolute;
inset: 0;
display: grid;
place-items: center;
font-size: 22px;
text-shadow: 0 0 6px rgba(0, 0, 0, 0.8);
color: #fff;
}
.qm-media .qm-slot {
width: auto;
padding: 0 10px;
}
.qm-media-title {
margin: 2px 0 4px;
text-align: center;
font-size: 12px;
opacity: 0.85;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.qm-tilt {
display: grid;
gap: 4px;
margin-top: 8px;
font-size: 12px;
color: var(--nf-muted);
}
.qm-tilt-buttons {
display: flex;
gap: 6px;
justify-content: center;
margin-top: 8px;
}
.qm-tilt-buttons .qm-slot {
width: auto;
padding: 0 10px;
font-size: 12px;
}
.qm-slider {
width: 100%;
margin: 4px 0 6px;
accent-color: var(--nf-accent);
}
.qm-look {
display: block;
width: 100%;
margin-top: -4px;
}
.qm-details {
border: 0;
background: none;
color: var(--nf-accent);
font: inherit;
font-size: 13px;
padding: 6px;
cursor: pointer;
}
.qm-note {
color: var(--nf-muted);
}
`,
];
}
function kelvinCss(k: number): string {
const t = Math.min(1, Math.max(0, (k - 2200) / 4300));
const mix = (a: number, b: number) => Math.round(a + (b - a) * t);
return `rgb(${mix(255, 200)},${mix(170, 225)},${mix(80, 255)})`;
}
if (!customElements.get("nf-quick-menu")) customElements.define("nf-quick-menu", NfQuickMenu);