본문으로 건너뛰기
Skillpedia
웹사이트 및 UI (프런트엔드)7.8k · #13077

push-based-widget-module-pattern

하는 일

이 스킬은 호출하는 쪽에서 데이터를 받고 바뀐 부분만 업데이트하는 간단한 위젯을 만드는 방법을 보여 줍니다. 자주 새로고침되는 사이드바나 패널을 만드는 개발자를 위한 스킬입니다.

사용하는 경우

  • ✓사이드바나 위젯이 자주 새 데이터를 받고 전체를 다시 그리지 않고 업데이트해야 할 때.
  • ✓데이터가 위젯 바깥의 컨트롤러나 이벤트 시스템에서 올 때.
  • ✓클래스나 프레임워크 컴포넌트보다 간단한 모듈을 선호할 때.

스킬 링크

https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/push-based-widget-module-pattern/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/push-based-widget-module-pattern/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“앱이 새 데이터를 보낼 때마다 업데이트되는 사이드바 위젯을 만들어 주실 수 있나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

위젯은 주요 페이지 요소에 대한 참조를 유지합니다. 새 데이터가 들어오면 그 요소들만 바꾸고, 위젯 전체를 다시 만들지 않습니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 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: createMyWidget should be callable only once per page. If called again, consider returning the existing containerEl (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 currentData to data before 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
자주 묻는 질문

push 기반이란 무엇을 뜻하나요?

위젯이 데이터를 직접 가져오지 않고, 앱의 나머지 부분이 새 데이터를 보내기를 기다린다는 뜻입니다.

프레임워크가 필요한가요?

아니요. 이 패턴은 순수 TypeScript 모듈을 사용합니다.

왜 위젯의 일부만 업데이트하나요?

부분 업데이트는 데이터가 자주 바뀔 때 페이지를 빠르게 유지하고 깜빡임을 줄여 줍니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
7.8k
순위
#13077
라이선스
MIT
업데이트
2026. 11. 1.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬