Skip to content

Commit

Permalink
feat: lint code
Browse files Browse the repository at this point in the history
  • Loading branch information
iamjoel committed Jun 10, 2023
1 parent 2e46f79 commit cfd0c95
Show file tree
Hide file tree
Showing 36 changed files with 226 additions and 210 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@
],
"react-hooks/exhaustive-deps": "warn"
}
}
}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

# misc
.DS_Store
.vscode
*.pem

# debug
Expand Down
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@
}
}
]
}
}
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@
"i18n/lang",
"app/api/messages"
]
}
}
8 changes: 4 additions & 4 deletions app/api/chat-messages/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { type NextRequest } from 'next/server'
import { getInfo, client } from '@/app/api/utils/common'
import { client, getInfo } from '@/app/api/utils/common'
import { OpenAIStream } from '@/app/api/utils/stream'

export async function POST(request: NextRequest) {
Expand All @@ -8,10 +8,10 @@ export async function POST(request: NextRequest) {
inputs,
query,
conversation_id: conversationId,
response_mode: responseMode
response_mode: responseMode,
} = body
const { user } = getInfo(request);
const { user } = getInfo(request)
const res = await client.createChatMessage(inputs, query, user, responseMode, conversationId)
const stream = await OpenAIStream(res as any)
return new Response(stream as any)
}
}
10 changes: 5 additions & 5 deletions app/api/conversations/route.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { type NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import { getInfo, setSession, client } from '@/app/api/utils/common'
import { client, getInfo, setSession } from '@/app/api/utils/common'

export async function GET(request: NextRequest) {
const { sessionId, user } = getInfo(request);
const { data }: any = await client.getConversations(user);
const { sessionId, user } = getInfo(request)
const { data }: any = await client.getConversations(user)
return NextResponse.json(data, {
headers: setSession(sessionId)
headers: setSession(sessionId),
})
}
}
6 changes: 3 additions & 3 deletions app/api/messages/[messageId]/feedbacks/route.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { type NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import { getInfo, client } from '@/app/api/utils/common'
import { client, getInfo } from '@/app/api/utils/common'

export async function POST(request: NextRequest, { params }: {
params: { messageId: string }
}) {
const body = await request.json()
const {
rating
rating,
} = body
const { messageId } = params
const { user } = getInfo(request);
const { user } = getInfo(request)
const { data } = await client.messageFeedback(messageId, rating, user)
return NextResponse.json(data)
}
12 changes: 6 additions & 6 deletions app/api/messages/route.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { type NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import { getInfo, setSession, client } from '@/app/api/utils/common'
import { client, getInfo, setSession } from '@/app/api/utils/common'

export async function GET(request: NextRequest) {
const { sessionId, user } = getInfo(request);
const { searchParams } = new URL(request.url);
const { sessionId, user } = getInfo(request)
const { searchParams } = new URL(request.url)
const conversationId = searchParams.get('conversation_id')
const { data }: any = await client.getConversationMessages(user, conversationId as string);
const { data }: any = await client.getConversationMessages(user, conversationId as string)
return NextResponse.json(data, {
headers: setSession(sessionId)
headers: setSession(sessionId),
})
}
}
10 changes: 5 additions & 5 deletions app/api/parameters/route.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { type NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import { getInfo, setSession, client } from '@/app/api/utils/common'
import { client, getInfo, setSession } from '@/app/api/utils/common'

export async function GET(request: NextRequest) {
const { sessionId, user } = getInfo(request);
const { data } = await client.getApplicationParameters(user);
const { sessionId, user } = getInfo(request)
const { data } = await client.getApplicationParameters(user)
return NextResponse.json(data as object, {
headers: setSession(sessionId)
headers: setSession(sessionId),
})
}
}
12 changes: 6 additions & 6 deletions app/api/utils/common.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import { type NextRequest } from 'next/server'
import { APP_ID, API_KEY, API_URL } from '@/config'
import { ChatClient } from 'dify-client'
import { v4 } from 'uuid'
import { API_KEY, API_URL, APP_ID } from '@/config'

const userPrefix = `user_${APP_ID}:`;
const userPrefix = `user_${APP_ID}:`

export const getInfo = (request: NextRequest) => {
const sessionId = request.cookies.get('session_id')?.value || v4();
const user = userPrefix + sessionId;
const sessionId = request.cookies.get('session_id')?.value || v4()
const user = userPrefix + sessionId
return {
sessionId,
user
user,
}
}

export const setSession = (sessionId: string) => {
return { 'Set-Cookie': `session_id=${sessionId}` }
}

export const client = new ChatClient(API_KEY, API_URL ? API_URL : undefined)
export const client = new ChatClient(API_KEY, API_URL || undefined)
20 changes: 10 additions & 10 deletions app/api/utils/stream.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
export async function OpenAIStream(res: { body: any }) {
const reader = res.body.getReader();
const reader = res.body.getReader()

const stream = new ReadableStream({
// https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams
// https://github.com/whichlight/chatgpt-api-streaming/blob/master/pages/api/OpenAIStream.ts
start(controller) {
return pump();
return pump()
function pump() {
return reader.read().then(({ done, value }: any) => {
// When no more data needs to be consumed, close the stream
if (done) {
controller.close();
return;
controller.close()
return
}
// Enqueue the next data chunk into our target stream
controller.enqueue(value);
return pump();
});
controller.enqueue(value)
return pump()
})
}
},
});
})

return stream;
}
return stream
}
3 changes: 1 addition & 2 deletions app/components/app-unavailable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@ const AppUnavailable: FC<IAppUnavailableProps> = ({
}) => {
const { t } = useTranslation()
let message = errMessage
if (!errMessage) {
if (!errMessage)
message = (isUnknwonReason ? t('app.common.appUnkonwError') : t('app.common.appUnavailable')) as string
}

return (
<div className='flex items-center justify-center w-screen h-screen'>
Expand Down
1 change: 1 addition & 0 deletions app/components/base/auto-height-textarea/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const AutoHeightTextarea = forwardRef(
{ value, onChange, placeholder, className, minHeight = 36, maxHeight = 96, autoFocus, controlFocus, onKeyDown, onKeyUp }: IProps,
outerRef: any,
) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const ref = outerRef || useRef<HTMLTextAreaElement>(null)

const doFocus = () => {
Expand Down
2 changes: 1 addition & 1 deletion app/components/base/markdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function Markdown(props: { content: string }) {
components={{
code({ node, inline, className, children, ...props }) {
const match = /language-(\w+)/.exec(className || '')
return !inline && match
return (!inline && match)
? (
<SyntaxHighlighter
{...props}
Expand Down
27 changes: 14 additions & 13 deletions app/components/chat/index.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
'use client'
import type { FC, } from 'react'
import type { FC } from 'react'
import React, { useEffect, useRef } from 'react'
import cn from 'classnames'
import { HandThumbDownIcon, HandThumbUpIcon } from '@heroicons/react/24/outline'
import { useTranslation } from 'react-i18next'
import s from './style.module.css'
import LoadingAnim from './loading-anim'
import { randomString } from '@/utils/string'
import type { Feedbacktype, MessageRating } from '@/types/app'
import Tooltip from '@/app/components/base/tooltip'
import Toast from '@/app/components/base/toast'
import AutoHeightTextarea from '@/app/components/base/auto-height-textarea'
import { Markdown } from '@/app/components/base/markdown'
import LoadingAnim from './loading-anim'

export type FeedbackFunc = (messageId: string, feedback: Feedbacktype) => Promise<any>

Expand Down Expand Up @@ -168,8 +168,8 @@ const Answer: FC<IAnswerProps> = ({ item, feedbackDisabled = false, onFeedback,
<div key={id}>
<div className='flex items-start'>
<div className={`${s.answerIcon} w-10 h-10 shrink-0`}>
{isResponsing &&
<div className={s.typeingIcon}>
{isResponsing
&& <div className={s.typeingIcon}>
<LoadingAnim type='avatar' />
</div>
}
Expand All @@ -183,13 +183,15 @@ const Answer: FC<IAnswerProps> = ({ item, feedbackDisabled = false, onFeedback,
<div className='text-xs text-gray-500'>{t('app.chat.openingStatementTitle')}</div>
</div>
)}
{(isResponsing && !content) ? (
<div className='flex items-center justify-center w-6 h-5'>
<LoadingAnim type='text' />
</div>
) : (
<Markdown content={content} />
)}
{(isResponsing && !content)
? (
<div className='flex items-center justify-center w-6 h-5'>
<LoadingAnim type='text' />
</div>
)
: (
<Markdown content={content} />
)}
</div>
<div className='absolute top-[-14px] right-[-14px] flex flex-row justify-end gap-1'>
{!feedbackDisabled && !item.feedbackDisabled && renderItemOperation()}
Expand Down Expand Up @@ -282,9 +284,8 @@ const Chat: FC<IChatProps> = ({
if (e.code === 'Enter') {
e.preventDefault()
// prevent send message when using input method enter
if (!e.shiftKey && !isUseInputMethod.current) {
if (!e.shiftKey && !isUseInputMethod.current)
handleSend()
}
}
}

Expand Down
7 changes: 4 additions & 3 deletions app/components/chat/loading-anim/index.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
'use client'
import React, { FC } from 'react'
import type { FC } from 'react'
import React from 'react'
import s from './style.module.css'

export interface ILoaidingAnimProps {
export type ILoaidingAnimProps = {
type: 'text' | 'avatar'
}

const LoaidingAnim: FC<ILoaidingAnimProps> = ({
type
type,
}) => {
return (
<div className={`${s['dot-flashing']} ${s[type]}`}></div>
Expand Down
15 changes: 7 additions & 8 deletions app/components/index.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-use-before-define */
'use client'
import type { FC } from 'react'
import React, { useEffect, useRef, useState } from 'react'
Expand All @@ -10,15 +11,14 @@ import Sidebar from '@/app/components/sidebar'
import ConfigSence from '@/app/components/config-scence'
import Header from '@/app/components/header'
import { fetchAppParams, fetchChatList, fetchConversations, sendChatMessage, updateFeedback } from '@/service'
import type { ConversationItem, Feedbacktype, IChatItem, PromptConfig, AppInfo } from '@/types/app'
import type { ConversationItem, Feedbacktype, IChatItem, PromptConfig } from '@/types/app'
import Chat from '@/app/components/chat'
import { setLocaleOnClient } from '@/i18n/client'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import Loading from '@/app/components/base/loading'
import { replaceVarWithValues } from '@/utils/prompt'
import { replaceVarWithValues, userInputsFormToPromptVariables } from '@/utils/prompt'
import AppUnavailable from '@/app/components/app-unavailable'
import { APP_ID, API_KEY, APP_INFO, isShowPrompt, promptTemplate } from '@/config'
import { userInputsFormToPromptVariables } from '@/utils/prompt'
import { API_KEY, APP_ID, APP_INFO, isShowPrompt, promptTemplate } from '@/config'

const Main: FC = () => {
const { t } = useTranslation()
Expand All @@ -37,9 +37,8 @@ const Main: FC = () => {
const [isShowSidebar, { setTrue: showSidebar, setFalse: hideSidebar }] = useBoolean(false)

useEffect(() => {
if (APP_INFO?.title) {
if (APP_INFO?.title)
document.title = `${APP_INFO.title} - Powered by Dify`
}
}, [APP_INFO?.title])

/*
Expand Down Expand Up @@ -318,9 +317,9 @@ const Main: FC = () => {
},
async onCompleted() {
setResponsingFalse()
if (!tempNewConversationId) {
if (!tempNewConversationId)
return
}

if (getConversationIdChangeBecauseOfNew()) {
const { data: conversations }: any = await fetchConversations()
setConversationList(conversations as ConversationItem[])
Expand Down
4 changes: 2 additions & 2 deletions app/components/welcome/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useTranslation } from 'react-i18next'
import TemplateVarPanel, { PanelTitle, VarOpBtnGroup } from '../value-panel'
import s from './style.module.css'
import { AppInfoComp, ChatBtn, EditBtn, FootLogo, PromptTemplate } from './massive-component'
import type { PromptConfig, AppInfo } from '@/types/app'
import type { AppInfo, PromptConfig } from '@/types/app'
import Toast from '@/app/components/base/toast'
import Select from '@/app/components/base/select'
import { DEFAULT_VALUE_MAX_LEN } from '@/config'
Expand Down Expand Up @@ -276,7 +276,7 @@ const Welcome: FC<IWelcomeProps> = ({
}

const renderHasSetInputs = () => {
if (!isPublicVersion && !canEidtInpus || !hasVar)
if ((!isPublicVersion && !canEidtInpus) || !hasVar)
return null

return (
Expand Down
14 changes: 7 additions & 7 deletions config/index.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { AppInfo } from "@/types/app"
import type { AppInfo } from '@/types/app'
export const APP_ID = ''
export const API_KEY = ''
export const API_URL = ''
export const APP_INFO: AppInfo = {
"title": 'Chat APP',
"description": '',
"copyright": '',
"privacy_policy": '',
"default_language": 'zh-Hans'
title: 'Chat APP',
description: '',
copyright: '',
privacy_policy: '',
default_language: 'zh-Hans',
}

export const isShowPrompt = false
export const promptTemplate = 'I want you to act as a javascript console.'

export const API_PREFIX = '/api';
export const API_PREFIX = '/api'

export const LOCALE_COOKIE_NAME = 'locale'

Expand Down
Loading

0 comments on commit cfd0c95

Please sign in to comment.