Next.js Tailwind CSS UI组件

在这里插入图片描述
摘要: 官网

今天公司使用到一个前端ui框架——Next.js Tailwind CSS UI组件!这从头构建一个AI驱动的前端UI组件生成器,生成Next.js Tailwind CSS UI组件:
1、用Next.js、ts和Tailwind CSS构建UI组件生成器Web应用程序。
2、用CopilotKit将AI功能集成到UI组件生成器中。
3、集成嵌入式代码编辑器,对生成的代码进行更改。

准备:

1、Ace Code Editor —— 使用JavaScript编写的可嵌入代码编辑器,具有与原生编辑器相匹配的功能和性能。
2、Langchain —— 提供一个框架,使AI代理能够搜索网络并研究任何主题。
3、OpenAI API —— 提供一个API密钥,能够使用ChatGPT模型执行各种任务。
4、Tavily AI —— 搜索引擎,使AI代理能够在应用程序中进行研究并访问实时知识。。
5、CopilotKit —— 用于构建自定义AI聊天机器人、应用内AI代理和文本区域的开源协作框架。

项目设置和包安装:

创建一个Next.js应用程序:

npx create-next-app@latest aiuigenerator

在这里插入图片描述

安装Ace代码编辑器和Langchain包及其依赖项

npm install react-ace @langchain/langgraph

安装CopilotKit。从React状态中检索数据并将AI协同助手添加到应用程序中。

npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend

以上步骤已经准备好构建一个由人工智能驱动的博客!

构建UI组件生成器前端界:

/[root]/src/app目录,创建components文件夹。components内创建Header.tsx和CodeTutorial.tsx。

在Header.tsx文件中定义一个名为Header的函数组件,用于渲染生成器的导航栏。

"use client";

import Link from "next/link";

export default function Header() {
  return (
    <>
      <header className="flex flex-wrap sm:justify-start sm:flex-nowrap z-50 w-full bg-gray-800 border-b border-gray-200 text-sm py-3 sm:py-0 ">
        <nav
          className="relative max-w-7xl w-full mx-auto px-4 sm:flex sm:items-center sm:justify-between sm:px-6 lg:px-8"
          aria-label="Global">
          <div className="flex items-center justify-between">
            <Link
              className="w-full flex-none text-xl text-white font-semibold p-6"
              href="/"
              aria-label="Brand">
              AI-UI-Components-Generator
            </Link>
          </div>
        </nav>
      </header>
    </>
  );
}

CodeTutorial.tsx文件中,添加以下代码,定义一个名为CodeTutorial的函数组件,用于渲染生成器的主页,显示生成的UI组件、嵌入式代码编辑器和生成的实现教程

"use client";

import Markdown from "react-markdown";
import { useState } from "react";
import AceEditor from "react-ace";
import React from "react";

export default function CodeTutorial() {
  const [code, setCode] = useState<string[]>([
    `<h1 class="text-red-500">Hello World</h1>`,
  ]);
  const [codeToDisplay, setCodeToDisplay] = useState<string>(code[0] || "");
  const [codeTutorial, setCodeTutorial] = useState(``);

  function onChange(newCode: any) {
    setCodeToDisplay(newCode);
  }

  return (
    <>
      <main className=" min-h-screen px-4">
        <div className="w-full h-full min-h-[70vh] flex justify-between gap-x-1 ">
          <div className="w-2/3 min-h-[60vh] rounded-lg bg-white shadow-lg p-2 border mt-8 overflow-auto">
            <div
              className="w-full min-h-[60vh] rounded-lg"
              dangerouslySetInnerHTML={{ __html: codeToDisplay }}
            />
          </div>
          <AceEditor
            placeholder="Placeholder Text"
            mode="html"
            theme="monokai"
            name="blah2"
            className="w-[50%] min-h-[60vh] p-2 mt-8 rounded-lg"
            onChange={onChange}
            fontSize={14}
            lineHeight={19}
            showPrintMargin={true}
            showGutter={true}
            highlightActiveLine={true}
            value={codeToDisplay}
            setOptions={{
              enableBasicAutocompletion: true,
              enableLiveAutocompletion: true,
              enableSnippets: false,
              showLineNumbers: true,
              tabSize: 2,
            }}
          />
        </div>
        <div className="w-10/12 mx-auto">
          <div className="mt-8">
            <h1 className="text-white text-center text-xl font-semibold p-6">
              Code Tutorial
            </h1>
            {codeTutorial ? (
              <Markdown className="text-white">{codeTutorial}</Markdown>
            ) : (
              <div className="text-white">
                The Code Tutorial Will Appear Here
              </div>
            )}
          </div>
        </div>
      </main>
    </>
  );
}

/[root]/src/page.tsx文件,并添加以下代码,导入CodeTutorial和Header组件,并定义一个名为Home的函数组件

import React from "react";
import Header from "./components/Header";
import CodeTutorial from "./components/CodeTutorial";

export default function Home() {
  return (
    <>
      <Header />
      <CodeTutorial />
    </>
  );
}

删除 globals.css 文件中的 CSS 代码,并添加以下 CSS 代码

@tailwind base;
@tailwind components;
@tailwind utilities;

body {
  height: 100vh;
  background-color: rgb(16, 23, 42);
}

pre {
  margin: 1rem;
  padding: 1rem;
  border-radius: 10px;
  background-color: black;
  overflow: auto;
}

h2,
p {
  padding-bottom: 1rem;
  padding-top: 1rem;
}

code {
  margin-bottom: 2rem;
}

运行 npm run dev 命令,导航至 http://localhost:3000/。

使用 CopilotKit 将人工智能功能集成到组件生成器中

在这个部分,在UI组件生成器中添加一个AI copilot,用CopilotKit生成UI组件。

CopilotKit提供了前端和后端两个包。可以让您将React状态连接起来,并使用AI代理在后端处理应用程序数据。

首先,将CopilotKit的React组件添加到博客前端。

将CopilotKit添加到博客前端

将UI组件生成器与CopilotKit前端集成的过程,促进UI组件代码和实现教程的生成。

在 /[root]/src/app/components/CodeTutorial.tsx 文件的顶部导入 useMakeCopilotReadable 和 useCopilotAction自定义钩子。

import {
  useCopilotAction,
  useMakeCopilotReadable,
} from "@copilotkit/react-core";

在 CodeTutorial 函数内部,状态变量下面,使用 useMakeCopilotReadable 钩子(hook)来添加将作为应用内聊天机器人上下文的代码。该钩子使得代码对于copilot易于可读。

useMakeCopilotReadable(codeToDisplay);

使用useCopilotAction钩子来设置一个名为generateCodeAndImplementationTutorial的动作,该动作将启用生成UI组件代码和实现教程的功能。

该动作接收两个参数,code和tutorial,用于生成UI组件代码和实现教程。

该动作包含一个处理函数,该函数根据给定的提示生成UI组件代码和实现教程。

在处理函数内部,codeToDisplay状态被更新为新生成的代码,而codeTutorial状态被更新为新生成的教程,如下所示。

useCopilotAction(
    {
      name: "generateCodeAndImplementationTutorial",
      description:
        "Create Code Snippet with React.js(Next.js), tailwindcss and an implementation tutorial of the code generated.",
      parameters: [
        {
          name: "code",
          type: "string",
          description: "Code to be generated",
          required: true,
        },
        {
          name: "tutorial",
          type: "string",
          description:
            "Markdown of step by step guide tutorial on how to use the generated code accompanied with the code. Include introduction, prerequisites and what happens at every step accompanied with code generated earlier. Don't forget to add how to render the code on browser.",
          required: true,
        },
      ],
      handler: async ({ code, tutorial }) => {
        setCode((prev) => [...prev, code]);
        setCodeToDisplay(code);
        setCodeTutorial(tutorial);
      },
    },
    [codeToDisplay, codeTutorial]
  );

进入/[root]/src/app/page.tsx文件,并在顶部使用以下代码导入CopilotKit前端包和样式。

import { CopilotKit } from "@copilotkit/react-core";
  import { CopilotSidebar } from "@copilotkit/react-ui";
  import "@copilotkit/react-ui/styles.css";

然后,使用CopilotKit来包裹CopilotSidebar和CodeTutorial组件,如下所示。CopilotKit组件指定了CopilotKit后端端点的URL(/api/copilotkit/),而CopilotSidebar渲染了应用内聊天机器人,你可以通过它给出提示来生成UI组件代码和实现教程。

export default function Home() {
  return (
    <>
      <Header />
      <CopilotKit url="/api/copilotkit">
        <CopilotSidebar
          instructions="Help the user generate code. Ask the user if to generate its tutorial."
          defaultOpen={true}
          labels={{
            title: "Code & Tutorial Generator",
            initial: "Hi! 👋 I can help you generate code and its tutorial.",
          }}>
          <CodeTutorial />
        </CopilotSidebar>
      </CopilotKit>
    </>
  );
}

接下来,运行开发服务器并在浏览器中导航到http://localhost:3000。

将CopilotKit后端添加到博客

在这里,完成将UI组件生成器与CopilotKit后端集成,该后端负责处理来自前端的请求,并提供函数调用以及各种大型语言模型(LLM)后端,例如GPT。

此外,将集成一个名为Tavily的AI agent,它能够在网上研究任何主题。

在项目的根目录下创建一个名为.env.local的文件。然后,在文件中添加以下环境变量,这些变量将存储您的ChatGPT和Tavily搜索API密钥。

OPENAI_API_KEY="Your ChatGPT API key"
TAVILY_API_KEY="Your Tavily Search API key"

要获取ChatGPT API密钥,请导航到 https://platform.openai.com/api-keys。

要获取Tavily搜索API密钥,请访问 https://app.tavily.com/home。

之后,前往/[root]/src/app目录并创建一个名为api的文件夹。在api文件夹中,创建一个名为copilotkit的文件夹。

在copilotkit文件夹中,创建一个research.ts文件。然后导航到这个research.ts gist文件,复制代码,并将其添加到research.ts文件中。

接下来,在/[root]/src/app/api/copilotkit文件夹中创建一个route.ts文件。该文件将包含设置后端功能以处理POST请求的代码。它条件性地包含一个“research”动作,该动作对给定主题进行研究。

在文件的顶部导入以下模块:

import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; // For backend functionality with CopilotKit.
import { researchWithLangGraph } from "./research"; // Import a custom function for conducting research.
import { AnnotatedFunction } from "@copilotkit/shared"; // For annotating functions with metadata.

在上述代码下方定义一个运行时环境变量和一个researchAction的函数,该函数使用以下代码研究某个特定主题。

// Define a runtime environment variable, indicating the environment where the code is expected to run.
export const runtime = "edge";

// Define an annotated function for research. This object includes metadata and an implementation for the function.
const researchAction: AnnotatedFunction<any> = {
  name: "research", // Function name.
  description: "Call this function to conduct research on a certain topic. Respect other notes about when to call this function", // Function description.
  argumentAnnotations: [ // Annotations for arguments that the function accepts.
    {
      name: "topic", // Argument name.
      type: "string", // Argument type.
      description: "The topic to research. 5 characters or longer.", // Argument description.
      required: true, // Indicates that the argument is required.
    },
  ],
  implementation: async (topic) => { // The actual function implementation.
    console.log("Researching topic: ", topic); // Log the research topic.
    return await researchWithLangGraph(topic); // Call the research function and return its result.
  },
};

在上述代码下方添加以下代码,定义一个处理POST请求的异步函数。

// Define an asynchronous function that handles POST requests.
export async function POST(req: Request): Promise<Response> {
  const actions: AnnotatedFunction<any>[] = []; // Initialize an array to hold actions.

  // Check if a specific environment variable is set, indicating access to certain functionality.
  if (process.env.TAVILY_API_KEY) {
    actions.push(researchAction); // Add the research action to the actions array if the condition is true.
  }

  // Instantiate CopilotBackend with the actions defined above.
  const copilotKit = new CopilotBackend({
    actions: actions,
  });

  // Use the CopilotBackend instance to generate a response for the incoming request using an OpenAIAdapter.
  return copilotKit.response(req, new OpenAIAdapter());
}

如何生成UI组件

现在请转到您之前集成的应用内聊天机器人,并给它一个提示,例如:“生成一个联系表单”。一旦生成完成,您应该会看到生成的联系表单组件以及其使用教程,如下所示。您还可以使用嵌入式代码编辑器修改生成的代码。

结论

CopilotKit是一个令人惊叹的工具,它允许您在几分钟内将AI副驾驶添加到您的产品中。无论您对AI聊天机器人和助手感兴趣,还是希望自动化复杂任务,CopilotKit都能让这一切变得简单。

如果您需要构建一个AI产品或将其集成到您的软件应用程序中,您应该考虑使用CopilotKit。

  • 25
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Tailwind CSS 中,可以使用 JavaScript 来实现自定义动画。下面是一个使用 Tailwind CSS 和 JavaScript 实现自定义动画的示例步骤: 1. 首先,确保你已经在项目中引入了 Tailwind CSS,并且已经设置好了相关配置。 2. 创建一个包含你自定义动画的 CSS 类。可以在 `tailwind.config.js` 文件中的 `theme` 部分添加你的自定义动画类,例如: ```javascript module.exports = { theme: { extend: { keyframes: { 'bounce': { '0%, 100%': { transform: 'translateY(-25%)', animationTimingFunction: 'cubic-bezier(0.8, 0, 1, 1)', offset: 0 }, '50%': { transform: 'translateY(0)', animationTimingFunction: 'cubic-bezier(0, 0, 0.2, 1)', offset: 0.5 } } }, animation: { 'bounce': 'bounce 1s infinite' } } }, variants: {}, plugins: [] } ``` 这里创建了一个名为 `bounce` 的自定义动画,使用了 `keyframes` 和 `animation` 属性来定义动画效果和持续时间。 3. 在 HTML 元素中应用你的自定义动画类。例如: ```html <div class="animate-bounce">Hello Tailwind CSS</div> ``` 这里使用了 `animate-bounce` 类来应用之前定义的 `bounce` 动画。 4. (可选)如果需要在 JavaScript 中触发动画,可以使用 JavaScript 来添加或移除动画类。例如: ```javascript // 在 JavaScript 中触发动画 const element = document.querySelector('.animate-bounce'); element.classList.add('animate-bounce'); ``` 这样,当你执行这段 JavaScript 代码时,元素将开始应用 `animate-bounce` 类并展示自定义动画效果。 通过上述步骤,你就可以使用 Tailwind CSS 和 JavaScript 实现自定义动画效果了。记得根据你的项目需求进行相应的调整和样式定制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值