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

feat: πŸ§‘β€πŸ’» Allow users to use jinja-templates to display first tab dynamically #105

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions src/tabbed-card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ interface TabbedCardConfig extends LovelaceCardConfig {
}

interface options {
defaultTabIndex?: number;
defaultTabIndex?: string | number | undefined;
}

interface Tab {
Expand Down Expand Up @@ -103,6 +103,16 @@ export class TabbedCard extends LitElement {
}

async _createTabs(config: TabbedCardConfig) {
let template = config?.options?.defaultTabIndex;
if (typeof template === "undefined") {
this.selectedTabIndex = 0;
} else if (typeof template === "string") {
let result = await this.evaluateJinjaTemplate(this.hass, template || "0")
// Try to parse the result as a number, if it fails, default to 0 (first tab)
this.selectedTabIndex = parseInt(result) || 0;
} else {
this.selectedTabIndex = isFinite(template)? template : 0;
}
const tabs = await Promise.all(
config.tabs.map(async (tab) => {
return {
Expand Down Expand Up @@ -147,6 +157,18 @@ export class TabbedCard extends LitElement {
// this._tabs.splice(this._tabs.indexOf(cardElement), 1, newCardElement);
}

async evaluateJinjaTemplate(
hass: HomeAssistant,
template: string,
): Promise<any> {
return new Promise(resolve => {
hass.connection.subscribeMessage((msg: { result: string | Record<string, unknown> }) => resolve(msg.result.toString()), {
type: "render_template",
template: template,
});
});
}

render() {
if (!this.hass || !this._config || !this._helpers || !this._tabs?.length) {
return html``;
Expand All @@ -157,7 +179,7 @@ export class TabbedCard extends LitElement {
@MDCTabBar:activated=${(ev: mwcTabBarEvent) =>
(this.selectedTabIndex = ev.detail.index)}
style=${styleMap(this._styles)}
activeIndex=${ifDefined(this._config?.options?.defaultTabIndex)}
activeIndex=${this.selectedTabIndex}
>
<!-- no horizontal scrollbar shown when tabs overflow in chrome -->
${this._tabs.map(
Expand Down