小工具區域

本頁內容

小工具區域是樣板中可由管理員放置內容區塊的命名區域。可用於側邊欄、頁尾欄位、促銷橫幅,或任何需要編輯者不改程式碼就能控制的區塊。

查詢小工具區域

使用 getWidgetArea() 依名稱取得小工具區域:

---
import { getWidgetArea } from "emdash";

const sidebar = await getWidgetArea("sidebar");
---

{sidebar && sidebar.widgets.length > 0 && (
  <aside class="sidebar">
    {sidebar.widgets.map(widget => (
      <div class="widget">
        {widget.title && <h3>{widget.title}</h3>}
        <!-- 繪製小工具內容 -->
      </div>
    ))}
  </aside>
)}

若小工具區域不存在,函式會回傳 null

小工具區域結構

小工具區域包含中繼資料與一組小工具:

interface WidgetArea {
	id: string;
	name: string; // 唯一識別(如 "sidebar"、"footer-1")
	label: string; // 顯示名稱(如「主側邊欄」)
	description?: string;
	widgets: Widget[];
}

interface Widget {
	id: string;
	type: "content" | "menu" | "component";
	title?: string;
	// 依類型區分的欄位
	content?: PortableTextBlock[]; // 內容類小工具
	menuName?: string; // 選單類小工具
	componentId?: string; // 元件類小工具
	componentProps?: Record<string, unknown>;
}

小工具類型

EmDash 支援三種小工具類型:

內容小工具

以 Portable Text 儲存的富文字。使用 PortableText 元件繪製:

---
import { PortableText } from "emdash/ui";
---

{widget.type === "content" && widget.content && (
  <div class="widget-content">
    <PortableText value={widget.content} />
  </div>
)}

選單小工具

在小工具區域內顯示導覽選單:

---
import { getMenu } from "emdash";

const menu = widget.menuName ? await getMenu(widget.menuName) : null;
---

{widget.type === "menu" && menu && (
  <nav class="widget-nav">
    <ul>
      {menu.items.map(item => (
        <li><a href={item.url}>{item.label}</a></li>
      ))}
    </ul>
  </nav>
)}

元件小工具

繪製已註冊的元件並傳入可設定屬性。EmDash 內建下列核心元件:

元件 ID說明Props
core:recent-posts最近文章清單count, showThumbnails, showDate
core:categories分類清單showCount, hierarchical
core:tags標籤雲showCount, limit
core:search搜尋表單placeholder
core:archives按月/年封存type, limit

繪製小工具

建立可重複使用的小工具繪製元件:

---
import { PortableText } from "emdash/ui";
import { getMenu } from "emdash";
import type { Widget } from "emdash";

import RecentPosts from "./widgets/RecentPosts.astro";
import Categories from "./widgets/Categories.astro";
import TagCloud from "./widgets/TagCloud.astro";
import SearchForm from "./widgets/SearchForm.astro";
import Archives from "./widgets/Archives.astro";

interface Props {
  widget: Widget;
}

const { widget } = Astro.props;

const componentMap: Record<string, any> = {
  "core:recent-posts": RecentPosts,
  "core:categories": Categories,
  "core:tags": TagCloud,
  "core:search": SearchForm,
  "core:archives": Archives,
};

const menu = widget.type === "menu" && widget.menuName
  ? await getMenu(widget.menuName)
  : null;
---

<div class="widget">
  {widget.title && <h3 class="widget-title">{widget.title}</h3>}

  {widget.type === "content" && widget.content && (
    <div class="widget-content">
      <PortableText value={widget.content} />
    </div>
  )}

  {widget.type === "menu" && menu && (
    <nav class="widget-menu">
      <ul>
        {menu.items.map(item => (
          <li><a href={item.url}>{item.label}</a></li>
        ))}
      </ul>
    </nav>
  )}

  {widget.type === "component" && widget.componentId && componentMap[widget.componentId] && (
    <Fragment>
      {(() => {
        const Component = componentMap[widget.componentId!];
        return <Component {...widget.componentProps} />;
      })()}
    </Fragment>
  )}
</div>

範例小工具元件

最近文章小工具

---
import { getEmDashCollection } from "emdash";

interface Props {
  count?: number;
  showThumbnails?: boolean;
  showDate?: boolean;
}

const { count = 5, showThumbnails = false, showDate = true } = Astro.props;

const { entries: posts } = await getEmDashCollection("posts", {
  limit: count,
  orderBy: { publishedAt: "desc" },
});
---

<ul class="recent-posts">
  {posts.map(post => (
    <li>
      {showThumbnails && post.data.featured_image && (
        <img src={post.data.featured_image} alt="" class="thumbnail" />
      )}
      <a href={`/posts/${post.slug}`}>{post.data.title}</a>
      {showDate && post.data.publishedAt && (
        <time datetime={post.data.publishedAt.toISOString()}>
          {post.data.publishedAt.toLocaleDateString()}
        </time>
      )}
    </li>
  ))}
</ul>

搜尋小工具

---
interface Props {
  placeholder?: string;
}

const { placeholder = "搜尋…" } = Astro.props;
---

<form action="/search" method="get" class="search-form">
  <input
    type="search"
    name="q"
    placeholder={placeholder}
    aria-label="搜尋"
  />
  <button type="submit">搜尋</button>
</form>

在版面中使用小工具區域

以下為含側邊欄小工具區域的部落格版面範例:

---
import { getWidgetArea } from "emdash";
import WidgetRenderer from "../components/WidgetRenderer.astro";

const sidebar = await getWidgetArea("sidebar");
---

<div class="layout">
  <main class="content">
    <slot />
  </main>

  {sidebar && sidebar.widgets.length > 0 && (
    <aside class="sidebar">
      {sidebar.widgets.map(widget => (
        <WidgetRenderer widget={widget} />
      ))}
    </aside>
  )}
</div>

<style>
  .layout {
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 2rem;
  }

  @media (max-width: 768px) {
    .layout {
      grid-template-columns: 1fr;
    }
  }
</style>

列出所有小工具區域

使用 getWidgetAreas() 取得所有已填入小工具的區域:

import { getWidgetAreas } from "emdash";

const areas = await getWidgetAreas();
// 回傳所有區域及其小工具

建立小工具區域

在管理後台 /_emdash/admin/widgets 建立,或使用管理 API:

POST /_emdash/api/widget-areas
Content-Type: application/json

{
  "name": "footer-1",
  "label": "頁尾第 1 欄",
  "description": "頁尾第一欄"
}

新增內容小工具:

POST /_emdash/api/widget-areas/footer-1/widgets
Content-Type: application/json

{
  "type": "content",
  "title": "關於我們",
  "content": [
    {
      "_type": "block",
      "style": "normal",
      "children": [{ "_type": "span", "text": "歡迎造訪本站。" }]
    }
  ]
}

新增元件小工具:

POST /_emdash/api/widget-areas/sidebar/widgets
Content-Type: application/json

{
  "type": "component",
  "title": "最近文章",
  "componentId": "core:recent-posts",
  "componentProps": { "count": 5, "showDate": true }
}

API 參考

getWidgetArea(name)

依名稱取得小工具區域及其全部小工具。

參數:

  • name — 小工具區域的唯一識別(字串)

傳回: Promise<WidgetArea | null>

getWidgetAreas()

列出所有小工具區域及其小工具。

傳回: Promise<WidgetArea[]>

getWidgetComponents()

列出管理後台可用的小工具元件定義。

傳回: WidgetComponentDef[]