vue3.ts 15.8 KB
import { getProjectProfile, renderProfileConstraint } from '../../../utils/project-profile';
import type { FrameworkStrategy, FramePromptInput, ComponentPromptInput, RootInjectionInput } from './types';
import { buildComponentUsageGuidance, buildStretchGuidance } from './component-usage';

/**
 * Vue 3 strategy — a NEW, self-contained generation strategy that emits Vue 3
 * Single-File Components (SFC). It is intentionally separate from `prompt.ts`
 * (React) so the two never interfere. Adding support for another Vue UI kit is
 * a single entry in `VUE_LIBRARY_GUIDANCE` below (Open-Closed Principle).
 */

/** Renders the target-project profile constraint block (mirrors prompt.ts `profileConstraintSection`). */
function profileConstraintSection(): string {
    const p = getProjectProfile();
    return p ? renderProfileConstraint(p) : '';
}

const VUE_OUTPUT_FORMAT = `
  <output_format>
    **CRITICAL - Output Format Requirements (Vue 3 SFC):**
    - Return Vue 3 Single-File Components. Each file is a \`## <filename>\` section followed by a fenced code block.
    - Main component file MUST be named \`index.vue\`.
    - Style file (if separate) named \`index.module.less\` or \`index.module.scss\` (scoped CSS modules); otherwise inline \`<style scoped>\`.
    - Each file section MUST start with EXACTLY \`## \` (two hashes + one space) followed by the filename with extension.
    - Example:
    ## index.vue
    \`\`\`vue
    <template>
      <div class="container">...</div>
    </template>
    <script setup lang="ts">
    // component logic
    </script>
    <style scoped>
    .container { /* styles */ }
    </style>
    \`\`\`
  </output_format>`;

const ASSETS_HANDLING = `
      - **CRITICAL**: For any image URL starting with \`@/assets\`, import it at the top of \`<script setup>\`:
        \`import ArXivIcon from '@/assets/arxiv-1-2956.svg';\` and use \`<img :src="ArXivIcon" />\`.
      - NEVER use the raw string path directly in the template or styles.`;

const ICON_PROP_GUIDANCE = `
      - **CRITICAL — Icon props are COMPONENTS, not image URLs (a wrong usage causes a white-screen crash)**:
        - An imported asset file (\`import X from '@/assets/foo.svg'\`) is a **string URL** at runtime (in dev it may be a \`data:image/svg+xml,...\` data URI). It is NEVER a Vue component.
        - A URL string may ONLY be used as: (1) \`<img :src="X" />\`, or (2) a CSS \`background-image: url(...)\` value (use a relative/absolute path there, NOT the \`@\` alias).
        - NEVER pass it to a prop that expects a **component**, such as Element Plus \`el-select\` / \`el-input\` \`suffix-icon\`, \`prefix-icon\`, or \`el-button\`'s \`icon\`. Passing a URL there makes the library call \`createElement('data:image/svg+xml,...')\` → \`InvalidCharacterError\` → the WHOLE page renders blank.
        - ✅ To show a custom arrow/icon on a library control: import an ICON COMPONENT from the kit's icon package (e.g. \`import { ArrowDown } from '@element-plus/icons-vue'\`) and pass \`<el-select :suffix-icon="ArrowDown">\`; OR hide the default icon via CSS (\`.el-select__suffix { display: none }\`) and draw your own with \`.wrapper::after { background-image: url(...) }\`.
        - ❌ NEVER do \`<el-select :suffix-icon="importedSvgUrl">\` where \`importedSvgUrl\` is an imported \`.svg\`.`;

const LAYOUT_GUIDANCE = `
      - **Layout & Shell (CRITICAL — no overlapping regions)**:
        - When a frame contains a navigation/menu/sidebar region AND a content region meant to sit side-by-side, render them as flex children of a row container:
          \`display: flex; min-height: 100vh;\`
        - Give the menu/sidebar a FIXED width and \`flex-shrink: 0\` (e.g. \`width: 240px;\`), and the content area \`flex: 1; min-width: 0;\`.
        - Add spacing between them (e.g. \`gap: 16px;\` or padding) — the menu and content must NEVER touch or overlap.
        - NEVER use \`position: absolute\` to overlay the menu on top of the content. They must be separate flex children laid out left-to-right.
        - If the design is a top bar + content (vertical), use \`flex-direction: column\` with the header \`flex-shrink: 0\` and content \`flex: 1; overflow: auto;\`.
        - The content area must be allowed to scroll independently; never squeeze the menu width to 0.
        - Honor the explicit \`layout\` from \`frame_details\` (flex/grid/absolute); only apply the rules above when the design actually places regions side-by-side.`;

const CONTENT_REGION_GUIDANCE = `
      - **Content Region — NOT the whole app shell**:
        - If the design shows a persistent application chrome — a LEFT sidebar/menu, a TOP navigation bar, and/or a BREADCRUMB — treat those three areas as the host application's fixed shell, which is ALREADY provided by the parent app.
        - Generate ONLY the **main content region**: the area to the RIGHT of the left menu and BELOW the top nav and breadcrumb. Do NOT re-implement the left menu, top navigation, or breadcrumb.
        - The component you emit MUST BE the content area itself: a self-contained panel that fills the available space. When it sits beside a sidebar, give the content root \`flex: 1; min-width: 0; overflow: auto;\` and do NOT wrap it inside another app shell (no second sidebar, no second top bar).
        - If you must render the full frame (e.g. for a standalone preview), keep the menu / top nav / breadcrumb as minimal STATIC, NON-interactive placeholders (plain labeled containers) and spend all visual fidelity on the content region. NEVER build a real working menu / router / breadcrumb for them.
        - Rule of thumb: your output = "what lives inside the content area", not "the entire application chrome".`;

const DOM_IDS_REQUIREMENT = `
      - Assign an \`id\` attribute to the root container and any internal elements, matching \`frame_details\` (required for automated validation).`;

/**
 * Component-library guidance for the Vue ecosystem. Extend by adding a key;
 * matching is a case-insensitive substring so "Ant Design Vue",
 * "ant-design-vue", "Element Plus" all resolve. Unknown libraries fall back to
 * a generic instruction. This is the single extension point for new Vue kits.
 */
const VUE_LIBRARY_GUIDANCE: Record<string, string> = {
    'Element Plus': `
      - **UI Library: Element Plus**. Import the components you use, e.g. \`import { ElButton, ElCard, ElInput } from 'element-plus';\` (on-demand named imports).
      - Use Element Plus components in \`<template>\` (e.g. \`<el-button type="primary">…</el-button>\`, \`<el-card>…</el-card>\`).
      - Element Plus theming uses CSS variables; import \`element-plus/dist/index.css\` once at the app entry.`,
    'Ant Design Vue': `
      - **UI Library: Ant Design Vue**. Import the components you use, e.g. \`import { Button, Card, Input } from 'ant-design-vue';\`.
      - Use Ant Design Vue components in \`<template>\` (e.g. \`<a-button type="primary">…</a-button>\`, \`<a-card>…</a-card>\`).
      - Import \`ant-design-vue/dist/reset.css\` once at the app entry for base styles.`,
};

function libraryGuidance(componentLibrary?: string): string {
    if (!componentLibrary) return '';
    const key = Object.keys(VUE_LIBRARY_GUIDANCE).find((k) => componentLibrary.toLowerCase().includes(k.toLowerCase()));
    const guidance = key ? VUE_LIBRARY_GUIDANCE[key] : undefined;
    if (guidance) return guidance;
    return `
      - **UI Library**: The project uses "${componentLibrary}". Use its standard Vue 3 components in \`<template>\` and import them accordingly.`;
}

const DEFAULT_VUE_APP = `<template>
  <RootComponent />
</template>

<script setup lang="ts">
import RootComponent from '@/components';
</script>`;

function buildFramePrompt({
    frameDetails,
    childrenImports,
    styling,
    assetFiles,
    renderingModes,
    fillContainer,
}: FramePromptInput): string {
    const lib = libraryGuidance(getProjectProfile()?.componentLibrary);
    return `
<system_instructions>
  <role>
    You are a Vue 3 Architect.
    Your task is to assemble a "Frame" component (a Vue 3 SFC) that composes multiple child components based on Figma layout data, using \`<script setup lang="ts">\`.
  </role>

  <input_context>
    <frame_details>${frameDetails}</frame_details>
    <children>${childrenImports}</children>
    <styling>${styling}</styling>
    ${assetFiles ? `<available_assets>Available asset files: ${assetFiles}</available_assets>` : ''}

    <frame_structure>
      The \`frame_details\` contains:
      - \`layout\`: Layout info (flex/grid/absolute)
      - \`elements\`: CSS styles and asset URLs for all elements
      - \`states\` (optional): reusable components; each entry has \`state\` (data array), \`componentName\`, \`componentPath\`
    </frame_structure>
  </input_context>

  <requirements>
    <req_1>
      **Children Components & Props (CRITICAL)**:
      - Import child components at the top of \`<script setup>\` using the EXACT path from \`<children>\`.
      - Example: \`import TaskGrid from "@/components/tasks-section/task-grid";\`
      - Use them in \`<template>\` as \`<TaskGrid />\`.
      - When \`states\` exists, render via \`v-for\`:
        \`\`\`vue
        <TaskGrid v-for="(item, i) in states[0].state" :key="i" v-bind="item" />
        \`\`\`
      - ONLY pass props present in the state data.
    </req_1>

    <req_2>
      **Layout & Styling**:
      - Use \`layout\` for dimensions/spacing/flow (flex/grid).
      - Prefer \`<style scoped>\` or CSS Modules; if the stack uses Less/SCSS, emit \`index.module.less\`.
      - Use \`relative\` positioning for the container.
    </req_2>

    <req_8>
      **App Layout & Shell**:
${LAYOUT_GUIDANCE}
    </req_8>

    <req_9>
      **Content Region (dashboard / app pages)**:
${CONTENT_REGION_GUIDANCE}
    </req_9>

    <req_11>
      **Strict Tech-Stack Compliance (UI components)**:
${buildComponentUsageGuidance()}
    </req_11>

    <req_12>
      **Fill Container**:
${buildStretchGuidance(fillContainer !== false)}
    </req_12>

    <req_3>
      **Images & Assets**:
${ASSETS_HANDLING}
    </req_3>

    <req_13>
      **Icon Props ≠ Image URLs**:
${ICON_PROP_GUIDANCE}
    </req_13>

    <req_4>
      **DOM IDs**:
${DOM_IDS_REQUIREMENT}
    </req_4>

    <req_5>
      **File Naming**:
      - ALWAYS name the main component file \`index.vue\`.
      - NEVER use PascalCase file names like \`MainFrame.vue\`.
    </req_5>
${lib ? `    <req_6>\n      **Component Library**:\n${lib}\n    </req_6>` : ''}
${renderingModes.hasStates ? `    <req_7>
      **List Rendering (States-based)**:
      - When \`frame_details\` contains a \`states\` array, render each entry with \`v-for\`:
        \`\`\`vue
        <ChildComp v-for="(item, i) in states[0].state" :key="i" v-bind="item" />
        \`\`\`
      - ONLY pass props that exist in the state data objects.
    </req_7>` : ''}
  </requirements>

${VUE_OUTPUT_FORMAT}
${profileConstraintSection()}
</system_instructions>
`.trim();
}

function buildComponentPrompt({
    componentName,
    componentDetails,
    styling,
    assetFiles,
    fillContainer,
}: ComponentPromptInput): string {
    const lib = libraryGuidance(getProjectProfile()?.componentLibrary);
    return `
<system_instructions>
  <role>
    You are a Pixel-Perfect Vue 3 Frontend Engineer.
    Your goal is to implement a specific UI component from Figma design data with 100% visual fidelity, as a Vue 3 SFC with \`<script setup lang="ts">\`.
  </role>

  <input_context>
    <component_details>${componentDetails}</component_details>
    ${assetFiles ? `<available_assets>Available asset files: ${assetFiles}</available_assets>` : ''}
    <styling>${styling}</styling>
  </input_context>

  <requirements>
    <req_1>
      **High Fidelity & Responsive**:
      - Use exact design values from \`component_details.elements\` (colors, spacing, font sizes, gradients, shadows).
      - Prefer \`<style scoped>\` or CSS Modules; if the stack uses Less/SCSS emit \`index.module.less\`.
    </req_1>

    <req_2>
      **DOM Identification**:
      - EVERY DOM element corresponding to a Figma node MUST have an \`id\` attribute matching the Figma node id.
    </req_2>

    <req_3>
      **Images & Assets**:
${ASSETS_HANDLING}
    </req_3>

    <req_13>
      **Icon Props ≠ Image URLs**:
${ICON_PROP_GUIDANCE}
    </req_13>

    <req_4>
      **Semantic HTML & Vue idioms**:
      - Use semantic tags: \`<header>\`, \`<footer>\`, \`<nav>\`, \`<section>\`, \`<button>\`.
      - Use \`v-for\` for lists, \`:prop\` for binding, \`@click\` for events.
    </req_4>

    <req_5>
      **Component Type & Props (CRITICAL)**:
      - IF \`component_details.componentName\` exists: generate \`const props = defineProps<${componentName}Props>()\` from \`component_details.props\`; reference props in template as \`{{ title }}\`, \`<img :src="iconSrc" />\`.
      - IF it does NOT exist: hardcode content from \`component_details.elements\` directly.
    </req_5>

    <req_6>
      **Naming & Structure**:
      - Component Name: **${componentName}** (PascalCase).
      - Export via \`<script setup lang="ts">\` (auto-exposed).
      - File name: \`index.vue\`.
    </req_6>
${lib ? `    <req_7>\n      **Component Library**:\n${lib}\n    </req_7>` : ''}
    <req_9>
      **App Layout & Shell**:
${LAYOUT_GUIDANCE}
    </req_9>

    <req_10>
      **Content Region (dashboard / app pages)**:
${CONTENT_REGION_GUIDANCE}
    </req_10>

    <req_11>
      **Strict Tech-Stack Compliance (UI components)**:
${buildComponentUsageGuidance()}
    </req_11>

    <req_12>
      **Fill Container**:
${buildStretchGuidance(fillContainer !== false)}
    </req_12>
  </requirements>

${VUE_OUTPUT_FORMAT}
${profileConstraintSection()}
</system_instructions>
`.trim();
}

function buildRootInjectionPrompt({ appContent, componentName }: RootInjectionInput): string {
    const lib = libraryGuidance(getProjectProfile()?.componentLibrary);
    return `
<system_instructions>
  <role>
    You are a Vue 3 code refactoring expert.
    Your task is to inject a root component into an existing App.vue file with minimal changes.
  </role>

  <input_context>
    <current_app_content>
${appContent}
    </current_app_content>
    <component_to_inject>
      - Component Name: ${componentName}
      - The root page component is published through the barrel at \`@/components\` (src/components/index.vue).
    </component_to_inject>
  </input_context>

  <requirements>
    <req_1>
      **Import Statement**:
      - The App entry MUST import the root component from the barrel \`@/components\`.
      - Keep EXACTLY ONE import line for the root component. If the current file already has
        \`import RootComponent from '@/components';\`, simply rename its local binding to \`${componentName}\`
        (do NOT add a second import line). Final result:
        \`import ${componentName} from '@/components';\`
    </req_1>

    <req_2>
      **Component Rendering**:
      - Inside the App component's \`<template>\`, replace the existing content with \`<${componentName} />\`.
      - Keep any wrapper element and its classes.
    </req_2>

    <req_3>
      **Preserve Existing Code**:
      - Keep all existing styles and logic.
      - Maintain the SFC structure (\`<template>\` / \`<script setup>\` / \`<style>\`).
    </req_3>

    <req_4>
      **Minimal Changes**:
      - Only rename the import binding and render the component.
      - Do NOT add comments or explanatory text, and do NOT duplicate the import.
    </req_4>
${lib ? `    <req_5>\n      **Component Library**:\n${lib}\n    </req_5>` : ''}
  </requirements>

  <output_format>
    Return ONLY the complete updated App.vue code (full SFC) without markdown code blocks or explanation.
    It must be valid Vue 3 that can be written directly to App.vue.
  </output_format>
</system_instructions>
`.trim();
}

export const vue3Strategy: FrameworkStrategy = {
    id: 'vue',
    label: 'Vue 3',
    isVue: true,
    entryFileName: 'index.vue',
    rootFileName: 'App.vue',
    defaultAppContent: DEFAULT_VUE_APP,

    buildFramePrompt,
    buildComponentPrompt,
    buildRootInjectionPrompt,
    libraryGuidance,
};