Chuyển đến nội dung
Skillpedia
Website và giao diện (frontend)7.8k · #13077

push-based-widget-module-pattern

Skill này làm gì

Skill này hướng dẫn cách xây dựng một widget đơn giản nhận dữ liệu từ bên gọi và chỉ cập nhật những phần đã thay đổi. Skill dành cho lập trình viên làm thanh bên hoặc panel được làm mới thường xuyên.

Khi nào nên dùng

  • ✓Khi thanh bên hoặc widget thường xuyên nhận dữ liệu mới và cần cập nhật mà không vẽ lại toàn bộ.
  • ✓Khi dữ liệu đến từ một controller hoặc hệ thống sự kiện nằm ngoài widget.
  • ✓Khi bạn thích một module đơn giản hơn là lớp hoặc component của framework.

Liên kết skill

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

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/push-based-widget-module-pattern/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Bạn có thể tạo một widget thanh bên tự cập nhật mỗi khi ứng dụng gửi dữ liệu mới cho nó không?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Widget giữ tham chiếu đến các phần tử trang chính của nó. Khi dữ liệu mới đến, nó chỉ thay đổi những phần tử đó thay vì dựng lại toàn bộ widget.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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
Câu hỏi thường gặp

Push-based nghĩa là gì ở đây?

Nghĩa là widget chờ phần còn lại của ứng dụng gửi dữ liệu mới, thay vì tự lấy dữ liệu.

Tôi có cần framework không?

Không. Mẫu này dùng các module TypeScript thuần.

Vì sao chỉ cập nhật một phần của widget?

Cập nhật từng phần giúp trang nhanh hơn và tránh nhấp nháy khi dữ liệu thay đổi thường xuyên.

Chi tiết

Mô tả gốc của tác giả

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

Độ phổ biến

Sao GitHub
7.8k
Vị trí xếp hạng
#13077
Giấy phép
MIT
Cập nhật
1/11/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự