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

Refactor localization to allow configured language and better use of server language #123

Merged
merged 1 commit into from
Aug 24, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ Otherwise, the integration may complain of a duplicate unique ID.
| tap_action | object | **Optional** | Action to take on tap | `action: more-info` |
| hold_action | object | **Optional** | Action to take on hold | `none` |
| double_tap_action | object | **Optional** | Action to take on double tap | `none` |
| language | string | **Optional** | Language to use for card (overrides HA & user settings) | |

### Templating

Expand Down
19 changes: 18 additions & 1 deletion cypress/e2e/localization.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,33 @@ describe('Localization', () => {
it('uses HA server language if no user language is selected', () => {
cy.visitHarness();
cy.window().then(win => {
win.localStorage.setItem('haServerLanguage', 'de');
win.localStorage.removeItem('selectedLanguage');
});
cy.reload();
cy.setLocale({
language: 'de'
});
cy.get('weather-bar')
.shadow()
.find('div.bar > div > span.condition-label')
.first()
.should('have.text', 'Bewölkt');
});
it('prioritizes using configured language', () => {
cy.visitHarness();
cy.window().then(win => {
win.localStorage.removeItem('selectedLanguage');
});
cy.reload();
cy.configure({
language: 'es'
});
cy.get('weather-bar')
.shadow()
.find('div.bar > div > span.condition-label')
.first()
.should('have.text', 'Nublado');
});
const expectedTranslations = {
de: 'Bewölkt',
en: 'Cloudy',
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,9 @@
"@lit/reactive-element": "1.2.1"
},
"scripts": {
"start": "rollup -c rollup.config.dev.js --watch",
"start": "npm run build:dev -- --watch",
"build": "npm run lint && npm run rollup",
"build:dev": "rollup -c rollup.config.dev.js",
"lint": "eslint src/*.ts",
"rollup": "rollup -c",
"test:server": "http-server ./ -c-1 -p 8000 -s",
Expand Down
32 changes: 15 additions & 17 deletions src/conditions.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
import { localize } from "./localize/localize";

export const LABELS = {
'clear-night': localize('conditions.clear'),
'cloudy': localize('conditions.cloudy'),
'fog': localize('conditions.fog'),
'hail': localize('conditions.hail'),
'lightning': localize('conditions.thunderstorm'),
'lightning-rainy': localize('conditions.thunderstorm'),
'partlycloudy': localize('conditions.partlyCloudy'),
'pouring': localize('conditions.heavyRain'),
'rainy': localize('conditions.rain'),
'snowy': localize('conditions.snow'),
'snowy-rainy': localize('conditions.mixedPrecip'),
'sunny': localize('conditions.sunny'),
'windy': localize('conditions.windy'),
'windy-variant': localize('conditions.windy'),
'exceptional': localize('conditions.clear')
'clear-night': 'conditions.clear',
'cloudy': 'conditions.cloudy',
'fog': 'conditions.fog',
'hail': 'conditions.hail',
'lightning': 'conditions.thunderstorm',
'lightning-rainy': 'conditions.thunderstorm',
'partlycloudy': 'conditions.partlyCloudy',
'pouring': 'conditions.heavyRain',
'rainy': 'conditions.rain',
'snowy': 'conditions.snow',
'snowy-rainy': 'conditions.mixedPrecip',
'sunny': 'conditions.sunny',
'windy': 'conditions.windy',
'windy-variant': 'conditions.windy',
'exceptional': 'conditions.clear'
};
export const ICONS = {
'clear-night': 'weather-night',
Expand Down
3 changes: 2 additions & 1 deletion src/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { formfieldDefinition } from '../elements/formfield';
import { selectDefinition } from '../elements/select';
import { switchDefinition } from '../elements/switch';
import { textfieldDefinition } from '../elements/textfield';
import { localize } from './localize/localize';
import { getLocalizer } from './localize/localize';

@customElement('hourly-weather-editor')
export class HourlyWeatherCardEditor extends ScopedRegistryHost(LitElement) implements LovelaceCardEditor {
Expand Down Expand Up @@ -72,6 +72,7 @@ export class HourlyWeatherCardEditor extends ScopedRegistryHost(LitElement) impl
}

const entities = Object.keys(this.hass.states).filter(e => e.startsWith('weather.'));
const localize = getLocalizer(this._config?.language, this.hass?.locale?.language);

return html`
<mwc-select
Expand Down
78 changes: 56 additions & 22 deletions src/hourly-weather.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,23 @@ import type {
ConditionSpan,
ForecastSegment,
HourlyWeatherCardConfig,
LocalizerLastSettings,
RenderTemplateResult,
SegmentTemperature
} from './types';
import { actionHandler } from './action-handler-directive';
import { version } from '../package.json';
import { localize } from './localize/localize';
import { getLocalizer } from './localize/localize';
import { WeatherBar } from './weather-bar';
import { ICONS } from './conditions';
import { ICONS, LABELS } from './conditions';
customElements.define('weather-bar', WeatherBar);

// Naive localizer is used before we can get at card configuration data
const naiveLocalizer = getLocalizer(void 0, void 0);

/* eslint no-console: 0 */
console.info(
`%c HOURLY-WEATHER-CARD \n%c ${localize('common.version')} ${version} `,
`%c HOURLY-WEATHER-CARD \n%c ${naiveLocalizer('common.version')} ${version} `,
'color: orange; font-weight: bold; background: black',
'color: white; font-weight: bold; background: dimgray',
);
Expand All @@ -44,8 +48,8 @@ console.info(
(window as any).customCards = (window as any).customCards || [];
(window as any).customCards.push({
type: 'hourly-weather',
name: localize('common.title_card'),
description: localize('common.description'),
name: naiveLocalizer('common.title_card'),
description: naiveLocalizer('common.description'),
});

@customElement('hourly-weather')
Expand All @@ -69,20 +73,54 @@ export class HourlyWeatherCard extends LitElement {

private configRenderPending = false;

private localizer?: ReturnType<typeof getLocalizer> = void 0;
private localizerLastSettings: LocalizerLastSettings = {
configuredLanguage: void 0,
haServerLanguage: void 0
};

private _labels = LABELS;
private labelsLocalized = false;

private localize(string: string, search = '', replace = ''): string {
if (!this.localizer ||
this.localizerSettingsChanged) {
this.localizer = getLocalizer(this.config?.language, this.hass?.locale?.language);
this.localizerLastSettings.configuredLanguage = this.config?.language;
this.localizerLastSettings.haServerLanguage = this.hass?.locale?.language;
this.labelsLocalized = false;
}

return this.localizer(string, search, replace);
}

private get localizerSettingsChanged() {
return this.localizerLastSettings.configuredLanguage !== this.config?.language ||
this.localizerLastSettings.haServerLanguage !== this.hass?.locale?.language;
}

private get labels() {
if (!this.labelsLocalized || this.localizerSettingsChanged) {
this._labels = Object.fromEntries(Object.entries(LABELS).map(([key, msg]) => [key, this.localize(msg)])) as typeof LABELS;
this.labelsLocalized = true;
}
return this._labels;
}

// https://lit.dev/docs/components/properties/#accessors-custom
public setConfig(config: HourlyWeatherCardConfig): void {
if (!config) {
throw new Error(localize('common.invalid_configuration'));
throw new Error(this.localize('common.invalid_configuration'));
}

if (!config.entity) {
throw new Error(localize('errors.missing_entity'));
throw new Error(this.localize('errors.missing_entity'));
}

if (config.label_spacing) {
const numLabelSpacing = parseInt(config.label_spacing, 10);
if (!Number.isNaN(numLabelSpacing) && (numLabelSpacing < 2 || numLabelSpacing % 2 !== 0)) {
throw new Error(localize('errors.label_spacing_positive_even_int'));
throw new Error(this.localize('errors.label_spacing_positive_even_int'));
}
}

Expand All @@ -91,7 +129,7 @@ export class HourlyWeatherCard extends LitElement {
}

this.config = {
name: localize('common.title'),
name: this.localize('common.title'),
...config,
};

Expand Down Expand Up @@ -153,12 +191,6 @@ export class HourlyWeatherCard extends LitElement {
}

protected updated(): void {
// Update local storage if no selected language is specified
if (this.hass?.locale?.language && !window.localStorage.getItem('selectedLanguage')) {
// Don't mess with `selectedLanguage` since that might have unintended consequences
window.localStorage.setItem('haServerLanguage', this.hass.locale.language);
}

if (this.hass?.connection && this.configRenderPending) {
this.configRenderPending = false;
this.triggerConfigRender();
Expand Down Expand Up @@ -187,19 +219,19 @@ export class HourlyWeatherCard extends LitElement {

if (numSegments < 2) {
// REMARK: Ok, so I'm re-using a localized string here. Probably not the best, but it avoids repeating for no good reason
return await this._showError(localize('errors.label_spacing_positive_even_int').replace('label_spacing', 'num_segments'));
return await this._showError(this.localize('errors.label_spacing_positive_even_int', 'label_spacing', 'num_segments'));
}

if (offset < 0) {
return await this._showError(localize('errors.offset_must_be_positive_int'));
return await this._showError(this.localize('errors.offset_must_be_positive_int'));
}

if (numSegments > (forecast.length - offset)) {
return await this._showError(localize('errors.too_many_segments_requested'));
return await this._showError(this.localize('errors.too_many_segments_requested'));
}

if (labelSpacing < 2 || labelSpacing % 2 !== 0) {
return await this._showError(localize('errors.label_spacing_positive_even_int'));
return await this._showError(this.localize('errors.label_spacing_positive_even_int'));
}

const isForecastDaily = this.isForecastDaily(forecast);
Expand All @@ -221,17 +253,19 @@ export class HourlyWeatherCard extends LitElement {
>
<div class="card-content">
${isForecastDaily ?
this._showWarning(localize('errors.daily_forecasts')) : ''}
this._showWarning(this.localize('errors.daily_forecasts')) : ''}
${colorSettings.warnings.length ?
this._showWarning(localize('errors.invalid_colors') + colorSettings.warnings.join(', ')) : ''}
this._showWarning(this.localize('errors.invalid_colors') + colorSettings.warnings.join(', ')) : ''}
<!-- @ts-ignore -->
<weather-bar
.conditions=${conditionList}
.temperatures=${temperatures}
.icons=${!!config.icons}
.colors=${colorSettings.validColors}
.hide_hours=${!!config.hide_hours}
.hide_temperatures=${!!config.hide_temperatures}
.label_spacing=${labelSpacing}></weather-bar>
.label_spacing=${labelSpacing}
.labels=${this.labels}></weather-bar>
</div>
</ha-card>
`;
Expand Down
31 changes: 18 additions & 13 deletions src/localize/localize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,26 @@ const languages: any = {
pt,
};

export function localize(string: string, search = '', replace = ''): string {
const lang = (localStorage.getItem('selectedLanguage') || localStorage.getItem('haServerLanguage') || 'en').replace(/['"]+/g, '').replace('-', '_');
export function getLocalizer(configuredLanguage: string | undefined, haServerLanguage: string | undefined) {
return function localize(string: string, search = '', replace = ''): string {
const lang = (configuredLanguage ||
localStorage.getItem('selectedLanguage') ||
haServerLanguage ||
'en').replace(/['"]+/g, '').replace('-', '_');

let translated: string;
let translated: string;

try {
translated = string.split('.').reduce((o, i) => o[i], languages[lang]);
} catch (e) {
translated = string.split('.').reduce((o, i) => o[i], languages['en']);
}
try {
translated = string.split('.').reduce((o, i) => o[i], languages[lang]);
} catch (e) {
translated = string.split('.').reduce((o, i) => o[i], languages['en']);
}

if (translated === undefined) translated = string.split('.').reduce((o, i) => o[i], languages['en']);
if (translated === undefined) translated = string.split('.').reduce((o, i) => o[i], languages['en']);

if (search !== '' && replace !== '') {
translated = translated.replace(search, replace);
}
return translated;
if (search !== '' && replace !== '') {
translated = translated.replace(search, replace);
}
return translated;
};
}
7 changes: 6 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ declare global {
}
}

// TODO Add your configuration elements here for type-checking
export interface HourlyWeatherCardConfig extends LovelaceCardConfig {
type: string;
entity: string;
Expand All @@ -25,6 +24,7 @@ export interface HourlyWeatherCardConfig extends LovelaceCardConfig {
tap_action?: ActionConfig;
hold_action?: ActionConfig;
double_tap_action?: ActionConfig;
language?: string;
}

export interface ColorConfig {
Expand Down Expand Up @@ -77,3 +77,8 @@ export interface ColorSettings {
export interface RenderTemplateResult {
result: string
}

export interface LocalizerLastSettings {
configuredLanguage: string | undefined,
haServerLanguage: string | undefined
}
7 changes: 5 additions & 2 deletions src/weather-bar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export class WeatherBar extends LitElement {
@property({ type: Boolean })
icons = false;

@property({ type: Object })
@property({ attribute: false })
colors: ColorMap | undefined = void 0;

@property({ type: Boolean })
Expand All @@ -29,13 +29,16 @@ export class WeatherBar extends LitElement {
@property({ type: Number })
label_spacing = 2;

@property({ type: Object })
labels = LABELS;

private tips: Instance[] = [];

render() {
const conditionBars: TemplateResult[] = [];
let gridStart = 1;
for (const cond of this.conditions) {
const label = LABELS[cond[0]];
const label = this.labels[cond[0]];
let icon = ICONS[cond[0]];
if (icon === cond[0]) icon = 'mdi:weather-' + icon;
else icon = 'mdi:' + icon;
Expand Down