push-based-widget-module-pattern
O que ela faz
Esta skill mostra como criar um widget simples que recebe dados de quem o chama e atualiza apenas as partes que mudaram. É para desenvolvedores que criam barras laterais ou painéis que são atualizados com frequência.
Quando usar
- ✓Quando uma barra lateral ou um widget recebe novos dados com frequência e deve atualizar sem redesenhar tudo.
- ✓Quando os dados vêm de um controlador ou de um sistema de eventos externo ao widget.
- ✓Quando você prefere um módulo simples a uma classe ou a um componente de framework.
Link da skill
https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/push-based-widget-module-pattern/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Pode criar um widget de barra lateral que se atualize sempre que meu app lhe enviar novos dados?”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
O widget guarda referências aos seus principais elementos da página. Quando chegam novos dados, ele altera apenas esses elementos, em vez de reconstruir o widget inteiro.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do GitHub.
Push-Based Widget Module Pattern
Use this pattern when a UI sidebar or widget component needs to be updated by its caller (push-based) rather than fetching data itself. Instead of a class or framework component, implement the widget as a plain module with singleton state, a factory function to create the DOM, and an update function to efficiently patch it.
When to Use
- A sidebar, panel, or widget is rendered once but updated frequently with new data.
- The data source lives outside the component (e.g., a parent controller, event bus, or store).
- You want lightweight partial re-renders without rebuilding the entire DOM tree.
- You prefer a simple module interface over a class-based or framework-based component.
Core Structure
widgets/
MyWidget.ts # The module (singleton state + exports)
MyWidget.types.ts # (Optional) Exported data interface
Step-by-Step Instructions
1. Define the Data Interface
Export a typed interface so callers know exactly what data to push.
// MyWidget.types.ts (or inline at top of MyWidget.ts)
export interface MyWidgetData {
title: string;
items: string[];
status: "idle" | "active" | "error";
// ... all fields the widget needs to render
}
2. Declare Module-Level Singleton Refs
At module scope, keep references to the container and any frequently updated child nodes. This avoids querying the DOM on every update.
// MyWidget.ts
import type { MyWidgetData } from "./MyWidget.types";
// Singleton DOM refs
let containerEl: HTMLElement | null = null;
let titleEl: HTMLElement | null = null;
let itemListEl: HTMLElement | null = null;
let statusEl: HTMLElement | null = null;
// Current state snapshot (optional — useful for diffing)
let currentData: MyWidgetData | null = null;
3. Export a Factory Function (createMyWidget)
The factory builds the full DOM tree once, stores refs to mutable nodes, and returns the root element to be mounted by the caller.
export function createMyWidget(): HTMLElement {
// Build the container
containerEl = document.createElement("aside");
containerEl.className = "my-widget";
// Build static structure; keep refs to dynamic parts
titleEl = document.createElement("h2");
titleEl.className = "my-widget__title";
itemListEl = document.createElement("ul");
itemListEl.className = "my-widget__list";
statusEl = document.createElement("span");
statusEl.className = "my-widget__status";
// Compose the tree
const header = document.createElement("header");
header.appendChild(titleEl);
header.appendChild(statusEl);
containerEl.appendChild(header);
containerEl.appendChild(itemListEl);
return containerEl;
}
Rule:
createMyWidgetshould be callable only once per page. If called again, consider returning the existingcontainerEl(idempotent factory).
4. Export an Update Function (updateMyWidget)
The update function receives the new data object and performs surgical DOM mutations on the stored refs. It does NOT rebuild the whole tree.
export function updateMyWidget(data: MyWidgetData): void {
if (!containerEl) {
console.warn("updateMyWidget called before createMyWidget");
return;
}
currentData = data;
// Update only what changed
if (titleEl) titleEl.textContent = data.title;
if (statusEl) {
statusEl.textContent = data.status;
statusEl.dataset.status = data.status; // for CSS hooks
}
// Rebuild only dynamic list items
if (itemListEl) {
itemListEl.innerHTML = ""; // clear previous items
data.items.forEach((item) => {
const li = document.createElement("li");
li.textContent = item;
itemListEl!.appendChild(li);
});
}
}
Optimization tip: For large lists, compare
currentDatatodatabefore clearing and rebuilding, or use a keyed reconciliation approach.
5. Caller Usage Pattern
The caller mounts the widget once and pushes updates whenever its data changes.
import { createMyWidget, updateMyWidget } from "./widgets/MyWidget";
import type { MyWidgetData } from "./widgets/MyWidget.types";
// Mount once
const sidebar = document.getElementById("sidebar")!;
sidebar.appendChild(createMyWidget());
// Push updates (e.g., from a store subscription, WebSocket, timer)
function onDataChange(newData: MyWidgetData) {
updateMyWidget(newData);
}
// Example: push an initial state immedi
Perguntas frequentes
O que significa push-based aqui?
Significa que o widget espera o resto do app enviar novos dados, em vez de buscar ele mesmo os dados.
Preciso de um framework?
Não. O padrão usa módulos TypeScript simples.
Por que atualizar só partes do widget?
Atualizações parciais mantêm a página rápida e evitam piscar quando os dados mudam com frequência.
Detalhes
Descrição original do autor
How to implement sidebar/widget UI components that receive pushed data updates from a caller, using a singleton module pattern with exported factory and update functions plus module-level DOM refs for efficient partial re-renders.
repo: HKUDS/AgentPilot
Popularidade
- Estrelas no GitHub
- 7,8 mil
- Posição no ranking
- #13077
- Licença
- MIT
- Atualizada em
- 01/11/2026
Comentários
- …
Mais skills deste repositório
agentpilot
7,8 milAjuda seu agente a melhorar um projeto passo a passo, preparando uma tarefa e executando o ciclo do AgentPilot, que propõe, testa e pontua mudanças.
openspace
7,8 milAjuda seu agente a configurar o OpenSpace, uma ferramenta que armazena e busca skills de agentes, e a conectá-la ao seu app de IA pelo MCP.
rsi-arena
7,8 milAjuda seu agente a configurar e rodar testes padrão de benchmark de IA, como AIME e Terminal-Bench, para comparar diferentes métodos de melhoria.
experiment-guide
7,8 milAjuda seu agente a planejar pequenos experimentos, ler seus resultados e registrar descobertas enquanto investiga como melhorar um programa.
Skills parecidas
angular-developer
280 milAjuda seu agente a criar código Angular e a dar conselhos sobre a estrutura do projeto. É útil para iniciar novos projetos, criar partes do código ou melhorar a performance e acessibilidade.
frontend-a11y
280 milAjuda seu agente a tornar interfaces web acessíveis para todos. Ele garante que sites e apps funcionem bem com leitores de tela e navegação por teclado.
frontend-patterns
280 milFaz seu agente aplicar padrões modernos no desenvolvimento frontend. Ele otimiza performance, gerencia estado e segue boas práticas em React e Next.js.