导航

v2.1.0
结构

分隔条

两个窗格和中间的手柄,手柄用于调节两个窗格各自占用的空间。

本页内容

分隔条由两个窗格和中间的手柄组成。手柄决定两个窗格如何分配空间,例如文件列表与编辑器左右并排,或编辑器与终端上下排列。两个窗格以一条细线相接。指针悬停在线上或细线获得焦点时,细线呈现墨色,并显示一个小握柄。

分隔条是用在布局中的组件,本身并不构成一种布局。它的手柄有自己的材质、状态和键盘交互契约。如果两个窗格的尺寸无需调整,请参阅主从布局。

样式表绘制分隔条并安排其布局,splitter 行为负责移动手柄。该行为只写入两处:将第一个窗格的尺寸写入容器的 --splitter-size,并将同一数值写入手柄的 aria-valuenow。

分隔条

<div class="splitter sheet overflow-hidden h(240)" style="--splitter-size: 36%">  <div class="splitter-pane p-md text-sm fg-text-body">    <p class="m(0) fg-text-strong">Files</p>    <p class="mt-sm m(0)">theme.css</p>    <p class="m(0)">master.css</p>    <p class="m(0)">components/</p>  </div>  <div class="splitter-handle" role="separator" tabindex="0" aria-label="Resize the file list" aria-valuenow="36" aria-valuemin="15" aria-valuemax="85"></div>  <div class="splitter-pane p-md text-sm fg-text-body">    <p class="m(0) fg-text-strong">Editor</p>    <p class="mt-sm m(0)">Drag the line between the panes, or focus it and press the arrow keys.</p>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="splitter sheet overflow-hidden h(240)" style={{ '--splitter-size': '36%' } as React.CSSProperties}>      <div className="splitter-pane p-md text-sm fg-text-body">        <p className="m(0) fg-text-strong">Files</p>        <p className="mt-sm m(0)">theme.css</p>        <p className="m(0)">master.css</p>        <p className="m(0)">components/</p>      </div>      <div className="splitter-handle" role="separator" tabIndex={0} aria-label="Resize the file list" aria-valuenow={36} aria-valuemin={15} aria-valuemax={85}></div>      <div className="splitter-pane p-md text-sm fg-text-body">        <p className="m(0) fg-text-strong">Editor</p>        <p className="mt-sm m(0)">          Drag the line between the panes, or focus it and press the arrow keys.        </p>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div class="splitter sheet overflow-hidden h(240)" style="--splitter-size: 36%" {@attach attach}>  <div class="splitter-pane p-md text-sm fg-text-body">    <p class="m(0) fg-text-strong">Files</p>    <p class="mt-sm m(0)">theme.css</p>    <p class="m(0)">master.css</p>    <p class="m(0)">components/</p>  </div>  <div class="splitter-handle" role="separator" tabindex="0" aria-label="Resize the file list" aria-valuenow="36" aria-valuemin="15" aria-valuemax="85"></div>  <div class="splitter-pane p-md text-sm fg-text-body">    <p class="m(0) fg-text-strong">Editor</p>    <p class="mt-sm m(0)">Drag the line between the panes, or focus it and press the arrow keys.</p>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="splitter sheet overflow-hidden h(240)" style="--splitter-size: 36%">    <div class="splitter-pane p-md text-sm fg-text-body">      <p class="m(0) fg-text-strong">Files</p>      <p class="mt-sm m(0)">theme.css</p>      <p class="m(0)">master.css</p>      <p class="m(0)">components/</p>    </div>    <div class="splitter-handle" role="separator" tabindex="0" aria-label="Resize the file list" aria-valuenow="36" aria-valuemin="15" aria-valuemax="85"></div>    <div class="splitter-pane p-md text-sm fg-text-body">      <p class="m(0) fg-text-strong">Editor</p>      <p class="mt-sm m(0)">        Drag the line between the panes, or focus it and press the arrow keys.      </p>    </div>  </div></template>
拖动分隔线,或让它获得焦点后使用方向键、Home 键和 End 键。

#行为

splitter 接收带有 splitter 类的根元素,并返回用于解绑行为的函数。它移动的手柄是根元素的直接子元素 splitter-handle,因此窗格内可以嵌套自己的分隔条。

app.js
import { splitter } from '@master/ui/behaviors/splitter.js'const root = document.querySelector('.splitter')splitter(root, { step: 10 })root.addEventListener('change', (event) => {  localStorage.setItem('files-width', event.target.getAttribute('aria-valuenow'))})
  • 拖动。 发生 pointerdown 时,手柄捕获指针。指针移动期间,该行为将指针在容器内的位置写为百分比。
  • 按键。 按与手柄移动轴对应的方向键,手柄移动一个步长。Home 和 End 分别将窗格尺寸调至最小值和最大值。
  • 每次变化都会设置根元素的 --splitter-size 和手柄的 aria-valuenow。尺寸限制在手柄的 aria-valuemin 与 aria-valuemax 之间,未设置时分别默认为 0 和 100。
  • 事件。 每次尺寸变化时,手柄都会触发 input。拖动结束或按键使手柄移动后,手柄会触发 change。两个事件都会冒泡。从手柄读取 aria-valuenow。
  • 禁用。 带有 aria-disabled="true" 的手柄无法移动。
选项设置内容
step按一次方向键时手柄移动的幅度,以百分比计,默认为 5

无论指定什么尺寸,样式表都会将第一个窗格的尺寸限制在一定范围内,使分隔线与容器两端各相距至少 --splitter-min。按住手柄时,样式表会阻止文本选中,并根据手柄的方向切换布局。未绑定该行为时,两个窗格保持 --splitter-size 指定的比例,手柄固定不动。

#上下排列的窗格

aria-orientation 指定分隔线的方向。默认情况下,分隔线竖直,两个窗格左右并排。设置 aria-orientation="horizontal" 后,窗格上下排列,手柄变为水平线。容器直接读取该属性,无需同步修改器类。

上下排列的窗格

<div class="splitter sheet overflow-hidden h(280) max-w(420) mx-auto" style="--splitter-size: 60%">  <div class="splitter-pane p-md text-sm fg-text-body">    <p class="m(0) fg-text-strong">Editor</p>  </div>  <div class="splitter-handle" role="separator" tabindex="0" aria-orientation="horizontal" aria-label="Resize the editor" aria-valuenow="60" aria-valuemin="15" aria-valuemax="85"></div>  <div class="splitter-pane p-md text-sm fg-text-body">    <p class="m(0) fg-text-strong">Terminal</p>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="splitter sheet overflow-hidden h(280) max-w(420) mx-auto" style={{ '--splitter-size': '60%' } as React.CSSProperties}>      <div className="splitter-pane p-md text-sm fg-text-body">        <p className="m(0) fg-text-strong">Editor</p>      </div>      <div className="splitter-handle" role="separator" tabIndex={0} aria-orientation="horizontal" aria-label="Resize the editor" aria-valuenow={60} aria-valuemin={15} aria-valuemax={85}></div>      <div className="splitter-pane p-md text-sm fg-text-body">        <p className="m(0) fg-text-strong">Terminal</p>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div class="splitter sheet overflow-hidden h(280) max-w(420) mx-auto" style="--splitter-size: 60%" {@attach attach}>  <div class="splitter-pane p-md text-sm fg-text-body">    <p class="m(0) fg-text-strong">Editor</p>  </div>  <div class="splitter-handle" role="separator" tabindex="0" aria-orientation="horizontal" aria-label="Resize the editor" aria-valuenow="60" aria-valuemin="15" aria-valuemax="85"></div>  <div class="splitter-pane p-md text-sm fg-text-body">    <p class="m(0) fg-text-strong">Terminal</p>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="splitter sheet overflow-hidden h(280) max-w(420) mx-auto" style="--splitter-size: 60%">    <div class="splitter-pane p-md text-sm fg-text-body">      <p class="m(0) fg-text-strong">Editor</p>    </div>    <div class="splitter-handle" role="separator" tabindex="0" aria-orientation="horizontal" aria-label="Resize the editor" aria-valuenow="60" aria-valuemin="15" aria-valuemax="85"></div>    <div class="splitter-pane p-md text-sm fg-text-body">      <p class="m(0) fg-text-strong">Terminal</p>    </div>  </div></template>

#键盘操作

按键操作
ArrowLeft, ArrowRight窗格左右并排时,将第一个窗格缩小或增大一个步长。布局方向为从右到左时,调整方向相反。
ArrowUp, ArrowDown窗格上下排列时,将第一个窗格缩小或增大一个步长。
Home, End移动手柄,将第一个窗格的尺寸设为最小值或最大值,分别对应 aria-valuemin 和 aria-valuemax。

#无障碍

  • 手柄是可聚焦的 role="separator",其无障碍名称指明它调整的对象,aria-valuenow、aria-valuemin 和 aria-valuemax 均以第一个窗格所占的百分比表示。辅助技术据此将手柄识别为窗口分隔条。
  • 键盘必须支持指针能完成的所有操作。该行为支持用方向键移动手柄,用 Home 键和 End 键将手柄移到两端。
  • 分隔线在布局中占 1px,垂直于线的交互区域宽 9px。触摸屏上该区域宽 25px,握柄始终可见。
  • 窗格可独立滚动。如果可滚动的窗格内没有可聚焦的内容,请为窗格设置无障碍名称和 tabindex="0",使其可以通过键盘获得焦点。

#React、Svelte 和 Vue

splitter 组件绑定该行为,接收并传出尺寸值。两个窗格的标记仍由页面提供。使用 npx master-ui add splitter 将组件复制到项目中。有关组件的实现与用法,请参阅 React、Svelte 和 Vue。

ui/splitter.tsx
'use client'import { useRef, useState, type ComponentProps, type CSSProperties, type ReactNode } from 'react'import { splitter } from '@master/ui/behaviors/splitter.js'import { useBehavior } from './use-behavior'export interface SplitterProps extends Omit<ComponentProps<'div'>, 'defaultValue' | 'children' | 'ref'> {  /** The first and the second pane. */  start: ReactNode  end: ReactNode  /** The first pane's size, in percent of the container. */  value?: number  defaultValue?: number  /** Called as the handle moves. */  onValueChange?: (value: number) => void  /** Called once a drag ends or a key moved the handle. */  onValueCommit?: (value: number) => void  /** The least and the greatest size, in percent. */  min?: number  max?: number  /** How far an arrow key moves the handle, in percent. */  step?: number  /** Stack the panes, with a handle that moves up and down. */  stacked?: boolean  /** The name of the handle: what it resizes. */  label: string  disabled?: boolean}/** Two panes and the handle between them. */export function Splitter({ start, end, value, defaultValue = 50, onValueChange, onValueCommit, min = 0, max = 100, step = 5, stacked, label, disabled, className, style, ...root }: SplitterProps) {  const [first] = useState(value ?? defaultValue)  const size = useRef(first)  const ref = useBehavior(splitter, { step }, {    value,    defaultValue,    onValueChange: (next: number) => { size.current = next; onValueChange?.(next) },    // The handle says change once a drag ends or a key moved it. A field in a pane says change too.    on: { change: (event) => { if ((event.target as Element).parentElement === event.currentTarget && (event.target as Element).classList.contains('splitter-handle')) onValueCommit?.(size.current) } },  })  return (    <div className={className ? `splitter ${className}` : 'splitter'} style={{ '--splitter-size': `${first}%`, ...style } as CSSProperties} ref={ref} {...root}>      <div className="splitter-pane">{start}</div>      <div className="splitter-handle" role="separator" tabIndex={disabled ? -1 : 0} aria-label={label} aria-valuenow={Math.round(first)} aria-valuemin={min} aria-valuemax={max} aria-orientation={stacked ? 'horizontal' : undefined} aria-disabled={disabled || undefined} />      <div className="splitter-pane">{end}</div>    </div>  )}
ui/Splitter.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { HTMLAttributes } from 'svelte/elements'  export interface SplitterProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {    /** The first and the second pane. */    start: Snippet    end: Snippet    /** The first pane's size, in percent of the container. Bind it, or leave it out: it starts at 50. */    value?: number    /** Called as the handle moves. */    onValueChange?: (value: number) => void    /** Called once a drag ends or a key moved the handle. */    onValueCommit?: (value: number) => void    /** The least and the greatest size, in percent. */    min?: number    max?: number    /** How far an arrow key moves the handle, in percent. */    step?: number    /** Stack the panes, with a handle that moves up and down. */    stacked?: boolean    /** The name of the handle: what it resizes. */    label: string    disabled?: boolean  }</script><script lang="ts">  import { untrack } from 'svelte'  import { splitter } from '@master/ui/behaviors/splitter.js'  import { behavior } from './behavior.svelte.js'  let { start, end, value = $bindable(), onValueChange, onValueCommit, min = 0, max = 100, step = 5, stacked, label, disabled, class: className, ...root }: SplitterProps = $props()  const first = untrack(() => value) ?? 50  // Svelte writes a style again whenever its owner changes it, so it writes the size the behavior holds.  let size = $state(first)  const attach = behavior(splitter, () => ({ step }), {    value: () => value,    change: (next) => { value = size = next; onValueChange?.(next) },    settled: (held) => { size = held },    // The handle says change once a drag ends or a key moved it. A field in a pane says change too.    on: { change: (event) => { if ((event.target as Element).parentElement === event.currentTarget && (event.target as Element).classList.contains('splitter-handle')) onValueCommit?.(size) } },  })</script><!--  @component  Two panes and the handle between them.--><div class={['splitter', className]} style:--splitter-size="{size}%" {@attach attach} {...root}>  <div class="splitter-pane">{@render start()}</div>  <!-- A separator that takes focus is a control: the keys move it. -->  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->  <div class="splitter-handle" role="separator" tabindex={disabled ? -1 : 0} aria-label={label} aria-valuenow={Math.round(first)} aria-valuemin={min} aria-valuemax={max} aria-orientation={stacked ? 'horizontal' : undefined} aria-disabled={disabled || undefined}></div>  <div class="splitter-pane">{@render end()}</div></div>
ui/Splitter.vue
<script setup lang="ts">import { useTemplateRef } from 'vue'import { splitter } from '@master/ui/behaviors/splitter.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { min = 0, max = 100, step = 5 } = defineProps<{  /** The least and the greatest size, in percent. */  min?: number  max?: number  /** How far an arrow key moves the handle, in percent. */  step?: number  /** Stack the panes, with a handle that moves up and down. */  stacked?: boolean  /** The name of the handle: what it resizes. */  label: string  disabled?: boolean}>()/** The first pane's size, in percent of the container: `v-model`. It changes as the handle moves. */const model = defineModel<number>({ default: 50 })const emit = defineEmits<{  /** The size, once a drag ends or a key moved the handle. */  valueCommit: [value: number]}>()defineSlots<{  /** The first and the second pane. */  start?: () => unknown  end?: () => unknown}>()/* Two panes and the handle between them. */const first = model.valueconst root = useTemplateRef<HTMLDivElement>('root')const handle = useTemplateRef<HTMLDivElement>('handle')const current = useBehavior(root, splitter, () => ({ step }), model, {  // The handle says change once a drag ends or a key moved it. A field in a pane says change too.  change: (event) => { if (event.target === handle.value) emit('valueCommit', size()) },})// Vue writes a style again each time it renders, so it writes the size the behavior holds, not the first one.const size = () => {  const held = current()  return held !== undefined && Number.isFinite(held) ? held : first}</script><template>  <div class="splitter" :style="{ '--splitter-size': `${size()}%` }" ref="root" v-bind="$attrs">    <div class="splitter-pane"><slot name="start" /></div>    <div class="splitter-handle" role="separator" ref="handle" :tabindex="disabled ? -1 : 0" :aria-label="label" :aria-valuenow="Math.round(first)" :aria-valuemin="min" :aria-valuemax="max" :aria-orientation="stacked ? 'horizontal' : undefined" :aria-disabled="disabled || undefined" />    <div class="splitter-pane"><slot name="end" /></div>  </div></template>

#类名

类名说明
splitter容器依次包含第一个窗格、手柄和第二个窗格,由手柄的 aria-orientation 决定两个窗格横排还是纵排。
splitter-pane可独立滚动的窗格
splitter-handle窗格之间可聚焦的 role="separator" 元素,以细线显示,操作热区为 9px,触屏上为 25px。其可访问名称说明它调整哪个窗格的大小。aria-valuenow、aria-valuemin 和 aria-valuemax 均以第一个窗格的尺寸百分比表示

#自定义属性

属性默认值说明
--splitter-size50%第一个窗格的尺寸,由脚本写入
--splitter-min4rem两个窗格各自保留的最小尺寸。

#源码

@master/ui/components/splitter.css
/* * Splitter: two panes and the handle between them that sets how they share the space. * The stylesheet draws it and lays it out; a script moves it. The script writes the first pane's size to * --splitter-size and the same number to the handle's aria-valuenow, on pointer drag and on the arrow keys. * The handle is a role="separator" that can take focus. Its aria-orientation says which way the line runs: * vertical (the default) between panes side by side, horizontal between panes stacked. * The line is a hairline until it is touched; then a grip appears on it and the line takes ink. */@layer components.ui {  .splitter {    --splitter-size: 50%;    --splitter-min: 4rem;    /* The first pane's track: the size asked for, kept --splitter-min away from both ends. */    --splitter-track: clamp(var(--splitter-min), var(--splitter-size), calc(100% - var(--splitter-min) - 1px));    /* The handle stands over the panes inside the splitter, not over a sticky header that scrolls past it. */    isolation: isolate;    display: grid;    grid-template-columns: var(--splitter-track) auto minmax(0, 1fr);    min-width: 0;    min-height: 0;    &:has(.splitter-handle[aria-orientation="horizontal"]) {      grid-template-rows: var(--splitter-track) auto minmax(0, 1fr);      grid-template-columns: none;    }    /* While the handle is held, nothing in the panes is selected by the drag. */    &:has(.splitter-handle:active) {      user-select: none;      -webkit-user-select: none;    }  }  /* A pane scrolls by itself, so a long one never moves its neighbor. */  .splitter-pane {    min-width: 0;    min-height: 0;    overflow: auto;    scrollbar-width: thin;    scrollbar-color: var(--color-line-strong) transparent;  }  /*   * The handle is one pixel of line in the layout, with a target of 9px across it, so the panes meet at   * a hairline and the hand still finds it.   */  .splitter-handle {    position: relative;    z-index: 1;    width: 1px;    margin: 0;    padding: 0;    border: 0;    outline: none;    background: var(--color-line-divider);    cursor: col-resize;    touch-action: none;    -webkit-tap-highlight-color: transparent;    transition: background-color var(--duration-quick) var(--easing-glide);    /* The target, wider than the line. */    &::before {      content: '';      position: absolute;      inset: 0 -4px;    }    /* The grip: a small pill of sheet on the line, shown when the handle is touched or focused. */    &::after {      content: '';      position: absolute;      top: calc(50% - .75rem);      left: -2.5px;      width: 6px;      height: 1.5rem;      border-radius: 999px;      @apply --surface-sheet;      box-shadow: var(--shadow-raised);      opacity: 0;      scale: .6 .8;      transition-property: opacity, scale;      transition-duration: var(--duration-quick);      transition-timing-function: var(--easing-glide);    }    @media (hover: hover) {      &:hover {        background: var(--color-line-mark);      }      &:hover::after {        opacity: 1;        scale: 1;      }    }    &:is(:focus-visible, :active) {      background: var(--color-focus);    }    &:is(:focus-visible, :active)::after {      opacity: 1;      scale: 1;    }    &:focus-visible::after {      @apply --focus-ring;    }    &[aria-orientation="horizontal"] {      width: auto;      height: 1px;      cursor: row-resize;      &::before {        inset: -4px 0;      }      &::after {        top: -2.5px;        left: calc(50% - .75rem);        width: 1.5rem;        height: 6px;        scale: .8 .6;      }      &:is(:focus-visible, :active)::after {        scale: 1;      }      @media (hover: hover) {        &:hover::after {          scale: 1;        }      }    }    &[aria-disabled="true"] {      background: var(--color-line-divider);      cursor: default;      pointer-events: none;    }    @media (pointer: coarse) {      &::before {        inset: 0 -12px;      }      &[aria-orientation="horizontal"]::before {        inset: -12px 0;      }      /* Without a pointer to hover, the grip is always there to be found, at its full size either way. */      &::after, &[aria-orientation="horizontal"]::after {        opacity: 1;        scale: 1;      }    }    /* The grip fades in without growing, whichever way the line runs. */    @media (prefers-reduced-motion: reduce) {      &::after, &[aria-orientation="horizontal"]::after {        scale: none;      }    }    /* Each state's line is written again in a system color, at the weight of its own rule above. */    @media (forced-colors: active) {      background: CanvasText;      &:hover {        background: CanvasText;      }      &:is(:focus-visible, :active) {        background: Highlight;      }      &[aria-disabled="true"] {        background: GrayText;      }      /* An outline, not a border, so the grip keeps its size and stays centered on the line. */      &::after {        outline: 1px solid CanvasText;        outline-offset: -1px;        background: Canvas;      }    }  }}