Compare commits

...

10 Commits

Author SHA1 Message Date
6ff7cfe005 Fix bugs for agent/tools. (#9930)
### What problem does this PR solve?
1 Fix typos
2 Fix agent/tools/crawler.py return bug.
3 Fix agent/tools/deepl.py  component_name  bug.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Refactoring
- [x] Performance Improvement

Signed-off-by: zhanluxianshen <zhanluxianshen@163.com>
2025-09-05 12:31:44 +08:00
4e16936fa4 Refactor: Use re compile for weight method (#9929)
### What problem does this PR solve?

Use re compile for the weight method

### Type of change

- [x] Refactoring
- [x] Performance Improvement
2025-09-05 12:29:44 +08:00
677c99b090 Feat: Add metadata filtering function for /api/v1/retrieval (#9877)
-Added the metadata_dedition parameter in the document retrieval
interface to filter document metadata -Updated the API documentation and
added explanations for the metadata_dedition parameter

### What problem does this PR solve?

Make /api/v1/retrieval api also can use metadata filter

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
2025-09-05 11:12:15 +08:00
8e30a75e5c Update .env (#9923)
### What problem does this PR solve?


### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
2025-09-05 10:20:36 +08:00
b14052e5a2 code cleans. (#9916)
### What problem does this PR solve?



### Type of change

- [x] Refactoring
- [x] Performance Improvement

Signed-off-by: zhanluxianshen <zhanluxianshen@163.com>
2025-09-05 09:59:27 +08:00
ddaed541ff Fix S3 client initialization with signature_version and addressing_style (#9911)
### What problem does this PR solve?

Moved `signature_version` and `addressing_style` parameters to a
`Config` object from `botocore.config`
`signature_version` is now passed as `Config(signature_version='v4')`
`addressing_style` is now passed as `Config(s3={'addressing_style':
'path'})`
The `Config` object is then passed to `boto3.client()` via the `config`
parameter



## Changes Made
- Modified `rag/utils/s3_conn.py` in the `__open__()` method
- Updated parameter handling logic to use `config_kwargs` dictionary
- Maintained backward compatibility for configurations without these
parameters



## Related Issue
Fixes #9910


### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)

Co-authored-by: Syed Shahmeer Ali <ashahmeer73@gmail.com>
2025-09-05 09:58:30 +08:00
1ee9c0b8d9 fix xss in excel_parser (#9909)
### What problem does this PR solve?



### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Refactoring
- [x] Performance Improvement

Signed-off-by: zhanluxianshen <zhanluxianshen@163.com>
2025-09-05 09:58:03 +08:00
9b724b3b5e Fix python_version in show_env.sh when its meets python3. (#9894)
### What problem does this PR solve?

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)

Signed-off-by: zhanluxianshen <zhanluxianshen@163.com>
2025-09-05 09:57:39 +08:00
3b1ee769eb fix: Optimize internationalization configuration #3221 (#9924)
### What problem does this PR solve?

fix: Optimize internationalization configuration

- Update multi-language options, adding general translations for
functions like Select All and Clear
- Add internationalization support for modules like Chat, Search, and
Datasets

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
2025-09-05 09:57:15 +08:00
41cb94324a Feat: Added RenameDialog NumberInput and Spin storybook #9914 (#9925)
### What problem does this PR solve?

Feat: Added RenameDialog NumberInput and Spin storybook 

### Type of change


- [x] New Feature (non-breaking change which adds functionality)
2025-09-05 09:57:00 +08:00
70 changed files with 768 additions and 960 deletions

View File

@ -481,7 +481,7 @@ class Canvas(Graph):
except Exception as e:
logging.exception(e)
def add_refernce(self, chunks: list[object], doc_infos: list[object]):
def add_reference(self, chunks: list[object], doc_infos: list[object]):
if not self.retrieval:
self.retrieval = [{"chunks": {}, "doc_aggs": {}}]

View File

@ -166,7 +166,7 @@ class ToolBase(ComponentBase):
"count": 1,
"url": url
})
self._canvas.add_refernce(chunks, aggs)
self._canvas.add_reference(chunks, aggs)
self.set_output("formalized_content", "\n".join(kb_prompt({"chunks": chunks, "doc_aggs": aggs}, 200000, True)))
def thoughts(self) -> str:

View File

@ -64,5 +64,5 @@ class Crawler(ToolBase, ABC):
elif self._param.extract_type == 'markdown':
return result.markdown
elif self._param.extract_type == 'content':
result.extracted_content
return result.extracted_content
return result.markdown

View File

@ -43,7 +43,7 @@ class DeepLParam(ComponentParamBase):
class DeepL(ComponentBase, ABC):
component_name = "GitHub"
component_name = "DeepL"
def _run(self, history, **kwargs):
ans = self.get_input()

View File

@ -163,7 +163,7 @@ class Retrieval(ToolBase, ABC):
self.set_output("formalized_content", self._param.empty_response)
return
self._canvas.add_refernce(kbinfos["chunks"], kbinfos["doc_aggs"])
self._canvas.add_reference(kbinfos["chunks"], kbinfos["doc_aggs"])
form_cnt = "\n".join(kb_prompt(kbinfos, 200000, True))
self.set_output("formalized_content", form_cnt)
return form_cnt

View File

@ -35,6 +35,8 @@ from api.db.services.knowledgebase_service import KnowledgebaseService
from api.db.services.llm_service import LLMBundle
from api.db.services.tenant_llm_service import TenantLLMService
from api.db.services.task_service import TaskService, queue_tasks
from api.db.services.dialog_service import meta_filter
from api.apps.sdk.dify_retrieval import convert_conditions
from api.utils.api_utils import check_duplicate_ids, construct_json_result, get_error_data_result, get_parser_config, get_result, server_error_response, token_required
from rag.app.qa import beAdoc, rmPrefix
from rag.app.tag import label_question
@ -1350,6 +1352,9 @@ def retrieval_test(tenant_id):
highlight:
type: boolean
description: Whether to highlight matched content.
metadata_condition:
type: object
description: metadata filter condition.
- in: header
name: Authorization
type: string
@ -1413,6 +1418,10 @@ def retrieval_test(tenant_id):
for doc_id in doc_ids:
if doc_id not in doc_ids_list:
return get_error_data_result(f"The datasets don't own the document {doc_id}")
if not doc_ids:
metadata_condition = req.get("metadata_condition", {})
metas = DocumentService.get_meta_by_kbs(kb_ids)
doc_ids = meta_filter(metas, convert_conditions(metadata_condition))
similarity_threshold = float(req.get("similarity_threshold", 0.2))
vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
top = int(req.get("top_k", 1024))

View File

@ -124,7 +124,7 @@ class RAGFlowExcelParser:
if c.value is None:
tb += "<td></td>"
else:
tb += f"<td>{c.value}</td>"
tb += f"<td>{escape(_fmt(c.value))}</td>"
tb += "</tr>"
tb += "</table>\n"
tb_chunks.append(tb)

View File

@ -115,7 +115,7 @@ RAGFLOW_IMAGE=infiniflow/ragflow:v0.20.4-slim
# RAGFLOW_IMAGE=registry.cn-hangzhou.aliyuncs.com/infiniflow/ragflow:nightly
# The local time zone.
TIMEZONE='Asia/Shanghai'
TIMEZONE=Asia/Shanghai
# Uncomment the following line if you have limited access to huggingface.co:
# HF_ENDPOINT=https://hf-mirror.com

View File

@ -1808,7 +1808,8 @@ Retrieves chunks from specified datasets.
- `"rerank_id"`: `string`
- `"keyword"`: `boolean`
- `"highlight"`: `boolean`
- `"cross_languages"`: `list[string]`
- `"cross_languages"`: `list[string]`
- `"metadata_condition"`: `object`
##### Request example
@ -1855,7 +1856,8 @@ curl --request POST \
- `false`: Disable highlighting of matched terms (default).
- `"cross_languages"`: (*Body parameter*) `list[string]`
The languages that should be translated into, in order to achieve keywords retrievals in different languages.
- `"metadata_condition"`: (*Body parameter*), `object`
The metadata condition for filtering chunks.
#### Response
Success:

View File

@ -921,7 +921,7 @@ chunk.update({"content":"sdfx..."})
### Retrieve chunks
```python
RAGFlow.retrieve(question:str="", dataset_ids:list[str]=None, document_ids=list[str]=None, page:int=1, page_size:int=30, similarity_threshold:float=0.2, vector_similarity_weight:float=0.3, top_k:int=1024,rerank_id:str=None,keyword:bool=False,highlight:bool=False) -> list[Chunk]
RAGFlow.retrieve(question:str="", dataset_ids:list[str]=None, document_ids=list[str]=None, page:int=1, page_size:int=30, similarity_threshold:float=0.2, vector_similarity_weight:float=0.3, top_k:int=1024,rerank_id:str=None,keyword:bool=False,cross_languages:list[str]=None,metadata_condition: dict=None) -> list[Chunk]
```
Retrieves chunks from specified datasets.
@ -971,17 +971,14 @@ Indicates whether to enable keyword-based matching:
- `True`: Enable keyword-based matching.
- `False`: Disable keyword-based matching (default).
##### highlight: `bool`
Specifies whether to enable highlighting of matched terms in the results:
- `True`: Enable highlighting of matched terms.
- `False`: Disable highlighting of matched terms (default).
##### cross_languages: `list[string]`
The languages that should be translated into, in order to achieve keywords retrievals in different languages.
##### metadata_condition: `dict`
filter condition for meta_fields
#### Returns
- Success: A list of `Chunk` objects representing the document chunks.

View File

@ -36,10 +36,8 @@ try:
updated_dataset = dataset_instance.update(updated_message)
# get the dataset (list datasets)
dataset_list = ragflow_instance.list_datasets(id=dataset_instance.id)
dataset_instance_2 = dataset_list[0]
print(dataset_instance)
print(dataset_instance_2)
print(updated_dataset)
# delete the dataset (delete datasets)
to_be_deleted_datasets = [dataset_instance.id]

View File

@ -21,7 +21,7 @@ class NodeEmbeddings:
embeddings: np.ndarray
def embed_nod2vec(
def embed_node2vec(
graph: nx.Graph | nx.DiGraph,
dimensions: int = 1536,
num_walks: int = 10,
@ -44,13 +44,13 @@ def embed_nod2vec(
return NodeEmbeddings(embeddings=lcc_tensors[0], nodes=lcc_tensors[1])
def run(graph: nx.Graph, args: dict[str, Any]) -> NodeEmbeddings:
def run(graph: nx.Graph, args: dict[str, Any]) -> dict:
"""Run method definition."""
if args.get("use_lcc", True):
graph = stable_largest_connected_component(graph)
# create graph embedding using node2vec
embeddings = embed_nod2vec(
embeddings = embed_node2vec(
graph=graph,
dimensions=args.get("dimensions", 1536),
num_walks=args.get("num_walks", 10),

View File

@ -23,7 +23,7 @@ import trio
from api.utils import get_uuid
from graphrag.query_analyze_prompt import PROMPTS
from graphrag.utils import get_entity_type2sampels, get_llm_cache, set_llm_cache, get_relation
from graphrag.utils import get_entity_type2samples, get_llm_cache, set_llm_cache, get_relation
from rag.utils import num_tokens_from_string, get_float
from rag.utils.doc_store_conn import OrderByExpr
@ -42,7 +42,7 @@ class KGSearch(Dealer):
return response
def query_rewrite(self, llm, question, idxnms, kb_ids):
ty2ents = trio.run(lambda: get_entity_type2sampels(idxnms, kb_ids))
ty2ents = trio.run(lambda: get_entity_type2samples(idxnms, kb_ids))
hint_prompt = PROMPTS["minirag_query2kwd"].format(query=question,
TYPE_POOL=json.dumps(ty2ents, ensure_ascii=False, indent=2))
result = self._chat(llm, hint_prompt, [{"role": "user", "content": "Output:"}], {})

View File

@ -561,7 +561,7 @@ def merge_tuples(list1, list2):
return result
async def get_entity_type2sampels(idxnms, kb_ids: list):
async def get_entity_type2samples(idxnms, kb_ids: list):
es_res = await trio.to_thread.run_sync(lambda: settings.retrievaler.search({"knowledge_graph_kwd": "ty2ents", "kb_id": kb_ids, "size": 10000, "fields": ["content_with_weight"]}, idxnms, kb_ids))
res = defaultdict(list)

View File

@ -160,15 +160,15 @@ class Dealer:
return tks
def weights(self, tks, preprocess=True):
def skill(t):
if t not in self.sk:
return 1
return 6
num_pattern = re.compile(r"[0-9,.]{2,}$")
short_letter_pattern = re.compile(r"[a-z]{1,2}$")
num_space_pattern = re.compile(r"[0-9. -]{2,}$")
letter_pattern = re.compile(r"[a-z. -]+$")
def ner(t):
if re.match(r"[0-9,.]{2,}$", t):
if num_pattern.match(t):
return 2
if re.match(r"[a-z]{1,2}$", t):
if short_letter_pattern.match(t):
return 0.01
if not self.ne or t not in self.ne:
return 1
@ -189,10 +189,10 @@ class Dealer:
return 1
def freq(t):
if re.match(r"[0-9. -]{2,}$", t):
if num_space_pattern.match(t):
return 3
s = rag_tokenizer.freq(t)
if not s and re.match(r"[a-z. -]+$", t):
if not s and letter_pattern.match(t):
return 300
if not s:
s = 0
@ -207,11 +207,11 @@ class Dealer:
return max(s, 10)
def df(t):
if re.match(r"[0-9. -]{2,}$", t):
if num_space_pattern.match(t):
return 5
if t in self.df:
return self.df[t] + 3
elif re.match(r"[a-z. -]+$", t):
elif letter_pattern.match(t):
return 300
elif len(t) >= 4:
s = [tt for tt in rag_tokenizer.fine_grained_tokenize(t).split() if len(tt) > 1]

View File

@ -80,10 +80,13 @@ class RAGFlowS3:
s3_params['region_name'] = self.region_name
if self.endpoint_url:
s3_params['endpoint_url'] = self.endpoint_url
# Configure signature_version and addressing_style through Config object
if self.signature_version:
s3_params['signature_version'] = self.signature_version
config_kwargs['signature_version'] = self.signature_version
if self.addressing_style:
s3_params['addressing_style'] = self.addressing_style
config_kwargs['s3'] = {'addressing_style': self.addressing_style}
if config_kwargs:
s3_params['config'] = Config(**config_kwargs)

View File

@ -197,7 +197,8 @@ class RAGFlow:
top_k=1024,
rerank_id: str | None = None,
keyword: bool = False,
cross_languages: list[str]|None = None
cross_languages: list[str]|None = None,
metadata_condition: dict | None = None,
):
if document_ids is None:
document_ids = []
@ -212,7 +213,8 @@ class RAGFlow:
"question": question,
"dataset_ids": dataset_ids,
"document_ids": document_ids,
"cross_languages": cross_languages
"cross_languages": cross_languages,
"metadata_condition": metadata_condition
}
# Send a POST request to the backend service (using requests library as an example, actual implementation may vary)
res = self.post("/retrieval", json=data_json)

View File

@ -41,12 +41,7 @@ else
fi
# get python version
python_version=''
if command -v python &> /dev/null; then
python_version=$(python --version | cut -d ' ' -f2)
else
python_version="Python not installed"
fi
python_version=$(python3 --version 2>&1 || python --version 2>&1 || echo "Python not installed")
# Print all information
echo "Current Repository: $git_repo_name"

View File

@ -1,3 +1,4 @@
import '@/locales/config';
import type { Preview } from '@storybook/react-webpack5';
import { createElement } from 'react';
import { TooltipProvider } from '../src/components/ui/tooltip';

View File

@ -1,48 +0,0 @@
import isObject from 'lodash/isObject';
import { DvaModel } from 'umi';
import { BaseState } from './interfaces/common';
type State = Record<string, any>;
type DvaModelKey<T> = keyof DvaModel<T>;
export const modelExtend = <T>(
baseModel: Partial<DvaModel<any>>,
extendModel: DvaModel<any>,
): DvaModel<T> => {
return Object.keys(extendModel).reduce<DvaModel<T>>((pre, cur) => {
const baseValue = baseModel[cur as DvaModelKey<State>];
const value = extendModel[cur as DvaModelKey<State>];
if (isObject(value) && isObject(baseValue) && typeof value !== 'string') {
const key = cur as Exclude<DvaModelKey<State>, 'namespace'>;
pre[key] = {
...baseValue,
...value,
} as any;
} else {
pre[cur as DvaModelKey<State>] = value as any;
}
return pre;
}, {} as DvaModel<T>);
};
export const paginationModel: Partial<DvaModel<BaseState>> = {
state: {
searchString: '',
pagination: {
total: 0,
current: 1,
pageSize: 10,
},
},
reducers: {
setSearchString(state, { payload }) {
return { ...state, searchString: payload };
},
setPagination(state, { payload }) {
return { ...state, pagination: { ...state.pagination, ...payload } };
},
},
};

View File

@ -6,6 +6,8 @@ import {
} from '@/components/ui/form';
import { MultiSelect } from '@/components/ui/multi-select';
import { cn } from '@/lib/utils';
import { t } from 'i18next';
import { toLower } from 'lodash';
import { useFormContext } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
@ -20,7 +22,10 @@ const Languages = [
'Vietnamese',
];
const options = Languages.map((x) => ({ label: x, value: x }));
const options = Languages.map((x) => ({
label: t('language.' + toLower(x)),
value: x,
}));
type CrossLanguageItemProps = {
name?: string;

View File

@ -52,6 +52,7 @@ export function DelimiterFormField() {
<FormItem className=" items-center space-y-0 ">
<div className="flex items-center gap-1">
<FormLabel
required
tooltip={t('knowledgeDetails.delimiterTip')}
className="text-sm text-muted-foreground whitespace-break-spaces w-1/4"
>

View File

@ -18,6 +18,7 @@ import { TreeData } from '@antv/g6/lib/types';
import isEmpty from 'lodash/isEmpty';
import React, { useCallback, useEffect, useRef } from 'react';
import { ErrorBoundary, FallbackProps } from 'react-error-boundary';
import { useIsDarkTheme } from '../theme-provider';
const rootId = 'root';
@ -322,7 +323,7 @@ const IndentedTree = ({ data, show, style = {} }: IProps) => {
node.children.forEach((child, idx) => assignIds(child, node.id, idx));
}
}, []);
const isDark = useIsDarkTheme();
const render = useCallback(
async (data: TreeData) => {
const graph: Graph = new Graph({
@ -335,7 +336,8 @@ const IndentedTree = ({ data, show, style = {} }: IProps) => {
labelBackground: (datum) => datum.id === rootId,
labelBackgroundRadius: 0,
labelBackgroundFill: '#576286',
labelFill: (datum) => (datum.id === rootId ? '#fff' : '#666'),
labelFill: isDark ? '#fff' : '#333',
// labelFill: (datum) => (datum.id === rootId ? '#fff' : '#666'),
labelText: (d) => d.style?.labelText || d.id,
labelTextAlign: (datum) =>
datum.id === rootId ? 'center' : 'left',

View File

@ -134,7 +134,9 @@ export function KnowledgeBaseFormField({
name="kb_ids"
render={({ field }) => (
<FormItem>
<FormLabel>{t('chat.knowledgeBases')}</FormLabel>
<FormLabel tooltip={t('chat.knowledgeBasesTip')}>
{t('chat.knowledgeBases')}
</FormLabel>
<FormControl>
<MultiSelect
options={options}

View File

@ -18,6 +18,7 @@ import {
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { t } from 'i18next';
import { FilterChange, FilterCollection, FilterValue } from './interface';
export type CheckboxFormMultipleProps = {
@ -134,10 +135,10 @@ function CheckboxFormMultiple({
size={'sm'}
onClick={onReset}
>
Clear
{t('common.clear')}
</Button>
<Button type="submit" size={'sm'}>
Submit
{t('common.submit')}
</Button>
</div>
</form>

View File

@ -14,6 +14,7 @@ export function MaxTokenNumberFormField({ max = 2048, initialValue }: IProps) {
<SliderInputFormField
name={'parser_config.chunk_token_num'}
label={t('chunkTokenNumber')}
tooltip={t('chunkTokenNumberTip')}
max={max}
defaultValue={initialValue ?? 0}
layout={FormLayout.Horizontal}

View File

@ -15,6 +15,7 @@ import {
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { cn } from '@/lib/utils';
import { t } from 'i18next';
import { CircleStop, Paperclip, Send, Upload, X } from 'lucide-react';
import * as React from 'react';
import { toast } from 'sonner';
@ -141,7 +142,7 @@ export function NextMessageInput({
<Textarea
value={value}
onChange={onInputChange}
placeholder="Type your message here..."
placeholder={t('chat.messagePlaceholder')}
className="field-sizing-content min-h-10 w-full resize-none border-0 bg-transparent p-0 shadow-none focus-visible:ring-0 dark:bg-transparent"
disabled={isUploading || disabled || sendLoading}
onKeyDown={handleKeyDown}

View File

@ -95,7 +95,9 @@ const RaptorFormFields = () => {
tooltip={t('useRaptorTip')}
className="text-sm text-muted-foreground w-1/4 whitespace-break-spaces"
>
{t('useRaptor')}
<div className="w-auto xl:w-20 2xl:w-24 3xl:w-28 4xl:w-auto ">
{t('useRaptor')}
</div>
</FormLabel>
<div className="w-3/4">
<FormControl>

View File

@ -94,8 +94,9 @@ const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & {
tooltip?: React.ReactNode;
required?: boolean;
}
>(({ className, tooltip, ...props }, ref) => {
>(({ className, tooltip, required = false, ...props }, ref) => {
const { error, formItemId } = useFormField();
return (
@ -105,6 +106,7 @@ const FormLabel = React.forwardRef<
htmlFor={formItemId}
{...props}
>
{required && <span className="text-destructive">*</span>}
{props.children}
{tooltip && <FormTooltip tooltip={tooltip}></FormTooltip>}
</Label>

View File

@ -29,6 +29,7 @@ import {
} from '@/components/ui/popover';
import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';
import { t } from 'i18next';
import { isEmpty } from 'lodash';
export type MultiSelectOptionType = {
@ -193,7 +194,7 @@ export const MultiSelect = React.forwardRef<
onValueChange,
variant,
defaultValue = [],
placeholder = 'Select options',
placeholder = t('common.selectPlaceholder'),
animation = 0,
maxCount = 3,
modalPopover = false,
@ -379,7 +380,7 @@ export const MultiSelect = React.forwardRef<
>
<Command>
<CommandInput
placeholder="Search..."
placeholder={t('common.search') + '...'}
onKeyDown={handleInputKeyDown}
/>
<CommandList>
@ -401,7 +402,7 @@ export const MultiSelect = React.forwardRef<
>
<CheckIcon className="h-4 w-4" />
</div>
<span>(Select All)</span>
<span>({t('common.selectAll')})</span>
</CommandItem>
)}
{!options.some((x) => 'options' in x) &&
@ -457,7 +458,7 @@ export const MultiSelect = React.forwardRef<
onSelect={() => setIsPopoverOpen(false)}
className="flex-1 justify-center cursor-pointer max-w-full"
>
Close
{t('common.close')}
</CommandItem>
</div>
</CommandGroup>

View File

@ -3,6 +3,7 @@ export default {
common: {
noResults: 'No results.',
selectPlaceholder: 'select value',
selectAll: 'Select All',
delete: 'Delete',
deleteModalTitle: 'Are you sure to delete this item?',
ok: 'Yes',
@ -37,6 +38,7 @@ export default {
pleaseSelect: 'Please select',
pleaseInput: 'Please input',
submit: 'Submit',
clear: 'Clear',
embedIntoSite: 'Embed into webpage',
previousPage: 'Previous',
nextPage: 'Next',
@ -145,7 +147,8 @@ export default {
vectorSimilarityWeightTip:
'This sets the weight of keyword similarity in the combined similarity score, either used with vector cosine similarity or with reranking score. The total of the two weights must equal 1.0.',
keywordSimilarityWeight: 'Keyword similarity weight',
keywordSimilarityWeightTip: '',
keywordSimilarityWeightTip:
'This sets the weight of keyword similarity in the combined similarity score, either used with vector cosine similarity or with reranking score. The total of the two weights must equal 1.0.',
testText: 'Test text',
testTextPlaceholder: 'Input your question here!',
testingLabel: 'Testing',
@ -441,6 +444,12 @@ This auto-tagging feature enhances retrieval by adding another layer of domain-s
delete: 'Delete',
},
chat: {
messagePlaceholder: 'Type your message here...',
exit: 'Exit',
multipleModels: 'Multiple Models',
applyModelConfigs: 'Apply model configs',
conversations: 'Conversations',
chatApps: 'Chat Apps',
newConversation: 'New conversation',
createAssistant: 'Create an Assistant',
assistantSetting: 'Assistant settings',
@ -839,6 +848,7 @@ This auto-tagging feature enhances retrieval by adding another layer of domain-s
hint: 'hint',
},
fileManager: {
files: 'Files',
name: 'Name',
uploadDate: 'Upload Date',
knowledgeBase: 'Dataset',
@ -864,6 +874,12 @@ This auto-tagging feature enhances retrieval by adding another layer of domain-s
pleaseUploadAtLeastOneFile: 'Please upload at least one file',
},
flow: {
recommended: 'Recommended',
customerSupport: 'Customer Support',
marketing: 'Marketing',
consumerApp: 'Consumer App',
other: 'Other',
agents: 'Agents',
days: 'Days',
beginInput: 'Begin Input',
ref: 'Variable',
@ -1527,6 +1543,7 @@ This delimiter is used to split the input text into several text pieces echo of
editMCP: 'Edit MCP',
},
search: {
searchApps: 'Search Apps',
createSearch: 'Create Search',
searchGreeting: 'How can I help you today ',
profile: 'Hide Profile',
@ -1551,5 +1568,15 @@ This delimiter is used to split the input text into several text pieces echo of
okText: 'Save',
cancelText: 'Cancel',
},
language: {
english: 'English',
chinese: 'Chinese',
spanish: 'Spanish',
french: 'French',
german: 'German',
japanese: 'Japanese',
korean: 'Korean',
vietnamese: 'Vietnamese',
},
},
};

View File

@ -3,6 +3,7 @@ export default {
common: {
noResults: '无结果。',
selectPlaceholder: '请选择',
selectAll: '全选',
delete: '删除',
deleteModalTitle: '确定删除吗?',
ok: '是',
@ -36,6 +37,7 @@ export default {
pleaseSelect: '请选择',
pleaseInput: '请输入',
submit: '提交',
clear: '清空',
embedIntoSite: '嵌入网站',
previousPage: '上一页',
nextPage: '下一页',
@ -105,7 +107,7 @@ export default {
testing: '检索测试',
configuration: '配置',
knowledgeGraph: '知识图谱',
files: '文件',
files: '文件',
name: '名称',
namePlaceholder: '请输入名称',
doc: '文档',
@ -136,7 +138,8 @@ export default {
vectorSimilarityWeightTip:
'我们使用混合相似性评分来评估两行文本之间的距离。它是加权关键字相似性和矢量余弦相似性或rerank得分0〜1。两个权重的总和为1.0。',
keywordSimilarityWeight: '关键词相似度权重',
keywordSimilarityWeightTip: '',
keywordSimilarityWeightTip:
'我们使用混合相似性评分来评估两行文本之间的距离。它是加权关键字相似性和矢量余弦相似性或rerank得分0〜1。两个权重的总和为1.0。',
testText: '测试文本',
testTextPlaceholder: '请输入您的问题!',
testingLabel: '测试',
@ -440,6 +443,12 @@ General实体和关系提取提示来自 GitHub - microsoft/graphrag基于
delete: '删除',
},
chat: {
messagePlaceholder: '请输入消息...',
exit: '退出',
multipleModels: '多模型',
applyModelConfigs: '应用模型配置',
conversations: '会话',
chatApps: '聊天',
createChat: '创建聊天',
newConversation: '新会话',
createAssistant: '新建助理',
@ -798,6 +807,7 @@ General实体和关系提取提示来自 GitHub - microsoft/graphrag基于
hint: '提示',
},
fileManager: {
files: '文件',
name: '名称',
uploadDate: '上传日期',
knowledgeBase: '知识库',
@ -822,6 +832,12 @@ General实体和关系提取提示来自 GitHub - microsoft/graphrag基于
pleaseUploadAtLeastOneFile: '请上传至少一个文件',
},
flow: {
recommended: '推荐',
customerSupport: '客户支持',
marketing: '营销',
consumerApp: '消费者应用',
other: '其他',
agents: '智能体',
beginInput: '开始输入',
seconds: '秒',
ref: '引用变量',
@ -1441,6 +1457,7 @@ General实体和关系提取提示来自 GitHub - microsoft/graphrag基于
cancelText: '取消',
},
search: {
searchApps: '搜索',
createSearch: '创建查询',
searchGreeting: '今天我能为你做些什么?',
profile: '隐藏个人资料',
@ -1465,5 +1482,15 @@ General实体和关系提取提示来自 GitHub - microsoft/graphrag基于
okText: '保存',
cancelText: '返回',
},
language: {
english: '英语',
chinese: '中文',
spanish: '西班牙语',
french: '法语',
german: '德语',
japanese: '日语',
korean: '韩语',
vietnamese: '越南语',
},
},
};

View File

@ -114,7 +114,7 @@ export default function Agent() {
<BreadcrumbList>
<BreadcrumbItem>
<BreadcrumbLink onClick={navigateToAgents}>
Agent
{t('header.flow')}
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />

View File

@ -36,7 +36,7 @@ export default function Agents() {
<section className="flex flex-col w-full flex-1">
<div className="px-8 pt-8 ">
<ListFilterBar
title="Agents"
title={t('flow.agents')}
searchString={searchString}
onSearchChange={handleInputChange}
icon="agent"

View File

@ -1,5 +1,7 @@
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { t } from 'i18next';
import { lowerFirst } from 'lodash';
import {
Box,
ChartPie,
@ -23,26 +25,38 @@ const menuItems = [
items: [
{
icon: Sparkle,
label: MenuItemKey.Recommended,
label: t('flow.' + lowerFirst(MenuItemKey.Recommended)),
key: MenuItemKey.Recommended,
},
{ icon: Box, label: MenuItemKey.Agent, key: MenuItemKey.Agent },
{
icon: Box,
label: t('flow.' + lowerFirst(MenuItemKey.Agent)),
key: MenuItemKey.Agent,
},
{
icon: MessageCircleCode,
label: MenuItemKey.CustomerSupport,
label: t(
'flow.' + lowerFirst(MenuItemKey.CustomerSupport).replace(' ', ''),
),
key: MenuItemKey.CustomerSupport,
},
{
icon: ChartPie,
label: MenuItemKey.Marketing,
label: t('flow.' + lowerFirst(MenuItemKey.Marketing)),
key: MenuItemKey.Marketing,
},
{
icon: Component,
label: MenuItemKey.ConsumerApp,
label: t(
'flow.' + lowerFirst(MenuItemKey.ConsumerApp.replace(' ', '')),
),
key: MenuItemKey.ConsumerApp,
},
{ icon: PencilRuler, label: MenuItemKey.Other, key: MenuItemKey.Other },
{
icon: PencilRuler,
label: t('flow.' + lowerFirst(MenuItemKey.Other)),
key: MenuItemKey.Other,
},
],
},
];

View File

@ -140,11 +140,11 @@ const ChunkCreatingModal: React.FC<IModalProps<any> & kFProps> = ({
render={({ field }) => (
<FormItem>
<FormLabel className="flex justify-start items-start">
<div className="flex items-center gap-0">
<div className="flex items-center gap-1">
<span>{t('chunk.question')}</span>
<HoverCard>
<HoverCardTrigger asChild>
<span className="text-xs mt-[-3px] text-center scale-[90%] font-thin text-primary cursor-pointer rounded-full w-[16px] h-[16px] border-muted-foreground/50 border">
<span className="text-xs mt-[0px] text-center scale-[90%] text-text-secondary cursor-pointer rounded-full w-[17px] h-[17px] border-text-secondary border-2">
?
</span>
</HoverCardTrigger>

View File

@ -95,7 +95,10 @@ export default ({
</PopoverContent>
</Popover>
<div className="w-[20px]"></div>
<Button onClick={() => createChunk()} className="bg-bg-card text-primary">
<Button
onClick={() => createChunk()}
className="bg-bg-card text-primary hover:bg-card"
>
<Plus size={44} />
</Button>
</div>

View File

@ -28,6 +28,7 @@ export function ChunkMethodItem() {
<FormItem className=" items-center space-y-0 ">
<div className="flex items-center">
<FormLabel
required
tooltip={t('chunkMethodTip')}
className="text-sm text-muted-foreground whitespace-wrap w-1/4"
>
@ -68,6 +69,7 @@ export function EmbeddingModelItem() {
<FormItem className=" items-center space-y-0 ">
<div className="flex items-center">
<FormLabel
required
tooltip={t('embeddingModelTip')}
className="text-sm text-muted-foreground whitespace-wrap w-1/4"
>

View File

@ -16,4 +16,5 @@ export const ImageMap = {
table: getImageName('table', 2),
one: getImageName('one', 2),
knowledge_graph: getImageName('knowledge-graph', 2),
tag: getImageName('tag', 2),
};

View File

@ -83,7 +83,7 @@ export default function TestingForm({
<FormContainer className="p-10">
<SimilaritySliderFormField
vectorSimilarityWeightName="keywords_similarity_weight"
isTooltipShown
isTooltipShown={true}
></SimilaritySliderFormField>
<RerankFormFields></RerankFormFields>
<UseKnowledgeGraphFormField name="use_kg"></UseKnowledgeGraphFormField>

View File

@ -4,6 +4,7 @@ import { SharedBadge } from '@/components/shared-badge';
import { Card, CardContent } from '@/components/ui/card';
import { useNavigatePage } from '@/hooks/logic-hooks/navigate-hooks';
import { IKnowledge } from '@/interfaces/database/knowledge';
import { t } from 'i18next';
import { ChevronRight } from 'lucide-react';
import { DatasetDropdown } from './dataset-dropdown';
import { useRenameDataset } from './use-rename-dataset';
@ -20,7 +21,10 @@ export function DatasetCard({
return (
<HomeCard
data={{ ...dataset, description: `${dataset.doc_num} files` }}
data={{
...dataset,
description: `${dataset.doc_num} ${t('knowledgeDetails.files')}`,
}}
moreDropdown={
<DatasetDropdown
showDatasetRenameModal={showDatasetRenameModal}

View File

@ -55,7 +55,7 @@ export default function Datasets() {
return (
<section className="py-4 flex-1 flex flex-col">
<ListFilterBar
title={t('header.knowledgeBase')}
title={t('header.dataset')}
searchString={searchString}
onSearchChange={handleInputChange}
value={filterValue}

View File

@ -78,7 +78,11 @@ export default function Files() {
const leftPanel = (
<div>
{breadcrumbItems.length > 0 ? <FileBreadcrumb></FileBreadcrumb> : 'File'}
{breadcrumbItems.length > 0 ? (
<FileBreadcrumb></FileBreadcrumb>
) : (
t('fileManager.files')
)}
</div>
);

View File

@ -26,8 +26,8 @@ export function Applications() {
const options = useMemo(
() => [
{ value: Routes.Chats, label: t('header.chat') },
{ value: Routes.Searches, label: t('header.search') },
{ value: Routes.Chats, label: t('chat.chatApps') },
{ value: Routes.Searches, label: t('search.searchApps') },
{ value: Routes.Agents, label: t('header.flow') },
],
[t],

View File

@ -22,7 +22,7 @@ export function Datasets() {
<section>
<h2 className="text-2xl font-bold mb-6 flex gap-2.5 items-center">
<IconFont name="data" className="size-8"></IconFont>
{t('header.knowledgeBase')}
{t('header.dataset')}
</h2>
<div className="flex gap-6">
{loading ? (

View File

@ -43,7 +43,7 @@ export default function ChatBasicSetting() {
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>{t('assistantName')}</FormLabel>
<FormLabel required>{t('assistantName')}</FormLabel>
<FormControl>
<Input {...field}></Input>
</FormControl>
@ -69,7 +69,9 @@ export default function ChatBasicSetting() {
name={'prompt_config.empty_response'}
render={({ field }) => (
<FormItem>
<FormLabel>{t('emptyResponse')}</FormLabel>
<FormLabel tooltip={t('emptyResponseTip')}>
{t('emptyResponse')}
</FormLabel>
<FormControl>
<Textarea {...field}></Textarea>
</FormControl>
@ -82,7 +84,9 @@ export default function ChatBasicSetting() {
name={'prompt_config.prologue'}
render={({ field }) => (
<FormItem>
<FormLabel>{t('setAnOpener')}</FormLabel>
<FormLabel tooltip={t('setAnOpenerTip')}>
{t('setAnOpener')}
</FormLabel>
<FormControl>
<Textarea {...field}></Textarea>
</FormControl>
@ -93,14 +97,17 @@ export default function ChatBasicSetting() {
<SwitchFormField
name={'prompt_config.quote'}
label={t('quote')}
tooltip={t('quoteTip')}
></SwitchFormField>
<SwitchFormField
name={'prompt_config.keyword'}
label={t('keyword')}
tooltip={t('keywordTip')}
></SwitchFormField>
<SwitchFormField
name={'prompt_config.tts'}
label={t('tts')}
tooltip={t('ttsTip')}
></SwitchFormField>
<TavilyFormField></TavilyFormField>
<KnowledgeBaseFormField></KnowledgeBaseFormField>

View File

@ -37,11 +37,12 @@ export function ChatPromptEngine() {
</FormItem>
)}
/>
<SimilaritySliderFormField></SimilaritySliderFormField>
<SimilaritySliderFormField isTooltipShown></SimilaritySliderFormField>
<TopNFormField></TopNFormField>
<SwitchFormField
name={'prompt_config.refine_multiturn'}
label={t('multiTurn')}
tooltip={t('multiTurnTip')}
></SwitchFormField>
<UseKnowledgeGraphFormField name="prompt_config.use_kg"></UseKnowledgeGraphFormField>
<SwitchFormField

View File

@ -23,6 +23,7 @@ import {
import { useFetchUserInfo } from '@/hooks/user-setting-hooks';
import { buildMessageUuidWithRole } from '@/utils/chat';
import { zodResolver } from '@hookform/resolvers/zod';
import { t } from 'i18next';
import { isEmpty, omit } from 'lodash';
import { ListCheck, Plus, Trash2 } from 'lucide-react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
@ -139,7 +140,7 @@ const ChatCard = forwardRef(function ChatCard(
</Button>
</TooltipTrigger>
<TooltipContent>
<p>Apply model configs</p>
<p>{t('chat.applyModelConfigs')}</p>
</TooltipContent>
</Tooltip>
{!isLatestChat || chatBoxIds.length === 3 ? (

View File

@ -63,10 +63,10 @@ export default function Chat() {
<section className="pt-14 h-[100vh] pb-24">
<div className="flex items-center justify-between px-10 pb-5">
<span className="text-2xl">
Multiple Models ({chatBoxIds.length}/3)
{t('chat.multipleModels')} ({chatBoxIds.length}/3)
</span>
<Button variant={'ghost'} onClick={switchDebugMode}>
Exit <LogOut />
{t('chat.exit')} <LogOut />
</Button>
</div>
<MultipleChatBox
@ -124,7 +124,7 @@ export default function Chat() {
isNew === 'true'
}
>
<ArrowUpRight /> Multiple Models
<ArrowUpRight /> {t('chat.multipleModels')}
</Button>
</CardTitle>
</CardHeader>

View File

@ -71,7 +71,7 @@ export function Sessions({
</section>
<div className="flex justify-between items-center mb-4 pt-10">
<div className="flex items-center gap-3">
<span className="text-base font-bold">Conversations</span>
<span className="text-base font-bold">{t('chat.conversations')}</span>
<span className="text-text-secondary text-xs">
{conversationList.length}
</span>

View File

@ -38,7 +38,7 @@ export default function ChatList() {
<section className="flex flex-col w-full flex-1">
<div className="px-8 pt-8">
<ListFilterBar
title="Chat apps"
title={t('chat.chatApps')}
icon="chat"
onSearchChange={handleInputChange}
searchString={searchString}

View File

@ -62,7 +62,7 @@ export default function SearchPage() {
<BreadcrumbList>
<BreadcrumbItem>
<BreadcrumbLink onClick={navigateToSearchList}>
Search
{t('header.search')}
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />

View File

@ -397,7 +397,11 @@ const SearchSetting: React.FC<SearchSettingProps> = ({
name="search_config.similarity_threshold"
render={({ field }) => (
<FormItem>
<FormLabel>Similarity Threshold</FormLabel>
<FormLabel
tooltip={t('knowledgeDetails.similarityThresholdTip')}
>
{t('knowledgeDetails.similarityThreshold')}
</FormLabel>
<div
className={cn(
'flex items-center gap-4 justify-between',
@ -433,9 +437,11 @@ const SearchSetting: React.FC<SearchSettingProps> = ({
name="search_config.vector_similarity_weight"
render={({ field }) => (
<FormItem>
<FormLabel>
<span className="text-destructive mr-1"> *</span>Vector
Similarity Weight
<FormLabel
tooltip={t('knowledgeDetails.vectorSimilarityWeightTip')}
>
<span className="text-destructive mr-1"> *</span>
{t('knowledgeDetails.vectorSimilarityWeight')}
</FormLabel>
<div
className={cn(

View File

@ -239,7 +239,7 @@ export default function SearchingView({
searchData.search_config.related_search && (
<div className="mt-14 w-full overflow-hidden opacity-100 max-h-96">
<p className="text-text-primary mb-2 text-xl">
{t('relatedSearch')}
{t('search.relatedSearch')}
</p>
<div className="mt-2 flex flex-wrap justify-start gap-2">
{relatedQuestions?.map((x, idx) => (

View File

@ -49,7 +49,7 @@ export default function SearchList() {
<div className="px-8 pt-8">
<ListFilterBar
icon="search"
title="Search apps"
title={t('searchApps')}
showFilter={false}
onSearchChange={(e) => handleSearchChange(e.target.value)}
>

View File

@ -41,7 +41,6 @@ function MyComponent() {
\`\`\`
### Features
- Supports image upload with drag & drop
- Image preview with hover effects
- Remove button to clear selected image
- Base64 encoding for easy handling

View File

@ -1,30 +0,0 @@
.storybook-button {
display: inline-block;
cursor: pointer;
border: 0;
border-radius: 3em;
font-weight: 700;
line-height: 1;
font-family: 'Nunito Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.storybook-button--primary {
background-color: #555ab9;
color: white;
}
.storybook-button--secondary {
box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 0px 1px inset;
background-color: transparent;
color: #333;
}
.storybook-button--small {
padding: 10px 16px;
font-size: 12px;
}
.storybook-button--medium {
padding: 11px 20px;
font-size: 14px;
}
.storybook-button--large {
padding: 12px 24px;
font-size: 16px;
}

View File

@ -1,54 +0,0 @@
import type { Meta, StoryObj } from '@storybook/react-webpack5';
import { fn } from 'storybook/test';
import { Button } from './button';
// More on how to set up stories at: https://storybook.js.org/docs/writing-stories#default-export
const meta = {
title: 'Example/Button',
component: Button,
parameters: {
// Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
layout: 'centered',
},
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {
backgroundColor: { control: 'color' },
},
// Use `fn` to spy on the onClick arg, which will appear in the actions panel once invoked: https://storybook.js.org/docs/essentials/actions#action-args
args: { onClick: fn() },
} satisfies Meta<typeof Button>;
export default meta;
type Story = StoryObj<typeof meta>;
// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const Primary: Story = {
args: {
primary: true,
label: 'Button',
},
};
export const Secondary: Story = {
args: {
label: 'Button',
},
};
export const Large: Story = {
args: {
size: 'large',
label: 'Button',
},
};
export const Small: Story = {
args: {
size: 'small',
label: 'Button',
},
};

View File

@ -1,39 +0,0 @@
import './button.css';
export interface ButtonProps {
/** Is this the principal call to action on the page? */
primary?: boolean;
/** What background color to use */
backgroundColor?: string;
/** How large should the button be? */
size?: 'small' | 'medium' | 'large';
/** Button contents */
label: string;
/** Optional click handler */
onClick?: () => void;
}
/** Primary UI component for user interaction */
export const Button = ({
primary = false,
size = 'medium',
backgroundColor,
label,
...props
}: ButtonProps) => {
const mode = primary
? 'storybook-button--primary'
: 'storybook-button--secondary';
return (
<button
type="button"
className={['storybook-button', `storybook-button--${size}`, mode].join(
' ',
)}
style={{ backgroundColor }}
{...props}
>
{label}
</button>
);
};

View File

@ -1,364 +0,0 @@
import { Meta } from "@storybook/addon-docs/blocks";
import Github from "./assets/github.svg";
import Discord from "./assets/discord.svg";
import Youtube from "./assets/youtube.svg";
import Tutorials from "./assets/tutorials.svg";
import Styling from "./assets/styling.png";
import Context from "./assets/context.png";
import Assets from "./assets/assets.png";
import Docs from "./assets/docs.png";
import Share from "./assets/share.png";
import FigmaPlugin from "./assets/figma-plugin.png";
import Testing from "./assets/testing.png";
import Accessibility from "./assets/accessibility.png";
import Theming from "./assets/theming.png";
import AddonLibrary from "./assets/addon-library.png";
export const RightArrow = () => <svg
viewBox="0 0 14 14"
width="8px"
height="14px"
style={{
marginLeft: '4px',
display: 'inline-block',
shapeRendering: 'inherit',
verticalAlign: 'middle',
fill: 'currentColor',
'path fill': 'currentColor'
}}
>
<path d="m11.1 7.35-5.5 5.5a.5.5 0 0 1-.7-.7L10.04 7 4.9 1.85a.5.5 0 1 1 .7-.7l5.5 5.5c.2.2.2.5 0 .7Z" />
</svg>
<Meta title="Configure your project" />
<div className="sb-container">
<div className='sb-section-title'>
# Configure your project
Because Storybook works separately from your app, you'll need to configure it for your specific stack and setup. Below, explore guides for configuring Storybook with popular frameworks and tools. If you get stuck, learn how you can ask for help from our community.
</div>
<div className="sb-section">
<div className="sb-section-item">
<img
src={Styling}
alt="A wall of logos representing different styling technologies"
/>
<h4 className="sb-section-item-heading">Add styling and CSS</h4>
<p className="sb-section-item-paragraph">Like with web applications, there are many ways to include CSS within Storybook. Learn more about setting up styling within Storybook.</p>
<a
href="https://storybook.js.org/docs/configure/styling-and-css/?renderer=react&ref=configure"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-section-item">
<img
src={Context}
alt="An abstraction representing the composition of data for a component"
/>
<h4 className="sb-section-item-heading">Provide context and mocking</h4>
<p className="sb-section-item-paragraph">Often when a story doesn't render, it's because your component is expecting a specific environment or context (like a theme provider) to be available.</p>
<a
href="https://storybook.js.org/docs/writing-stories/decorators/?renderer=react&ref=configure#context-for-mocking"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-section-item">
<img src={Assets} alt="A representation of typography and image assets" />
<div>
<h4 className="sb-section-item-heading">Load assets and resources</h4>
<p className="sb-section-item-paragraph">To link static files (like fonts) to your projects and stories, use the
`staticDirs` configuration option to specify folders to load when
starting Storybook.</p>
<a
href="https://storybook.js.org/docs/configure/images-and-assets/?renderer=react&ref=configure"
target="_blank"
>Learn more<RightArrow /></a>
</div>
</div>
</div>
</div>
<div className="sb-container">
<div className='sb-section-title'>
# Do more with Storybook
Now that you know the basics, let's explore other parts of Storybook that will improve your experience. This list is just to get you started. You can customise Storybook in many ways to fit your needs.
</div>
<div className="sb-section">
<div className="sb-features-grid">
<div className="sb-grid-item">
<img src={Docs} alt="A screenshot showing the autodocs tag being set, pointing a docs page being generated" />
<h4 className="sb-section-item-heading">Autodocs</h4>
<p className="sb-section-item-paragraph">Auto-generate living,
interactive reference documentation from your components and stories.</p>
<a
href="https://storybook.js.org/docs/writing-docs/autodocs/?renderer=react&ref=configure"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<img src={Share} alt="A browser window showing a Storybook being published to a chromatic.com URL" />
<h4 className="sb-section-item-heading">Publish to Chromatic</h4>
<p className="sb-section-item-paragraph">Publish your Storybook to review and collaborate with your entire team.</p>
<a
href="https://storybook.js.org/docs/sharing/publish-storybook/?renderer=react&ref=configure#publish-storybook-with-chromatic"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<img src={FigmaPlugin} alt="Windows showing the Storybook plugin in Figma" />
<h4 className="sb-section-item-heading">Figma Plugin</h4>
<p className="sb-section-item-paragraph">Embed your stories into Figma to cross-reference the design and live
implementation in one place.</p>
<a
href="https://storybook.js.org/docs/sharing/design-integrations/?renderer=react&ref=configure#embed-storybook-in-figma-with-the-plugin"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<img src={Testing} alt="Screenshot of tests passing and failing" />
<h4 className="sb-section-item-heading">Testing</h4>
<p className="sb-section-item-paragraph">Use stories to test a component in all its variations, no matter how
complex.</p>
<a
href="https://storybook.js.org/docs/writing-tests/?renderer=react&ref=configure"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<img src={Accessibility} alt="Screenshot of accessibility tests passing and failing" />
<h4 className="sb-section-item-heading">Accessibility</h4>
<p className="sb-section-item-paragraph">Automatically test your components for a11y issues as you develop.</p>
<a
href="https://storybook.js.org/docs/writing-tests/accessibility-testing/?renderer=react&ref=configure"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<img src={Theming} alt="Screenshot of Storybook in light and dark mode" />
<h4 className="sb-section-item-heading">Theming</h4>
<p className="sb-section-item-paragraph">Theme Storybook's UI to personalize it to your project.</p>
<a
href="https://storybook.js.org/docs/configure/theming/?renderer=react&ref=configure"
target="_blank"
>Learn more<RightArrow /></a>
</div>
</div>
</div>
</div>
<div className='sb-addon'>
<div className='sb-addon-text'>
<h4>Addons</h4>
<p className="sb-section-item-paragraph">Integrate your tools with Storybook to connect workflows.</p>
<a
href="https://storybook.js.org/addons/?ref=configure"
target="_blank"
>Discover all addons<RightArrow /></a>
</div>
<div className='sb-addon-img'>
<img src={AddonLibrary} alt="Integrate your tools with Storybook to connect workflows." />
</div>
</div>
<div className="sb-section sb-socials">
<div className="sb-section-item">
<img src={Github} alt="Github logo" className="sb-explore-image"/>
Join our contributors building the future of UI development.
<a
href="https://github.com/storybookjs/storybook"
target="_blank"
>Star on GitHub<RightArrow /></a>
</div>
<div className="sb-section-item">
<img src={Discord} alt="Discord logo" className="sb-explore-image"/>
<div>
Get support and chat with frontend developers.
<a
href="https://discord.gg/storybook"
target="_blank"
>Join Discord server<RightArrow /></a>
</div>
</div>
<div className="sb-section-item">
<img src={Youtube} alt="Youtube logo" className="sb-explore-image"/>
<div>
Watch tutorials, feature previews and interviews.
<a
href="https://www.youtube.com/@chromaticui"
target="_blank"
>Watch on YouTube<RightArrow /></a>
</div>
</div>
<div className="sb-section-item">
<img src={Tutorials} alt="A book" className="sb-explore-image"/>
<p>Follow guided walkthroughs on for key workflows.</p>
<a
href="https://storybook.js.org/tutorials/?ref=configure"
target="_blank"
>Discover tutorials<RightArrow /></a>
</div>
</div>
<style>
{`
.sb-container {
margin-bottom: 48px;
}
.sb-section {
width: 100%;
display: flex;
flex-direction: row;
gap: 20px;
}
img {
object-fit: cover;
}
.sb-section-title {
margin-bottom: 32px;
}
.sb-section a:not(h1 a, h2 a, h3 a) {
font-size: 14px;
}
.sb-section-item, .sb-grid-item {
flex: 1;
display: flex;
flex-direction: column;
}
.sb-section-item-heading {
padding-top: 20px !important;
padding-bottom: 5px !important;
margin: 0 !important;
}
.sb-section-item-paragraph {
margin: 0;
padding-bottom: 10px;
}
.sb-chevron {
margin-left: 5px;
}
.sb-features-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 32px 20px;
}
.sb-socials {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
.sb-socials p {
margin-bottom: 10px;
}
.sb-explore-image {
max-height: 32px;
align-self: flex-start;
}
.sb-addon {
width: 100%;
display: flex;
align-items: center;
position: relative;
background-color: #EEF3F8;
border-radius: 5px;
border: 1px solid rgba(0, 0, 0, 0.05);
background: #EEF3F8;
height: 180px;
margin-bottom: 48px;
overflow: hidden;
}
.sb-addon-text {
padding-left: 48px;
max-width: 240px;
}
.sb-addon-text h4 {
padding-top: 0px;
}
.sb-addon-img {
position: absolute;
left: 345px;
top: 0;
height: 100%;
width: 200%;
overflow: hidden;
}
.sb-addon-img img {
width: 650px;
transform: rotate(-15deg);
margin-left: 40px;
margin-top: -72px;
box-shadow: 0 0 1px rgba(255, 255, 255, 0);
backface-visibility: hidden;
}
@media screen and (max-width: 800px) {
.sb-addon-img {
left: 300px;
}
}
@media screen and (max-width: 600px) {
.sb-section {
flex-direction: column;
}
.sb-features-grid {
grid-template-columns: repeat(1, 1fr);
}
.sb-socials {
grid-template-columns: repeat(2, 1fr);
}
.sb-addon {
height: 280px;
align-items: flex-start;
padding-top: 32px;
overflow: hidden;
}
.sb-addon-text {
padding-left: 24px;
}
.sb-addon-img {
right: 0;
left: 0;
top: 130px;
bottom: 0;
overflow: hidden;
height: auto;
width: 124%;
}
.sb-addon-img img {
width: 1200px;
transform: rotate(-12deg);
margin-left: 0;
margin-top: 48px;
margin-bottom: -40px;
margin-left: -24px;
}
}
`}
</style>

View File

@ -1,32 +0,0 @@
.storybook-header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
padding: 15px 20px;
font-family: 'Nunito Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.storybook-header svg {
display: inline-block;
vertical-align: top;
}
.storybook-header h1 {
display: inline-block;
vertical-align: top;
margin: 6px 0 6px 10px;
font-weight: 700;
font-size: 20px;
line-height: 1;
}
.storybook-header button + button {
margin-left: 10px;
}
.storybook-header .welcome {
margin-right: 10px;
color: #333;
font-size: 14px;
}

View File

@ -1,34 +0,0 @@
import type { Meta, StoryObj } from '@storybook/react-webpack5';
import { fn } from 'storybook/test';
import { Header } from './header';
const meta = {
title: 'Example/Header',
component: Header,
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
parameters: {
// More on how to position stories at: https://storybook.js.org/docs/configure/story-layout
layout: 'fullscreen',
},
args: {
onLogin: fn(),
onLogout: fn(),
onCreateAccount: fn(),
},
} satisfies Meta<typeof Header>;
export default meta;
type Story = StoryObj<typeof meta>;
export const LoggedIn: Story = {
args: {
user: {
name: 'Jane Doe',
},
},
};
export const LoggedOut: Story = {};

View File

@ -1,69 +0,0 @@
import { Button } from './button';
import './header.css';
type User = {
name: string;
};
export interface HeaderProps {
user?: User;
onLogin?: () => void;
onLogout?: () => void;
onCreateAccount?: () => void;
}
export const Header = ({
user,
onLogin,
onLogout,
onCreateAccount,
}: HeaderProps) => (
<header>
<div className="storybook-header">
<div>
<svg
width="32"
height="32"
viewBox="0 0 32 32"
xmlns="http://www.w3.org/2000/svg"
>
<g fill="none" fillRule="evenodd">
<path
d="M10 0h12a10 10 0 0110 10v12a10 10 0 01-10 10H10A10 10 0 010 22V10A10 10 0 0110 0z"
fill="#FFF"
/>
<path
d="M5.3 10.6l10.4 6v11.1l-10.4-6v-11zm11.4-6.2l9.7 5.5-9.7 5.6V4.4z"
fill="#555AB9"
/>
<path
d="M27.2 10.6v11.2l-10.5 6V16.5l10.5-6zM15.7 4.4v11L6 10l9.7-5.5z"
fill="#91BAF8"
/>
</g>
</svg>
<h1>Acme</h1>
</div>
<div>
{user ? (
<>
<span className="welcome">
Welcome, <b>{user.name}</b>!
</span>
<Button size="small" onClick={onLogout} label="Log out" />
</>
) : (
<>
<Button size="small" onClick={onLogin} label="Log in" />
<Button
primary
size="small"
onClick={onCreateAccount}
label="Sign up"
/>
</>
)}
</div>
</div>
</header>
);

View File

@ -0,0 +1,184 @@
import type { Meta, StoryObj } from '@storybook/react-webpack5';
import { fn } from 'storybook/test';
import NumberInput from '@/components/originui/number-input';
// More on how to set up stories at: https://storybook.js.org/docs/writing-stories#default-export
const meta = {
title: 'Example/NumberInput',
component: NumberInput,
parameters: {
// Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
layout: 'centered',
docs: {
description: {
component: `
## NumberInput Component
NumberInput is a numeric input component with increment/decrement buttons. It provides a user-friendly interface for entering numeric values with built-in validation and keyboard controls.
### Import Path
\`\`\`typescript
import NumberInput from '@/components/originui/number-input';
\`\`\`
### Basic Usage
\`\`\`tsx
import { useState } from 'react';
import NumberInput from '@/components/originui/number-input';
function MyComponent() {
const [value, setValue] = useState(0);
return (
<NumberInput
value={value}
onChange={(newValue) => setValue(newValue)}
/>
);
}
\`\`\`
### Features
- Increment/decrement buttons for easy value adjustment
- Keyboard input validation (only allows numeric input)
- Customizable height and styling
- Non-negative number validation
- Responsive design with Tailwind CSS
`,
},
},
},
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {
value: {
description: 'The current numeric value',
control: { type: 'number' },
},
onChange: {
description: 'Callback function called when value changes',
control: false,
},
height: {
description: 'Custom height for the input component',
control: { type: 'text' },
},
className: {
description: 'Additional CSS classes for styling',
control: { type: 'text' },
},
},
// Use `fn` to spy on the onChange arg, which will appear in the actions panel once invoked: https://storybook.js.org/docs/essentials/actions#action-args
args: { onChange: fn() },
} satisfies Meta<typeof NumberInput>;
export default meta;
type Story = StoryObj<typeof meta>;
// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const Default: Story = {
args: {
value: 0,
},
parameters: {
docs: {
description: {
story: `
### Default Number Input
Shows the basic number input with default styling and zero value.
\`\`\`tsx
<NumberInput
value={0}
onChange={(value) => console.log('Value changed:', value)}
/>
\`\`\`
`,
},
},
},
tags: ['!dev'],
};
export const WithInitialValue: Story = {
args: {
value: 10,
},
parameters: {
docs: {
description: {
story: `
### With Initial Value
Shows the number input with a predefined initial value.
\`\`\`tsx
<NumberInput
value={10}
onChange={(value) => console.log('Value changed:', value)}
/>
\`\`\`
`,
},
},
},
tags: ['!dev'],
};
export const CustomHeight: Story = {
args: {
value: 5,
height: '60px',
},
parameters: {
docs: {
description: {
story: `
### Custom Height
Shows the number input with custom height styling.
\`\`\`tsx
<NumberInput
value={5}
height="60px"
onChange={(value) => console.log('Value changed:', value)}
/>
\`\`\`
`,
},
},
},
tags: ['!dev'],
};
export const WithCustomClass: Story = {
args: {
value: 3,
className: 'border-blue-500 bg-blue-50',
},
parameters: {
docs: {
description: {
story: `
### With Custom Styling
Shows the number input with custom CSS classes for styling.
\`\`\`tsx
<NumberInput
value={3}
className="border-blue-500 bg-blue-50"
onChange={(value) => console.log('Value changed:', value)}
/>
\`\`\`
`,
},
},
},
tags: ['!dev'],
};

View File

@ -1,68 +0,0 @@
.storybook-page {
margin: 0 auto;
padding: 48px 20px;
max-width: 600px;
color: #333;
font-size: 14px;
line-height: 24px;
font-family: 'Nunito Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.storybook-page h2 {
display: inline-block;
vertical-align: top;
margin: 0 0 4px;
font-weight: 700;
font-size: 32px;
line-height: 1;
}
.storybook-page p {
margin: 1em 0;
}
.storybook-page a {
color: inherit;
}
.storybook-page ul {
margin: 1em 0;
padding-left: 30px;
}
.storybook-page li {
margin-bottom: 8px;
}
.storybook-page .tip {
display: inline-block;
vertical-align: top;
margin-right: 10px;
border-radius: 1em;
background: #e7fdd8;
padding: 4px 12px;
color: #357a14;
font-weight: 700;
font-size: 11px;
line-height: 12px;
}
.storybook-page .tip-wrapper {
margin-top: 40px;
margin-bottom: 40px;
font-size: 13px;
line-height: 20px;
}
.storybook-page .tip-wrapper svg {
display: inline-block;
vertical-align: top;
margin-top: 3px;
margin-right: 4px;
width: 12px;
height: 12px;
}
.storybook-page .tip-wrapper svg path {
fill: #1ea7fd;
}

View File

@ -1,33 +0,0 @@
import type { Meta, StoryObj } from '@storybook/react-webpack5';
import { expect, userEvent, within } from 'storybook/test';
import { Page } from './page';
const meta = {
title: 'Example/Page',
component: Page,
parameters: {
// More on how to position stories at: https://storybook.js.org/docs/configure/story-layout
layout: 'fullscreen',
},
} satisfies Meta<typeof Page>;
export default meta;
type Story = StoryObj<typeof meta>;
export const LoggedOut: Story = {};
// More on component testing: https://storybook.js.org/docs/writing-tests/interaction-testing
export const LoggedIn: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const loginButton = canvas.getByRole('button', { name: /Log in/i });
await expect(loginButton).toBeInTheDocument();
await userEvent.click(loginButton);
await expect(loginButton).not.toBeInTheDocument();
const logoutButton = canvas.getByRole('button', { name: /Log out/i });
await expect(logoutButton).toBeInTheDocument();
},
};

View File

@ -1,91 +0,0 @@
import React from 'react';
import { Header } from './header';
import './page.css';
type User = {
name: string;
};
export const Page: React.FC = () => {
const [user, setUser] = React.useState<User>();
return (
<article>
<Header
user={user}
onLogin={() => setUser({ name: 'Jane Doe' })}
onLogout={() => setUser(undefined)}
onCreateAccount={() => setUser({ name: 'Jane Doe' })}
/>
<section className="storybook-page">
<h2>Pages in Storybook</h2>
<p>
We recommend building UIs with a{' '}
<a
href="https://componentdriven.org"
target="_blank"
rel="noopener noreferrer"
>
<strong>component-driven</strong>
</a>{' '}
process starting with atomic components and ending with pages.
</p>
<p>
Render pages with mock data. This makes it easy to build and review
page states without needing to navigate to them in your app. Here are
some handy patterns for managing page data in Storybook:
</p>
<ul>
<li>
Use a higher-level connected component. Storybook helps you compose
such data from the "args" of child component stories
</li>
<li>
Assemble data in the page component from your services. You can mock
these services out using Storybook.
</li>
</ul>
<p>
Get a guided tutorial on component-driven development at{' '}
<a
href="https://storybook.js.org/tutorials/"
target="_blank"
rel="noopener noreferrer"
>
Storybook tutorials
</a>
. Read more in the{' '}
<a
href="https://storybook.js.org/docs"
target="_blank"
rel="noopener noreferrer"
>
docs
</a>
.
</p>
<div className="tip-wrapper">
<span className="tip">Tip</span> Adjust the width of the canvas with
the{' '}
<svg
width="10"
height="10"
viewBox="0 0 12 12"
xmlns="http://www.w3.org/2000/svg"
>
<g fill="none" fillRule="evenodd">
<path
d="M1.5 5.2h4.8c.3 0 .5.2.5.4v5.1c-.1.2-.3.3-.4.3H1.4a.5.5 0 01-.5-.4V5.7c0-.3.2-.5.5-.5zm0-2.1h6.9c.3 0 .5.2.5.4v7a.5.5 0 01-1 0V4H1.5a.5.5 0 010-1zm0-2.1h9c.3 0 .5.2.5.4v9.1a.5.5 0 01-1 0V2H1.5a.5.5 0 010-1zm4.3 5.2H2V10h3.8V6.2z"
id="a"
fill="#999"
/>
</g>
</svg>
Viewports addon in the toolbar
</div>
</section>
</article>
);
};

View File

@ -0,0 +1,258 @@
import type { Meta, StoryObj } from '@storybook/react-webpack5';
import { useState } from 'react';
import { fn } from 'storybook/test';
import { RenameDialog } from '@/components/rename-dialog';
import { Button } from '@/components/ui/button';
// More on how to set up stories at: https://storybook.js.org/docs/writing-stories#default-export
const meta = {
title: 'Example/RenameDialog',
component: RenameDialog,
parameters: {
// Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
layout: 'centered',
docs: {
description: {
component: `
## Component Description
RenameDialog is a modal dialog component for renaming items. It provides a form with input validation and loading states, commonly used in chat applications for renaming conversations or creating new ones.
### Features
- Modal dialog with form input
- Loading state support
- Customizable title
- Initial name pre-filling
- Form validation and submission
### Import Path
\`\`\`tsx
import { RenameDialog } from '@/components/rename-dialog';
\`\`\`
### Basic Usage
\`\`\`tsx
import { RenameDialog } from '@/components/rename-dialog';
import { Button } from '@/components/ui/button';
import { useState } from 'react';
function MyComponent() {
const [visible, setVisible] = useState(false);
const [loading, setLoading] = useState(false);
return (
<div>
<Button onClick={() => setVisible(true)}>
Open Rename Dialog
</Button>
{visible && (
<RenameDialog
hideModal={() => setVisible(false)}
onOk={async (name) => {
setLoading(true);
// Handle save logic
console.log('New name:', name);
setLoading(false);
setVisible(false);
}}
initialName=""
loading={loading}
/>
)}
</div>
);
}
\`\`\`
`,
},
},
},
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {
initialName: {
control: 'text',
description: 'Initial name value for the input field',
},
title: {
control: 'text',
description: 'Custom title for the dialog',
},
loading: {
control: 'boolean',
description: 'Loading state of the save button',
},
},
// Use `fn` to spy on the args, which will appear in the actions panel once invoked: https://storybook.js.org/docs/essentials/actions#action-args
args: {
hideModal: fn(),
onOk: fn(),
},
} satisfies Meta<typeof RenameDialog>;
export default meta;
type Story = StoryObj<typeof meta>;
// Story components to handle useState hooks
const DefaultStoryComponent = (args: any) => {
const [visible, setVisible] = useState(false);
return (
<div>
<Button onClick={() => setVisible(true)}>Open Rename Dialog</Button>
{visible && (
<RenameDialog
{...args}
hideModal={() => setVisible(false)}
onOk={(name) => {
args.onOk?.(name);
setVisible(false);
}}
/>
)}
</div>
);
};
const WithInitialNameStoryComponent = (args: any) => {
const [visible, setVisible] = useState(false);
return (
<div>
<Button onClick={() => setVisible(true)}>
Open Rename Dialog (with initial name)
</Button>
{visible && (
<RenameDialog
{...args}
hideModal={() => setVisible(false)}
onOk={(name) => {
args.onOk?.(name);
setVisible(false);
}}
/>
)}
</div>
);
};
const CreateNewChatStoryComponent = (args: any) => {
const [visible, setVisible] = useState(false);
return (
<div>
<Button onClick={() => setVisible(true)}>Create New Chat</Button>
{visible && (
<RenameDialog
{...args}
hideModal={() => setVisible(false)}
onOk={(name) => {
args.onOk?.(name);
setVisible(false);
}}
/>
)}
</div>
);
};
const LoadingStateStoryComponent = (args: any) => {
const [visible, setVisible] = useState(false);
return (
<div>
<Button onClick={() => setVisible(true)}>
Open Dialog (Loading State)
</Button>
{visible && (
<RenameDialog
{...args}
hideModal={() => setVisible(false)}
onOk={(name) => {
args.onOk?.(name);
}}
/>
)}
</div>
);
};
// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const Default: Story = {
render: (args) => <DefaultStoryComponent {...args} />,
args: {
initialName: '',
loading: false,
},
parameters: {
docs: {
description: {
story: `
### Default Rename Dialog
Basic rename dialog without initial name value. Click the button to open the dialog.
`,
},
},
},
};
export const WithInitialName: Story = {
render: (args) => <WithInitialNameStoryComponent {...args} />,
args: {
initialName: 'My Chat Session',
loading: false,
},
parameters: {
docs: {
description: {
story: `
### Rename Dialog with Initial Name
Rename dialog pre-filled with an existing name for editing. Click the button to open the dialog.
`,
},
},
},
};
export const CreateNewChat: Story = {
render: (args) => <CreateNewChatStoryComponent {...args} />,
args: {
initialName: '',
title: 'Create Chat',
loading: false,
},
parameters: {
docs: {
description: {
story: `
### Create New Chat Dialog
Dialog for creating a new chat with custom title. Click the button to open the dialog.
`,
},
},
},
};
export const LoadingState: Story = {
render: (args) => <LoadingStateStoryComponent {...args} />,
args: {
initialName: 'Saving changes...',
loading: true,
},
parameters: {
docs: {
description: {
story: `
### Loading State
Dialog showing loading state during save operation. The dialog remains open while loading.
`,
},
},
},
};

View File

@ -0,0 +1,98 @@
import type { Meta, StoryObj } from '@storybook/react-webpack5';
import { Spin } from '@/components/ui/spin';
// More on how to set up stories at: https://storybook.js.org/docs/writing-stories#default-export
const meta = {
title: 'Example/Spin',
component: Spin,
parameters: {
// Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
layout: 'centered',
docs: {
description: {
component: `
## Spin Component
Spin is a loading spinner component that can be used to indicate loading states. It supports different sizes and can wrap other content to create loading overlays.
### Import Path
\`\`\`typescript
import { Spin } from '@/components/ui/spin';
\`\`\`
### Basic Usage
\`\`\`tsx
import { Spin } from '@/components/ui/spin';
function MyComponent() {
return (
<Spin spinning={true}>
<div>Your content here</div>
</Spin>
);
}
\`\`\`
### Features
- Three different sizes: small, default, and large
- Can wrap content to create loading overlays
- Smooth animation with CSS transitions
- Customizable styling with className prop
- Built with Tailwind CSS
`,
},
},
},
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {
spinning: {
description: 'Whether the spinner is active',
control: { type: 'boolean' },
},
size: {
description: 'Size of the spinner',
control: { type: 'select' },
options: ['small', 'default', 'large'],
},
className: {
description: 'Additional CSS classes for styling',
control: { type: 'text' },
},
children: {
description: 'Content to be wrapped by the spinner',
control: false,
},
},
// Use `fn` to spy on any callbacks
args: {},
} satisfies Meta<typeof Spin>;
export default meta;
type Story = StoryObj<typeof meta>;
// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const Default: Story = {
args: {
spinning: true,
size: 'default',
},
parameters: {
docs: {
description: {
story: `
### Default Spinner
Shows the basic spinner with default size and active state.
\`\`\`tsx
<Spin spinning={true} size="default" />
\`\`\`
`,
},
},
},
tags: ['!dev'],
};

View File

@ -17,6 +17,15 @@ module.exports = {
'2xl': '1400px',
},
},
screens: {
sm: '640px',
md: '768px',
lg: '1024px',
xl: '1280px',
'2xl': '1400px',
'3xl': '1780px',
'4xl': '1980px',
},
extend: {
colors: {
border: 'var(--colors-outline-neutral-strong)',