Bump babel and eslint (#9049)

This commit is contained in:
Bram Kragten 2021-04-30 21:15:31 +02:00 committed by GitHub
parent d4118ade0f
commit 5754f4463d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
244 changed files with 1814 additions and 2804 deletions

View File

@ -4,8 +4,7 @@
"plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended",
"plugin:wc/recommended", "plugin:wc/recommended",
"plugin:lit/recommended", "plugin:lit/recommended",
"prettier", "prettier"
"prettier/@typescript-eslint"
], ],
"parser": "@typescript-eslint/parser", "parser": "@typescript-eslint/parser",
"parserOptions": { "parserOptions": {
@ -85,6 +84,25 @@
"@typescript-eslint/explicit-function-return-type": 0, "@typescript-eslint/explicit-function-return-type": 0,
"@typescript-eslint/explicit-module-boundary-types": 0, "@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-shadow": ["error"], "@typescript-eslint/no-shadow": ["error"],
"@typescript-eslint/naming-convention": [
0,
{
"selector": "default",
"format": ["camelCase", "snake_case"],
"leadingUnderscore": "allow",
"trailingUnderscore": "allow"
},
{
"selector": ["variable"],
"format": ["camelCase", "snake_case", "UPPER_CASE"],
"leadingUnderscore": "allow",
"trailingUnderscore": "allow"
},
{
"selector": "typeLike",
"format": ["PascalCase"]
}
],
"lit/attribute-value-entities": 0 "lit/attribute-value-entities": 0
}, },
"plugins": ["disable", "import", "lit", "prettier", "@typescript-eslint"], "plugins": ["disable", "import", "lit", "prettier", "@typescript-eslint"],

View File

@ -37,9 +37,11 @@ jobs:
- name: Build resources - name: Build resources
run: ./node_modules/.bin/gulp gen-icons-json build-translations gather-gallery-demos run: ./node_modules/.bin/gulp gen-icons-json build-translations gather-gallery-demos
- name: Run eslint - name: Run eslint
run: ./node_modules/.bin/eslint '{**/src,src}/**/*.{js,ts,html}' --ignore-path .gitignore run: yarn run lint:eslint
- name: Run tsc - name: Run tsc
run: ./node_modules/.bin/tsc run: yarn run lint:types
- name: Run prettier
run: yarn run lint:prettier
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:

View File

@ -54,9 +54,7 @@ class HcCast extends LitElement {
const error = const error =
this.castManager.castState === "NO_DEVICES_AVAILABLE" this.castManager.castState === "NO_DEVICES_AVAILABLE"
? html` ? html`
<p> <p>There were no suitable Chromecast devices to cast to found.</p>
There were no suitable Chromecast devices to cast to found.
</p>
` `
: undefined; : undefined;

View File

@ -86,9 +86,7 @@ export class HcConnect extends LitElement {
</div> </div>
<div class="card-actions"> <div class="card-actions">
<a href="/"> <a href="/">
<mwc-button> <mwc-button> Retry </mwc-button>
Retry
</mwc-button>
</a> </a>
<div class="spacer"></div> <div class="spacer"></div>
<mwc-button @click=${this._handleLogout}>Log out</mwc-button> <mwc-button @click=${this._handleLogout}>Log out</mwc-button>

View File

@ -3,8 +3,6 @@ import { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
export const mockTranslations = (hass: MockHomeAssistant) => { export const mockTranslations = (hass: MockHomeAssistant) => {
hass.mockWS( hass.mockWS(
"frontend/get_translations", "frontend/get_translations",
(/* msg: {language: string, category: string} */) => { (/* msg: {language: string, category: string} */) => ({ resources: {} })
return { resources: {} };
}
); );
}; };

View File

@ -47,9 +47,7 @@ class HassioAddonRepositoryEl extends LitElement {
const repo = this.repo; const repo = this.repo;
let _addons = this.addons; let _addons = this.addons;
if (!this.hass.userData?.showAdvanced) { if (!this.hass.userData?.showAdvanced) {
_addons = _addons.filter((addon) => { _addons = _addons.filter((addon) => !addon.advanced);
return !addon.advanced;
});
} }
const addons = this._getAddons(_addons, this.filter); const addons = this._getAddons(_addons, this.filter);
@ -68,9 +66,7 @@ class HassioAddonRepositoryEl extends LitElement {
} }
return html` return html`
<div class="content"> <div class="content">
<h1> <h1>${repo.name}</h1>
${repo.name}
</h1>
<div class="card-group"> <div class="card-group">
${addons.map( ${addons.map(
(addon) => html` (addon) => html`

View File

@ -86,9 +86,7 @@ class HassioAddonStore extends LitElement {
main-page main-page
supervisor supervisor
> >
<span slot="header"> <span slot="header"> ${this.supervisor.localize("panel.store")} </span>
${this.supervisor.localize("panel.store")}
</span>
<ha-button-menu <ha-button-menu
corner="BOTTOM_START" corner="BOTTOM_START"
slot="toolbar-icon" slot="toolbar-icon"
@ -154,8 +152,8 @@ class HassioAddonStore extends LitElement {
repositories: HassioAddonRepository[], repositories: HassioAddonRepository[],
addons: HassioAddonInfo[], addons: HassioAddonInfo[],
filter?: string filter?: string
) => { ) =>
return repositories.sort(sortRepos).map((repo) => { repositories.sort(sortRepos).map((repo) => {
const filteredAddons = addons.filter( const filteredAddons = addons.filter(
(addon) => addon.repository === repo.slug (addon) => addon.repository === repo.slug
); );
@ -171,8 +169,7 @@ class HassioAddonStore extends LitElement {
></hassio-addon-repository> ></hassio-addon-repository>
` `
: html``; : html``;
}); })
}
); );
private _handleAction(ev: CustomEvent<ActionDetail>) { private _handleAction(ev: CustomEvent<ActionDetail>) {

View File

@ -69,13 +69,13 @@ class HassioAddonAudio extends LitElement {
.selected=${this._selectedInput!} .selected=${this._selectedInput!}
> >
${this._inputDevices && ${this._inputDevices &&
this._inputDevices.map((item) => { this._inputDevices.map(
return html` (item) => html`
<paper-item device=${item.device || ""}> <paper-item device=${item.device || ""}>
${item.name} ${item.name}
</paper-item> </paper-item>
`; `
})} )}
</paper-listbox> </paper-listbox>
</paper-dropdown-menu> </paper-dropdown-menu>
<paper-dropdown-menu <paper-dropdown-menu
@ -90,13 +90,13 @@ class HassioAddonAudio extends LitElement {
.selected=${this._selectedOutput!} .selected=${this._selectedOutput!}
> >
${this._outputDevices && ${this._outputDevices &&
this._outputDevices.map((item) => { this._outputDevices.map(
return html` (item) => html`
<paper-item device=${item.device || ""} <paper-item device=${item.device || ""}
>${item.name}</paper-item >${item.name}</paper-item
> >
`; `
})} )}
</paper-listbox> </paper-listbox>
</paper-dropdown-menu> </paper-dropdown-menu>
</div> </div>

View File

@ -65,19 +65,15 @@ class HassioAddonConfig extends LitElement {
@query("ha-yaml-editor") private _editor?: HaYamlEditor; @query("ha-yaml-editor") private _editor?: HaYamlEditor;
public computeLabel = (entry: HaFormSchema): string => { public computeLabel = (entry: HaFormSchema): string =>
return (
this.addon.translations[this.hass.language]?.configuration?.[entry.name] this.addon.translations[this.hass.language]?.configuration?.[entry.name]
?.name || ?.name ||
this.addon.translations.en?.configuration?.[entry.name].name || this.addon.translations.en?.configuration?.[entry.name].name ||
entry.name entry.name;
);
};
private _filteredShchema = memoizeOne( private _filteredShchema = memoizeOne(
(options: Record<string, unknown>, schema: HaFormSchema[]) => { (options: Record<string, unknown>, schema: HaFormSchema[]) =>
return schema.filter((entry) => entry.name in options || entry.required); schema.filter((entry) => entry.name in options || entry.required)
}
); );
protected render(): TemplateResult { protected render(): TemplateResult {

View File

@ -79,12 +79,10 @@ class HassioAddonNetwork extends LitElement {
"addon.configuration.network.host" "addon.configuration.network.host"
)} )}
</th> </th>
<th> <th>${this.supervisor.localize("common.description")}</th>
${this.supervisor.localize("common.description")}
</th>
</tr> </tr>
${this._config!.map((item) => { ${this._config!.map(
return html` (item) => html`
<tr> <tr>
<td>${item.container}</td> <td>${item.container}</td>
<td> <td>
@ -100,8 +98,8 @@ class HassioAddonNetwork extends LitElement {
</td> </td>
<td>${this._computeDescription(item)}</td> <td>${this._computeDescription(item)}</td>
</tr> </tr>
`; `
})} )}
</tbody> </tbody>
</table> </table>
</div> </div>
@ -124,25 +122,20 @@ class HassioAddonNetwork extends LitElement {
} }
} }
private _computeDescription = (item: NetworkItem): string => { private _computeDescription = (item: NetworkItem): string =>
return (
this.addon.translations[this.hass.language]?.network?.[item.container] this.addon.translations[this.hass.language]?.network?.[item.container]
?.description || ?.description ||
this.addon.translations.en?.network?.[item.container]?.description || this.addon.translations.en?.network?.[item.container]?.description ||
item.description item.description;
);
};
private _setNetworkConfig(): void { private _setNetworkConfig(): void {
const network = this.addon.network || {}; const network = this.addon.network || {};
const description = this.addon.network_description || {}; const description = this.addon.network_description || {};
const items: NetworkItem[] = Object.keys(network).map((key) => { const items: NetworkItem[] = Object.keys(network).map((key) => ({
return {
container: key, container: key,
host: network[key], host: network[key],
description: description[key], description: description[key],
}; }));
});
this._config = items.sort((a, b) => (a.container > b.container ? 1 : -1)); this._config = items.sort((a, b) => (a.container > b.container ? 1 : -1));
} }

View File

@ -566,9 +566,7 @@ class HassioAddonInfo extends LitElement {
<span slot="heading"> <span slot="heading">
${this.supervisor.localize("addon.dashboard.hostname")} ${this.supervisor.localize("addon.dashboard.hostname")}
</span> </span>
<code slot="description"> <code slot="description"> ${this.addon.hostname} </code>
${this.addon.hostname}
</code>
</ha-settings-row> </ha-settings-row>
${metrics.map( ${metrics.map(
(metric) => (metric) =>
@ -997,7 +995,7 @@ class HassioAddonInfo extends LitElement {
addons: [this.addon.slug], addons: [this.addon.slug],
homeassistant: false, homeassistant: false,
}, },
updateHandler: async () => await this._updateAddon(), updateHandler: async () => this._updateAddon(),
}); });
} }

View File

@ -56,13 +56,13 @@ class HassioCardContent extends LitElement {
></ha-svg-icon> ></ha-svg-icon>
`} `}
<div> <div>
<div class="title"> <div class="title">${this.title}</div>
${this.title}
</div>
<div class="addition"> <div class="addition">
${this.description} ${this.description}
${/* treat as available when undefined */ ${
this.available === false ? " (Not available)" : ""} /* treat as available when undefined */
this.available === false ? " (Not available)" : ""
}
${this.datetime ${this.datetime
? html` ? html`
<ha-relative-time <ha-relative-time

View File

@ -23,13 +23,9 @@ class SupervisorMetric extends LitElement {
protected render(): TemplateResult { protected render(): TemplateResult {
const roundedValue = roundWithOneDecimal(this.value); const roundedValue = roundWithOneDecimal(this.value);
return html`<ha-settings-row> return html`<ha-settings-row>
<span slot="heading"> <span slot="heading"> ${this.description} </span>
${this.description}
</span>
<div slot="description" .title=${this.tooltip ?? ""}> <div slot="description" .title=${this.tooltip ?? ""}>
<span class="value"> <span class="value"> ${roundedValue} % </span>
${roundedValue} %
</span>
<ha-bar <ha-bar
class="${classMap({ class="${classMap({
"target-warning": roundedValue > 50, "target-warning": roundedValue > 50,

View File

@ -40,9 +40,8 @@ import { HomeAssistant } from "../../../src/types";
import { showDialogSupervisorUpdate } from "../dialogs/update/show-dialog-update"; import { showDialogSupervisorUpdate } from "../dialogs/update/show-dialog-update";
import { hassioStyle } from "../resources/hassio-style"; import { hassioStyle } from "../resources/hassio-style";
const computeVersion = (key: string, version: string): string => { const computeVersion = (key: string, version: string): string =>
return key === "os" ? version : `${key}-${version}`; key === "os" ? version : `${key}-${version}`;
};
@customElement("hassio-update") @customElement("hassio-update")
export class HassioUpdate extends LitElement { export class HassioUpdate extends LitElement {
@ -50,11 +49,12 @@ export class HassioUpdate extends LitElement {
@property({ attribute: false }) public supervisor!: Supervisor; @property({ attribute: false }) public supervisor!: Supervisor;
private _pendingUpdates = memoizeOne((supervisor: Supervisor): number => { private _pendingUpdates = memoizeOne(
return Object.keys(supervisor).filter( (supervisor: Supervisor): number =>
Object.keys(supervisor).filter(
(value) => supervisor[value].update_available (value) => supervisor[value].update_available
).length; ).length
}); );
protected render(): TemplateResult { protected render(): TemplateResult {
if (!this.supervisor) { if (!this.supervisor) {

View File

@ -47,7 +47,8 @@ import { HassioNetworkDialogParams } from "./show-dialog-network";
const IP_VERSIONS = ["ipv4", "ipv6"]; const IP_VERSIONS = ["ipv4", "ipv6"];
@customElement("dialog-hassio-network") @customElement("dialog-hassio-network")
export class DialogHassioNetwork extends LitElement export class DialogHassioNetwork
extends LitElement
implements HassDialog<HassioNetworkDialogParams> { implements HassDialog<HassioNetworkDialogParams> {
@property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public hass!: HomeAssistant;
@ -76,9 +77,9 @@ export class DialogHassioNetwork extends LitElement
this._dirty = false; this._dirty = false;
this._curTabIndex = 0; this._curTabIndex = 0;
this.supervisor = params.supervisor; this.supervisor = params.supervisor;
this._interfaces = params.supervisor.network.interfaces.sort((a, b) => { this._interfaces = params.supervisor.network.interfaces.sort((a, b) =>
return a.primary > b.primary ? -1 : 1; a.primary > b.primary ? -1 : 1
}); );
this._interface = { ...this._interfaces[this._curTabIndex] }; this._interface = { ...this._interfaces[this._curTabIndex] };
await this.updateComplete; await this.updateComplete;

View File

@ -108,8 +108,8 @@ class HassioRegistriesDialog extends LitElement {
</mwc-button> </mwc-button>
` `
: html`${this._registries?.length : html`${this._registries?.length
? this._registries.map((entry) => { ? this._registries.map(
return html` (entry) => html`
<mwc-list-item class="option" hasMeta twoline> <mwc-list-item class="option" hasMeta twoline>
<span>${entry.registry}</span> <span>${entry.registry}</span>
<span slot="secondary" <span slot="secondary"
@ -129,8 +129,8 @@ class HassioRegistriesDialog extends LitElement {
<ha-svg-icon .path=${mdiDelete}></ha-svg-icon> <ha-svg-icon .path=${mdiDelete}></ha-svg-icon>
</mwc-icon-button> </mwc-icon-button>
</mwc-list-item> </mwc-list-item>
`; `
}) )
: html` : html`
<mwc-list-item> <mwc-list-item>
<span <span

View File

@ -87,8 +87,8 @@ class HassioRepositoriesDialog extends LitElement {
${this._error ? html`<div class="error">${this._error}</div>` : ""} ${this._error ? html`<div class="error">${this._error}</div>` : ""}
<div class="form"> <div class="form">
${repositories.length ${repositories.length
? repositories.map((repo) => { ? repositories.map(
return html` (repo) => html`
<paper-item class="option"> <paper-item class="option">
<paper-item-body three-line> <paper-item-body three-line>
<div>${repo.name}</div> <div>${repo.name}</div>
@ -105,13 +105,9 @@ class HassioRepositoriesDialog extends LitElement {
<ha-svg-icon .path=${mdiDelete}></ha-svg-icon> <ha-svg-icon .path=${mdiDelete}></ha-svg-icon>
</mwc-icon-button> </mwc-icon-button>
</paper-item> </paper-item>
`; `
}) )
: html` : html` <paper-item> No repositories </paper-item> `}
<paper-item>
No repositories
</paper-item>
`}
<div class="layout horizontal bottom"> <div class="layout horizontal bottom">
<paper-input <paper-input
class="flex-auto" class="flex-auto"
@ -207,9 +203,7 @@ class HassioRepositoriesDialog extends LitElement {
} }
this._prosessing = true; this._prosessing = true;
const repositories = this._filteredRepositories(this._repositories!); const repositories = this._filteredRepositories(this._repositories!);
const newRepositories = repositories.map((repo) => { const newRepositories = repositories.map((repo) => repo.source);
return repo.source;
});
newRepositories.push(input.value); newRepositories.push(input.value);
try { try {
@ -228,19 +222,13 @@ class HassioRepositoriesDialog extends LitElement {
private async _removeRepository(ev: Event) { private async _removeRepository(ev: Event) {
const slug = (ev.currentTarget as any).slug; const slug = (ev.currentTarget as any).slug;
const repositories = this._filteredRepositories(this._repositories!); const repositories = this._filteredRepositories(this._repositories!);
const repository = repositories.find((repo) => { const repository = repositories.find((repo) => repo.slug === slug);
return repo.slug === slug;
});
if (!repository) { if (!repository) {
return; return;
} }
const newRepositories = repositories const newRepositories = repositories
.map((repo) => { .map((repo) => repo.source)
return repo.source; .filter((repo) => repo !== repository.source);
})
.filter((repo) => {
return repo !== repository.source;
});
try { try {
await setSupervisorOption(this.hass, { await setSupervisorOption(this.hass, {

View File

@ -18,7 +18,8 @@ import "../../components/hassio-upload-snapshot";
import { HassioSnapshotUploadDialogParams } from "./show-dialog-snapshot-upload"; import { HassioSnapshotUploadDialogParams } from "./show-dialog-snapshot-upload";
@customElement("dialog-hassio-snapshot-upload") @customElement("dialog-hassio-snapshot-upload")
export class DialogHassioSnapshotUpload extends LitElement export class DialogHassioSnapshotUpload
extends LitElement
implements HassDialog<HassioSnapshotUploadDialogParams> { implements HassDialog<HassioSnapshotUploadDialogParams> {
@property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public hass!: HomeAssistant;
@ -57,9 +58,7 @@ export class DialogHassioSnapshotUpload extends LitElement
> >
<div slot="heading"> <div slot="heading">
<ha-header-bar> <ha-header-bar>
<span slot="title"> <span slot="title"> Upload snapshot </span>
Upload snapshot
</span>
<mwc-icon-button slot="actionItems" dialogAction="cancel"> <mwc-icon-button slot="actionItems" dialogAction="cancel">
<ha-svg-icon .path=${mdiClose}></ha-svg-icon> <ha-svg-icon .path=${mdiClose}></ha-svg-icon>
</mwc-icon-button> </mwc-icon-button>

View File

@ -53,14 +53,13 @@ const _computeFolders = (folders) => {
return list; return list;
}; };
const _computeAddons = (addons) => { const _computeAddons = (addons) =>
return addons.map((addon) => ({ addons.map((addon) => ({
slug: addon.slug, slug: addon.slug,
name: addon.name, name: addon.name,
version: addon.version, version: addon.version,
checked: true, checked: true,
})); }));
};
interface AddonItem { interface AddonItem {
slug: string; slug: string;
@ -122,9 +121,7 @@ class HassioSnapshotDialog extends LitElement {
<ha-dialog open @closing=${this._closeDialog} .heading=${true}> <ha-dialog open @closing=${this._closeDialog} .heading=${true}>
<div slot="heading"> <div slot="heading">
<ha-header-bar> <ha-header-bar>
<span slot="title"> <span slot="title"> ${this._computeName} </span>
${this._computeName}
</span>
<mwc-icon-button slot="actionItems" dialogAction="cancel"> <mwc-icon-button slot="actionItems" dialogAction="cancel">
<ha-svg-icon .path=${mdiClose}></ha-svg-icon> <ha-svg-icon .path=${mdiClose}></ha-svg-icon>
</mwc-icon-button> </mwc-icon-button>
@ -152,8 +149,8 @@ class HassioSnapshotDialog extends LitElement {
? html` ? html`
<div>Folders:</div> <div>Folders:</div>
<paper-dialog-scrollable class="no-margin-top"> <paper-dialog-scrollable class="no-margin-top">
${this._folders.map((item) => { ${this._folders.map(
return html` (item) => html`
<paper-checkbox <paper-checkbox
.checked=${item.checked} .checked=${item.checked}
@change="${(ev: Event) => @change="${(ev: Event) =>
@ -164,8 +161,8 @@ class HassioSnapshotDialog extends LitElement {
> >
${item.name} ${item.name}
</paper-checkbox> </paper-checkbox>
`; `
})} )}
</paper-dialog-scrollable> </paper-dialog-scrollable>
` `
: ""} : ""}
@ -173,8 +170,8 @@ class HassioSnapshotDialog extends LitElement {
? html` ? html`
<div>Add-on:</div> <div>Add-on:</div>
<paper-dialog-scrollable class="no-margin-top"> <paper-dialog-scrollable class="no-margin-top">
${this._addons.map((item) => { ${this._addons.map(
return html` (item) => html`
<paper-checkbox <paper-checkbox
.checked=${item.checked} .checked=${item.checked}
@change="${(ev: Event) => @change="${(ev: Event) =>
@ -185,8 +182,8 @@ class HassioSnapshotDialog extends LitElement {
> >
${item.name} ${item.name}
</paper-checkbox> </paper-checkbox>
`; `
})} )}
</paper-dialog-scrollable> </paper-dialog-scrollable>
` `
: ""} : ""}

View File

@ -132,9 +132,7 @@ class HassioSnapshots extends LitElement {
</ha-button-menu> </ha-button-menu>
<div class="content"> <div class="content">
<h1> <h1>${this.supervisor.localize("snapshot.create_snapshot")}</h1>
${this.supervisor.localize("snapshot.create_snapshot")}
</h1>
<p class="description"> <p class="description">
${this.supervisor.localize("snapshot.description")} ${this.supervisor.localize("snapshot.description")}
</p> </p>

View File

@ -178,7 +178,7 @@ class HassioCoreInfo extends LitElement {
folders: ["homeassistant"], folders: ["homeassistant"],
homeassistant: true, homeassistant: true,
}, },
updateHandler: async () => await this._updateCore(), updateHandler: async () => this._updateCore(),
}); });
} }

View File

@ -97,9 +97,7 @@ class HassioHostInfo extends LitElement {
<span slot="heading"> <span slot="heading">
${this.supervisor.localize("system.host.ip_address")} ${this.supervisor.localize("system.host.ip_address")}
</span> </span>
<span slot="description"> <span slot="description"> ${primaryIpAddress} </span>
${primaryIpAddress}
</span>
<mwc-button <mwc-button
.label=${this.supervisor.localize("system.host.change")} .label=${this.supervisor.localize("system.host.change")}
@click=${this._changeNetworkClicked} @click=${this._changeNetworkClicked}

View File

@ -264,9 +264,7 @@ class HassioSupervisorInfo extends LitElement {
title: this.supervisor.localize("system.supervisor.warning"), title: this.supervisor.localize("system.supervisor.warning"),
text: html`${this.supervisor.localize("system.supervisor.beta_warning")} text: html`${this.supervisor.localize("system.supervisor.beta_warning")}
<br /> <br />
<b> <b> ${this.supervisor.localize("system.supervisor.beta_backup")} </b>
${this.supervisor.localize("system.supervisor.beta_backup")}
</b>
<br /><br /> <br /><br />
${this.supervisor.localize("system.supervisor.beta_release_items")} ${this.supervisor.localize("system.supervisor.beta_release_items")}
<ul> <ul>

View File

@ -87,13 +87,13 @@ class HassioSupervisorLog extends LitElement {
attr-for-selected="provider" attr-for-selected="provider"
.selected=${this._selectedLogProvider} .selected=${this._selectedLogProvider}
> >
${logProviders.map((provider) => { ${logProviders.map(
return html` (provider) => html`
<paper-item provider=${provider.key}> <paper-item provider=${provider.key}>
${provider.name} ${provider.name}
</paper-item> </paper-item>
`; `
})} )}
</paper-listbox> </paper-listbox>
</paper-dropdown-menu> </paper-dropdown-menu>
` `

View File

@ -39,9 +39,7 @@ class HassioSystem extends LitElement {
main-page main-page
supervisor supervisor
> >
<span slot="header"> <span slot="header"> ${this.supervisor.localize("panel.system")} </span>
${this.supervisor.localize("panel.system")}
</span>
<div class="content"> <div class="content">
<div class="card-group"> <div class="card-group">
<hassio-core-info <hassio-core-info

View File

@ -14,10 +14,10 @@
"format:prettier": "prettier \"**/src/**/*.{js,ts,json,css,md}\" --write", "format:prettier": "prettier \"**/src/**/*.{js,ts,json,css,md}\" --write",
"lint:types": "tsc", "lint:types": "tsc",
"lint:lit": "lit-analyzer \"**/src/**/*.ts\" --format markdown --outFile result.md", "lint:lit": "lit-analyzer \"**/src/**/*.ts\" --format markdown --outFile result.md",
"lint": "npm run lint:eslint && npm run lint:prettier && npm run lint:types", "lint": "yarn run lint:eslint && yarn run lint:prettier && yarn run lint:types",
"format": "npm run format:eslint && npm run format:prettier", "format": "yarn run format:eslint && yarn run format:prettier",
"mocha": "node_modules/.bin/ts-mocha -p test-mocha/tsconfig.test.json --opts test-mocha/mocha.opts", "mocha": "node_modules/.bin/ts-mocha -p test-mocha/tsconfig.test.json --opts test-mocha/mocha.opts",
"test": "npm run lint && npm run mocha" "test": "yarn run lint && yarn run mocha"
}, },
"author": "Paulus Schoutsen <Paulus@PaulusSchoutsen.nl> (http://paulusschoutsen.nl)", "author": "Paulus Schoutsen <Paulus@PaulusSchoutsen.nl> (http://paulusschoutsen.nl)",
"license": "Apache-2.0", "license": "Apache-2.0",
@ -147,17 +147,17 @@
"xss": "^1.0.6" "xss": "^1.0.6"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.11.6", "@babel/core": "^7.14.0",
"@babel/plugin-external-helpers": "^7.10.4", "@babel/plugin-external-helpers": "^7.12.13",
"@babel/plugin-proposal-class-properties": "^7.10.4", "@babel/plugin-proposal-class-properties": "^7.13.0",
"@babel/plugin-proposal-decorators": "^7.10.5", "@babel/plugin-proposal-decorators": "^7.13.15",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.10.4", "@babel/plugin-proposal-nullish-coalescing-operator": "^7.13.8",
"@babel/plugin-proposal-object-rest-spread": "^7.11.0", "@babel/plugin-proposal-object-rest-spread": "^7.13.8",
"@babel/plugin-proposal-optional-chaining": "^7.11.0", "@babel/plugin-proposal-optional-chaining": "^7.13.12",
"@babel/plugin-syntax-dynamic-import": "^7.8.3", "@babel/plugin-syntax-dynamic-import": "^7.8.3",
"@babel/plugin-syntax-import-meta": "^7.10.4", "@babel/plugin-syntax-import-meta": "^7.10.4",
"@babel/preset-env": "^7.11.5", "@babel/preset-env": "^7.14.0",
"@babel/preset-typescript": "^7.10.4", "@babel/preset-typescript": "^7.13.0",
"@koa/cors": "^3.1.0", "@koa/cors": "^3.1.0",
"@open-wc/dev-server-hmr": "^0.0.2", "@open-wc/dev-server-hmr": "^0.0.2",
"@rollup/plugin-babel": "^5.2.1", "@rollup/plugin-babel": "^5.2.1",
@ -177,23 +177,23 @@
"@types/resize-observer-browser": "^0.1.3", "@types/resize-observer-browser": "^0.1.3",
"@types/sortablejs": "^1.10.6", "@types/sortablejs": "^1.10.6",
"@types/webspeechapi": "^0.0.29", "@types/webspeechapi": "^0.0.29",
"@typescript-eslint/eslint-plugin": "^4.4.0", "@typescript-eslint/eslint-plugin": "^4.22.0",
"@typescript-eslint/parser": "^4.4.0", "@typescript-eslint/parser": "^4.22.0",
"@web/dev-server": "^0.0.24", "@web/dev-server": "^0.0.24",
"@web/dev-server-rollup": "^0.2.11", "@web/dev-server-rollup": "^0.2.11",
"babel-loader": "^8.1.0", "babel-loader": "^8.1.0",
"chai": "^4.2.0", "chai": "^4.2.0",
"cpx": "^1.5.0", "cpx": "^1.5.0",
"del": "^4.0.0", "del": "^4.0.0",
"eslint": "^6.8.0", "eslint": "^7.25.0",
"eslint-config-airbnb-typescript": "^7.2.1", "eslint-config-airbnb-typescript": "^12.3.1",
"eslint-config-prettier": "^6.10.1", "eslint-config-prettier": "^8.3.0",
"eslint-import-resolver-webpack": "^0.13.0", "eslint-import-resolver-webpack": "^0.13.0",
"eslint-plugin-disable": "^2.0.1", "eslint-plugin-disable": "^2.0.1",
"eslint-plugin-import": "^2.20.2", "eslint-plugin-import": "^2.22.1",
"eslint-plugin-lit": "^1.2.0", "eslint-plugin-lit": "^1.3.0",
"eslint-plugin-prettier": "^3.1.3", "eslint-plugin-prettier": "^3.4.0",
"eslint-plugin-wc": "^1.2.0", "eslint-plugin-wc": "^1.3.0",
"fancy-log": "^1.3.3", "fancy-log": "^1.3.3",
"fs-extra": "^7.0.1", "fs-extra": "^7.0.1",
"gulp": "^4.0.0", "gulp": "^4.0.0",

View File

@ -38,11 +38,7 @@ class HaAuthFlow extends litLocalizeLiteMixin(LitElement) {
@internalProperty() private _errorMessage?: string; @internalProperty() private _errorMessage?: string;
protected render() { protected render() {
return html` return html` <form>${this._renderForm()}</form> `;
<form>
${this._renderForm()}
</form>
`;
} }
protected firstUpdated(changedProps: PropertyValues) { protected firstUpdated(changedProps: PropertyValues) {

View File

@ -17,9 +17,8 @@ export const hex2rgb = (hex: string): [number, number, number] => {
]; ];
}; };
export const rgb2hex = (rgb: [number, number, number]): string => { export const rgb2hex = (rgb: [number, number, number]): string =>
return `#${rgb_hex(rgb[0])}${rgb_hex(rgb[1])}${rgb_hex(rgb[2])}`; `#${rgb_hex(rgb[0])}${rgb_hex(rgb[1])}${rgb_hex(rgb[2])}`;
};
// Conversion between LAB, XYZ and RGB from https://github.com/gka/chroma.js // Conversion between LAB, XYZ and RGB from https://github.com/gka/chroma.js
// Copyright (c) 2011-2019, Gregor Aisch // Copyright (c) 2011-2019, Gregor Aisch
@ -49,13 +48,10 @@ const xyz_lab = (t: number) => {
return t / t2 + t0; return t / t2 + t0;
}; };
const xyz_rgb = (r: number) => { const xyz_rgb = (r: number) =>
return 255 * (r <= 0.00304 ? 12.92 * r : 1.055 * r ** (1 / 2.4) - 0.055); 255 * (r <= 0.00304 ? 12.92 * r : 1.055 * r ** (1 / 2.4) - 0.055);
};
const lab_xyz = (t: number) => { const lab_xyz = (t: number) => (t > t1 ? t * t * t : t2 * (t - t0));
return t > t1 ? t * t * t : t2 * (t - t0);
};
// Conversions between RGB and LAB // Conversions between RGB and LAB
@ -114,6 +110,5 @@ export const rgb2hsv = (
return [60 * (h < 0 ? h + 6 : h), v && c / v, v]; return [60 * (h < 0 ? h + 6 : h), v && c / v, v];
}; };
export const rgb2hs = (rgb: [number, number, number]): [number, number] => { export const rgb2hs = (rgb: [number, number, number]): [number, number] =>
return rgb2hsv(rgb).slice(0, 2) as [number, number]; rgb2hsv(rgb).slice(0, 2) as [number, number];
};

View File

@ -4,13 +4,9 @@
export const labDarken = ( export const labDarken = (
lab: [number, number, number], lab: [number, number, number],
amount = 1 amount = 1
): [number, number, number] => { ): [number, number, number] => [lab[0] - 18 * amount, lab[1], lab[2]];
return [lab[0] - 18 * amount, lab[1], lab[2]];
};
export const labBrighten = ( export const labBrighten = (
lab: [number, number, number], lab: [number, number, number],
amount = 1 amount = 1
): [number, number, number] => { ): [number, number, number] => labDarken(lab, -amount);
return labDarken(lab, -amount);
};

View File

@ -2,12 +2,9 @@ import { PageNavigation } from "../../layouts/hass-tabs-subpage";
import { HomeAssistant } from "../../types"; import { HomeAssistant } from "../../types";
import { isComponentLoaded } from "./is_component_loaded"; import { isComponentLoaded } from "./is_component_loaded";
export const canShowPage = (hass: HomeAssistant, page: PageNavigation) => { export const canShowPage = (hass: HomeAssistant, page: PageNavigation) =>
return (
(isCore(page) || isLoadedIntegration(hass, page)) && (isCore(page) || isLoadedIntegration(hass, page)) &&
!hideAdvancedPage(hass, page) !hideAdvancedPage(hass, page);
);
};
const isLoadedIntegration = (hass: HomeAssistant, page: PageNavigation) => const isLoadedIntegration = (hass: HomeAssistant, page: PageNavigation) =>
!page.component || isComponentLoaded(hass, page.component); !page.component || isComponentLoaded(hass, page.component);

View File

@ -86,13 +86,10 @@ export const LocalStorage = (
storageKey?: string, storageKey?: string,
property?: boolean, property?: boolean,
propertyOptions?: PropertyDeclaration propertyOptions?: PropertyDeclaration
): any => { ): any => (clsElement: ClassElement) => {
return (clsElement: ClassElement) => {
const key = String(clsElement.key); const key = String(clsElement.key);
storageKey = storageKey || String(clsElement.key); storageKey = storageKey || String(clsElement.key);
const initVal = clsElement.initializer const initVal = clsElement.initializer ? clsElement.initializer() : undefined;
? clsElement.initializer()
: undefined;
storage.addFromStorage(storageKey); storage.addFromStorage(storageKey);
@ -101,11 +98,8 @@ export const LocalStorage = (
el.requestUpdate(clsElement.key, oldValue); el.requestUpdate(clsElement.key, oldValue);
}); });
const getValue = (): any => { const getValue = (): any =>
return storage.hasKey(storageKey!) storage.hasKey(storageKey!) ? storage.getValue(storageKey!) : initVal;
? storage.getValue(storageKey!)
: initVal;
};
const setValue = (el: UpdatingElement, value: any) => { const setValue = (el: UpdatingElement, value: any) => {
let oldValue: unknown | undefined; let oldValue: unknown | undefined;
@ -151,5 +145,4 @@ export const LocalStorage = (
} }
}, },
}; };
};
}; };

View File

@ -1,8 +1,9 @@
import type { LitElement } from "lit-element"; import type { LitElement } from "lit-element";
import type { ClassElement } from "../../types"; import type { ClassElement } from "../../types";
export const restoreScroll = (selector: string): any => { export const restoreScroll = (selector: string): any => (
return (element: ClassElement) => ({ element: ClassElement
) => ({
kind: "method", kind: "method",
placement: "prototype", placement: "prototype",
key: element.key, key: element.key,
@ -29,5 +30,4 @@ export const restoreScroll = (selector: string): any => {
} }
}; };
}, },
}); });
};

View File

@ -1,13 +1,9 @@
// Load a resource and get a promise when loading done. // Load a resource and get a promise when loading done.
// From: https://davidwalsh.name/javascript-loader // From: https://davidwalsh.name/javascript-loader
const _load = ( const _load = (tag: "link" | "script" | "img", url: string, type?: "module") =>
tag: "link" | "script" | "img",
url: string,
type?: "module"
) => {
// This promise will be used by Promise.all to determine success or failure // This promise will be used by Promise.all to determine success or failure
return new Promise((resolve, reject) => { new Promise((resolve, reject) => {
const element = document.createElement(tag); const element = document.createElement(tag);
let attr = "src"; let attr = "src";
let parent = "body"; let parent = "body";
@ -35,8 +31,6 @@ const _load = (
element[attr] = url; element[attr] = url;
document[parent].appendChild(element); document[parent].appendChild(element);
}); });
};
export const loadCSS = (url: string) => _load("link", url); export const loadCSS = (url: string) => _load("link", url);
export const loadJS = (url: string) => _load("script", url); export const loadJS = (url: string) => _load("script", url);
export const loadImg = (url: string) => _load("img", url); export const loadImg = (url: string) => _load("img", url);

View File

@ -48,8 +48,8 @@ export const replaceTileLayer = (
const createTileLayer = ( const createTileLayer = (
leaflet: LeafletModuleType, leaflet: LeafletModuleType,
darkMode: boolean darkMode: boolean
): TileLayer => { ): TileLayer =>
return leaflet.tileLayer( leaflet.tileLayer(
`https://{s}.basemaps.cartocdn.com/${ `https://{s}.basemaps.cartocdn.com/${
darkMode ? "dark_all" : "light_all" darkMode ? "dark_all" : "light_all"
}/{z}/{x}/{y}${leaflet.Browser.retina ? "@2x.png" : ".png"}`, }/{z}/{x}/{y}${leaflet.Browser.retina ? "@2x.png" : ".png"}`,
@ -61,4 +61,3 @@ const createTileLayer = (
maxZoom: 20, maxZoom: 20,
} }
); );
};

View File

@ -1,3 +1,2 @@
export const computeDomain = (entityId: string): string => { export const computeDomain = (entityId: string): string =>
return entityId.substr(0, entityId.indexOf(".")); entityId.substr(0, entityId.indexOf("."));
};

View File

@ -1,4 +1,3 @@
/** Compute the object ID of a state. */ /** Compute the object ID of a state. */
export const computeObjectId = (entityId: string): string => { export const computeObjectId = (entityId: string): string =>
return entityId.substr(entityId.indexOf(".") + 1); entityId.substr(entityId.indexOf(".") + 1);
};

View File

@ -1,6 +1,5 @@
import { HassEntity } from "home-assistant-js-websocket"; import { HassEntity } from "home-assistant-js-websocket";
import { computeDomain } from "./compute_domain"; import { computeDomain } from "./compute_domain";
export const computeStateDomain = (stateObj: HassEntity) => { export const computeStateDomain = (stateObj: HassEntity) =>
return computeDomain(stateObj.entity_id); computeDomain(stateObj.entity_id);
};

View File

@ -1,8 +1,7 @@
import { HassEntity } from "home-assistant-js-websocket"; import { HassEntity } from "home-assistant-js-websocket";
import { computeObjectId } from "./compute_object_id"; import { computeObjectId } from "./compute_object_id";
export const computeStateName = (stateObj: HassEntity): string => { export const computeStateName = (stateObj: HassEntity): string =>
return stateObj.attributes.friendly_name === undefined stateObj.attributes.friendly_name === undefined
? computeObjectId(stateObj.entity_id).replace(/_/g, " ") ? computeObjectId(stateObj.entity_id).replace(/_/g, " ")
: stateObj.attributes.friendly_name || ""; : stateObj.attributes.friendly_name || "";
};

View File

@ -1,7 +1,4 @@
import { HassEntity } from "home-assistant-js-websocket"; import { HassEntity } from "home-assistant-js-websocket";
export const hasLocation = (stateObj: HassEntity) => { export const hasLocation = (stateObj: HassEntity) =>
return ( "latitude" in stateObj.attributes && "longitude" in stateObj.attributes;
"latitude" in stateObj.attributes && "longitude" in stateObj.attributes
);
};

View File

@ -3,7 +3,6 @@ import { HassEntity } from "home-assistant-js-websocket";
export const supportsFeature = ( export const supportsFeature = (
stateObj: HassEntity, stateObj: HassEntity,
feature: number feature: number
): boolean => { ): boolean =>
// eslint-disable-next-line no-bitwise // eslint-disable-next-line no-bitwise
return (stateObj.attributes.supported_features! & feature) !== 0; (stateObj.attributes.supported_features! & feature) !== 0;
};

View File

@ -119,6 +119,7 @@ export const extractColors = (url: string, downsampleColors = 16) =>
colorCount: downsampleColors, colorCount: downsampleColors,
}) })
.getPalette() .getPalette()
.then(({ foreground, background }) => { .then(({ foreground, background }) => ({
return { background: background!, foreground: foreground! }; background: background!,
}); foreground: foreground!,
}));

View File

@ -71,8 +71,8 @@ type FuzzyFilterSort = <T extends ScorableTextItem>(
items: T[] items: T[]
) => T[]; ) => T[];
export const fuzzyFilterSort: FuzzyFilterSort = (filter, items) => { export const fuzzyFilterSort: FuzzyFilterSort = (filter, items) =>
return items items
.map((item) => { .map((item) => {
item.score = fuzzySequentialMatch(filter, item); item.score = fuzzySequentialMatch(filter, item);
return item; return item;
@ -81,4 +81,3 @@ export const fuzzyFilterSort: FuzzyFilterSort = (filter, items) => {
.sort(({ score: scoreA = 0 }, { score: scoreB = 0 }) => .sort(({ score: scoreA = 0 }, { score: scoreB = 0 }) =>
scoreA > scoreB ? -1 : scoreA < scoreB ? 1 : 0 scoreA > scoreB ? -1 : scoreA < scoreB ? 1 : 0
); );
};

View File

@ -2,8 +2,7 @@ export const afterNextRender = (cb: (value: unknown) => void): void => {
requestAnimationFrame(() => setTimeout(cb, 0)); requestAnimationFrame(() => setTimeout(cb, 0));
}; };
export const nextRender = () => { export const nextRender = () =>
return new Promise((resolve) => { new Promise((resolve) => {
afterNextRender(resolve); afterNextRender(resolve);
}); });
};

View File

@ -485,9 +485,7 @@ export class HaDataTable extends LitElement {
data: DataTableRowData[], data: DataTableRowData[],
columns: SortableColumnContainer, columns: SortableColumnContainer,
filter: string filter: string
): Promise<DataTableRowData[]> => { ): Promise<DataTableRowData[]> => filterData(data, columns, filter)
return filterData(data, columns, filter);
}
); );
private _handleHeaderClick(ev: Event) { private _handleHeaderClick(ev: Event) {

View File

@ -1,13 +1,13 @@
import { wrap } from "comlink"; import { Remote, wrap } from "comlink";
import type { api } from "./sort_filter_worker"; import type { Api } from "./sort_filter_worker";
type FilterDataType = api["filterData"]; type FilterDataType = Api["filterData"];
type FilterDataParamTypes = Parameters<FilterDataType>; type FilterDataParamTypes = Parameters<FilterDataType>;
type SortDataType = api["sortData"]; type SortDataType = Api["sortData"];
type SortDataParamTypes = Parameters<SortDataType>; type SortDataParamTypes = Parameters<SortDataType>;
let worker: any | undefined; let worker: Remote<Api> | undefined;
export const filterData = async ( export const filterData = async (
data: FilterDataParamTypes[0], data: FilterDataParamTypes[0],
@ -18,7 +18,7 @@ export const filterData = async (
worker = wrap(new Worker(new URL("./sort_filter_worker", import.meta.url))); worker = wrap(new Worker(new URL("./sort_filter_worker", import.meta.url)));
} }
return await worker.filterData(data, columns, filter); return worker.filterData(data, columns, filter);
}; };
export const sortData = async ( export const sortData = async (
@ -31,5 +31,5 @@ export const sortData = async (
worker = wrap(new Worker(new URL("./sort_filter_worker", import.meta.url))); worker = wrap(new Worker(new URL("./sort_filter_worker", import.meta.url)));
} }
return await worker.sortData(data, columns, direction, sortColumn); return worker.sortData(data, columns, direction, sortColumn);
}; };

View File

@ -14,8 +14,8 @@ const filterData = (
filter: string filter: string
) => { ) => {
filter = filter.toUpperCase(); filter = filter.toUpperCase();
return data.filter((row) => { return data.filter((row) =>
return Object.entries(columns).some((columnEntry) => { Object.entries(columns).some((columnEntry) => {
const [key, column] = columnEntry; const [key, column] = columnEntry;
if (column.filterable) { if (column.filterable) {
if ( if (
@ -27,8 +27,8 @@ const filterData = (
} }
} }
return false; return false;
}); })
}); );
}; };
const sortData = ( const sortData = (
@ -80,6 +80,6 @@ const api = {
sortData, sortData,
}; };
export type api = typeof api; export type Api = typeof api;
expose(api); expose(api);

View File

@ -64,12 +64,8 @@ export abstract class HaDeviceAutomationPicker<
private _createNoAutomation: (deviceId?: string) => T; private _createNoAutomation: (deviceId?: string) => T;
constructor( constructor(
localizeDeviceAutomation: HaDeviceAutomationPicker< localizeDeviceAutomation: HaDeviceAutomationPicker<T>["_localizeDeviceAutomation"],
T fetchDeviceAutomations: HaDeviceAutomationPicker<T>["_fetchDeviceAutomations"],
>["_localizeDeviceAutomation"],
fetchDeviceAutomations: HaDeviceAutomationPicker<
T
>["_fetchDeviceAutomations"],
createNoAutomation: HaDeviceAutomationPicker<T>["_createNoAutomation"] createNoAutomation: HaDeviceAutomationPicker<T>["_createNoAutomation"]
) { ) {
super(); super();

View File

@ -8,9 +8,7 @@ import "../ha-paper-dropdown-menu";
import { HaDeviceAutomationPicker } from "./ha-device-automation-picker"; import { HaDeviceAutomationPicker } from "./ha-device-automation-picker";
@customElement("ha-device-condition-picker") @customElement("ha-device-condition-picker")
class HaDeviceConditionPicker extends HaDeviceAutomationPicker< class HaDeviceConditionPicker extends HaDeviceAutomationPicker<DeviceCondition> {
DeviceCondition
> {
protected get NO_AUTOMATION_TEXT() { protected get NO_AUTOMATION_TEXT() {
return this.hass.localize( return this.hass.localize(
"ui.panel.config.devices.automation.conditions.no_conditions" "ui.panel.config.devices.automation.conditions.no_conditions"

View File

@ -212,8 +212,7 @@ export class HaDevicePicker extends SubscribeMixin(LitElement) {
); );
} }
const outputDevices = inputDevices.map((device) => { const outputDevices = inputDevices.map((device) => ({
return {
id: device.id, id: device.id,
name: computeDeviceName( name: computeDeviceName(
device, device,
@ -223,8 +222,7 @@ export class HaDevicePicker extends SubscribeMixin(LitElement) {
area: device.area_id area: device.area_id
? areaLookup[device.area_id].name ? areaLookup[device.area_id].name
: this.hass.localize("ui.components.device-picker.no_area"), : this.hass.localize("ui.components.device-picker.no_area"),
}; }));
});
if (!outputDevices.length) { if (!outputDevices.length) {
return [ return [
{ {

View File

@ -4,9 +4,9 @@ import { mixinBehaviors } from "@polymer/polymer/lib/legacy/class";
import type { Constructor } from "../../types"; import type { Constructor } from "../../types";
import { HaIronFocusablesHelper } from "./ha-iron-focusables-helper"; import { HaIronFocusablesHelper } from "./ha-iron-focusables-helper";
const paperDialogClass = customElements.get("paper-dialog") as Constructor< const paperDialogClass = customElements.get(
PaperDialogElement "paper-dialog"
>; ) as Constructor<PaperDialogElement>;
// behavior that will override existing iron-overlay-behavior and call the fixed implementation // behavior that will override existing iron-overlay-behavior and call the fixed implementation
const haTabFixBehaviorImpl = { const haTabFixBehaviorImpl = {

View File

@ -57,9 +57,7 @@ export class HaAnalytics extends LitElement {
> >
</ha-checkbox> </ha-checkbox>
</span> </span>
<span slot="heading" data-for="base"> <span slot="heading" data-for="base"> Basic analytics </span>
Basic analytics
</span>
<span slot="description" data-for="base"> <span slot="description" data-for="base">
This includes information about your system. This includes information about your system.
</span> </span>
@ -101,9 +99,7 @@ export class HaAnalytics extends LitElement {
> >
</ha-checkbox> </ha-checkbox>
</span> </span>
<span slot="heading" data-for="diagnostics"> <span slot="heading" data-for="diagnostics"> Diagnostics </span>
Diagnostics
</span>
<span slot="description" data-for="diagnostics"> <span slot="description" data-for="diagnostics">
Share crash reports when unexpected errors occur. Share crash reports when unexpected errors occur.
</span> </span>

View File

@ -391,11 +391,9 @@ export class HaAreaPicker extends SubscribeMixin(LitElement) {
`; `;
} }
private _area = memoizeOne((areaId: string): private _area = memoizeOne((areaId: string): AreaRegistryEntry | undefined =>
| AreaRegistryEntry this._areas?.find((area) => area.area_id === areaId)
| undefined => { );
return this._areas?.find((area) => area.area_id === areaId);
});
private _clearValue(ev: Event) { private _clearValue(ev: Event) {
ev.stopPropagation(); ev.stopPropagation();

View File

@ -36,12 +36,8 @@ class HaAttributes extends LitElement {
).map( ).map(
(attribute) => html` (attribute) => html`
<div class="data-entry"> <div class="data-entry">
<div class="key"> <div class="key">${formatAttributeName(attribute)}</div>
${formatAttributeName(attribute)} <div class="value">${this.formatAttribute(attribute)}</div>
</div>
<div class="value">
${this.formatAttribute(attribute)}
</div>
</div> </div>
` `
)} )}
@ -92,9 +88,9 @@ class HaAttributes extends LitElement {
if (!this.stateObj) { if (!this.stateObj) {
return []; return [];
} }
return Object.keys(this.stateObj.attributes).filter((key) => { return Object.keys(this.stateObj.attributes).filter(
return filtersArray.indexOf(key) === -1; (key) => filtersArray.indexOf(key) === -1
}); );
} }
private formatAttribute(attribute: string): string | TemplateResult { private formatAttribute(attribute: string): string | TemplateResult {

View File

@ -45,16 +45,13 @@ const i18n = {
clear: "Clear", clear: "Clear",
today: "Today", today: "Today",
cancel: "Cancel", cancel: "Cancel",
formatTitle: (monthName, fullYear) => { formatTitle: (monthName, fullYear) => monthName + " " + fullYear,
return monthName + " " + fullYear; formatDate: (d: { day: number; month: number; year: number }) =>
}, [
formatDate: (d: { day: number; month: number; year: number }) => {
return [
("0000" + String(d.year)).slice(-4), ("0000" + String(d.year)).slice(-4),
("0" + String(d.month + 1)).slice(-2), ("0" + String(d.month + 1)).slice(-2),
("0" + String(d.day)).slice(-2), ("0" + String(d.day)).slice(-2),
].join("-"); ].join("-"),
},
parseDate: (text: string) => { parseDate: (text: string) => {
const parts = text.split("-"); const parts = text.split("-");
const today = new Date(); const today = new Date();

View File

@ -88,9 +88,7 @@ export class HaDateRangePicker extends LitElement {
> >
<mwc-list @action=${this._setDateRange} activatable> <mwc-list @action=${this._setDateRange} activatable>
${Object.keys(this.ranges).map( ${Object.keys(this.ranges).map(
(name) => html`<mwc-list-item> (name) => html`<mwc-list-item> ${name} </mwc-list-item>`
${name}
</mwc-list-item>`
)} )}
</mwc-list> </mwc-list>
</div>` </div>`

View File

@ -28,9 +28,7 @@ export class HaDialog extends MwcDialog {
} }
protected renderHeading() { protected renderHeading() {
return html`<slot name="heading"> return html`<slot name="heading"> ${super.renderHeading()} </slot>`;
${super.renderHeading()}
</slot>`;
} }
protected static get styles(): CSSResult[] { protected static get styles(): CSSResult[] {

View File

@ -79,9 +79,7 @@ export class HaFileUpload extends LitElement {
dragged: this._drag, dragged: this._drag,
})} })}
> >
<label for="input" slot="label"> <label for="input" slot="label"> ${this.label} </label>
${this.label}
</label>
<iron-input slot="input"> <iron-input slot="input">
<input <input
id="input" id="input"

View File

@ -80,7 +80,8 @@ export class HaFormMultiSelect extends LitElement implements HaFormElement {
@selected-items-changed=${this._valueChanged} @selected-items-changed=${this._valueChanged}
@iron-select=${this._onSelect} @iron-select=${this._onSelect}
> >
${// TS doesn't work with union array types https://github.com/microsoft/TypeScript/issues/36390 ${
// TS doesn't work with union array types https://github.com/microsoft/TypeScript/issues/36390
// @ts-ignore // @ts-ignore
options.map((item: string | [string, string]) => { options.map((item: string | [string, string]) => {
const value = this._optionValue(item); const value = this._optionValue(item);
@ -93,7 +94,8 @@ export class HaFormMultiSelect extends LitElement implements HaFormElement {
${this._optionLabel(item)} ${this._optionLabel(item)}
</paper-icon-item> </paper-icon-item>
`; `;
})} })
}
</paper-listbox> </paper-listbox>
</paper-menu-button> </paper-menu-button>
`; `;

View File

@ -41,7 +41,8 @@ export class HaFormSelect extends LitElement implements HaFormElement {
.selected=${this.data} .selected=${this.data}
@selected-item-changed=${this._valueChanged} @selected-item-changed=${this._valueChanged}
> >
${// TS doesn't work with union array types https://github.com/microsoft/TypeScript/issues/36390 ${
// TS doesn't work with union array types https://github.com/microsoft/TypeScript/issues/36390
// @ts-ignore // @ts-ignore
this.schema.options!.map( this.schema.options!.map(
(item: string | [string, string]) => html` (item: string | [string, string]) => html`
@ -49,7 +50,8 @@ export class HaFormSelect extends LitElement implements HaFormElement {
${this._optionLabel(item)} ${this._optionLabel(item)}
</paper-item> </paper-item>
` `
)} )
}
</paper-listbox> </paper-listbox>
</ha-paper-dropdown-menu> </ha-paper-dropdown-menu>
`; `;

View File

@ -4,9 +4,9 @@ import { style } from "@material/mwc-formfield/mwc-formfield-css";
import { css, CSSResult, customElement } from "lit-element"; import { css, CSSResult, customElement } from "lit-element";
import { Constructor } from "../types"; import { Constructor } from "../types";
const MwcFormfield = customElements.get("mwc-formfield") as Constructor< const MwcFormfield = customElements.get(
Formfield "mwc-formfield"
>; ) as Constructor<Formfield>;
@customElement("ha-formfield") @customElement("ha-formfield")
export class HaFormfield extends MwcFormfield { export class HaFormfield extends MwcFormfield {

View File

@ -36,9 +36,7 @@ export class HaSelectSelector extends LitElement {
> >
${this.selector.select.options.map( ${this.selector.select.options.map(
(item: string) => html` (item: string) => html`
<paper-item .itemValue=${item}> <paper-item .itemValue=${item}> ${item} </paper-item>
${item}
</paper-item>
` `
)} )}
</paper-listbox> </paper-listbox>

View File

@ -140,13 +140,11 @@ export class HaServiceControl extends LitElement {
const fields = Object.entries( const fields = Object.entries(
serviceDomains[domain][serviceName].fields serviceDomains[domain][serviceName].fields
).map(([key, value]) => { ).map(([key, value]) => ({
return {
key, key,
...value, ...value,
selector: value.selector as Selector | undefined, selector: value.selector as Selector | undefined,
}; }));
});
return { return {
...serviceDomains[domain][serviceName], ...serviceDomains[domain][serviceName],
fields, fields,

View File

@ -5,9 +5,9 @@ import type { PaperTabsElement } from "@polymer/paper-tabs/paper-tabs";
import { customElement } from "lit-element"; import { customElement } from "lit-element";
import { Constructor } from "../types"; import { Constructor } from "../types";
const PaperTabs = customElements.get("paper-tabs") as Constructor< const PaperTabs = customElements.get(
PaperTabsElement "paper-tabs"
>; ) as Constructor<PaperTabsElement>;
let subTemplate: HTMLTemplateElement; let subTemplate: HTMLTemplateElement;

View File

@ -2,9 +2,9 @@ import "@polymer/paper-toast/paper-toast";
import type { PaperToastElement } from "@polymer/paper-toast/paper-toast"; import type { PaperToastElement } from "@polymer/paper-toast/paper-toast";
import type { Constructor } from "../types"; import type { Constructor } from "../types";
const PaperToast = customElements.get("paper-toast") as Constructor< const PaperToast = customElements.get(
PaperToastElement "paper-toast"
>; ) as Constructor<PaperToastElement>;
export class HaToast extends PaperToast { export class HaToast extends PaperToast {
private _resizeListener?: (obj: { matches: boolean }) => unknown; private _resizeListener?: (obj: { matches: boolean }) => unknown;

View File

@ -122,9 +122,7 @@ export class HaMediaPlayerBrowse extends LitElement {
}); });
} else { } else {
return html` return html`
<div class="container"> <div class="container">${this._renderError(this._error)}</div>
${this._renderError(this._error)}
</div>
`; `;
} }
} }
@ -202,13 +200,7 @@ export class HaMediaPlayerBrowse extends LitElement {
` `
: ""} : ""}
<h1 class="title">${currentItem.title}</h1> <h1 class="title">${currentItem.title}</h1>
${subtitle ${subtitle ? html` <h2 class="subtitle">${subtitle}</h2> ` : ""}
? html`
<h2 class="subtitle">
${subtitle}
</h2>
`
: ""}
</div> </div>
${currentItem.can_play && (!currentItem.thumbnail || !this._narrow) ${currentItem.can_play && (!currentItem.thumbnail || !this._narrow)
? html` ? html`
@ -247,9 +239,7 @@ export class HaMediaPlayerBrowse extends LitElement {
<div class="content" @scroll=${this._scroll} @touchmove=${this._scroll}> <div class="content" @scroll=${this._scroll} @touchmove=${this._scroll}>
${this._error ${this._error
? html` ? html`
<div class="container"> <div class="container">${this._renderError(this._error)}</div>
${this._renderError(this._error)}
</div>
` `
: currentItem.children?.length : currentItem.children?.length
? childrenMediaClass.layout === "grid" ? childrenMediaClass.layout === "grid"

View File

@ -1,8 +1,7 @@
import { Trigger, Condition } from "./automation"; import { Trigger, Condition } from "./automation";
export const describeTrigger = (trigger: Trigger) => { export const describeTrigger = (trigger: Trigger) =>
return `${trigger.platform} trigger`; `${trigger.platform} trigger`;
};
export const describeCondition = (condition: Condition) => { export const describeCondition = (condition: Condition) => {
if (condition.alias) { if (condition.alias) {

View File

@ -6,11 +6,12 @@ export const subscribeBootstrapIntegrations = (
hass: HomeAssistant, hass: HomeAssistant,
callback: (message: BootstrapIntegrationsTimings) => void callback: (message: BootstrapIntegrationsTimings) => void
) => { ) => {
const unsubProm = hass.connection.subscribeMessage< const unsubProm = hass.connection.subscribeMessage<BootstrapIntegrationsTimings>(
BootstrapIntegrationsTimings (message) => callback(message),
>((message) => callback(message), { {
type: "subscribe_bootstrap_integrations", type: "subscribe_bootstrap_integrations",
}); }
);
return unsubProm; return unsubProm;
}; };

View File

@ -74,8 +74,8 @@ const getCalendarDate = (dateObj: any): string | undefined => {
return undefined; return undefined;
}; };
export const getCalendars = (hass: HomeAssistant): Calendar[] => { export const getCalendars = (hass: HomeAssistant): Calendar[] =>
return Object.keys(hass.states) Object.keys(hass.states)
.filter((eid) => computeDomain(eid) === "calendar") .filter((eid) => computeDomain(eid) === "calendar")
.sort() .sort()
.map((eid, idx) => ({ .map((eid, idx) => ({
@ -83,4 +83,3 @@ export const getCalendars = (hass: HomeAssistant): Calendar[] => {
name: computeStateName(hass.states[eid]), name: computeStateName(hass.states[eid]),
backgroundColor: `#${HA_COLOR_PALETTE[idx % HA_COLOR_PALETTE.length]}`, backgroundColor: `#${HA_COLOR_PALETTE[idx % HA_COLOR_PALETTE.length]}`,
})); }));
};

View File

@ -48,14 +48,11 @@ export const computeDeviceName = (
device: DeviceRegistryEntry, device: DeviceRegistryEntry,
hass: HomeAssistant, hass: HomeAssistant,
entities?: EntityRegistryEntry[] | string[] entities?: EntityRegistryEntry[] | string[]
) => { ) =>
return (
device.name_by_user || device.name_by_user ||
device.name || device.name ||
(entities && fallbackDeviceName(hass, entities)) || (entities && fallbackDeviceName(hass, entities)) ||
hass.localize("ui.panel.config.devices.unnamed_device") hass.localize("ui.panel.config.devices.unnamed_device");
);
};
export const devicesInArea = (devices: DeviceRegistryEntry[], areaId: string) => export const devicesInArea = (devices: DeviceRegistryEntry[], areaId: string) =>
devices.filter((device) => device.area_id === areaId); devices.filter((device) => device.area_id === areaId);

View File

@ -9,9 +9,7 @@ export interface DiscoveryInformation {
version: string; version: string;
} }
export const fetchDiscoveryInformation = async (): Promise< export const fetchDiscoveryInformation = async (): Promise<DiscoveryInformation> => {
DiscoveryInformation
> => {
const response = await fetch("/api/discovery_info", { method: "GET" }); const response = await fetch("/api/discovery_info", { method: "GET" });
return await response.json(); return response.json();
}; };

View File

@ -135,7 +135,7 @@ export const fetchHassioAddonsInfo = async (
hass: HomeAssistant hass: HomeAssistant
): Promise<HassioAddonsInfo> => { ): Promise<HassioAddonsInfo> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/addons", endpoint: "/addons",
method: "get", method: "get",
@ -152,7 +152,7 @@ export const fetchHassioAddonInfo = async (
slug: string slug: string
): Promise<HassioAddonDetails> => { ): Promise<HassioAddonDetails> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: `/addons/${slug}/info`, endpoint: `/addons/${slug}/info`,
method: "get", method: "get",
@ -170,23 +170,15 @@ export const fetchHassioAddonInfo = async (
export const fetchHassioAddonChangelog = async ( export const fetchHassioAddonChangelog = async (
hass: HomeAssistant, hass: HomeAssistant,
slug: string slug: string
) => { ) => hass.callApi<string>("GET", `hassio/addons/${slug}/changelog`);
return hass.callApi<string>("GET", `hassio/addons/${slug}/changelog`);
};
export const fetchHassioAddonLogs = async ( export const fetchHassioAddonLogs = async (hass: HomeAssistant, slug: string) =>
hass: HomeAssistant, hass.callApi<string>("GET", `hassio/addons/${slug}/logs`);
slug: string
) => {
return hass.callApi<string>("GET", `hassio/addons/${slug}/logs`);
};
export const fetchHassioAddonDocumentation = async ( export const fetchHassioAddonDocumentation = async (
hass: HomeAssistant, hass: HomeAssistant,
slug: string slug: string
) => { ) => hass.callApi<string>("GET", `hassio/addons/${slug}/documentation`);
return hass.callApi<string>("GET", `hassio/addons/${slug}/documentation`);
};
export const setHassioAddonOption = async ( export const setHassioAddonOption = async (
hass: HomeAssistant, hass: HomeAssistant,
@ -215,7 +207,7 @@ export const validateHassioAddonOption = async (
slug: string slug: string
): Promise<{ message: string; valid: boolean }> => { ): Promise<{ message: string; valid: boolean }> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: `/addons/${slug}/options/validate`, endpoint: `/addons/${slug}/options/validate`,
method: "post", method: "post",
@ -232,7 +224,7 @@ export const validateHassioAddonOption = async (
export const startHassioAddon = async (hass: HomeAssistant, slug: string) => { export const startHassioAddon = async (hass: HomeAssistant, slug: string) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: `/addons/${slug}/start`, endpoint: `/addons/${slug}/start`,
method: "post", method: "post",
@ -245,7 +237,7 @@ export const startHassioAddon = async (hass: HomeAssistant, slug: string) => {
export const stopHassioAddon = async (hass: HomeAssistant, slug: string) => { export const stopHassioAddon = async (hass: HomeAssistant, slug: string) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: `/addons/${slug}/stop`, endpoint: `/addons/${slug}/stop`,
method: "post", method: "post",

View File

@ -20,13 +20,12 @@ export interface HassioStats {
export const hassioApiResultExtractor = <T>(response: HassioResponse<T>) => export const hassioApiResultExtractor = <T>(response: HassioResponse<T>) =>
response.data; response.data;
export const extractApiErrorMessage = (error: any): string => { export const extractApiErrorMessage = (error: any): string =>
return typeof error === "object" typeof error === "object"
? typeof error.body === "object" ? typeof error.body === "object"
? error.body.message || "Unknown error, see supervisor logs" ? error.body.message || "Unknown error, see supervisor logs"
: error.body || error.message || "Unknown error, see supervisor logs" : error.body || error.message || "Unknown error, see supervisor logs"
: error; : error;
};
const ignoredStatusCodes = new Set([502, 503, 504]); const ignoredStatusCodes = new Set([502, 503, 504]);
@ -50,7 +49,7 @@ export const fetchHassioStats = async (
container: string container: string
): Promise<HassioStats> => { ): Promise<HassioStats> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: `/${container}/stats`, endpoint: `/${container}/stats`,
method: "get", method: "get",

View File

@ -10,7 +10,7 @@ export const fetchHassioDockerRegistries = async (
hass: HomeAssistant hass: HomeAssistant
): Promise<HassioDockerRegistries> => { ): Promise<HassioDockerRegistries> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: `/docker/registries`, endpoint: `/docker/registries`,
method: "get", method: "get",

View File

@ -26,7 +26,7 @@ export const fetchHassioHardwareAudio = async (
hass: HomeAssistant hass: HomeAssistant
): Promise<HassioHardwareAudioList> => { ): Promise<HassioHardwareAudioList> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: `/hardware/audio`, endpoint: `/hardware/audio`,
method: "get", method: "get",
@ -45,7 +45,7 @@ export const fetchHassioHardwareInfo = async (
hass: HomeAssistant hass: HomeAssistant
): Promise<HassioHardwareInfo> => { ): Promise<HassioHardwareInfo> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: `/hardware/info`, endpoint: `/hardware/info`,
method: "get", method: "get",

View File

@ -28,7 +28,7 @@ export const fetchHassioHostInfo = async (
hass: HomeAssistant hass: HomeAssistant
): Promise<HassioHostInfo> => { ): Promise<HassioHostInfo> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/host/info", endpoint: "/host/info",
method: "get", method: "get",
@ -46,7 +46,7 @@ export const fetchHassioHassOsInfo = async (
hass: HomeAssistant hass: HomeAssistant
): Promise<HassioHassOSInfo> => { ): Promise<HassioHassOSInfo> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/os/info", endpoint: "/os/info",
method: "get", method: "get",
@ -63,7 +63,7 @@ export const fetchHassioHassOsInfo = async (
export const rebootHost = async (hass: HomeAssistant) => { export const rebootHost = async (hass: HomeAssistant) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/host/reboot", endpoint: "/host/reboot",
method: "post", method: "post",
@ -76,7 +76,7 @@ export const rebootHost = async (hass: HomeAssistant) => {
export const shutdownHost = async (hass: HomeAssistant) => { export const shutdownHost = async (hass: HomeAssistant) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/host/shutdown", endpoint: "/host/shutdown",
method: "post", method: "post",
@ -89,7 +89,7 @@ export const shutdownHost = async (hass: HomeAssistant) => {
export const updateOS = async (hass: HomeAssistant) => { export const updateOS = async (hass: HomeAssistant) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/os/update", endpoint: "/os/update",
method: "post", method: "post",
@ -102,7 +102,7 @@ export const updateOS = async (hass: HomeAssistant) => {
export const configSyncOS = async (hass: HomeAssistant) => { export const configSyncOS = async (hass: HomeAssistant) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/os/config/sync", endpoint: "/os/config/sync",
method: "post", method: "post",
@ -115,7 +115,7 @@ export const configSyncOS = async (hass: HomeAssistant) => {
export const changeHostOptions = async (hass: HomeAssistant, options: any) => { export const changeHostOptions = async (hass: HomeAssistant, options: any) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/host/options", endpoint: "/host/options",
method: "post", method: "post",

View File

@ -56,7 +56,7 @@ export const fetchNetworkInfo = async (
hass: HomeAssistant hass: HomeAssistant
): Promise<NetworkInfo> => { ): Promise<NetworkInfo> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/network/info", endpoint: "/network/info",
method: "get", method: "get",
@ -99,7 +99,7 @@ export const accesspointScan = async (
network_interface: string network_interface: string
): Promise<AccessPoints> => { ): Promise<AccessPoints> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: `/network/interface/${network_interface}/accesspoints`, endpoint: `/network/interface/${network_interface}/accesspoints`,
method: "get", method: "get",

View File

@ -13,7 +13,7 @@ export const fetchHassioResolution = async (
hass: HomeAssistant hass: HomeAssistant
): Promise<HassioResolution> => { ): Promise<HassioResolution> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/resolution/info", endpoint: "/resolution/info",
method: "get", method: "get",

View File

@ -61,7 +61,7 @@ export const fetchHassioSnapshotInfo = async (
): Promise<HassioSnapshotDetail> => { ): Promise<HassioSnapshotDetail> => {
if (hass) { if (hass) {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: `/snapshots/${snapshot}/info`, endpoint: `/snapshots/${snapshot}/info`,
method: "get", method: "get",
@ -163,5 +163,5 @@ export const uploadSnapshot = async (
} else if (resp.status !== 200) { } else if (resp.status !== 200) {
throw new Error(`${resp.status} ${resp.statusText}`); throw new Error(`${resp.status} ${resp.statusText}`);
} }
return await resp.json(); return resp.json();
}; };

View File

@ -128,7 +128,7 @@ export const fetchHassioHomeAssistantInfo = async (
hass: HomeAssistant hass: HomeAssistant
): Promise<HassioHomeAssistantInfo> => { ): Promise<HassioHomeAssistantInfo> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/core/info", endpoint: "/core/info",
method: "get", method: "get",
@ -147,7 +147,7 @@ export const fetchHassioSupervisorInfo = async (
hass: HomeAssistant hass: HomeAssistant
): Promise<HassioSupervisorInfo> => { ): Promise<HassioSupervisorInfo> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/supervisor/info", endpoint: "/supervisor/info",
method: "get", method: "get",
@ -166,7 +166,7 @@ export const fetchHassioInfo = async (
hass: HomeAssistant hass: HomeAssistant
): Promise<HassioInfo> => { ): Promise<HassioInfo> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/info", endpoint: "/info",
method: "get", method: "get",
@ -178,12 +178,8 @@ export const fetchHassioInfo = async (
); );
}; };
export const fetchHassioLogs = async ( export const fetchHassioLogs = async (hass: HomeAssistant, provider: string) =>
hass: HomeAssistant, hass.callApi<string>("GET", `hassio/${provider}/logs`);
provider: string
) => {
return hass.callApi<string>("GET", `hassio/${provider}/logs`);
};
export const setSupervisorOption = async ( export const setSupervisorOption = async (
hass: HomeAssistant, hass: HomeAssistant,

View File

@ -88,14 +88,13 @@ export const fetchDate = (
startTime: Date, startTime: Date,
endTime: Date, endTime: Date,
entityId entityId
): Promise<HassEntity[][]> => { ): Promise<HassEntity[][]> =>
return hass.callApi( hass.callApi(
"GET", "GET",
`history/period/${startTime.toISOString()}?end_time=${endTime.toISOString()}&minimal_response${ `history/period/${startTime.toISOString()}?end_time=${endTime.toISOString()}&minimal_response${
entityId ? `&filter_entity_id=${entityId}` : `` entityId ? `&filter_entity_id=${entityId}` : ``
}` }`
); );
};
const equalState = (obj1: LineChartState, obj2: LineChartState) => const equalState = (obj1: LineChartState, obj2: LineChartState) =>
obj1.state === obj2.state && obj1.state === obj2.state &&

View File

@ -33,7 +33,7 @@ export const createImage = async (
} else if (resp.status !== 200) { } else if (resp.status !== 200) {
throw new Error("Unknown error"); throw new Error("Unknown error");
} }
return await resp.json(); return resp.json();
}; };
export const updateImage = ( export const updateImage = (

View File

@ -36,25 +36,20 @@ export const SUPPORT_TRANSITION = 32;
export const lightSupportsColorMode = ( export const lightSupportsColorMode = (
entity: LightEntity, entity: LightEntity,
mode: LightColorModes mode: LightColorModes
) => { ) => entity.attributes.supported_color_modes?.includes(mode);
return entity.attributes.supported_color_modes?.includes(mode);
};
export const lightIsInColorMode = (entity: LightEntity) => { export const lightIsInColorMode = (entity: LightEntity) =>
return modesSupportingColor.includes(entity.attributes.color_mode); modesSupportingColor.includes(entity.attributes.color_mode);
};
export const lightSupportsColor = (entity: LightEntity) => { export const lightSupportsColor = (entity: LightEntity) =>
return entity.attributes.supported_color_modes?.some((mode) => entity.attributes.supported_color_modes?.some((mode) =>
modesSupportingColor.includes(mode) modesSupportingColor.includes(mode)
); );
};
export const lightSupportsDimming = (entity: LightEntity) => { export const lightSupportsDimming = (entity: LightEntity) =>
return entity.attributes.supported_color_modes?.some((mode) => entity.attributes.supported_color_modes?.some((mode) =>
modesSupportingDimming.includes(mode) modesSupportingDimming.includes(mode)
); );
};
export const getLightCurrentModeRgbColor = ( export const getLightCurrentModeRgbColor = (
entity: LightEntity entity: LightEntity

View File

@ -37,12 +37,11 @@ export const subscribeMQTTTopic = (
hass: HomeAssistant, hass: HomeAssistant,
topic: string, topic: string,
callback: (message: MQTTMessage) => void callback: (message: MQTTMessage) => void
) => { ) =>
return hass.connection.subscribeMessage<MQTTMessage>(callback, { hass.connection.subscribeMessage<MQTTMessage>(callback, {
type: "mqtt/subscribe", type: "mqtt/subscribe",
topic, topic,
}); });
};
export const removeMQTTDeviceEntry = ( export const removeMQTTDeviceEntry = (
hass: HomeAssistant, hass: HomeAssistant,

View File

@ -38,7 +38,7 @@ export const fetchSupervisorStore = async (
hass: HomeAssistant hass: HomeAssistant
): Promise<SupervisorStore> => { ): Promise<SupervisorStore> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) { if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return await hass.callWS({ return hass.callWS({
type: "supervisor/api", type: "supervisor/api",
endpoint: "/store", endpoint: "/store",
method: "get", method: "get",

View File

@ -280,8 +280,7 @@ export const weatherSVGStyles = css`
const getWeatherStateSVG = ( const getWeatherStateSVG = (
state: string, state: string,
nightTime?: boolean nightTime?: boolean
): SVGTemplateResult => { ): SVGTemplateResult => svg`
return svg`
<svg <svg
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 17 17" viewBox="0 0 17 17"
@ -416,7 +415,6 @@ const getWeatherStateSVG = (
: "" : ""
} }
</svg>`; </svg>`;
};
export const getWeatherStateIcon = ( export const getWeatherStateIcon = (
state: string, state: string,

View File

@ -21,9 +21,8 @@ export const subscribeRenderTemplate = (
variables?: Record<string, unknown>; variables?: Record<string, unknown>;
timeout?: number; timeout?: number;
} }
): Promise<UnsubscribeFunc> => { ): Promise<UnsubscribeFunc> =>
return conn.subscribeMessage((msg: RenderTemplateResult) => onChange(msg), { conn.subscribeMessage((msg: RenderTemplateResult) => onChange(msg), {
type: "render_template", type: "render_template",
...params, ...params,
}); });
};

View File

@ -136,15 +136,14 @@ export const reconfigureNode = (
hass: HomeAssistant, hass: HomeAssistant,
ieeeAddress: string, ieeeAddress: string,
callbackFunction: (message: ClusterConfigurationEvent) => void callbackFunction: (message: ClusterConfigurationEvent) => void
) => { ) =>
return hass.connection.subscribeMessage( hass.connection.subscribeMessage(
(message: ClusterConfigurationEvent) => callbackFunction(message), (message: ClusterConfigurationEvent) => callbackFunction(message),
{ {
type: "zha/devices/reconfigure", type: "zha/devices/reconfigure",
ieee: ieeeAddress, ieee: ieeeAddress,
} }
); );
};
export const refreshTopology = (hass: HomeAssistant): Promise<void> => export const refreshTopology = (hass: HomeAssistant): Promise<void> =>
hass.callWS({ hass.callWS({
@ -240,12 +239,11 @@ export const unbindDeviceFromGroup = (
export const readAttributeValue = ( export const readAttributeValue = (
hass: HomeAssistant, hass: HomeAssistant,
data: ReadAttributeServiceData data: ReadAttributeServiceData
): Promise<string> => { ): Promise<string> =>
return hass.callWS({ hass.callWS({
...data, ...data,
type: "zha/devices/clusters/attributes/value", type: "zha/devices/clusters/attributes/value",
}); });
};
export const fetchCommandsForCluster = ( export const fetchCommandsForCluster = (
hass: HomeAssistant, hass: HomeAssistant,

View File

@ -162,8 +162,8 @@ export const reinterviewNode = (
entry_id: string, entry_id: string,
node_id: number, node_id: number,
callbackFunction: (message: ZWaveJSRefreshNodeStatusMessage) => void callbackFunction: (message: ZWaveJSRefreshNodeStatusMessage) => void
): Promise<UnsubscribeFunc> => { ): Promise<UnsubscribeFunc> =>
return hass.connection.subscribeMessage( hass.connection.subscribeMessage(
(message: any) => callbackFunction(message), (message: any) => callbackFunction(message),
{ {
type: "zwave_js/refresh_node_info", type: "zwave_js/refresh_node_info",
@ -171,7 +171,6 @@ export const reinterviewNode = (
node_id: node_id, node_id: node_id,
} }
); );
};
export const getIdentifiersFromDevice = ( export const getIdentifiersFromDevice = (
device: DeviceRegistryEntry device: DeviceRegistryEntry

View File

@ -27,9 +27,7 @@ class StepFlowExternal extends LitElement {
const localize = this.hass.localize; const localize = this.hass.localize;
return html` return html`
<h2> <h2>${this.flowConfig.renderExternalStepHeader(this.hass, this.step)}</h2>
${this.flowConfig.renderExternalStepHeader(this.hass, this.step)}
</h2>
<div class="content"> <div class="content">
${this.flowConfig.renderExternalStepDescription(this.hass, this.step)} ${this.flowConfig.renderExternalStepDescription(this.hass, this.step)}
<div class="open-button"> <div class="open-button">

View File

@ -55,9 +55,7 @@ class StepFlowForm extends LitElement {
); );
return html` return html`
<h2> <h2>${this.flowConfig.renderShowFormStepHeader(this.hass, this.step)}</h2>
${this.flowConfig.renderShowFormStepHeader(this.hass, this.step)}
</h2>
<div class="content"> <div class="content">
${this._errorMsg ${this._errorMsg
? html` <div class="error">${this._errorMsg}</div> ` ? html` <div class="error">${this._errorMsg}</div> `

View File

@ -54,12 +54,10 @@ class StepFlowPickHandler extends LitElement {
private _getHandlers = memoizeOne( private _getHandlers = memoizeOne(
(h: string[], filter?: string, _localize?: LocalizeFunc) => { (h: string[], filter?: string, _localize?: LocalizeFunc) => {
const handlers: HandlerObj[] = h.map((handler) => { const handlers: HandlerObj[] = h.map((handler) => ({
return {
name: domainToName(this.hass.localize, handler), name: domainToName(this.hass.localize, handler),
slug: handler, slug: handler,
}; }));
});
if (filter) { if (filter) {
const options: Fuse.IFuseOptions<HandlerObj> = { const options: Fuse.IFuseOptions<HandlerObj> = {
@ -113,9 +111,7 @@ class StepFlowPickHandler extends LitElement {
referrerpolicy="no-referrer" referrerpolicy="no-referrer"
/> />
<paper-item-body> <paper-item-body> ${handler.name} </paper-item-body>
${handler.name}
</paper-item-body>
<ha-icon-next></ha-icon-next> <ha-icon-next></ha-icon-next>
</paper-icon-item> </paper-icon-item>
` `

View File

@ -19,7 +19,8 @@ import { HassDialog } from "../make-dialog-manager";
import { HaDomainTogglerDialogParams } from "./show-dialog-domain-toggler"; import { HaDomainTogglerDialogParams } from "./show-dialog-domain-toggler";
@customElement("dialog-domain-toggler") @customElement("dialog-domain-toggler")
class DomainTogglerDialog extends LitElement class DomainTogglerDialog
extends LitElement
implements HassDialog<HaDomainTogglerDialogParams> { implements HassDialog<HaDomainTogglerDialogParams> {
public hass!: HomeAssistant; public hass!: HomeAssistant;

View File

@ -78,9 +78,9 @@ export const showConfirmationDialog = (
element: HTMLElement, element: HTMLElement,
dialogParams: ConfirmationDialogParams dialogParams: ConfirmationDialogParams
) => ) =>
showDialogHelper(element, dialogParams, { confirmation: true }) as Promise< showDialogHelper(element, dialogParams, {
boolean confirmation: true,
>; }) as Promise<boolean>;
export const showPromptDialog = ( export const showPromptDialog = (
element: HTMLElement, element: HTMLElement,

View File

@ -51,9 +51,7 @@ class MoreInfoHumidifier extends LitElement {
<div class="container-humidity"> <div class="container-humidity">
<div>${hass.localize("ui.card.humidifier.humidity")}</div> <div>${hass.localize("ui.card.humidifier.humidity")}</div>
<div class="single-row"> <div class="single-row">
<div class="target-humidity"> <div class="target-humidity">${stateObj.attributes.humidity} %</div>
${stateObj.attributes.humidity} %
</div>
<ha-slider <ha-slider
class="humidity" class="humidity"
step="1" step="1"

View File

@ -46,9 +46,7 @@ class MoreInfoRemote extends LitElement {
> >
${stateObj.attributes.activity_list!.map( ${stateObj.attributes.activity_list!.map(
(activity) => html` (activity) => html`
<paper-item .itemName=${activity}> <paper-item .itemName=${activity}> ${activity} </paper-item>
${activity}
</paper-item>
` `
)} )}
</paper-listbox> </paper-listbox>

View File

@ -29,8 +29,8 @@ class MoreInfoSun extends LitElement {
const order = risingDate > settingDate ? ["set", "ris"] : ["ris", "set"]; const order = risingDate > settingDate ? ["set", "ris"] : ["ris", "set"];
return html` return html`
${order.map((item) => { ${order.map(
return html` (item) => html`
<div class="row"> <div class="row">
<div class="key"> <div class="key">
<span <span
@ -54,8 +54,8 @@ class MoreInfoSun extends LitElement {
)} )}
</div> </div>
</div> </div>
`; `
})} )}
<div class="row"> <div class="row">
<div class="key"> <div class="key">
${this.hass.localize("ui.dialogs.more_info_control.sun.elevation")} ${this.hass.localize("ui.dialogs.more_info_control.sun.elevation")}

View File

@ -177,9 +177,7 @@ class MoreInfoVacuum extends LitElement {
> >
${stateObj.attributes.fan_speed_list!.map( ${stateObj.attributes.fan_speed_list!.map(
(mode) => html` (mode) => html`
<paper-item .itemName=${mode}> <paper-item .itemName=${mode}> ${mode} </paper-item>
${mode}
</paper-item>
` `
)} )}
</paper-listbox> </paper-listbox>

View File

@ -169,8 +169,8 @@ class MoreInfoWeather extends LitElement {
<div class="section"> <div class="section">
${this.hass.localize("ui.card.weather.forecast")}: ${this.hass.localize("ui.card.weather.forecast")}:
</div> </div>
${this.stateObj.attributes.forecast.map((item) => { ${this.stateObj.attributes.forecast.map(
return html` (item) => html`
<div class="flex"> <div class="flex">
${item.condition ${item.condition
? html` ? html`
@ -210,8 +210,8 @@ class MoreInfoWeather extends LitElement {
: ""} : ""}
</div> </div>
</div> </div>
`; `
})} )}
` `
: ""} : ""}
${this.stateObj.attributes.attribution ${this.stateObj.attributes.attribution

View File

@ -29,9 +29,7 @@ export class HuiPersistentNotificationItem extends LitElement {
return html` return html`
<notification-item-template> <notification-item-template>
<span slot="header"> <span slot="header"> ${this.notification.title} </span>
${this.notification.title}
</span>
<ha-markdown <ha-markdown
breaks breaks

View File

@ -70,9 +70,8 @@ interface EntityItem extends QuickBarItem {
icon?: string; icon?: string;
} }
const isCommandItem = (item: QuickBarItem): item is CommandItem => { const isCommandItem = (item: QuickBarItem): item is CommandItem =>
return (item as CommandItem).categoryKey !== undefined; (item as CommandItem).categoryKey !== undefined;
};
interface QuickBarNavigationItem extends CommandItem { interface QuickBarNavigationItem extends CommandItem {
path: string; path: string;
@ -579,9 +578,8 @@ export class QuickBar extends LitElement {
} }
private _filterItems = memoizeOne( private _filterItems = memoizeOne(
(items: QuickBarItem[], filter: string): QuickBarItem[] => { (items: QuickBarItem[], filter: string): QuickBarItem[] =>
return fuzzyFilterSort<QuickBarItem>(filter.trimLeft(), items); fuzzyFilterSort<QuickBarItem>(filter.trimLeft(), items)
}
); );
static get styles() { static get styles() {

Some files were not shown because too many files have changed in this diff Show More