# 胶囊灵动展开（Dynamic island pill）

- 俗称：灵动岛胶囊展开；顶部状态胶囊伸缩；通知胶囊丝滑变宽变高；灵动岛交互
- 用在：导航、按钮（工具和应用、个人网站、品牌官网）
- 触发：点击
- 感觉：俏皮、科技感
- 版本：1，更新于 2026-11-17

## 原理

切换状态前先记下当前胶囊的宽高，切换显示内容并量出目标宽高后，用 Web Animations API 对容器的 width 和 height 从旧尺寸平滑过渡到新尺寸，同时让内部详情淡入并保持紧凑区不换行，避免切换瞬间生硬跳变；减少动态时跳过宽高动画直接切换。

适合：音乐播放条、后台导出状态、即时通话/计时提示，平时只占一个小胶囊，需要操作时顺滑展开。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `duration` | 伸缩时长 | 420ms | 180–900ms |
| `easing` | 缓动 | cubic-bezier(0.22, 1, 0.36, 1) | — |

## 质量要求

- 开启"减少动态"时：跳过宽高伸缩动画，点击或状态变化时直接切换到紧凑或展开内容。
- 手机上：展开宽度不超过屏幕安全边距（max-width: calc(100vw - 24px)），点击按钮区域不小于 44px。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

## 提示词（可以直接交给 AI）

```text
请在我的项目里给导航加上「胶囊灵动展开」（Dynamic island pill）效果：切换状态前先记下当前胶囊的宽高，切换显示内容并量出目标宽高后，用 Web Animations API 对容器的 width 和 height 从旧尺寸平滑过渡到新尺寸，同时让内部详情淡入并保持紧凑区不换行，避免切换瞬间生硬跳变；减少动态时跳过宽高动画直接切换。
参数：伸缩时长 420ms，缓动 cubic-bezier(0.22, 1, 0.36, 1)。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/dynamic-island.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<div class="dis-pill" id="island">
  <button type="button" class="dis-trigger">播放中 · 2:14</button>
  <div class="dis-expanded">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;">
      <strong>Night Walk</strong>
      <button type="button" data-dis-collapse>收起</button>
    </div>
    <small>Lo-Fi · 2:14 / 3:40</small>
  </div>
</div>

<script type="module">
  import { dynamicIsland } from './dynamic-island.js';
  dynamicIsland(document.getElementById('island'));
</script>
```

CSS：

```css
/* 胶囊灵动展开（Dynamic island pill）样式，配合 dynamic-island.js。 */
.dis-pill {
  position: relative;
  display: inline-grid;
  justify-items: stretch;
  border-radius: 22px;
  background: var(--dis-bg, #141519);
  color: var(--dis-ink, #ffffff);
  overflow: hidden;
  box-shadow: 0 12px 28px -12px rgb(0 0 0 / 0.45);
  max-width: calc(100vw - 24px);
}

.dis-trigger {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  min-height: 38px;
  padding: 6px 14px;
  border: 0;
  background: transparent;
  color: inherit;
  font: inherit;
  white-space: nowrap;
  cursor: pointer;
}

.dis-expanded {
  padding: 0 16px 12px;
  display: grid;
  gap: 6px;
  min-width: 210px;
}

.dis-pill:not([data-expanded="true"]) .dis-expanded {
  display: none;
}
```

JS（原生，不依赖任何库）：

```js
// 胶囊灵动展开（Dynamic island pill）参考实现。
// 用法：容器 .dis-pill 内含 .dis-trigger（紧凑态）与 .dis-expanded（展开态）。
// 调 const ctl = dynamicIsland(root, { duration: 420, easing: '...' }); 销毁调 ctl.destroy()。

export function dynamicIsland(root, {
  expanded = false,
  duration = 420,
  easing = 'cubic-bezier(0.22, 1, 0.36, 1)',
  ignoreReducedMotion = false,
} = {}) {
  if (!(root instanceof Element)) return null;
  const compact = root.querySelector('.dis-trigger');
  const panel = root.querySelector('.dis-expanded');
  if (!compact || !panel) return null;

  const dur = Number(duration) || 420;
  const easeStr = String(easing);
  const reduceQuery = typeof matchMedia === 'function' ? matchMedia('(prefers-reduced-motion: reduce)') : null;
  const isReduced = () => Boolean(reduceQuery?.matches && !ignoreReducedMotion);

  root.classList.add('dis-pill');
  let isExpanded = Boolean(expanded);
  let activeAnim = null;
  let destroyed = false;

  const syncAttr = () => {
    root.dataset.expanded = String(isExpanded);
    compact.setAttribute('aria-expanded', String(isExpanded));
  };

  syncAttr();

  const setExpanded = (next, { animate = true } = {}) => {
    if (destroyed) return;
    const target = Boolean(next);
    if (target === isExpanded) return;

    if (activeAnim) { activeAnim.cancel(); activeAnim = null; }
    const fromRect = root.getBoundingClientRect();
    isExpanded = target;
    syncAttr();
    const toRect = root.getBoundingClientRect();

    if (animate && !isReduced() && fromRect.width > 0 && toRect.width > 0) {
      activeAnim = root.animate(
        [
          { width: `${fromRect.width}px`, height: `${fromRect.height}px`, borderRadius: target ? '22px' : '18px' },
          { width: `${toRect.width}px`, height: `${toRect.height}px`, borderRadius: target ? '18px' : '22px' },
        ],
        { duration: dur, easing: easeStr, fill: 'none' },
      );
      activeAnim.finished.then(() => { if (!destroyed) activeAnim = null; }).catch(() => undefined);
    }

    if (destroyed) return;
    root.dispatchEvent(new CustomEvent('islandchange', { bubbles: true, detail: { expanded: isExpanded } }));
  };

  const onCompactClick = () => setExpanded(true);
  const onPanelClick = (ev) => {
    if (ev.target instanceof Element && ev.target.closest('[data-dis-collapse]')) setExpanded(false);
  };
  const onKeyDown = (ev) => {
    if (ev.key === 'Escape' && isExpanded) {
      ev.preventDefault();
      setExpanded(false);
      if (compact instanceof HTMLElement && compact.tabIndex !== -1) compact.focus();
    }
  };

  compact.addEventListener('click', onCompactClick);
  panel.addEventListener('click', onPanelClick);
  root.addEventListener('keydown', onKeyDown);

  return {
    setExpanded,
    toggle() { setExpanded(!isExpanded); },
    isExpanded: () => isExpanded,
    destroy() {
      if (destroyed) return;
      destroyed = true;
      if (activeAnim) { activeAnim.cancel(); activeAnim = null; }
      compact.removeEventListener('click', onCompactClick);
      panel.removeEventListener('click', onPanelClick);
      root.removeEventListener('keydown', onKeyDown);
      delete root.dataset.expanded;
      compact.removeAttribute('aria-expanded');
    },
  };
}
```

## 出处

- 第四批备选（灵动岛交互），本站自研 FLIP 尺寸测量与 WAAPI 宽高过渡实现，没有复制代码
