Highlight
Storybook 的 Highlight 附加元件是一個有用的工具,可視覺化偵錯您的元件。當作為獨立附加元件使用時,它能讓您醒目提示 story 內的特定 DOM 節點;或者,它也能增強其他附加元件(例如 Accessibility 附加元件),以通知您元件內的可訪問性問題。
醒目提示 DOM 元素
若要使用此附加元件醒目提示 DOM 元素,您需要從 story 或附加元件內發出 HIGHLIGHT
事件。事件酬載必須包含 elements
屬性,該屬性被賦予一個選擇器陣列,用於匹配您想要醒目提示的元素。例如
import type { Meta, StoryObj } from '@storybook/react';
import { useChannel } from '@storybook/preview-api';
import { HIGHLIGHT } from '@storybook/addon-highlight';
import { MyComponent } from './MyComponent';
const meta: Meta<typeof MyComponent> = {
component: MyComponent,
};
export default meta;
type Story = StoryObj<typeof MyComponent>;
export const Highlighted: Story = {
decorators: [
(storyFn) => {
const emit = useChannel({});
emit(HIGHLIGHT, {
elements: ['h2', 'a', '.storybook-button'],
});
return storyFn();
},
],
};
我們建議選擇盡可能精確的選擇器,以避免醒目提示其他附加元件使用的元素。這是因為此附加元件會嘗試將選擇器與整個 DOM 樹進行匹配。
重置醒目提示的元素
預設情況下,Storybook 會在 story 之間轉換時自動移除醒目提示的元素。但是,如果您需要手動清除它們,您可以從 story 或附加元件內發出 RESET_HIGHLIGHT
事件。例如
import type { Meta, StoryObj } from '@storybook/react';
import { useChannel } from '@storybook/preview-api';
import { HIGHLIGHT, RESET_HIGHLIGHT } from '@storybook/addon-highlight';
import { MyComponent } from './MyComponent';
const meta: Meta<typeof MyComponent> = {
component: MyComponent,
};
export default meta;
type Story = StoryObj<typeof MyComponent>;
export const ResetHighlight: Story = {
decorators: [
(storyFn) => {
const emit = useChannel({});
emit(RESET_HIGHLIGHT); //👈 Remove previously highlighted elements
emit(HIGHLIGHT, {
elements: ['header', 'section', 'footer'],
});
return storyFn();
},
],
};
emit
函數源自 useChannel
API Hook,它會在 Storybook 的 UI 中建立一個通訊管道,以監聽事件並據此更新 UI。Highlight 附加元件使用此管道來監聽自訂事件,並據此更新醒目提示的元素(如果有的話)。
自訂樣式
預設情況下,此附加元件會將標準樣式應用於您為 story 啟用的醒目提示元素。但是,您可以透過擴展酬載物件並提供 color
和/或 style
屬性來啟用您的自訂樣式。例如
import type { Meta, StoryObj } from '@storybook/react';
import { useChannel } from '@storybook/preview-api';
import { HIGHLIGHT } from '@storybook/addon-highlight';
import { MyComponent } from './MyComponent';
const meta: Meta<typeof MyComponent> = {
component: MyComponent,
};
export default meta;
type Story = StoryObj<typeof MyComponent>;
export const StyledHighlight: Story = {
decorators: [
(storyFn) => {
const emit = useChannel({});
emit(HIGHLIGHT, {
elements: ['h2', 'a', '.storybook-button'],
color: 'blue',
style: 'double', // 'dotted' | 'dashed' | 'solid' | 'double'
});
return storyFn();
},
],
};
API
Parameters
此附加元件在 highlight
命名空間下,為 Storybook 貢獻了以下 parameters
disable
類型:boolean
停用此附加元件的行為。如果您希望為整個 Storybook 停用此附加元件,您應該在註冊 addon-essentials
時執行此操作。請參閱必要附加元件的文件以取得更多資訊。
此參數最有用之處在於允許在更精細的層級進行覆寫。例如,如果此參數在專案層級設定為 true
,則可以透過在 meta(元件)或 story 層級將其設定為 false
來重新啟用它。
Exports
此附加元件為 Storybook 貢獻了以下 exports
import { HIGHLIGHT, RESET_HIGHLIGHT } from '@storybook/addon-highlight';
HIGHLIGHT
類型:string
一個醒目提示 DOM 元素的事件。事件酬載必須包含 elements
屬性,該屬性被賦予一個選擇器陣列,用於匹配您想要醒目提示的元素。請參閱上方的使用範例。
RESET_HIGHLIGHT
類型:string
一個清除所有醒目提示元素之醒目提示的事件。請參閱上方的使用範例。