Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

More translation fixes #673

Merged
merged 1 commit into from
Jun 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 32 additions & 64 deletions src/dashboards/hacs-dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,37 +86,33 @@ export class HacsDashboard extends LitElement {

@property({ type: Boolean }) public isWide!: boolean;

@storage({key: "hacs-table-filters", state: true, subscribe: false})
@storage({ key: "hacs-table-filter", state: true, subscribe: false })
private activeFilters?: string[] = [];

@storage({key: "hacs-table-sort", state: true, subscribe: false})
@storage({ key: "hacs-table-sort", state: true, subscribe: false })
private activeSort?: { column: string; direction: SortingDirection };

@storage({key: "hacs-active-search", state: true, subscribe: false})
@storage({ key: "hacs-active-search", state: true, subscribe: false })
private _activeSearch?: string;

@storage({key: "hacs-table-active-columns", state: true, subscribe: false})
@storage({ key: "hacs-table-active-columns", state: true, subscribe: false })
private _tableColumns: Record<tableColumnDefaultsType, boolean> = tableColumnDefaults;

protected async firstUpdated(changedProperties: PropertyValues): Promise<void> {
super.firstUpdated(changedProperties);
const baseFilters =
this.activeFilters && this.activeFilters.length === 0
? [this.hacs.localize("common.downloaded")]
: this.activeFilters;
this.activeFilters && this.activeFilters.length === 0 ? ["downloaded"] : this.activeFilters;

const filters = !this._activeSearch?.length
? baseFilters
: baseFilters?.filter((filter) => filter !== this.hacs.localize("common.downloaded"));
: baseFilters?.filter((filter) => filter !== "downloaded");
this.activeFilters = filters?.length ? filters : undefined;
}

protected updated(changedProperties: PropertyValues): void {
super.updated(changedProperties);
if (changedProperties.has("_activeSearch") && this._activeSearch?.length) {
this.activeFilters = this.activeFilters?.filter(
(filter) => filter !== this.hacs.localize("common.downloaded")
);
this.activeFilters = this.activeFilters?.filter((filter) => filter !== "downloaded");
}
}

Expand All @@ -141,8 +137,14 @@ export class HacsDashboard extends LitElement {
.route=${this.route}
clickable
.filter=${this._activeSearch}
.activeFilters=${this.activeFilters}
.noDataText=${this.activeFilters?.includes(this.hacs.localize("common.downloaded"))
.activeFilters=${this.activeFilters?.map(
(filter) =>
this.hacs.localize(
// @ts-ignore
`common.${filter.startsWith("category_") ? filter.replace("category_", "") : filter}`
) || filter
)}
.noDataText=${this.activeFilters?.includes("downloaded")
? "No downloaded repositories"
: "No repositories matching search"}
@row-click=${this._handleRowClicked}
Expand Down Expand Up @@ -218,16 +220,15 @@ export class HacsDashboard extends LitElement {
<ha-check-list-item
@request-selected=${this._handleDownloadFilterChange}
graphic="control"
.selected=${this.activeFilters?.includes(this.hacs.localize("common.downloaded")) ??
false}
.selected=${this.activeFilters?.includes("downloaded") ?? false}
left
>
${this.hacs.localize("common.downloaded")}
</ha-check-list-item>
<ha-check-list-item
@request-selected=${this._handleNewFilterChange}
graphic="control"
.selected=${this.activeFilters?.includes(this.hacs.localize("common.new")) ?? false}
.selected=${this.activeFilters?.includes("new") ?? false}
left
>
${this.hacs.localize("common.new")}
Expand All @@ -239,20 +240,12 @@ export class HacsDashboard extends LitElement {
@selected=${this._handleCategoryFilterChange}
@closed=${stopPropagation}
naturalMenuWidth
.value=${this.activeFilters?.find((filter) =>
filter.startsWith(
`${this.hacs.localize(`dialog_custom_repositories.category`)}: `
)
) || ""}
.value=${this.activeFilters?.find((filter) => filter.startsWith("category_")) || ""}
>
${this.hacs.info.categories.map(
(category) =>
html`
<mwc-list-item
.value="${this.hacs.localize(
`dialog_custom_repositories.category`
)}: ${this.hacs.localize(`common.${category}`)}"
>
<mwc-list-item .value="${`category_${category}`}">
${this.hacs.localize(`common.${category}`)}
</mwc-list-item>
`
Expand All @@ -279,16 +272,10 @@ export class HacsDashboard extends LitElement {
<ha-formfield .label=${this.hacs.localize(`common.${category}`)}>
<ha-radio
@change=${this._handleCategoryFilterChange}
value="${this.hacs.localize(
`dialog_custom_repositories.category`
)}: ${this.hacs.localize(`common.${category}`)}"
.value=${`category_${category}`}
name="category"
.checked=${this.activeFilters?.some(
(filter) =>
filter ===
`${this.hacs.localize(
`dialog_custom_repositories.category`
)}: ${this.hacs.localize(`common.${category}`)}`
(filter) => filter === `category_${category}`
) ?? false}
>
</ha-radio>
Expand All @@ -302,25 +289,16 @@ export class HacsDashboard extends LitElement {
private _filterRepositories = memoize(
(repositories: RepositoryBase[], activeFilters?: string[]): RepositoryBase[] =>
repositories
.filter((reposiotry) => {
if (
this.activeFilters?.includes(this.hacs.localize("common.downloaded")) &&
!reposiotry.installed
) {
.filter((repository) => {
if (this.activeFilters?.includes("downloaded") && !repository.installed) {
return false;
}
if (this.activeFilters?.includes(this.hacs.localize("common.new")) && !reposiotry.new) {
if (this.activeFilters?.includes("new") && !repository.new) {
return false;
}
if (
activeFilters?.filter((filter) =>
filter.startsWith(this.hacs.localize(`dialog_custom_repositories.category`))
).length &&
!activeFilters.includes(
`${this.hacs.localize(`dialog_custom_repositories.category`)}: ${this.hacs.localize(
`common.${reposiotry.category}`
)}`
)
activeFilters?.filter((filter) => filter.startsWith("category_")).length &&
!activeFilters.includes(`category_${repository.category}`)
) {
return false;
}
Expand Down Expand Up @@ -511,17 +489,13 @@ export class HacsDashboard extends LitElement {
if ((ev.target as any).nodeName === "HA-RADIO" && (ev.target as any).checked === false) {
this.activeFilters = [
...(this.activeFilters?.filter(
(filter) =>
!filter.startsWith(this.hacs.localize(`dialog_custom_repositories.category`)) &&
filter !== categoryFilter
(filter) => !filter.startsWith("category_") && filter !== categoryFilter
) || []),
];
} else {
this.activeFilters = [
...(this.activeFilters?.filter(
(filter) =>
!filter.startsWith(this.hacs.localize(`dialog_custom_repositories.category`)) &&
filter !== categoryFilter
(filter) => !filter.startsWith("category_") && filter !== categoryFilter
) || []),
categoryFilter,
];
Expand Down Expand Up @@ -553,23 +527,17 @@ export class HacsDashboard extends LitElement {
}

private _handleDownloadFilterChange(ev: CustomEvent) {
const updatedFilters =
this.activeFilters?.filter(
(filter) => !filter.startsWith(this.hacs.localize("common.downloaded"))
) || [];
const updatedFilters = this.activeFilters?.filter((filter) => filter !== "downloaded") || [];
if (ev.detail.selected) {
updatedFilters.push(this.hacs.localize("common.downloaded"));
updatedFilters.push("downloaded");
}
this.activeFilters = updatedFilters.length ? updatedFilters : undefined;
}

private _handleNewFilterChange(ev: CustomEvent) {
const updatedFilters =
this.activeFilters?.filter(
(filter) => !filter.startsWith(this.hacs.localize("common.new"))
) || [];
const updatedFilters = this.activeFilters?.filter((filter) => filter !== "new") || [];
if (ev.detail.selected) {
updatedFilters.push(this.hacs.localize("common.new"));
updatedFilters.push("new");
}
this.activeFilters = updatedFilters.length ? updatedFilters : undefined;
}
Expand Down
107 changes: 82 additions & 25 deletions src/hacs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,61 +7,118 @@ import { ProvideHassLitMixin } from "../homeassistant-frontend/src/mixins/provid
import type { HomeAssistant } from "../homeassistant-frontend/src/types";
import { computeLocalize } from "../homeassistant-frontend/src/common/translations/localize";
import { getTranslation } from "../homeassistant-frontend/src/util/common-translation";

const ALWAYS_UPDATE = new Set(["localize"]);
import { fetchHacsInfo, getRepositories, websocketSubscription } from "./data/websocket";
import { HacsDispatchEvent } from "./data/common";

export class HacsElement extends ProvideHassLitMixin(LitElement) {
@property({ attribute: false }) public hacs: Partial<Hacs> = {
language: "en",
repositories: [],
info: {} as any,
log: new HacsLogger(),
};
@property({ attribute: false }) public hacs: Partial<Hacs> = { localize: () => "" };

@state() private _language = "en";

public connectedCallback() {
public connectedCallback(): void {
super.connectedCallback();

this._initializeLocalize();

this.addEventListener("update-hacs", (e) =>
this._updateHacs((e as any).detail as Partial<Hacs>)
);
if (!this.hasUpdated) {
return;
}
this._initHacs();
}

protected willUpdate(changedProperties: PropertyValues) {
if (!this.hasUpdated) {
this._initHacs();
}
if (changedProperties.has("hass")) {
const oldHass = changedProperties.get("hass") as HomeAssistant | undefined;
if (oldHass?.language !== this.hass.language) {
this._language = this.hass.language;
this.hacs.language = this.hass.language;
}
}

if (changedProperties.has("_language")) {
if (changedProperties.has("_language") || !this.hasUpdated) {
this._initializeLocalize();
}
}

private async _initHacs(): Promise<void> {
websocketSubscription(
this.hass,
() => this._updateProperties("configuration"),
HacsDispatchEvent.CONFIG
);

websocketSubscription(
this.hass,
() => this._updateProperties("status"),
HacsDispatchEvent.STATUS
);

websocketSubscription(
this.hass,
() => this._updateProperties("status"),
HacsDispatchEvent.STAGE
);

websocketSubscription(
this.hass,
() => this._updateProperties("repositories"),
HacsDispatchEvent.REPOSITORY
);

this.hass.connection.subscribeEvents(
async () => this._updateProperties("lovelace"),
"lovelace_updated"
);

this._updateHacs({
log: new HacsLogger(),
});

this._updateProperties();

this.addEventListener("update-hacs", (e) =>
this._updateHacs((e as any).detail as Partial<Hacs>)
);
}

private async _initializeLocalize() {
const { language, data } = await getTranslation(null, this._language);

console.log({ language, data });

this._updateHacs({
localize: await computeLocalize<HacsLocalizeKeys>(this.constructor.prototype, language, {
[language]: data,
}),
});
}

protected _updateHacs(obj: Partial<Hacs>) {
if (
Object.keys(obj).some(
(key) =>
ALWAYS_UPDATE.has(key) || JSON.stringify(this.hacs[key] !== JSON.stringify(obj[key]))
)
) {
this.hacs = { ...this.hacs, ...obj };
private async _updateProperties(prop = "all") {
const _updates: any = {};
const _fetch: any = {};

if (prop === "all") {
[_fetch.repositories, _fetch.info] = await Promise.all([
getRepositories(this.hass),
fetchHacsInfo(this.hass),
]);
} else if (prop === "info") {
_fetch.info = await fetchHacsInfo(this.hass);
} else if (prop === "repositories") {
_fetch.repositories = await getRepositories(this.hass);
}

Object.keys(_fetch).forEach((update) => {
if (_fetch[update] !== undefined) {
_updates[update] = _fetch[update];
}
});
if (_updates) {
this._updateHacs(_updates);
this.requestUpdate();
}
}

protected _updateHacs(update: Partial<Hacs>) {
this.hacs = { ...this.hacs, ...update };
}
}
Loading