Painel de música: cartão de busca com sugestões
Cartão personalizado em JavaScript: campo de busca com sugestões enquanto digita, que segue a origem escolhida (Navidrome, Spotify ou YouTube Music).
// Busca da view Música: campo no tema Futurista com sugestões enquanto digita.
// Procura artistas, álbuns e faixas no Navidrome pelo Music Assistant (music_assistant.search).
// Clicar numa sugestão toca nos destinos escolhidos (script.musica_tocar); Enter grava o texto em
// input_text.musica_busca, e a grade de capas da view mostra todos os resultados.
const MA_ENTRY = "TROQUE_PELO_ID_DA_INTEGRACAO_MUSIC_ASSISTANT";
const TIPOS = { artist: "Artista", album: "Álbum", track: "Faixa" };
// Fonte escolhida na view (input_text.musica_fonte): navidrome busca só na biblioteca; spotify e ytmusic nos provedores.
const FONTES = {
navidrome: { nome: "Navidrome", prefixo: "library", biblioteca: true },
spotify: { nome: "Spotify", prefixo: "spotify", biblioteca: false },
ytmusic: { nome: "YouTube Music", prefixo: "ytmusic", biblioteca: false },
};
class MusicaBuscaCard extends HTMLElement {
setConfig(config) {
this.config = { entity: "input_text.musica_busca", ...config };
this.itens = [];
this.sel = -1;
this.seq = 0;
}
set hass(hass) {
this._hass = hass;
if (!this.shadowRoot) this.montar();
const carr = hass.states["input_text.musica_carregando"]?.state || "";
if (this.tocando) {
if (carr === this.tocando.u) this.vistoCarregando = true;
else if (this.vistoCarregando || Date.now() - this.tocando.desde > 20000) {
this.tocando = null;
this.lista.hidden = true;
this.campo.blur();
}
}
const f = hass.states["input_text.musica_fonte"]?.state || "navidrome";
if (f !== this.fonteAtual) {
const primeira = this.fonteAtual === undefined;
this.fonteAtual = f;
this.campo.placeholder = "Buscar no " + (FONTES[f]?.nome || f) + ": artista, álbum ou música";
const q = this.campo.value.trim();
if (!primeira && q.length >= 2) this.buscar(q);
}
const v = hass.states[this.config.entity]?.state ?? "";
if (v !== this.ultimoEstado) {
this.ultimoEstado = v;
if (this.shadowRoot.activeElement !== this.campo) this.campo.value = v === "unknown" ? "" : v;
this.limpar.hidden = !this.campo.value;
}
}
getCardSize() { return 1; }
montar() {
const r = this.attachShadow({ mode: "open" });
r.innerHTML = `
<style>
:host { display: block; position: relative; z-index: 5; }
[hidden] { display: none !important; }
.caixa { display: flex; align-items: center; gap: 10px; height: 50px; padding: 0 14px; border-radius: 14px;
background: linear-gradient(145deg, rgba(14,34,66,0.78), rgba(8,18,40,0.78));
border: 1px solid rgba(60,200,255,0.25); box-shadow: 0 8px 30px rgba(0,0,0,0.45), inset 0 1px 0 rgba(255,255,255,0.06);
backdrop-filter: blur(14px); transition: border-color .15s, box-shadow .15s; }
.caixa:focus-within { border-color: #6fe3ff; box-shadow: 0 0 0 3px rgba(111,227,255,.15), 0 8px 30px rgba(0,0,0,0.45); }
ha-icon { --mdc-icon-size: 22px; color: #6fe3ff; flex: none; }
input { flex: 1; min-width: 0; height: 100%; border: 0; outline: 0; background: transparent; color: #eaf4ff;
font: inherit; font-size: 15px; }
input::placeholder { color: rgba(234,244,255,.45); }
button { border: 0; background: none; padding: 4px; cursor: pointer; display: flex; border-radius: 50%; }
button:hover { background: rgba(111,227,255,.12); }
button ha-icon { --mdc-icon-size: 18px; color: rgba(234,244,255,.6); }
.girando { width: 16px; height: 16px; border: 2px solid rgba(111,227,255,.25); border-top-color: #6fe3ff; border-radius: 50%;
animation: g .7s linear infinite; flex: none; }
@keyframes g { to { transform: rotate(360deg); } }
.lista { position: absolute; left: 0; right: 0; top: 56px; max-height: 420px; overflow-y: auto; padding: 6px;
border-radius: 14px; background: rgba(8,20,44,0.97); border: 1px solid rgba(111,227,255,.35);
box-shadow: 0 18px 50px rgba(0,0,0,.6); backdrop-filter: blur(18px); }
.grupo { font-size: 10.5px; letter-spacing: .08em; text-transform: uppercase; color: #6fe3ff; padding: 8px 10px 4px; }
.item { display: flex; align-items: center; gap: 12px; padding: 6px 10px; border-radius: 10px; cursor: pointer; color: #eaf4ff; }
.item.ativo, .item:hover { background: rgba(111,227,255,.12); }
.item img, .item .sem { width: 42px; height: 42px; border-radius: 8px; object-fit: cover; flex: none; background: rgba(111,227,255,.1); }
.item img.redondo, .item .sem.redondo { border-radius: 50%; }
.txt { min-width: 0; flex: 1; }
.n { font-size: 14px; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.n b { color: #6fe3ff; }
.a { font-size: 12px; opacity: .6; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.play { width: 34px; height: 34px; border-radius: 50%; background: #3fd77f; display: flex; align-items: center;
justify-content: center; opacity: 0; transition: opacity .15s; flex: none; }
.play ha-icon { --mdc-icon-size: 20px; color: #052012; }
.item.ativo .play, .item:hover .play, .item.tocando .play { opacity: 1; }
.item.tocando .play { background: none; }
.item.tocando .play span { width: 24px; height: 24px; border-radius: 50%; border: 3px solid rgba(63,215,127,.3);
border-top-color: #3fd77f; animation: g .8s linear infinite; }
.vazio { padding: 14px 10px; font-size: 13px; opacity: .7; }
.rodape { padding: 8px 10px 4px; font-size: 11.5px; opacity: .55; border-top: 1px solid rgba(111,227,255,.12); margin-top: 4px; }
</style>
<div class="caixa">
<ha-icon icon="mdi:magnify"></ha-icon>
<input type="text" placeholder="Buscar no Navidrome: artista, álbum ou música" autocomplete="off" spellcheck="false">
<span class="girando" hidden></span>
<button class="limpar" title="Limpar" hidden><ha-icon icon="mdi:close"></ha-icon></button>
</div>
<div class="lista" hidden></div>`;
this.campo = r.querySelector("input");
this.lista = r.querySelector(".lista");
this.limpar = r.querySelector(".limpar");
this.girando = r.querySelector(".girando");
this.campo.addEventListener("input", () => this.digitou());
this.campo.addEventListener("keydown", (e) => this.tecla(e));
this.campo.addEventListener("focus", () => { if (this.itens.length) this.lista.hidden = false; });
this.campo.addEventListener("blur", () => setTimeout(() => { if (!this.tocando) this.lista.hidden = true; }, 180));
this.limpar.addEventListener("click", () => {
this.campo.value = "";
this.itens = [];
this.lista.hidden = true;
this.limpar.hidden = true;
this.gravar("");
this.campo.focus();
});
}
digitou() {
const q = this.campo.value.trim();
this.limpar.hidden = !this.campo.value;
clearTimeout(this.timer);
if (q.length < 2) {
this.itens = [];
this.lista.hidden = true;
this.girando.hidden = true;
if (!q) this.gravar("");
return;
}
this.timer = setTimeout(() => this.buscar(q), 250);
// grava o texto sozinho (sem Enter) para a grade da view mostrar os resultados enquanto digita
clearTimeout(this.timerGravar);
this.timerGravar = setTimeout(() => this.gravar(q), 700);
}
async buscar(q) {
const meu = ++this.seq;
this.girando.hidden = false;
try {
const resp = await this._hass.connection.sendMessagePromise({
type: "call_service", domain: "music_assistant", service: "search", return_response: true,
service_data: { config_entry_id: MA_ENTRY, name: q, media_type: ["artist", "album", "track"], library_only: FONTES[this.fonteAtual]?.biblioteca !== false, limit: 6 },
});
if (meu !== this.seq) return;
const r = resp.response || {};
const pref = FONTES[this.fonteAtual]?.prefixo || "library";
for (const k of ["artists", "albums", "tracks"]) r[k] = (r[k] || []).filter((x) => (x.uri || "").split("://")[0].startsWith(pref)).slice(0, 5);
const nomes = (l) => (l || []).map((x) => x.name).join(", ");
this.itens = [
...(r.artists || []).map((a) => ({ t: "artist", n: a.name, a: "Artista", i: a.image, u: a.uri })),
...(r.albums || []).map((a) => ({ t: "album", n: a.name, a: nomes(a.artists), i: a.image, u: a.uri })),
...(r.tracks || []).map((a) => ({ t: "track", n: a.name, a: [nomes(a.artists), a.album?.name].filter(Boolean).join(" · "), i: a.image || a.album?.image, u: a.uri })),
];
this.sel = -1;
this.desenhar(q);
} catch (e) {
if (meu !== this.seq) return;
this.itens = [];
this.lista.innerHTML = `<div class="vazio">Não deu para buscar agora (${this.esc(e.message || e.code || "erro")}).</div>`;
this.lista.hidden = false;
} finally {
if (meu === this.seq) this.girando.hidden = true;
}
}
esc(s) {
return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
}
realce(nome, q) {
const s = String(nome ?? "");
const i = s.toLowerCase().indexOf(q.toLowerCase());
if (i < 0) return this.esc(s);
return this.esc(s.slice(0, i)) + "<b>" + this.esc(s.slice(i, i + q.length)) + "</b>" + this.esc(s.slice(i + q.length));
}
desenhar(q) {
if (!this.itens.length) {
this.lista.innerHTML = `<div class="vazio">Nada encontrado para <b>${this.esc(q)}</b>.</div>`;
this.lista.hidden = false;
return;
}
let html = "";
let grupo = "";
this.itens.forEach((it, k) => {
if (it.t !== grupo) {
grupo = it.t;
html += `<div class="grupo">${TIPOS[it.t]}s</div>`;
}
const red = it.t === "artist" ? " redondo" : "";
const img = it.i ? `<img class="${red}" src="${this.esc(it.i)}" loading="lazy">` : `<div class="sem${red}"></div>`;
const tocando = this.tocando && this.tocando.u === it.u;
const botao = tocando ? "<span></span>" : '<ha-icon icon="mdi:play"></ha-icon>';
html += `<div class="item${k === this.sel ? " ativo" : ""}${tocando ? " tocando" : ""}" data-k="${k}">${img}<div class="txt"><div class="n">${this.realce(it.n, q)}</div><div class="a">${this.esc(it.a)}</div></div><div class="play">${botao}</div></div>`;
});
html += `<div class="rodape">Clique para tocar · Enter mostra todos os resultados abaixo</div>`;
this.lista.innerHTML = html;
this.lista.querySelectorAll(".item").forEach((el) =>
el.addEventListener("mousedown", (e) => { e.preventDefault(); this.tocar(this.itens[+el.dataset.k]); }));
this.lista.hidden = false;
}
tecla(e) {
const n = this.itens.length;
if (e.key === "ArrowDown" && n) { e.preventDefault(); this.sel = (this.sel + 1) % n; this.desenhar(this.campo.value.trim()); }
else if (e.key === "ArrowUp" && n) { e.preventDefault(); this.sel = (this.sel - 1 + n) % n; this.desenhar(this.campo.value.trim()); }
else if (e.key === "Escape") { this.lista.hidden = true; }
else if (e.key === "Enter") {
e.preventDefault();
if (this.sel >= 0 && this.itens[this.sel]) this.tocar(this.itens[this.sel]);
else { this.gravar(this.campo.value.trim()); this.lista.hidden = true; this.campo.blur(); }
}
}
tocar(it) {
if (!it) return;
this.tocando = { u: it.u, desde: Date.now() };
this.vistoCarregando = false;
this.desenhar(this.campo.value.trim());
this._hass.callService("script", "musica_tocar", { tipo: it.t, midia: it.u });
}
gravar(v) {
this._hass.callService("input_text", "set_value", { entity_id: this.config.entity, value: v });
}
}
customElements.define("musica-busca-card", MusicaBuscaCard);
window.customCards = window.customCards || [];
window.customCards.push({ type: "musica-busca-card", name: "Busca de música", description: "Busca no Navidrome com sugestões" });
Como usar
Salve como musica-busca-card.js em /config/www/ e registre pelo arquivo de recursos.
Troque o TROQUE_PELO_ID_DA_INTEGRACAO_MUSIC_ASSISTANT no começo do arquivo pelo id da sua integração. Se editar o JavaScript depois, mude o ?v= do recurso para o navegador baixar de novo.
0 comentários
Carregando comentários…
Também respondo os comentários no YouTube.
Escolhidos para você
Veja também
Cartãoplacas-card.js: a página de placas com visual Mercosul, parecidas e correções
Cartão em um arquivo JavaScript só: lista por período, busca, placa no visual Mercosul, fotos, nomes, filtro de parecidas, juntar e desfazer.
15:50VídeoPainel de Saúde no Home Assistant: o que a sua casa esconde de você (passo a passo)
O sensor de movimento da minha sala estava com 3% de bateria e o Home Assistant não avisou nada. Neste vídeo eu mostro, passo a passo e com calma, o painel de saúde que eu uso…
11:33VídeoO jogo do seu time no Home Assistant: horário, onde passa e aviso antes da bola rolar
Que horas é o jogo do seu time? No meu Home Assistant está no painel: data, horário, adversário, estádio, campeonato e onde passa, para qualquer time da Série A e da Série B.…
15:40VídeoTema futurista para o Home Assistant: instalar, personalizar e usar os cartões (grátis)
Esse era o meu Home Assistant, e esse é ele agora: mesmas entidades, mesma casa, com visual de vidro azul. Neste vídeo eu mostro o tema Doug Futurista, que é grátis e já está no…
CartãoMapa da família: a página inteira pronta para colar
A view completa do vídeo: pessoas, rastro de 1 a 72 h, zonas e o botão Nova zona com sugestão de nome. Cole no painel e troque as pessoas.
11:09VídeoSua casa em 3D no Home Assistant: NeonPlan 3D do zero (grátis)
⚠️ AVISO IMPORTANTE: o Marketplace nativo chega na versão 2026.11 do Home Assistant, com lançamento estável previsto para 4 de novembro de 2026. Gravei este vídeo na versão beta.…