# 网格布局

## 使用方法

`Grid` 用 CSS 网格把子元素排进行和列，解决的是二维布局：卡片墙、仪表盘面板，以及任何需要多列对齐的区域。一维排布交给 `Stack` 系列，只有当行和列都要对齐时才换成 `Grid`。

给出列配置就能开始使用：

```vue
<script setup lang="ts">
import { Grid } from '@astryx-vue/core/Grid'
</script>

<template>
  <Grid :columns="3" :gap="4">
    <div>第一项</div>
    <div>第二项</div>
    <div>第三项</div>
  </Grid>
</template>
```

`columns` 传数字表示固定列数，每一列等宽。传对象则表示响应式列：`minWidth` 是每列的最小宽度（像素），网格按可用宽度自己决定能放几列，窄屏时自动减少列数。

```vue
<template>
  <Grid :columns="{ minWidth: 280 }" :gap="4">
    <div>第一项</div>
    <div>第二项</div>
  </Grid>
</template>
```

响应式配置里还有两个可选项。`repeat` 决定最后一行没排满时留下的空隙如何处理：`'fill'`（默认）保留空的轨道，所以每列宽度始终一致；`'fit'` 收起空轨道，让实际存在的列把整行撑满。`max` 限制最多几列，避免大屏上每一列被拉得过宽。列数上限加在轨道的最小尺寸上而不是最大尺寸上，因此列数不会超过 `max`，而排不满时留下的列依然会撑满整行，右侧不会出现空白。

`gap` 控制行列间距，`rowGap` 与 `columnGap` 可以分别在行、列方向覆盖它，取值都来自 Astryx 的间距刻度。`rowHeight` 用像素固定隐式行高，配合 `GridSpan` 的 `rows` 可以做出跨若干行的布局。

需要某一项跨列或跨行时，用 `GridSpan` 包一层。它的 `columns` 给数字表示跨几列，给 `'full'` 表示跨越整行；`rows` 表示跨几行。

```vue
<template>
  <Grid :columns="4" :gap="3">
    <GridSpan :columns="2">
      跨两列的项目
    </GridSpan>
    <div>普通项目</div>
    <GridSpan columns="full">
      跨越整行
    </GridSpan>
  </Grid>
</template>
```

`width`、`height`、`maxWidth`、`minHeight` 控制容器自身的尺寸，数字按像素处理，字符串原样使用。`align` 控制项目在行内的垂直对齐（`align-items`），`justify` 控制水平对齐（`justify-items`），两者默认都是 `stretch`，也就是撑满所在的单元格。

列模板写在容器的 CSS 变量 `--astryx-grid-template-columns` 上，而不是内联的 `grid-template-columns` 声明。因此在自有样式或媒体查询里重写这个变量、或者直接重写 `grid-template-columns`，都能生效。

### 结构

- **网格容器**: 按行和列排列使用方提供的项的二维布局容器。
- **跨列项**: 可选的 GridSpan，改变某一项参与列或行的方式。

## 最佳实践

| 指引 | 实践 |
| --- | --- |
| 推荐 | 布局需要随屏幕宽度变化时用响应式列（`:columns="{ minWidth: 280 }"`），让网格自己决定列数，不必再写媒体查询。 |
| 推荐 | 大屏上用 `max` 给列数封顶。没有上限时每一列会被拉得很宽，一行里的内容彼此离得太远。 |
| 推荐 | 需要每列宽度一致时保留默认的 `repeat: 'fill'`；希望不足一行的项目撑开剩余空间时改用 `'fit'`。 |
| 推荐 | 间距交给 `gap`，容器自身的尺寸交给 `width`、`maxWidth` 等属性，不要在子元素上再加外边距。 |
| 避免 | 手写 `display: grid` 和 `grid-template-columns` 并自己计算间距，`Grid` 已经把这些处理好了。 |
| 避免 | 用允许换行的 `HStack` 冒充网格。一维排布用 `Stack`，行和列都要对齐时才用 `Grid`。 |
| 避免 | 用 `columns` 的对象形式表达固定列数。固定列数直接传数字，语义更清楚。 |

## 示例

### 仪表盘布局

仪表盘把一张大的流量卡片、四项指标和一整行动态排在一起。

```vue
<script setup lang="ts">
import { Card } from '@astryx-vue/core/Card'
import { Grid, GridSpan } from '@astryx-vue/core/Grid'
import { Text } from '@astryx-vue/core/Text'

const metrics = [
  { label: 'Revenue', value: '$48,290' },
  { label: 'Active Users', value: '12,841' },
  { label: 'Conversion', value: '3.2%' },
  { label: 'Avg Response', value: '245ms' },
]
</script>

<template>
  <Grid :columns="4" :gap="4" width="100%" style="max-width: 500px">
    <GridSpan :columns="2" :rows="2">
      <Card>
        <Text display="block" type="label">
          Weekly Traffic
        </Text>
        <Text display="block" type="supporting">
          Page views and unique visitors over the last 7 days
        </Text>
      </Card>
    </GridSpan>
    <Card v-for="metric in metrics" :key="metric.label">
      <Text display="block" type="supporting">
        {{ metric.label }}
      </Text>
      <Text display="block" type="label">
        {{ metric.value }}
      </Text>
    </Card>
    <GridSpan columns="full">
      <Card>
        <Text display="block" type="label">
          Recent Activity
        </Text>
        <Text display="block" type="supporting">
          Latest events across all projects
        </Text>
      </Card>
    </GridSpan>
  </Grid>
</template>
```

### 卡片画廊

卡片保持一致的最小宽度，画廊变窄时自动换行。

```vue
<script setup lang="ts">
import { Card } from '@astryx-vue/core/Card'
import { Grid } from '@astryx-vue/core/Grid'
import { VStack } from '@astryx-vue/core/Stack'
import { Text } from '@astryx-vue/core/Text'

const cards = [
  { title: 'Getting Started', description: 'Learn the basics of the platform.' },
  { title: 'Components', description: 'Browse the full component library.' },
  { title: 'Design Tokens', description: 'Colors, spacing, and typography.' },
  { title: 'Theming', description: 'Customize the look and feel.' },
  { title: 'Accessibility', description: 'Build inclusive experiences.' },
  { title: 'Patterns', description: 'Common UI composition patterns.' },
]
</script>

<template>
  <Grid :columns="{ minWidth: 180 }" :gap="5" width="100%" style="max-width: 400px">
    <Card v-for="card in cards" :key="card.title">
      <VStack :gap="1">
        <Text display="block" type="label">
          {{ card.title }}
        </Text>
        <Text display="block" type="supporting">
          {{ card.description }}
        </Text>
      </VStack>
    </Card>
  </Grid>
</template>
```

### 自适应列宽

拖动分隔条。一行没排满时，卡片会把剩下的宽度撑满。

```vue
<script setup lang="ts">
import { useResizable } from '@astryx-vue/core'
import { Card } from '@astryx-vue/core/Card'
import { Grid } from '@astryx-vue/core/Grid'
import { Layout, LayoutContent, LayoutPanel } from '@astryx-vue/core/Layout'
import { ResizeHandle } from '@astryx-vue/core/Resizable'
import { VStack } from '@astryx-vue/core/Stack'
import { Text } from '@astryx-vue/core/Text'

const teams = [
  { name: 'Design Systems', members: 8 },
  { name: 'Frontend Platform', members: 12 },
  { name: 'Developer Experience', members: 6 },
  { name: 'Accessibility', members: 4 },
  { name: 'Performance', members: 7 },
  { name: 'Mobile Infrastructure', members: 9 },
]

const gridPanel = useResizable({
  defaultSize: 480,
  minSize: 100,
  maxSize: 480,
})
</script>

<template>
  <Card :height="400" :padding="0" variant="muted" width="100%" style="max-width: 500px">
    <Layout height="fill">
      <template #start>
        <LayoutPanel :has-divider="false" :width="gridPanel.size" style="padding: var(--astryx-spacing-4, 16px)">
          <Grid :columns="{ minWidth: 180, repeat: 'fit' }" :gap="4" width="100%">
            <Card v-for="team in teams" :key="team.name">
              <VStack :gap="1">
                <Text display="block" type="label">
                  {{ team.name }}
                </Text>
                <Text display="block" type="supporting">
                  {{ team.members }} members
                </Text>
              </VStack>
            </Card>
          </Grid>
        </LayoutPanel>
        <ResizeHandle
          direction="horizontal"
          has-divider
          is-always-visible
          label="Resize grid"
          :resizable="gridPanel.props"
        />
      </template>
      <LayoutContent />
    </Layout>
  </Card>
</template>
```

### 跨列

重点卡片跨过若干列和行，旁边是较小的统计项。

```vue
<script setup lang="ts">
import { Card } from '@astryx-vue/core/Card'
import { Grid, GridSpan } from '@astryx-vue/core/Grid'
import { VStack } from '@astryx-vue/core/Stack'
import { Text } from '@astryx-vue/core/Text'

const stats = [
  { label: 'Components', value: '54 available' },
  { label: 'Templates', value: '28 available' },
  { label: 'Tokens', value: '120 defined' },
  { label: 'Themes', value: '6 published' },
  { label: 'Icons', value: '312 available' },
  { label: 'Patterns', value: '18 documented' },
  { label: 'Contributors', value: '42 active' },
]
</script>

<template>
  <Grid :columns="3" :gap="4" width="100%" style="max-width: 500px">
    <GridSpan :rows="2">
      <Card variant="cyan">
        <VStack :gap="1">
          <Text display="block" type="label">
            Featured Release
          </Text>
          <Text display="block" type="supporting">
            Astryx 4.0 is now available with new layout primitives, refreshed tokens, and improved theming support across the system.
          </Text>
        </VStack>
      </Card>
    </GridSpan>
    <Card v-for="stat in stats" :key="stat.label">
      <Text display="block" type="label">
        {{ stat.label }}
      </Text>
      <Text display="block" type="supporting">
        {{ stat.value }}
      </Text>
    </Card>
    <GridSpan columns="full">
      <Card variant="cyan">
        <VStack :gap="1">
          <Text display="block" type="label">
            Community Showcase
          </Text>
          <Text display="block" type="supporting">
            See how teams are building with Astryx across the organization
          </Text>
        </VStack>
      </Card>
    </GridSpan>
  </Grid>
</template>
```

## Grid Props

| 名称 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `columns` | `number \| GridResponsiveColumns` | - | 列配置。传数字是固定列数，每一列等宽；传对象 `{ minWidth, max?, repeat? }` 是响应式列，按可用宽度自动决定列数。缺失、为 0 或为负数时回退为单列。 |
| `width` | `number \| string` | - | 容器宽度。数字按像素处理，字符串原样使用。 |
| `height` | `number \| string` | - | 容器高度。数字按像素处理，字符串原样使用。 |
| `maxWidth` | `number \| string` | - | 容器最大宽度。数字按像素处理，字符串原样使用。 |
| `minHeight` | `number \| string` | - | 容器最小高度。数字按像素处理，字符串原样使用。 |
| `gap` | `SpacingStep` | - | 行列间距，使用 Astryx 的间距刻度。 |
| `rowGap` | `SpacingStep` | - | 行间距，覆盖同一方向上的 `gap`。 |
| `columnGap` | `SpacingStep` | - | 列间距，覆盖同一方向上的 `gap`。在响应式列计算列数上限时，它也优先于 `gap`。 |
| `rowHeight` | `number` | - | 隐式行高，单位为像素（`grid-auto-rows`）。配合 `GridSpan` 的 `rows` 使用。 |
| `align` | `GridAlignment` | `'stretch'` | 项目在行内的垂直对齐（`align-items`），可选 start、center、end、stretch。 |
| `justify` | `GridAlignment` | `'stretch'` | 项目在同一行内的水平对齐（`justify-items`），可选 start、center、end、stretch。 |

`GridResponsiveColumns` 的形状如下：

```ts
interface GridResponsiveColumns {
  minWidth: number
  max?: number
  repeat?: 'fill' | 'fit'
}
```

容器比 `minWidth` 还窄时，唯一的那一列缩到容器宽度，不会撑出容器。

`SpacingStep` 支持以下值：

```ts
type SpacingStep = 0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10
```

## Grid Span Props

| 名称 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `columns` | `number \| 'full'` | - | 跨越的列数。`'full'` 渲染为 `grid-column: 1 / -1`，跨越整行，与列数无关。 |
| `rows` | `number` | - | 跨越的行数，渲染为 `grid-row: span N`。 |

## 插槽

| 名称 | 说明 |
| --- | --- |
| `default` | 要排布的项目。直接放子元素，或放 `GridSpan` 来改变其中一项的跨列、跨行行为。 |

`GridSpan` 同样只有一个默认插槽：

| 名称 | 说明 |
| --- | --- |
| `default` | 跨列项目的具体内容。 |

## CSS 变量

`Grid` 在根元素上写入以下变量。它们是内部实现，但可以被主题或应用覆盖：

| 名称 | 说明 |
| --- | --- |
| `--astryx-grid-template-columns` | 计算出的列模板。写在变量上而不是内联的 `grid-template-columns`，因此媒体查询里的覆盖仍然有效。 |
| `--astryx-grid-auto-rows` | `rowHeight` 转换出的隐式行高。 |
| `--astryx-grid-gap` | `gap` 对应的间距令牌，行、列共用。 |
| `--astryx-grid-row-gap` | `rowGap` 对应的间距令牌，覆盖 `--astryx-grid-gap`。 |
| `--astryx-grid-column-gap` | `columnGap` 对应的间距令牌，覆盖 `--astryx-grid-gap`。 |
| `--astryx-grid-default-gap` | 主题令牌，在没有传入任何间距属性时作为默认间距。Neutral 主题取 `--astryx-spacing-0`，也就是不留间距。 |

## 原生属性

`Grid` 与 `GridSpan` 的根元素都是 `<div>`。

以下内容传入根元素：

- HTML 属性。
- `aria-*` 属性。
- `data-*` 属性。
- `class`。
- `style`。

`class` 会与组件自身的类名合并。`style` 与尺寸属性（`width`、`height`、`maxWidth`、`minHeight`）同时出现时，尺寸属性优先；<code>GridSpan</code> 的 <code>columns</code>、<code>rows</code> 同理。

`Grid` 还额外写入 `data-columns`（仅在 `columns` 为数字时）、`data-gap`、`data-row-gap`、`data-column-gap`、`data-align`、`data-justify`，供主题按属性选择。
