Commit 43f6039d by liimin

fix: resolve merge conflicts and sync workspace changes

1 parent 3b9c4135
......@@ -2,29 +2,37 @@ import type { App } from "vue";
import {
VButton,
VCard,
VCell,
VDropdownItem,
VDropdownMenu,
VField,
VImage,
VList,
VNavBar,
VPicker,
VPopup,
VSearch,
VSwiper,
VTabbar,
VTabs,
} from "@vui/mobile";
import "vant/lib/index.css";
export function setupUI(app: App) {
app.component("VButton", VButton);
app.component("VCard", VCard);
app.component("VCell", VCell);
app.component("VDropdownItem", VDropdownItem);
app.component("VDropdownMenu", VDropdownMenu);
app.component("VField", VField);
app.component("VImage", VImage);
app.component("VList", VList);
app.component("VNavBar", VNavBar);
app.component("VPicker", VPicker);
app.component("VPopup", VPopup);
app.component("VSearch", VSearch);
app.component("VSwiper", VSwiper);
app.component("VTabbar", VTabbar);
app.component("VTabs", VTabs);
}
# AI Anti-Pattern Registry
本文件是 AI 反模式注册表,记录 AI 在代码生成过程中犯过的错误。
AI 管线在构建 prompt 时会自动读取本文件,防止同类错误重复出现。
## 格式约定
每个条目使用 `---` 分隔的 JSON 元数据块 + Markdown 正文。
字段说明:
| 字段 | 必填 | 说明 |
|------|------|------|
| `id` | 是 | 唯一标识,格式 `AP-NNN` |
| `category` | 是 | 错误类别:`component-misuse` / `style-error` / `type-error` / `arch-drift` / `import-error` / `logic-error` / `template-error` / `other` |
| `scope` | 是 | 作用域:`vue-sfc` / `css` / `typescript` / `template` / `router` / `api` / `config` / `general` |
| `severity` | 是 | 严重级别:`high` / `medium` / `low` |
| `pattern` | 是 | 错误模式简述(一句话) |
| `correction` | 是 | 正确做法简述(一句话) |
| `capturedAt` | 是 | 捕获时间(ISO 8601) |
| `capturedBy` | 否 | 捕获方式:`auto-lint` / `auto-typecheck` / `manual` |
| `sourceFile` | 否 | 首次发现错误的文件路径 |
正文部分包含:描述、错误示例、正确示例。
## 条目列表
---
{
"id": "AP-001",
"category": "component-misuse",
"scope": "vue-sfc",
"severity": "high",
"pattern": "重复 import 已全局注册的 VUI 组件",
"correction": "全局注册的组件直接在 template 中使用,禁止在 script 中 import",
"capturedAt": "2026-06-17T00:00:00.000Z",
"capturedBy": "manual",
"sourceFile": ""
}
---
### 描述
VUI 组件(如 VButton、VCell、VSearch 等)已在 `src/ui.ts` 中通过 `app.component()` 全局注册。
AI 经常在 `<script setup>` 中再次 import 这些组件,导致 vue/no-unused-import 或重复注册警告。
### 错误示例
```vue
<script setup lang="ts">
import { VSearch } from "@vui/mobile"; // 已全局注册,不需要 import
import { ref } from "vue";
</script>
```
### 正确示例
```vue
<script setup lang="ts">
import { ref } from "vue";
// VSearch 已在 ui.ts 中全局注册,直接在 template 中使用
</script>
```
---
{
"id": "AP-002",
"category": "style-error",
"scope": "css",
"severity": "medium",
"pattern": "CSS 属性顺序不符合 recess-order 规则",
"correction": "严格按 position → display → box-model → typography → visual → animation 顺序排列",
"capturedAt": "2026-06-17T00:00:00.000Z",
"capturedBy": "manual",
"sourceFile": ""
}
---
### 描述
AI 生成的 CSS 经常不按 stylelint-config-recess-order 要求的顺序排列属性。
常见错误:`text-overflow` 放在 `line-height` 之前,`white-space` 远离 `overflow`。
### 错误示例
```css
.title {
text-overflow: ellipsis;
line-height: 1.5;
white-space: nowrap;
overflow: hidden;
font-size: 14px;
}
```
### 正确示例
```css
.title {
overflow: hidden;
font-size: 14px;
line-height: 1.5;
white-space: nowrap;
text-overflow: ellipsis;
}
```
---
{
"id": "AP-003",
"category": "type-error",
"scope": "typescript",
"severity": "medium",
"pattern": "用宽泛 string 替代联合类型",
"correction": "必须使用组件库定义的精确定义类型,不能用 string 偷懒",
"capturedAt": "2026-06-17T00:00:00.000Z",
"capturedBy": "manual",
"sourceFile": ""
}
---
### 描述
AI 在定义 VUI / Element Plus 组件的 columns、align、status 等属性时,经常用 `string` 代替精确的联合类型,导致 TypeScript 类型检查失败。
### 错误示例
```ts
interface TableColumn {
prop: string;
align: string; // 太宽泛
status: string; // 太宽泛
}
```
### 正确示例
```ts
interface TableColumn {
prop: string;
align: "left" | "center" | "right";
status: "success" | "warning" | "danger" | "info";
}
```
---
{
"id": "AP-004",
"category": "template-error",
"scope": "vue-sfc",
"severity": "high",
"pattern": "template v-for 的 :key 放在了子元素上而不是 template 标签上",
"correction": "Vue 3.4+ 要求 :key 必须放在 <template v-for> 标签上,不能放在内部子元素",
"capturedAt": "2026-06-17T00:00:00.000Z",
"capturedBy": "auto-lint",
"sourceFile": "apps/web/ai-previews/diaobo-preview/src/views/car1/index.vue"
}
---
### 描述
Vue 3.4+ 要求 `<template v-for>` 的 `:key` **必须放在 `<template>` 标签上**。
早期版本(Vue 3.3 及以前)的 `vue/no-v-for-template-key` 规则曾要求放在子元素上,但该规则在 Vue 3.4 中已被废弃,替换为 `vue/no-v-for-template-key-on-child`。
Vue 3.4+ 编译器会报:`<template v-for> key should be placed on the <template> tag.`
### 错误示例
```vue
<template v-for="item in list">
<div :key="item.id">{{ item.name }}</div>
</template>
```
### 正确示例
```vue
<template v-for="item in list" :key="item.id">
<div>{{ item.name }}</div>
</template>
```
---
{
"id": "AP-005",
"category": "template-error",
"scope": "vue-sfc",
"severity": "high",
"pattern": "Vue template 属性语法损坏:属性名含引号或属性错位拼接",
"correction": "确保每个 HTML/Vue 属性在同一行内完整书写,属性名不含引号,属性值用成对引号包裹",
"capturedAt": "2026-06-17T00:00:00.000Z",
"capturedBy": "auto-lint",
"sourceFile": "apps/web/ai-previews/testpage-preview/src/views/car/index.vue"
}
---
### 描述
AI 生成的 Vue template 中,元素的属性被拆碎并错位拼接,导致属性名包含引号字符(`"`、`'`)或属性值跨行断裂。
Vue 编译器会报 `Attribute name cannot contain U+0022 ("), U+0027 ('), and U+003C (<)` 错误。
这类错误通常发生在 AI 对复杂多属性元素(如带 `:class`、`@click`、`v-if` 的标签)生成时,属性被错误地拆分成多行碎片。
### 错误示例
```vue
<span active:
"exterior"
activeView="=="
:class="["
exterior""@click="activeView = "
toggle-item",
{
}]">
外观
</span>
```
### 正确示例
```vue
<span
:class="['toggle-item', { active: activeView === 'exterior' }]"
@click="activeView = 'exterior'"
>
外观
</span>
```
{
"$schema": "../../../../../../contracts/ai/component-manifest-item.schema.json",
"name": "card",
"exportName": "VCard",
"source": "src/components/VCard/VCard.vue",
"category": "display",
"description": "移动端商品卡片组件,基于 Vant 4 Card,支持标题、描述、缩略图、价格等展示。",
"semanticRoles": ["product-card", "list-item-card", "info-card"],
"supportedKinds": ["CARD", "PRODUCT_CARD"],
"supportedScopes": ["list", "section"],
"priority": 5,
"props": [
{ "name": "title", "type": "string", "description": "标题。" },
{ "name": "desc", "type": "string", "description": "描述。" },
{ "name": "thumb", "type": "string", "description": "左侧图片 URL。" },
{ "name": "thumbLink", "type": "string", "description": "点击缩略图的跳转链接。" },
{ "name": "price", "type": "number | string", "description": "商品价格。" },
{ "name": "num", "type": "number | string", "description": "商品数量。" },
{ "name": "originPrice", "type": "number | string", "description": "商品原价,显示为划线价。" },
{ "name": "currency", "type": "string", "description": "货币符号。", "default": "'¥'" },
{ "name": "tag", "type": "string", "description": "图片左上角标签文字。" },
{ "name": "centered", "type": "boolean", "description": "是否垂直居中布局。", "default": "false" },
{ "name": "full", "type": "boolean", "description": "是否通栏卡片(无边距圆角)。", "default": "false" }
],
"events": [
{ "name": "click", "description": "卡片点击事件。", "payload": "MouseEvent" },
{ "name": "clickThumb", "description": "缩略图点击事件。" }
],
"slots": [
{ "name": "default", "description": "卡片内容区域。" },
{ "name": "title", "description": "自定义标题。" },
{ "name": "desc", "description": "自定义描述。" },
{ "name": "price", "description": "自定义价格。" },
{ "name": "price-top", "description": "价格上方自定义内容。" },
{ "name": "bottom", "description": "价格下方自定义内容。" },
{ "name": "thumb", "description": "自定义缩略图。" },
{ "name": "tag", "description": "自定义标签。" },
{ "name": "footer", "description": "底部操作区域。" },
{ "name": "header", "description": "顶部自定义内容。" },
{ "name": "tags", "description": "描述下方标签区域。" }
],
"figmaMapping": {
"keywords": ["card", "product card", "商品卡片", "列表项卡片"],
"nodeTypes": ["FRAME", "COMPONENT", "INSTANCE"],
"variantHints": ["thumb", "price", "tag", "desc"]
},
"usageGuidance": {
"recommendedScenarios": ["商品列表项", "订单列表项", "信息展示卡片"],
"avoidScenarios": ["纯文本信息展示(用 VCell)", "复杂表单容器"],
"dependencies": ["vant"]
}
}
<template>
<van-card
class="vui-card"
:class="{
'vui-card--centered': centered,
'vui-card--full': full,
}"
:title="title"
:desc="desc"
:thumb="thumb"
:price="price"
:num="num"
:origin-price="originPrice"
:tag="tag"
:currency="currency"
:thumb-link="thumbLink"
v-bind="$attrs"
@click="handleClick"
@click-thumb="handleClickThumb"
>
<template v-if="$slots.tag || tag" #tag>
<slot name="tag">
{{ tag }}
</slot>
</template>
<template v-if="$slots.title" #title>
<slot name="title" />
</template>
<template v-if="$slots.desc" #desc>
<slot name="desc" />
</template>
<template v-if="$slots.price" #price>
<slot name="price" />
</template>
<template v-if="$slots['price-top']" #price-top>
<slot name="price-top" />
</template>
<template v-if="$slots['bottom']" #bottom>
<slot name="bottom" />
</template>
<template v-if="$slots['thumb']" #thumb>
<slot name="thumb" />
</template>
<template v-if="$slots.footer" #footer>
<slot name="footer" />
</template>
<template v-if="$slots.header" #header>
<slot name="header" />
</template>
<template v-if="$slots.tags" #tags>
<slot name="tags" />
</template>
<slot />
</van-card>
</template>
<script setup lang="ts">
import { Card as vanCard } from "vant";
defineOptions({ name: "VCard" });
defineProps<{
centered?: boolean;
currency?: string;
desc?: string;
full?: boolean;
num?: number | string;
originPrice?: number | string;
price?: number | string;
tag?: string;
thumb?: string;
thumbLink?: string;
title?: string;
}>();
const emit = defineEmits<{
(event: "click", value: MouseEvent): void;
(event: "clickThumb"): void;
}>();
function handleClick(event: MouseEvent) {
emit("click", event);
}
function handleClickThumb() {
emit("clickThumb");
}
</script>
<style scoped>
.vui-card--centered {
display: flex;
align-items: center;
}
.vui-card--full {
margin: 0;
border-radius: 0;
}
</style>
import type { DefineComponent } from "vue";
declare const VCard: DefineComponent<{
centered?: boolean;
currency?: string;
desc?: string;
full?: boolean;
num?: number | string;
originPrice?: number | string;
price?: number | string;
tag?: string;
thumb?: string;
thumbLink?: string;
title?: string;
}>;
export default VCard;
export { default } from "./VCard.vue";
{
"$schema": "../../../../../../contracts/ai/component-manifest-item.schema.json",
"name": "image",
"exportName": "VImage",
"source": "src/components/VImage/VImage.vue",
"category": "display",
"description": "移动端图片组件,基于 Vant 4 Image,支持懒加载、加载占位、错误占位、多种裁剪模式。对应 Element Plus 的 el-image。",
"semanticRoles": ["product-image", "avatar", "thumbnail", "banner-image"],
"supportedKinds": ["IMAGE", "PHOTO", "PICTURE"],
"supportedScopes": ["list", "page", "section"],
"priority": 5,
"props": [
{ "name": "src", "type": "string", "description": "图片 URL。" },
{ "name": "fit", "type": "'contain' | 'cover' | 'fill' | 'none' | 'scale-down'", "description": "图片填充模式。", "default": "'fill'" },
{ "name": "position", "type": "'center' | 'top' | 'right' | 'bottom' | 'left'", "description": "图片显示位置(类似 object-position)。", "default": "'center'" },
{ "name": "alt", "type": "string", "description": "替代文本。" },
{ "name": "width", "type": "number | string", "description": "宽度,默认单位为 px。" },
{ "name": "height", "type": "number | string", "description": "高度,默认单位为 px。" },
{ "name": "radius", "type": "'sm' | 'md' | 'lg' | 'xl' | number | string", "description": "圆角大小。sm=4px, md=8px, lg=12px, xl=16px。" },
{ "name": "round", "type": "boolean", "description": "是否显示为圆形。", "default": "false" },
{ "name": "lazyLoad", "type": "boolean", "description": "是否开启懒加载。", "default": "false" },
{ "name": "showLoading", "type": "boolean", "description": "是否展示加载中提示。", "default": "true" },
{ "name": "showError", "type": "boolean", "description": "是否展示加载失败提示。", "default": "true" },
{ "name": "errorIcon", "type": "string", "description": "加载失败图标名称。" },
{ "name": "loadingIcon", "type": "string", "description": "加载中图标名称。" }
],
"events": [
{ "name": "click", "description": "点击图片时触发。", "payload": "MouseEvent" },
{ "name": "load", "description": "图片加载成功时触发。", "payload": "Event" },
{ "name": "error", "description": "图片加载失败时触发。", "payload": "Event" }
],
"slots": [
{ "name": "loading", "description": "自定义加载中内容。" },
{ "name": "error", "description": "自定义加载失败内容。" }
],
"figmaMapping": {
"keywords": ["image", "photo", "picture", "图片", "照片", "缩略图", "avatar"],
"nodeTypes": ["RECTANGLE", "COMPONENT", "INSTANCE"],
"variantHints": ["cover", "contain", "round", "radius"]
},
"usageGuidance": {
"recommendedScenarios": ["商品图片", "用户头像", "缩略图", "Banner 图"],
"avoidScenarios": ["纯图标展示(用 van-icon)", "背景图片(用 CSS background)"],
"dependencies": ["vant"]
}
}
<template>
<van-image
class="vui-image"
:class="{
'vui-image--round': round,
[`vui-image--radius-${radius}`]: radius,
}"
:src="src"
:fit="fit"
:position="position"
:alt="alt"
:width="width"
:height="height"
:radius="computedRadius"
:round="round"
:lazy-load="lazyLoad"
:show-loading="showLoading"
:show-error="showError"
:error-icon="errorIcon"
:loading-icon="loadingIcon"
v-bind="$attrs"
@click="handleClick"
@load="handleLoad"
@error="handleError"
>
<template v-if="$slots.loading" #loading>
<slot name="loading" />
</template>
<template v-if="$slots.error" #error>
<slot name="error" />
</template>
</van-image>
</template>
<script setup lang="ts">
import { computed } from "vue";
import { Image as vanImage } from "vant";
defineOptions({ name: "VImage" });
const props = defineProps<{
alt?: string;
errorIcon?: string;
fit?: "contain" | "cover" | "fill" | "none" | "scale-down";
height?: number | string;
lazyLoad?: boolean;
loadingIcon?: string;
position?: "bottom" | "center" | "left" | "right" | "top";
radius?: "lg" | "md" | "sm" | "xl" | number | string;
round?: boolean;
showError?: boolean;
showLoading?: boolean;
src?: string;
width?: number | string;
}>();
const radiusMap: Record<string, string> = {
sm: "4px",
md: "8px",
lg: "12px",
xl: "16px",
};
const computedRadius = computed(() => {
if (typeof props.radius === "number") return `${props.radius}px`;
if (typeof props.radius === "string" && props.radius in radiusMap) return radiusMap[props.radius];
return props.radius;
});
const emit = defineEmits<{
(event: "click", value: MouseEvent): void;
(event: "load", value: Event): void;
(event: "error", value: Event): void;
}>();
function handleClick(event: MouseEvent) {
emit("click", event);
}
function handleLoad(event: Event) {
emit("load", event);
}
function handleError(event: Event) {
emit("error", event);
}
</script>
<style scoped>
.vui-image--round {
overflow: hidden;
}
</style>
import type { DefineComponent } from "vue";
declare const VImage: DefineComponent<{
alt?: string;
errorIcon?: string;
fit?: "contain" | "cover" | "fill" | "none" | "scale-down";
height?: number | string;
lazyLoad?: boolean;
loadingIcon?: string;
position?: "bottom" | "center" | "left" | "right" | "top";
radius?: "lg" | "md" | "sm" | "xl" | number | string;
round?: boolean;
showError?: boolean;
showLoading?: boolean;
src?: string;
width?: number | string;
}>;
export default VImage;
export { default } from "./VImage.vue";
{
"$schema": "../../../../../../contracts/ai/component-manifest-item.schema.json",
"name": "swiper",
"exportName": "VSwiper",
"source": "src/components/VSwiper/VSwiper.vue",
"category": "display",
"description": "移动端轮播图组件,基于 Vant 4 Swipe,支持自动播放、循环、指示器等。",
"semanticRoles": ["image-carousel", "banner", "hero-gallery"],
"supportedKinds": ["SWIPE", "CAROUSEL", "GALLERY"],
"supportedScopes": ["page", "section"],
"priority": 5,
"props": [
{ "name": "items", "type": "(string | Record<string, unknown>)[]", "description": "轮播项数据,string 为图片 URL,object 为自定义内容。" },
{ "name": "autoplay", "type": "number | string", "description": "自动播放间隔(ms),0 或不传则不自动播放。", "default": "0" },
{ "name": "duration", "type": "number | string", "description": "动画时长(ms)。", "default": "500" },
{ "name": "loop", "type": "boolean", "description": "是否循环播放。", "default": "true" },
{ "name": "vertical", "type": "boolean", "description": "是否纵向滚动。", "default": "false" },
{ "name": "showIndicators", "type": "boolean", "description": "是否显示指示器。", "default": "true" },
{ "name": "indicatorColor", "type": "string", "description": "指示器颜色。" },
{ "name": "height", "type": "number | string", "description": "轮播高度。" },
{ "name": "width", "type": "number | string", "description": "轮播宽度。" },
{ "name": "touchable", "type": "boolean", "description": "是否可手势滑动。", "default": "true" },
{ "name": "initialSwipe", "type": "number", "description": "初始位置索引。", "default": "0" },
{ "name": "lazyRender", "type": "boolean", "description": "是否延迟渲染未展示的轮播。", "default": "false" }
],
"events": [
{ "name": "change", "description": "当前轮播切换时触发。", "payload": "number" }
],
"slots": [
{ "name": "default", "description": "自定义轮播内容(van-swipe-item 列表)。" },
{ "name": "item", "description": "使用 items 数据时自定义每项渲染。", "scope": "{ item, index }" },
{ "name": "indicator", "description": "自定义指示器。", "scope": "{ active, total }" }
],
"figmaMapping": {
"keywords": ["swipe", "carousel", "slider", "banner", "轮播", "轮播图"],
"nodeTypes": ["FRAME", "COMPONENT", "INSTANCE"],
"variantHints": ["autoplay", "indicator", "loop"]
},
"usageGuidance": {
"recommendedScenarios": ["商品图片轮播", "广告 banner", "图片画廊"],
"avoidScenarios": ["静态单图", "Tab 切换"],
"dependencies": ["vant"]
}
}
<template>
<van-swipe :autoplay="autoplay"
class="vui-swiper"
:duration="duration"
:height="height"
:indicator-color="indicatorColor"
:initial-swipe="initialSwipe"
:lazy-render="lazyRender"
:loop="loop"
:show-indicators="showIndicators"
:touchable="touchable"
:vertical="vertical"
:width="width"
v-bind="$attrs"
@change="handleChange">
<slot>
<van-swipe-item v-for="(item, index) in items" :key="index">
<slot :index="index"
:item="item"
name="item">
<img v-if="typeof item === 'string'"
:alt="`slide-${index}`"
class="vui-swiper__image"
:src="item" />
<div v-else class="vui-swiper__custom">
{{ item }}
</div>
</slot>
</van-swipe-item>
</slot>
<template v-if="$slots.indicator" #indicator="{ active, total }">
<slot :active="active"
name="indicator"
:total="total" />
</template>
</van-swipe>
</template>
<script setup lang="ts">
import { Swipe as vanSwipe, SwipeItem as vanSwipeItem } from "vant";
defineOptions({ name: "VSwiper" });
defineProps<{
autoplay?: number | string;
duration?: number | string;
height?: number | string;
indicatorColor?: string;
initialSwipe?: number;
items?: SwiperItem[];
lazyRender?: boolean;
loop?: boolean;
showIndicators?: boolean;
touchable?: boolean;
vertical?: boolean;
width?: number | string;
}>();
const emit = defineEmits<{
(event: "change", index: number): void;
}>();
export type SwiperItem = Record<string, unknown> | string;
function handleChange(index: number) {
emit("change", index);
}
</script>
<style scoped>
.vui-swiper__image {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.vui-swiper__custom {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
</style>
import type { DefineComponent } from "vue";
export type SwiperItem = string | Record<string, unknown>;
declare const VSwiper: DefineComponent<{
autoplay?: number | string;
duration?: number | string;
height?: number | string;
indicatorColor?: string;
initialSwipe?: number;
items?: SwiperItem[];
lazyRender?: boolean;
loop?: boolean;
showIndicators?: boolean;
touchable?: boolean;
vertical?: boolean;
width?: number | string;
}>;
export default VSwiper;
export { default } from "./VSwiper.vue";
{
"$schema": "../../../../../../contracts/ai/component-manifest-item.schema.json",
"name": "tabs",
"exportName": "VTabs",
"source": "src/components/VTabs/VTabs.vue",
"category": "navigation",
"description": "移动端标签页组件,基于 Vant 4 Tabs,支持 line/card 样式、滑动切换、内容懒加载。对应 Element Plus 的 el-tabs/el-tab-pane。",
"semanticRoles": ["section-tabs", "content-tabs", "image-type-switcher"],
"supportedKinds": ["TABS", "TAB_BAR", "SEGMENTED_CONTROL"],
"supportedScopes": ["page", "section"],
"priority": 5,
"props": [
{ "name": "items", "type": "TabItem[]", "description": "标签页数据,每项包含 title、name、content、disabled 等。" },
{ "name": "modelValue", "type": "number | string", "description": "当前激活的标签 name 或 index。" },
{ "name": "type", "type": "'line' | 'card'", "description": "标签样式类型。", "default": "'line'" },
{ "name": "color", "type": "string", "description": "标签主题色。" },
{ "name": "sticky", "type": "boolean", "description": "是否使用粘性定位。", "default": "false" },
{ "name": "shrink", "type": "boolean", "description": "是否开启左侧收缩布局。", "default": "false" },
{ "name": "animated", "type": "boolean", "description": "是否开启切换动画。", "default": "true" },
{ "name": "swipeable", "type": "boolean", "description": "是否开启手势滑动切换。", "default": "false" },
{ "name": "ellipsis", "type": "boolean", "description": "是否省略过长的标题文字。", "default": "true" },
{ "name": "lazyRender", "type": "boolean", "description": "是否延迟渲染未展示的标签页。", "default": "true" },
{ "name": "scrollspy", "type": "boolean", "description": "是否开启滚动导航。", "default": "false" },
{ "name": "titleActiveColor", "type": "string", "description": "标题选中态颜色。" },
{ "name": "titleInactiveColor", "type": "string", "description": "标题默认态颜色。" },
{ "name": "lineWidth", "type": "number | string", "description": "底部条宽度。" },
{ "name": "lineHeight", "type": "number | string", "description": "底部条高度。" },
{ "name": "border", "type": "boolean", "description": "是否展示外边框。", "default": "true" }
],
"events": [
{ "name": "update:modelValue", "description": "激活标签变化时触发。", "payload": "number | string" },
{ "name": "change", "description": "切换标签时触发。", "payload": "number | string" },
{ "name": "clickTab", "description": "点击标签时触发。", "payload": "{ name, title }" }
],
"slots": [
{ "name": "default", "description": "自定义标签页内容(van-tab 列表)。" },
{ "name": "tab-content", "description": "使用 items 数据时自定义标签页内容。", "scope": "{ item, index }" }
],
"figmaMapping": {
"keywords": ["tabs", "tab bar", "segment", "标签", "tab", "切换"],
"nodeTypes": ["FRAME", "COMPONENT", "INSTANCE"],
"variantHints": ["active", "inactive", "line", "card"]
},
"usageGuidance": {
"recommendedScenarios": ["图片类型切换(外观/内饰)", "内容区域切换", "导航标签"],
"avoidScenarios": ["底部全局导航(用 VTabbar)", "下拉筛选(用 VDropdownMenu)"],
"dependencies": ["vant"]
}
}
<template>
<van-tabs
class="vui-tabs"
:model-value="modelValue"
:type="type"
:color="color"
:sticky="sticky"
:shrink="shrink"
:animated="animated"
:ellipsis="ellipsis"
:swipeable="swipeable"
:lazy-render="lazyRender"
:scrollspy="scrollspy"
:line-width="lineWidth"
:line-height="lineHeight"
:duration="duration"
:title-active-color="titleActiveColor"
:title-inactive-color="titleInactiveColor"
:border="border"
v-bind="$attrs"
@update:model-value="handleUpdate"
@change="handleChange"
@click-tab="handleClickTab"
>
<slot>
<van-tab v-for="(item, index) in items" :key="item.name ?? index" :name="item.name ?? index" :title="item.title" :disabled="item.disabled" :badge="item.badge" :dot="item.dot">
<slot name="tab-content" :item="item" :index="index">
{{ item.content }}
</slot>
</van-tab>
</slot>
</van-tabs>
</template>
<script setup lang="ts">
import { Tab as vanTab, Tabs as vanTabs } from "vant";
defineOptions({ name: "VTabs" });
export type TabItem = {
badge?: number | string;
content?: string;
disabled?: boolean;
dot?: boolean;
name?: number | string;
title: string;
};
defineProps<{
animated?: boolean;
border?: boolean;
color?: string;
duration?: number | string;
ellipsis?: boolean;
items?: TabItem[];
lazyRender?: boolean;
lineHeight?: number | string;
lineWidth?: number | string;
modelValue?: number | string;
scrollspy?: boolean;
shrink?: boolean;
sticky?: boolean;
swipeable?: boolean;
titleActiveColor?: string;
titleInactiveColor?: string;
type?: "card" | "line";
}>();
const emit = defineEmits<{
(event: "update:modelValue", value: number | string): void;
(event: "change", value: number | string): void;
(event: "clickTab", value: { name: number | string; title: string }): void;
}>();
function handleUpdate(value: number | string) {
emit("update:modelValue", value);
}
function handleChange(value: number | string) {
emit("change", value);
}
function handleClickTab({ name, title }: { name: number | string; title: string }) {
emit("clickTab", { name, title });
}
</script>
import type { DefineComponent } from "vue";
export type TabItem = {
badge?: number | string;
content?: string;
disabled?: boolean;
dot?: boolean;
name?: number | string;
title: string;
};
declare const VTabs: DefineComponent<{
animated?: boolean;
border?: boolean;
color?: string;
duration?: number | string;
ellipsis?: boolean;
items?: TabItem[];
lazyRender?: boolean;
lineHeight?: number | string;
lineWidth?: number | string;
modelValue?: number | string;
scrollspy?: boolean;
shrink?: boolean;
sticky?: boolean;
swipeable?: boolean;
titleActiveColor?: string;
titleInactiveColor?: string;
type?: "card" | "line";
}>;
export default VTabs;
export { default } from "./VTabs.vue";
#!/usr/bin/env node
/**
* AI Direct - Figma to Design Spec 模块
*
* 从 Figma design context 中提取结构化 spec,包括:
* - section purpose (区域作用)
* - patterns (可复用 UI 模式)
* - token candidates (颜色、间距、字体等设计信号)
* - uncertainty (未明确的决策点)
*
* 这个 spec 作为 AI 代码生成的中间层输入,避免 AI 直接猜测设计意图。
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const _filename = fileURLToPath(import.meta.url);
const _dirname = path.dirname(_filename);
/**
* 从 Figma design context 中提取设计 spec
* @param {string} designContext - Figma YAML 或 HTML 格式的设计上下文
* @param {object} options - 选项
* @returns {object} design spec
*/
export function buildDesignSpec(designContext, options = {}) {
if (!designContext || typeof designContext !== "string") {
return null;
}
const spec = {
version: "1.0",
generatedAt: new Date().toISOString(),
sections: [],
uncertainty: [],
};
// 1. 提取 token candidates (颜色、间距、字体)
const tokens = extractTokenCandidates(designContext);
spec.tokens = tokens;
// 2. 识别 UI patterns (可复用模式)
const patterns = extractPatterns(designContext);
spec.patterns = patterns;
// 3. 标记 uncertainty (未明确的决策点)
const uncertainty = detectUncertainty(designContext);
spec.uncertainty = uncertainty;
// 4. 提取 section purpose (如果有多个 frame/section)
const sections = extractSections(designContext);
spec.sections = sections;
return spec;
}
/**
* 提取 token candidates:从 Figma 数据中识别设计信号
*/
function extractTokenCandidates(designContext) {
const tokens = {
colors: [],
spacing: [],
typography: [],
radius: [],
};
// 1. 提取颜色
const colorPattern = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/g;
const colorSet = new Set();
let match;
while ((match = colorPattern.exec(designContext)) !== null) {
const [r, g, b, a] = [
parseInt(match[1], 10),
parseInt(match[2], 10),
parseInt(match[3], 10),
match[4] ? parseFloat(match[4]) : 1,
];
const color = a < 1 ? `rgba(${r}, ${g}, ${b}, ${a})` : `rgb(${r}, ${g}, ${b})`;
if (!colorSet.has(color)) {
colorSet.add(color);
tokens.colors.push({
value: color,
role: inferColorRole(r, g, b, a, designContext, match.index),
});
}
}
// 2. 提取间距 (padding, margin, gap)
const spacingPattern = /(?:padding|margin|gap|w|h|width|height)[:\s]+(\d+)px/gi;
const spacingSet = new Set();
while ((match = spacingPattern.exec(designContext)) !== null) {
const value = parseInt(match[1], 10);
if (value > 0 && value <= 200 && !spacingSet.has(value)) {
spacingSet.add(value);
tokens.spacing.push({ value: `${value}px`, raw: value });
}
}
tokens.spacing.sort((a, b) => a.raw - b.raw);
// 3. 提取字体大小和行高
const fontSizePattern = /font-?size[:\s]+(\d+)px/gi;
const lineHeightPattern = /line-?height[:\s]+([\d.]+)/gi;
const typographySet = new Set();
while ((match = fontSizePattern.exec(designContext)) !== null) {
const size = parseInt(match[1], 10);
if (!typographySet.has(size)) {
typographySet.add(size);
tokens.typography.push({ fontSize: `${size}px`, raw: size });
}
}
while ((match = lineHeightPattern.exec(designContext)) !== null) {
const lh = parseFloat(match[1]);
const existing = tokens.typography.find((t) => t.lineHeight === lh);
if (!existing) {
tokens.typography.push({ lineHeight: lh, raw: lh });
}
}
tokens.typography.sort((a, b) => (a.raw || 0) - (b.raw || 0));
// 4. 提取圆角
const radiusPattern = /radius[:\s]+\[(\d+(?:,\s*\d+)*)\]/gi;
while ((match = radiusPattern.exec(designContext)) !== null) {
const values = match[1].split(",").map((v) => parseInt(v.trim(), 10));
tokens.radius.push({ value: values.map((v) => `${v}px`).join(" "), raw: values });
}
return tokens;
}
/**
* 推断颜色的语义角色
*/
function inferColorRole(r, g, b, a, context, index) {
// 高饱和度 = 主色/强调色
const saturation = Math.max(r, g, b) - Math.min(r, g, b);
// 主色 (蓝色系)
if (b > 180 && r < 100 && saturation > 150) {
return "primary";
}
// 错误/警告 (红色系)
if (r > 180 && g < 100 && saturation > 150) {
return "error";
}
// 成功 (绿色系)
if (g > 150 && r < 100 && b < 100) {
return "success";
}
// 文字色 (深灰/黑)
if (r === g && g === b && r < 100) {
return "text-primary";
}
// 次级文字 (中灰)
if (r === g && g === b && r >= 100 && r < 180) {
return "text-secondary";
}
// 背景色 (浅灰/白)
if (r === g && g === b && r >= 230) {
return "background";
}
// 边框 (中等灰度)
if (r === g && g === b && r >= 180 && r < 230) {
return "border";
}
return "unknown";
}
/**
* 识别 UI patterns (可复用模式)
*/
function extractPatterns(designContext) {
const patterns = [];
// 1. Key-Value 列表
if (/label|key|title[\s\S]{0,50}value|content|text/i.test(designContext)) {
patterns.push({
type: "key-value-list",
description: "标签-值对列表,常用于信息展示",
selector: ".label + .value 或 .key + .value",
});
}
// 2. 图片网格
if (/grid[\s\S]{0,100}image|photo|picture/i.test(designContext)) {
patterns.push({
type: "image-grid",
description: "图片网格布局",
selector: "display: grid + img",
});
}
// 3. 悬浮按钮/角标
if (/absolute[\s\S]{0,100}(top|right|bottom|left)/i.test(designContext)) {
patterns.push({
type: "floating-overlay",
description: "悬浮元素 (按钮、角标、计数器等)",
selector: "position: absolute",
});
}
// 4. 固定底栏
if (/fixed[\s\S]{0,50}bottom[:\s]+0/i.test(designContext)) {
patterns.push({
type: "fixed-bottom-bar",
description: "固定底栏 (操作按钮、导航等)",
selector: "position: fixed; bottom: 0",
});
}
// 5. 价格/倒计时区域
if (/price|countdown|timer/i.test(designContext)) {
patterns.push({
type: "price-countdown",
description: "价格或倒计时展示区域",
selector: ".price-section 或 .countdown",
});
}
return patterns;
}
/**
* 检测 uncertainty (未明确的决策点)
*/
function detectUncertainty(designContext) {
const uncertainty = [];
// 1. hover/focus 态
if (!/hover|:hover|focus|:focus/i.test(designContext)) {
uncertainty.push({
type: "interaction-state",
description: "hover/focus 态未在设计稿中明确",
impact: "需要设计师确认或参考同类组件",
});
}
// 2. 响应式/移动端
if (!/mobile|tablet|responsive|@media/i.test(designContext)) {
uncertainty.push({
type: "responsive",
description: "响应式/移动端布局未在设计稿中明确",
impact: "需要设计师确认或参考设计系统",
});
}
// 3. 暗色模式
if (!/dark|theme|mode/i.test(designContext)) {
uncertainty.push({
type: "dark-mode",
description: "暗色模式配色未在设计稿中明确",
impact: "如果项目支持暗色模式,需要设计师补充",
});
}
// 4. 空状态/加载态/错误态
if (!/empty|loading|error|skeleton/i.test(designContext)) {
uncertainty.push({
type: "edge-states",
description: "空状态/加载态/错误态未在设计稿中明确",
impact: "需要设计师补充或参考设计系统",
});
}
return uncertainty;
}
/**
* 提取多个 sections (如果 design context 包含多个 frame)
*/
function extractSections(designContext) {
const sections = [];
// 尝试识别 frame/section 边界
const framePattern = /name:\s*["']?([^"'\n]+)["']?[\s\S]{0,200}?type:\s*(?:FRAME|GROUP)/gi;
let match;
while ((match = framePattern.exec(designContext)) !== null) {
const name = match[1].trim();
sections.push({
name,
purpose: inferSectionPurpose(name),
});
}
return sections;
}
/**
* 推断 section 的作用
*/
function inferSectionPurpose(name) {
const lower = name.toLowerCase();
if (/hero|banner|header/i.test(lower)) return "页面顶部展示区";
if (/nav|menu|sidebar/i.test(lower)) return "导航/菜单";
if (/content|main|body/i.test(lower)) return "主要内容区";
if (/footer|bottom/i.test(lower)) return "页面底部";
if (/card|list|grid/i.test(lower)) return "卡片/列表展示";
if (/form|input|search/i.test(lower)) return "表单/输入";
if (/modal|dialog|popup/i.test(lower)) return "弹窗/浮层";
return "通用区域";
}
/**
* 将 spec 写入文件
*/
export function writeDesignSpec(spec, outputPath) {
const content = JSON.stringify(spec, null, 2);
fs.writeFileSync(outputPath, content, "utf-8");
console.log(`[ai-direct-spec] ✓ Design spec written to ${outputPath}`);
return outputPath;
}
/**
* 读取 spec 文件
*/
export function readDesignSpec(specPath) {
if (!fs.existsSync(specPath)) {
return null;
}
try {
const content = fs.readFileSync(specPath, "utf-8");
return JSON.parse(content);
} catch (err) {
console.warn(`[ai-direct-spec] Failed to read spec: ${err.message}`);
return null;
}
}
// CLI 入口
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const designContextPath = process.argv[2];
const outputPath = process.argv[3] || designContextPath.replace(/\.html$/, ".spec.json");
if (!designContextPath) {
console.error("Usage: node ai-direct-spec.mjs <design-context.html> [output.spec.json]");
process.exit(1);
}
if (!fs.existsSync(designContextPath)) {
console.error(`Error: File not found: ${designContextPath}`);
process.exit(1);
}
const designContext = fs.readFileSync(designContextPath, "utf-8");
const spec = buildDesignSpec(designContext);
writeDesignSpec(spec, outputPath);
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!