Skip to content

开发工具栏应用 API

Astro Dev Toolbar App API 允许你创建 Astro 集成,将应用添加到 Astro Dev Toolbar。这允许你添加新功能以及与第三方服务的集成。

¥The Astro Dev Toolbar App API allows you to create Astro Integrations that add apps to the Astro Dev Toolbar. This allows you to add new features and integrations with third-party services.

¥Toolbar app integration setup

集成可以将应用添加到 astro:config:setup 钩子 中的开发工具栏。

¥Integrations can add apps to the dev toolbar in the astro:config:setup hook.

my-integration.js
/**
* @type {() => import('astro').AstroIntegration}
*/
export default () => ({
name: "my-integration",
hooks: {
"astro:config:setup": ({ addDevToolbarApp }) => {
addDevToolbarApp({
id: "my-app",
name: "My App",
icon: "<svg>...</svg>",
entrypoint: "./my-app.js",
});
},
},
});

可用于 astro:config:setup 钩子 的函数,用于添加开发工具栏应用。它使用具有以下必需属性的对象来定义工具栏应用:idnameiconentrypoint

¥A function available to the astro:config:setup hook that adds dev toolbar apps. It takes an object with the following required properties to define the toolbar app: id, name, icon, and entrypoint.

应用的唯一标识符。这将用于唯一标识钩子和事件中的应用。

¥A unique identifier for the app. This will be used to uniquely identify the app in hooks and events.

my-integration.js
{
id: 'my-app',
// ...
}

应用的名称。每当需要使用人类可读的名称引用应用时,都会向用户显示此信息。

¥The name of the app. This will be shown to users whenever the app needs to be referenced using a human-readable name.

my-integration.js
{
// ...
name: 'My App',
// ...
}

用于在工具栏中显示应用的图标。这可以是 图标列表 中的图标,也可以是包含图标的 SVG 标记的字符串。

¥The icon used to display the app in the toolbar. This can either be an icon from the icon list, or a string containing the SVG markup of the icon.

my-integration.js
{
// ...
icon: '<svg>...</svg>', // or, e.g. 'astro:logo'
// ...
}

导出开发工具栏应用的文件的路径。

¥The path to the file that exports the dev toolbar app.

my-integration.js
{
// ...
entrypoint: './my-app.js',
}

开发工具栏应用的结构

Section titled 开发工具栏应用的结构

¥Structure of a Dev Toolbar App

Dev Toolbar App 是一个 .js.ts 文件,默认使用 astro/toolbar 模块提供的 defineToolbarApp() 功能 导出对象。

¥A Dev Toolbar App is a .js or .ts file that default exports an object using the defineToolbarApp() function available from the astro/toolbar module.

src/my-app.js
import { defineToolbarApp } from "astro/toolbar";
export default defineToolbarApp({
init(canvas) {
const text = document.createTextNode('Hello World!');
canvas.appendChild(text);
},
beforeTogglingOff() {
const confirmation = window.confirm('Really exit?');
return confirmation;
}
});

Added in: astro@4.7.0

定义工具栏应用加载和关闭时的逻辑的函数。

¥A function that defines the logic of your toolbar app when it is loaded and toggled off.

此函数接受一个带有 init() 函数的对象,该函数将在加载开发工具栏应用时调用。它还可以采用 beforeTogglingOff() 函数,该函数将在单击工具栏应用以关闭其活动状态时运行。

¥This function takes an object with an init() function that will be called when the dev toolbar app is loaded. It can also take a beforeTogglingOff() function that will run when the toolbar app is clicked to toggle off its active status.

签名:init(canvas: ShadowRoot, app: ToolbarAppEventTarget, server: ToolbarServerHelpers) => void

¥Signature: init(canvas: ShadowRoot, app: ToolbarAppEventTarget, server: ToolbarServerHelpers) => void

虽然不是必需的,但大多数应用都会使用此功能来定义应用的核心行为。此函数仅在加载应用时调用一次,即在浏览器空闲时或用户在 UI 中单击应用时,具体取决于哪个先发生。

¥Although not required, most apps will use this function to define the core behavior of the app. This function will be called only once when the app is loaded, which will either be when the browser is idle or when the user clicks on the app in the UI, depending on which one comes first.

该函数接收三个参数来定义你的应用逻辑:canvas(将元素渲染到屏幕上)、app(从开发工具栏发送和接收客户端事件)和 server(与服务器通信)。

¥The function receives three arguments to define your app logic: canvas (to render elements to the screen), app (to send and receive client-side events from the dev toolbar), and server (to communicate with the server).

应用可用于渲染其 UI 的标准 ShadowRoot。可以使用标准 DOM API 创建元素并将其添加到 ShadowRoot。

¥A standard ShadowRoot that the app can use to render its UI. Elements can be created and added to the ShadowRoot using the standard DOM APIs.

每个应用都会收到自己的专用 ShadowRoot 来渲染其 UI。此外,父元素使用 position: absolute; 定位,因此应用 UI 不会影响 Astro 页面的布局。

¥Every app receives its own dedicated ShadowRoot for rendering its UI. Additionally, the parent element is positioned using position: absolute; so the app UI will not affect the layout of an Astro page.

src/my-app.js
export default defineToolbarApp({
init(canvas) {
canvas.appendChild(document.createTextNode('Hello World!'))
}
});

Added in: astro@4.7.0

标准 EventTarget 加上一些额外的 客户端事件的辅助程序,可用于从 Dev 工具栏发送和接收事件。

¥A standard EventTarget with a few additional helpers for client-side events that can be used to send and receive events from the Dev toolbar.

src/my-app.js
export default defineToolbarApp({
init(canvas, app) {
app.onToggled(({ state }) => {
const text = document.createTextNode(
`The app is now ${state ? "enabled" : "disabled"}!`,
);
canvas.appendChild(text);
});
},
});

Added in: astro@4.7.0

可用于 与服务器通信 的对象。

¥An object that can be used to communicate with the server.

src/my-app.js
export default defineToolbarApp({
init(canvas, app, server) {
server.send('my-message', { message: 'Hello!' });
server.on('server-message', (data) => {
console.log(data.message);
});
},
});

签名:beforeTogglingOff(canvas: ShadowRoot): boolean | void

¥Signature: beforeTogglingOff(canvas: ShadowRoot): boolean | void

Added in: astro@4.7.0

当用户单击 UI 中的应用图标以关闭应用时,将调用此可选函数。例如,此函数可用于执行清理操作,或在关闭应用之前要求用户确认。

¥This optional function will be called when the user clicks on the app icon in the UI to toggle off the app. This function can be used, for example, to perform cleanup operations, or to ask the user for confirmation before toggling off the app.

如果返回虚假值,则切换将被取消,并且应用将保持启用状态。

¥If a falsy value is returned, the toggling off will be cancelled and the app will stay enabled.

src/my-app.js
export default defineToolbarApp({
// ...
beforeTogglingOff() {
const confirmation = window.confirm('Are you sure you want to disable this app?');
return confirmation;
}
});

应用的 ShadowRoot 可用于在关闭前渲染所需的任何 UI。与 init 函数的 canvas 参数 相同。

¥The ShadowRoot of the app, can be used to render any UI needed before closing. Same as the canvas argument of the init function.

¥Client-side Events

除了 EventTargetaddEventListenerdispatchEventremoveEventListener 等)的标准方法外,app 对象还具有以下方法:

¥In addition to the standard methods of an EventTarget (addEventListener, dispatchEvent, removeEventListeneretc.), the app object also has the following methods:

签名:onToggled(callback: (options: {state: boolean})) => void

¥Signature: onToggled(callback: (options: {state: boolean})) => void

Added in: astro@4.7.0

注册一个回调,在用户单击 UI 中的应用图标以打开或关闭应用时调用。

¥Registers a callback to be called when the user clicks on the app icon in the UI to toggle the app on or off.

src/my-app.js
app.onToggled((options) => {
console.log(`The app is now ${options.state ? 'enabled' : 'disabled'}!`);
});

签名:onToolbarPlacementUpdated(callback: (options: {placement: 'bottom-left' | 'bottom-center' | 'bottom-right'})) => void

¥Signature: onToolbarPlacementUpdated(callback: (options: {placement: 'bottom-left' | 'bottom-center' | 'bottom-right'})) => void

Added in: astro@4.7.0

当用户更改 Dev Toolbar 的位置时,将触发此事件。例如,可用于在移动工具栏时重新定位应用的 UI。

¥This event is fired when the user changes the placement of the Dev Toolbar. This can, for example, be used to reposition the app’s UI when the toolbar is moved.

src/my-app.js
app.onToolbarPlacementUpdated((options) => {
console.log(`The toolbar is now placed at ${options.placement}!`);
});

签名:toggleState(options: {state: boolean}) => void

¥Signature: toggleState(options: {state: boolean}) => void

Added in: astro@4.7.0

更改应用的状态。可用于以编程方式启用或禁用应用,例如,当用户单击应用 UI 中的按钮时。

¥Changes the state of the app. This can be used to enable or disable the app programmatically, for example, when the user clicks on a button in the app’s UI.

src/my-app.js
app.toggleState({ state: false });

签名:toggleNotification(options: {state?: boolean, level?: 'error' | 'warning' | 'info'}) => void

¥Signature: toggleNotification(options: {state?: boolean, level?: 'error' | 'warning' | 'info'}) => void

Added in: astro@4.7.0

在应用图标上切换通知。可用于通知用户应用需要注意,或删除当前通知。

¥Toggles a notification on the app icon. This can be used to inform the user that the app requires attention, or remove the current notification.

src/my-app.js
app.toggleNotification({
state: true,
level: 'warning',
});

指示应用是否有给用户的通知。当 true 时,应用图标将高亮。反之,当 false 时,高亮将被去除。如果未指定此属性,则将假定为 true

¥Indicates whether or not the app has a notification for the user. When true, the app icon will be highlighted. Conversely, when false, the highlight will be removed. If this property is not specified, true will be assumed.

表示通知的级别。这将用于确定应用图标上高亮的颜色和形状(深粉色圆圈、金色三角形或蓝色正方形)。如果未指定此属性,则将假定为 'error'

¥Indicates the level of the notification. This will be used to determine the color and shape (dark pink circle, gold triangle, or blue square) of the highlight on the app icon. If this property is not specified, 'error' will be assumed.

¥Client-Server Communication

使用 Vite 客户端与服务器端通信的方法,Dev Toolbar Apps 和服务器可以相互通信。为了方便发送和接收自定义消息,提供了辅助方法供你的工具栏应用(在客户端上)和集成(在服务器上)使用。

¥Using Vite’s methods for client-server communication, Dev Toolbar Apps and the server can communicate with each other. In order to facilitate sending and receiving custom messages, helper methods are provided for use both in your toolbar app (on the client) and in your integration (on the server).

¥On the client

在你的应用中,使用 init() 钩子上的 server 对象 向服务器发送消息和从服务器接收消息。

¥In your app, use the server object on the init() hook to send and receive messages to and from the server.

src/my-app.js
export default defineToolbarApp({
init(canvas, app, server) {
server.send('my-message', { message: 'Hello!' });
server.on('server-message', (data) => {
console.log(data.message);
});
},
});

签名:send<T>(event: stringify, data: T) => void

¥Signature: send<T>(event: stringify, data: T) => void

Added in: astro@4.7.0

从工具栏应用中定义的逻辑将数据发送到服务器。

¥Sends data to the server from logic defined in your toolbar app.

src/my-app.js
init(canvas, app, server) {
server.send('my-app:my-message', { message: 'Hello!' });
}

从客户端向服务器发送消息时,最好在事件名称前加上应用 ID 或其他命名空间,以避免与可能正在监听消息的其他应用或其他集成发生冲突。

¥When sending messages from the client to the server, it is good practice to prefix the event name with the app ID or other namespaces to avoid conflicts with other apps or other integrations that may be listening for messages.

签名:on<T>(event: string, callback: (data: T) => void) => void

¥Signature: on<T>(event: string, callback: (data: T) => void) => void

Added in: astro@4.7.0

注册一个回调,在服务器发送带有指定事件的消息时调用。

¥Registers a callback to be called when the server sends a message with the specified event.

src/my-app.js
init(canvas, app, server) {
server.on('server-message', (data) => {
console.log(data.message);
});
}

¥On the server

在集成(例如 添加工具栏应用的集成)中,使用 astro:server:setup 访问 toolbar 对象以向你的应用发送和接收消息。

¥In an integration, such as the integration that adds your toolbar app, use the astro:server:setup hook to access the toolbar object to send and receive messages to and from your apps.

my-integration.js
export default () => ({
name: "my-integration",
hooks: {
"astro:config:setup": ({ addDevToolbarApp }) => {},
"astro:server:setup": ({ toolbar }) => {},
},
});

签名:send<T>(event: string, data: T) => void

¥Signature: send<T>(event: string, data: T) => void

Added in: astro@4.7.0

将数据发送到客户端。

¥Sends data to the client.

my-integration.js
'astro:server:setup': ({ toolbar }) => {
toolbar.send('server-message', { message: 'Hello!' });
},

签名:on<T>(event: string, callback: (data: T) => void) => void

¥Signature: on<T>(event: string, callback: (data: T) => void) => void

Added in: astro@4.7.0

注册一个回调,在客户端发送带有指定事件的消息时调用。

¥Registers a callback to be called when the client sends a message with the specified event.

my-integration.js
'astro:server:setup': ({ toolbar }) => {
toolbar.on('my-app:my-message', (data) => {
console.log(data.message);
});
},

签名:onInitialized(appId: string, callback: () => void) => void

¥Signature: onInitialized(appId: string, callback: () => void) => void

Added in: astro@4.7.0

注册一个回调,在应用初始化时调用。

¥Registers a callback to be called when the app is initialized.

my-integration.js
'astro:server:setup': ({ toolbar }) => {
toolbar.onInitialized('my-app', () => {
console.log('The app is now initialized!');
});
},

签名:onAppToggled(appId: string, callback: (options: {state: boolean}) => void) => void

¥Signature: onAppToggled(appId: string, callback: (options: {state: boolean}) => void) => void

Added in: astro@4.7.0

注册一个回调,在用户单击 UI 中的应用图标以打开或关闭应用时调用。

¥Registers a callback to be called when the user clicks on the app icon in the UI to toggle the app on or off.

my-integration.js
'astro:server:setup': ({ toolbar }) => {
toolbar.onAppToggled('my-app', ({ state }) => {
console.log(`The app is now ${state ? 'enabled' : 'disabled'}!`);
});
},

¥Component Library

开发工具栏包含一组 Web 组件,可用于构建具有一致外观的应用。

¥The Dev Toolbar includes a set of web components that can be used to build apps with a consistent look and feel.

显示一个窗口。

¥Shows a window.

组件的槽将用作窗口的内容。

¥The slot of the component will be used as the content of the window.

<astro-dev-toolbar-window>
<p>My content</p>
</astro-dev-toolbar-window>

使用 JavaScript 构建窗口时,开槽内容必须位于组件的 light DOM 内部。

¥When building a window using JavaScript, slotted content must go inside the light DOM of the component.

const myWindow = document.createElement('astro-dev-toolbar-window');
const myContent = document.createElement('p');
myContent.textContent = 'My content';
// use appendChild directly on `window`, not `myWindow.shadowRoot`
myWindow.appendChild(myContent);

显示一个按钮。

¥Shows a button.

组件的插槽将用作按钮的内容。

¥The slot of the component will be used as the content of the button.

const myButton = document.createElement('astro-dev-toolbar-button');
myButton.textContent = 'Click me!';
myButton.buttonStyle = "purple";
myButton.size = "medium";
myButton.addEventListener('click', () => {
console.log('Clicked!');
});

按钮的大小(smallmediumlarge)。

¥The size of the button (small, medium, large).

按钮的样式(ghostoutlinepurplegrayredgreenyellowblue)。当使用 ghost 时,按钮本身是不可见的,只会显示按钮的内容。

¥The style of the button (ghost, outline, purple, gray, red, green, yellow, blue). When using ghost, the button itself is invisible and only the content of the button will be shown.

在 JavaScript 中,使用 buttonStyle 属性设置此属性,以避免与原生 style 属性发生冲突。

¥In JavaScript, set this property using the buttonStyle property to avoid conflict with the native style property.

Added in: astro@4.8.0

按钮的边框半径(normalrounded)。使用 rounded 时,按钮将具有圆角和四边均匀的填充。

¥The border radius of the button (normal, rounded). When using rounded, the button will have rounded corners and uniform padding on all sides.

在 JavaScript 中,使用 buttonBorderRadius 属性设置此属性。

¥In JavaScript, set this property using the buttonBorderRadius property.

显示徽章。

¥Shows a badge.

组件的插槽将用作徽章的内容。

¥The slot of the component will be used as the content of the badge.

<astro-dev-toolbar-badge>My badge</astro-dev-toolbar-badge>

徽章的尺寸(smalllarge)。

¥The size of the badge (small, large).

徽章的样式(颜色)(purplegrayredgreenyellowblue)。

¥The style (color) of the badge (purple, gray, red, green, yellow, blue).

在 JavaScript 中,使用 badgeStyle 属性设置此属性,以避免与原生 style 属性发生冲突。

¥In JavaScript, set this property using the badgeStyle property to avoid conflict with the native style property.

显示一张卡片。指定可选的 link 属性以使卡片充当 <a> 元素。

¥Shows a card. Specify an optional link attribute to make the card act like an <a> element.

当使用 JavaScript 制作卡片时,可以指定 clickAction 属性以使卡片像 <button> 元素一样运行。

¥When making a card using JavaScript, a clickAction property can be specified to make the card act like a <button> element.

组件的插槽将用作卡片的内容。

¥The slot of the component will be used as the content of the card.

<astro-dev-toolbar-card icon="astro:logo" link="https://github.com/withastro/astro/issues/new/choose">Report an issue</astro-dev-toolbar-card>

卡片的样式(purplegrayredgreenyellowblue)。颜色仅在悬停时应用于卡片的边框。

¥The style of the card (purple, gray, red, green, yellow, blue). The color is only applied to the border of the card on hover.

在 JavaScript 中,使用 cardStyle 设置此属性。

¥In JavaScript, set this property using the cardStyle.

显示一个切换元素,充当复选框。该元素在内部是原生 <input type="checkbox"> 元素的简单封装。可以使用 input 属性访问复选框元素。

¥Shows a toggle element, acting as a checkbox. This element internally is a simple wrapper around a native <input type="checkbox"> element. The checkbox element can be accessed using the input property.

const toggle = document.createElement('astro-dev-toolbar-toggle');
toggle.input.addEventListener('change', (evt) => {
console.log(`The toggle is now ${evt.currentTarget.checked ? 'enabled' : 'disabled'}!`);
});

astro-dev-toolbar-radio-checkbox

Section titled astro-dev-toolbar-radio-checkbox

Added in: astro@4.8.0

显示单选复选框。与 astro-dev-toolbar-toggle 组件类似,此元素是原生 <input type="radio"> 元素的简单封装器。可以使用 input 属性访问 radio 元素。

¥Shows a radio checkbox. Similar to the astro-dev-toolbar-toggle component, this element is a simple wrapper around a native <input type="radio"> element. The radio element can be accessed using the input property.

const radio = document.createElement('astro-dev-toolbar-radio-checkbox');
radio.input.addEventListener('change', (evt) => {
console.log(`The radio is now ${evt.currentTarget.checked ? 'enabled' : 'disabled'}!`);
});

切换的样式(purplegrayredgreenyellowblue)。

¥The style of the toggle (purple, gray, red, green, yellow, blue).

在 JavaScript 中,使用 toggleStyle 属性设置此属性。

¥In JavaScript, set this property using the toggleStyle property.

可用于高亮页面上的元素。在大多数情况下,你需要使用 topleftwidthheight CSS 属性来定位此元素并调整其大小,以匹配你要高亮的元素。

¥Can be used to highlight an element on the page. In most cases, you’ll want to position and resize this element using the top, left, width and height CSS properties to match the element you want to highlight.

<!-- Highlight the entire page -->
<astro-dev-toolbar-highlight style="top: 0; left: 0; width: 100%; height: 100%;"></astro-dev-toolbar-highlight>
const elementToHighlight = document.querySelector('h1');
const rect = elementToHighlight.getBoundingClientRect();
const highlight = document.createElement('astro-dev-toolbar-highlight');
highlight.style.top = `${Math.max(rect.top + window.scrollY - 10, 0)}px`;
highlight.style.left = `${Math.max(rect.left + window.scrollX - 10, 0)}px`;
highlight.style.width = `${rect.width + 15}px`;
highlight.style.height = `${rect.height + 15}px`;
highlight.icon = 'astro:logo';

高亮的样式(purplegrayredgreenyellowblue)。

¥The style of the highlight (purple, gray, red, green, yellow, blue).

一个 icon,显示在高亮的右上角。

¥An icon to show in the top right corner of the highlight.

显示包含不同部分的工具提示。该组件默认设置为 display: none;,并且可以使用 data-show="true" 属性使其可见。

¥Shows a tooltip with different sections. This component is set to display: none; by default and can be made visible using a data-show="true" attribute.

节是使用 sections 属性定义的。该属性是具有以下形状的对象数组:

¥Sections are defined using the sections property. This property is an array of objects with the following shape:

{
title?: string; // Title of the section
inlineTitle?: string; // Title of the section, shown inline next to the title
icon?: Icon; // Icon of the section
content?: string; // Content of the section
clickAction?: () => void | Promise<void>; // Action to perform when clicking on the section
clickDescription?: string; // Description of the action to perform when clicking on the section
}
const tooltip = document.createElement('astro-dev-toolbar-tooltip');
tooltip.sections = [{
title: 'My section',
icon: 'astro:logo',
content: 'My content',
clickAction: () => {
console.log('Clicked!')
},
clickDescription: 'Click me!'
}]

该组件通常与 astro-dev-toolbar-highlight 组件结合使用,以便在悬停高亮的元素时显示工具提示:

¥This component is often combined with the astro-dev-toolbar-highlight component to show a tooltip when hovering a highlighted element:

const highlight = document.createElement('astro-dev-toolbar-highlight');
// Position the highlight...
const tooltip = document.createElement('astro-dev-toolbar-tooltip');
// Add sections to the tooltip...
highlight.addEventListener('mouseover', () => {
tooltip.dataset.show = 'true';
});
highlight.addEventListener('mouseout', () => {
tooltip.dataset.show = 'false';
});

显示一个图标。可以使用 icon 属性指定 图标列表 中的图标,或者可以将图标的 SVG 标记作为槽传递。

¥Shows an icon. An icon from the icon list can be specified using the icon attribute, or the SVG markup of an icon can be passed as a slot.

<astro-dev-toolbar-icon icon="astro:logo" />
<astro-dev-toolbar-icon>
<svg>...</svg>
</astro-dev-toolbar-icon>

¥Icons

目前,以下图标可用,并且可以在任何接受图标的组件中使用:

¥Currently, the following icons are available and can be used in any component that accepts an icon:

  • astro:logo

  • warning

  • arrow-down

  • bug

  • file-search

  • check-circle

  • gear

  • lightbulb

  • checkmark

  • dots-three

  • copy

上述所有图标默认设置为 fill="currentColor",并将从父元素继承其颜色。

¥All of the above icons have fill="currentColor" set by default and will inherit their color from the parent element.

Astro 中文网 - 粤ICP备13048890号