### Install FlowToken with npm or yarn
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/integration-guide.md
Install the FlowToken library using your preferred package manager.
```bash
npm install flowtoken
# or
yarn add flowtoken
```
--------------------------------
### Install FlowToken with npm
Source: https://github.com/ephibbs/flowtoken/blob/main/README.md
Install the FlowToken library using npm. This command adds the package to your project's dependencies.
```bash
npm install flowtoken
```
--------------------------------
### Install FlowToken with yarn
Source: https://github.com/ephibbs/flowtoken/blob/main/README.md
Install the FlowToken library using yarn. This command adds the package to your project's dependencies.
```bash
yarn add flowtoken
```
--------------------------------
### Complete Chat Example with Flowtoken
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/quick-reference.md
This example demonstrates a full React chat interface using Flowtoken for animated markdown rendering. It includes message display, user input, and submission handling.
```jsx
'use client';
import { useState } from 'react';
import { useChat } from 'ai/react';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat();
return (
{messages.map((msg) => (
{msg.role}:
))}
);
}
```
--------------------------------
### React Example for highlight animation
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Applies the 'highlight' animation to markdown content. Recommended duration is 0.8s to 2.0s.
```jsx
```
--------------------------------
### Output HTML Structure Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/code-renderer.md
An example of the final HTML structure generated after processing. Each word is contained within a span element with animation styles.
```jsx
constgreeting=
{/* ... more spans ... */}
```
--------------------------------
### Simple Word Animation Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/tokenized-text.md
Demonstrates animating text word by word using the AnimatedMarkdown component. Ensure FlowToken CSS is imported.
```jsx
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function WordByWord() {
return (
);
}
```
--------------------------------
### elastic Animation Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Example of using the elastic animation with the AnimatedMarkdown component. Set the animation prop to 'elastic' and specify animationDuration.
```jsx
```
--------------------------------
### blurIn Animation Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Example of using the blurIn animation with the AnimatedMarkdown component. Set the animation prop to 'blurIn' and specify animationDuration.
```jsx
```
--------------------------------
### Inline Code and Code Block Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/default-code.md
Illustrates the difference between inline code, which remains unsyntax-highlighted, and code blocks, which are rendered with syntax highlighting and a copy button.
```markdown
This is `inline code` that stays unsyntax-highlighted.
But this is a code block:
\
\
```javascript
const x = 42;
\
```
```
--------------------------------
### React Example for blurAndSharpen animation
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Applies the 'blurAndSharpen' animation to markdown content. This animation is identical to 'blurIn' but uses an alternative name.
```jsx
```
--------------------------------
### bounceIn Animation Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Example of using the bounceIn animation with the AnimatedMarkdown component. Set the animation prop to 'bounceIn' and specify animationDuration.
```jsx
```
--------------------------------
### React Example for dropIn animation
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Applies the 'dropIn' animation to markdown content. This animation creates a directional entry from above.
```jsx
```
--------------------------------
### React Example for wave animation
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Applies the 'wave' animation to markdown content. This animation creates a continuous up and down wave motion.
```jsx
```
--------------------------------
### Manage Multiple Concurrent Streams with FlowToken
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/advanced-usage.md
This example demonstrates how to manage multiple concurrent streaming requests using FlowToken. It shows how to initiate streams, handle incoming data chunks, and update the UI for each stream independently.
```jsx
import React, { useState } from 'react';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function MultiStreamExample() {
const [streams, setStreams] = useState({});
const startStream = async (streamId, prompt) => {
setStreams(prev => ({ ...prev, [streamId]: { content: '', loading: true } }));
try {
const response = await fetch('/api/stream', {
method: 'POST',
body: JSON.stringify({ prompt }),
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
setStreams(prev => ({
...prev,
[streamId]: {
...prev[streamId],
content: prev[streamId].content + chunk,
}
}));
}
} finally {
setStreams(prev => ({
...prev,
[streamId]: { ...prev[streamId], loading: false }
}));
}
};
return (
{Object.entries(streams).map(([id, stream]) => (
Stream {id}
))}
);
}
```
--------------------------------
### Integrate FlowToken with Zustand
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/integration-guide.md
Utilize Zustand for a lightweight state management solution with AnimatedMarkdown. The example shows basic fetch logic within the store.
```jsx
import React from 'react';
import create from 'zustand';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
const useContentStore = create((set) => ({
content: '',
loading: false,
fetchContent: async (prompt) => {
set({ loading: true });
// Fetch logic here
set({ loading: false });
},
}));
export default function ZustandExample() {
const { content, loading } = useContentStore();
return (
);
}
```
--------------------------------
### Large Image with Cover Fit
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animated-image.md
This example demonstrates rendering a large hero image using AnimatedMarkdown, which automatically applies animations and uses the imgHeight prop for styling. Import 'flowtoken/dist/styles.css' for styles.
```jsx
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function HeroImage() {
return (
);
}
```
--------------------------------
### rotateIn Animation Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Example of using the rotateIn animation with the AnimatedMarkdown component. Set the animation prop to 'rotateIn' and specify animationDuration.
```jsx
```
--------------------------------
### fadeAndScale Animation Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Example of using the fadeAndScale animation with the AnimatedMarkdown component. Set the animation prop to 'fadeAndScale' and specify animationDuration.
```jsx
```
--------------------------------
### Custom Video/Media Component Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/integration-guide.md
Defines and uses a custom 'video' component. It renders an HTML5 video player using the provided 'src' prop. Any children are displayed as a caption below the video.
```jsx
const VideoComponent = ({ children, animateText, src }: any) => {
return (
{children &&
{animateText(children)}
}
);
};
export default function MediaExample() {
return (
Demo video description
`}
customComponents={{ video: VideoComponent }}
animation="fadeIn"
/>
);
}
```
--------------------------------
### React Example for slideUp animation
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Applies the 'slideUp' animation to markdown content. This animation creates an upward entrance effect.
```jsx
```
--------------------------------
### Virtualize Long Message Lists
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/advanced-usage.md
Optimize performance for chat interfaces with a large number of messages by using virtualization. This example utilizes 'react-window' to render only the visible messages.
```jsx
import React, { useState } from 'react';
import { FixedSizeList as List } from 'react-window';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
function MessageRow({ index, style, messages }) {
const msg = messages[index];
return (
);
}
export default function VirtualizedChat() {
const [messages, setMessages] = useState([
// Large array of messages...
]);
return (
{MessageRow}
);
}
```
--------------------------------
### slideInFromLeft Animation Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Example of using the slideInFromLeft animation with the AnimatedMarkdown component. Set the animation prop to 'slideInFromLeft' and specify animationDuration.
```jsx
```
--------------------------------
### fadeIn Animation Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Example of using the fadeIn animation with the AnimatedMarkdown component. Set the animation prop to 'fadeIn' and specify animationDuration.
```jsx
```
--------------------------------
### AnimatedMarkdown with Vercel AI SDK
Source: https://github.com/ephibbs/flowtoken/blob/main/README.md
Integrate AnimatedMarkdown within a chat interface using the Vercel AI SDK. This example displays chat messages with a drop-in animation. Remember to import FlowToken CSS.
```jsx
'use client'
import { useChat } from 'ai/react'
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat()
return (
{messages.map(m => (
{m.role}:
))}
)
}
```
--------------------------------
### Chat Interface with Vercel AI SDK
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/integration-guide.md
Integrates AnimatedMarkdown into a chat interface powered by Vercel's AI SDK. Ensure you have the 'ai/react' package installed.
```jsx
'use client';
import { useChat } from 'ai/react';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function ChatPage() {
const { messages, input, handleInputChange, handleSubmit } = useChat();
return (
{messages.map((message) => (
{message.role === 'assistant' ? (
) : (
{message.content}
)}
))}
);
}
```
--------------------------------
### Code Highlighting with Themes
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/quick-reference.md
Apply syntax highlighting to code blocks within markdown using various themes from `react-syntax-highlighter`. Example uses the `nightOwlStyle`.
```jsx
import doccoStyle from 'react-syntax-highlighter/dist/esm/styles/hljs/docco';
import nightOwlStyle from 'react-syntax-highlighter/dist/esm/styles/hljs/night-owl';
```
--------------------------------
### React SyntaxHighlighter Component
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/default-code.md
Example of using the SyntaxHighlighter component in React to render code. It includes props for styling, language, and a custom renderer.
```jsx
```
--------------------------------
### typewriter Animation Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Example of using the typewriter animation with the AnimatedMarkdown component. Set the animation prop to 'typewriter', specify animationDuration, and optionally 'sep' for character-based animation.
```jsx
```
--------------------------------
### Character-Based Tokenization Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/tokenized-text.md
Use 'char' separation to animate each character independently. This is ideal for typewriter effects or character-by-character reveal animations.
```jsx
// Renders: Hi
```
--------------------------------
### Word-Based Tokenization Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/tokenized-text.md
Use 'word' separation to animate each word and whitespace individually. This is suitable for general text animations where spaces should also be treated as distinct elements.
```jsx
// Renders: Helloworld
```
--------------------------------
### TypeScript Support for AnimatedMarkdown
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/integration-guide.md
Example of using AnimatedMarkdown with TypeScript, defining props for a functional component.
```typescript
import React, { FC } from 'react';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
interface PageProps {
markdown: string;
}
const Page: FC = ({ markdown }) => {
return (
);
};
export default Page;
```
--------------------------------
### Basic JavaScript Greeting
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/default-code.md
A simple JavaScript snippet to declare a string and log it to the console. This is often used for basic testing or as a starting point.
```javascript
const greeting = "Hello, World!";
console.log(greeting);
```
--------------------------------
### Streaming LLM Output Animation
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/README.md
Ideal for displaying streaming output from LLM models. This example uses 'fadeIn' animation while streaming and disables it upon completion. The 'diff' tokenization strategy is suitable for tracking changes.
```jsx
```
--------------------------------
### Custom Alert Component Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/integration-guide.md
Defines and uses a custom 'alert' component. Pass a 'type' prop (info, warning, error, success) to style the alert. The component renders a styled div with the provided content.
```jsx
const AlertComponent = ({ children, animateText, type = 'info' }: any) => {
const styles = {
info: { background: '#e3f2fd', border: '1px solid #2196f3' },
warning: { background: '#fff3e0', border: '1px solid #ff9800' },
error: { background: '#ffebee', border: '1px solid #f44336' },
success: { background: '#e8f5e9', border: '1px solid #4caf50' },
};
return (
{animateText(children)}
);
};
export default function AlertExample() {
return (
This is a warning
This is an errorThis is a success message
`}
customComponents={{ alert: AlertComponent }}
animation="slideUp"
/>
);
}
```
--------------------------------
### Use Diff Mode for Partial Updates with FlowToken
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/advanced-usage.md
This example showcases the `sep="diff"` mode in FlowToken, which is optimized for scenarios where content updates incrementally. Only new text animates on each update, and previous text does not re-animate.
```jsx
import React, { useState, useCallback } from 'react';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function DiffModeExample() {
const [content, setContent] = useState('');
// Simulate incremental updates
const addChunk = useCallback((chunk) => {
setContent(prev => prev + chunk);
}, []);
React.useEffect(() => {
// Example: Simulating token-by-token streaming
const tokens = ['The', ' ', 'quick', ' ', 'brown', ' ', 'fox'];
tokens.forEach((token, index) => {
setTimeout(() => addChunk(token), index * 100);
});
}, [addChunk]);
return (
);
}
```
--------------------------------
### Streaming Chat Integration Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/configuration.md
Use AnimatedMarkdown for streaming chat messages with a 'diff' separator and a 'fadeIn' animation. The animation can be conditionally applied based on message completion.
```jsx
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function ChatMessage({ message, isComplete }) {
return (
);
}
```
--------------------------------
### Accessible Slow Animation Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/configuration.md
Configure animations for accessibility, such as slower fade-in effects for users who prefer reduced motion or need more reading time. Use 'word' separation for a gradual reveal.
```jsx
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function AccessibleContent() {
return (
);
}
```
--------------------------------
### Custom Table Component Example
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/integration-guide.md
Defines and uses a custom 'table' component. It renders an HTML table with overflow handling for wider content. This component is suitable for displaying tabular data.
```jsx
const TableComponent = ({ children, animateText }: any) => {
return (
{animateText(children)}
);
};
export default function TableExample() {
return (
);
}
```
--------------------------------
### Basic Markdown Rendering with Fade-In Animation
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animated-markdown.md
Demonstrates how to render basic markdown content with a 'fadeIn' animation. Ensure 'flowtoken/dist/styles.css' is imported for styling.
```jsx
import React from 'react';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function BasicExample() {
return (
);
}
```
--------------------------------
### Rendering Markdown with Custom Components and 'slideUp' Animation
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animated-markdown.md
Shows how to integrate custom React components within markdown content and apply a 'slideUp' animation. Ensure 'flowtoken/dist/styles.css' is imported.
```jsx
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
const CustomAlert = ({ children, animateText, ...props }: any) => (
{animateText(children)}
);
export default function CustomComponentExample() {
const markdown = `
# Article
This is an important message
`;
return (
);
}
```
--------------------------------
### Token-by-Token Streaming Animation
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/streaming-text.md
Demonstrates how to stream text one token at a time for animation. This is useful for simulating LLM responses.
```jsx
import StreamingFadeInText from './components/AnimatedText';
export default function TokenStream() {
const [response, setResponse] = React.useState('');
React.useEffect(() => {
// Simulate LLM token streaming
const tokens = ['The', 'quick', 'brown', 'fox', 'jumps'];
let index = 0;
const interval = setInterval(() => {
if (index <= tokens.length) {
setResponse(tokens.slice(0, index).join(' '));
index++;
} else {
clearInterval(interval);
}
}, 200);
}, []);
return (
);
}
```
--------------------------------
### Streaming with OpenAI API
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/integration-guide.md
Demonstrates streaming responses from OpenAI's API and rendering them with AnimatedMarkdown. Requires the 'openai' package and a valid OpenAI API key set as REACT_APP_OPENAI_API_KEY.
```jsx
import React, { useState } from 'react';
import OpenAI from 'openai';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function OpenAIExample() {
const [response, setResponse] = useState('');
const [loading, setLoading] = useState(false);
const handleStream = async () => {
setLoading(true);
setResponse('');
const client = new OpenAI({
apiKey: process.env.REACT_APP_OPENAI_API_KEY,
});
const stream = await client.messages.stream({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'Explain React hooks' },
],
});
for await (const event of stream) {
if (event.type === 'content_block_delta') {
setResponse(prev => prev + event.delta.text);
}
}
setLoading(false);
};
return (
{response && (
)}
);
}
```
--------------------------------
### Apply Syntax Highlighting Styles
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/configuration.md
Demonstrates how to import and apply different syntax highlighting themes from react-syntax-highlighter to the AnimatedMarkdown component using the `codeStyle` prop. The default theme is `hljs.docco`.
```jsx
import doccoStyle from 'react-syntax-highlighter/dist/esm/styles/hljs/docco';
import nightOwlStyle from 'react-syntax-highlighter/dist/esm/styles/hljs/night-owl';
import atomDarkStyle from 'react-syntax-highlighter/dist/esm/styles/hljs/atom-one-dark';
// Docco theme (default, light)
// Night Owl theme (dark)
// Atom One Dark theme (dark)
// Default (docco)
```
--------------------------------
### React + Vite Integration
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/integration-guide.md
Demonstrates integrating AnimatedMarkdown within a React application managed by Vite.
```jsx
import React from 'react';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
function App() {
return (
);
}
export default App;
```
--------------------------------
### Import DefaultCode Component
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/module-structure.md
Demonstrates the internal import path for the DefaultCode component, which is used internally.
```typescript
import DefaultCode from './components/DefaultCode';
```
--------------------------------
### Style FlowToken with CSS Modules
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/integration-guide.md
Integrate FlowToken with CSS Modules for component-scoped styling. The example demonstrates applying custom styles to the message container.
```jsx
import React from 'react';
import { AnimatedMarkdown } from 'flowtoken';
import styles from './Chat.module.css';
import 'flowtoken/dist/styles.css';
export default function ChatMessage({ message }) {
return (
);
}
```
```css
/* Chat.module.css */
.messageContainer {
padding: 16px;
background: #f5f5f5;
border-radius: 8px;
margin-bottom: 12px;
}
```
--------------------------------
### Basic Image with Animation
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animated-image.md
Use this snippet to render a basic image with a specified CSS animation, duration, and height. Ensure 'flowtoken/dist/styles.css' is imported.
```jsx
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function ImageExample() {
return (
);
}
```
--------------------------------
### React Example for colorTransition animation
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animations.md
Applies the 'colorTransition' animation to markdown content. Note: This animation is hardcoded to red→black; use custom CSS for other colors.
```jsx
```
--------------------------------
### Import FlowToken Components and Styles
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/quick-reference.md
Import the AnimatedMarkdown component and its associated CSS styles.
```jsx
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
```
--------------------------------
### Streaming LLM Output with Incremental 'diff' Animation
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/animated-markdown.md
Simulates streaming LLM output and applies 'diff' animation for incremental updates, suitable for real-time responses. Requires 'flowtoken/dist/styles.css'.
```jsx
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function StreamingExample() {
const [llmOutput, setLlmOutput] = React.useState('');
React.useEffect(() => {
// Simulate streaming output
const words = ['This', 'is', 'a', 'streaming', 'response'];
let index = 0;
const interval = setInterval(() => {
if (index <= words.length) {
setLlmOutput(words.slice(0, index).join(' '));
index++;
} else {
clearInterval(interval);
}
}, 500);
}, []);
return (
);
}
```
--------------------------------
### Content-Based Animation Selection
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/advanced-usage.md
Dynamically select the animation type based on the content's characteristics. This example chooses animations for code blocks, images, or long text.
```jsx
import React from 'react';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function SmartAnimation() {
const getAnimationForContent = (content) => {
if (content.includes('```')) return 'slideUp'; // Code blocks
if (content.includes('![]')) return 'fadeIn'; // Images
if (content.length > 500) return 'dropIn'; // Long content
return 'fadeIn'; // Default
};
const content = "# Example\n\nLong content...";
const animation = getAnimationForContent(content);
return (
);
}
```
--------------------------------
### Input Code String
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/code-renderer.md
The initial code string to be processed.
```javascript
const code = `const greeting = \"Hello\";`;
```
--------------------------------
### Style FlowToken with Styled Components
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/integration-guide.md
Use Styled Components to create styled React components for integrating AnimatedMarkdown. This example shows custom styling for message containers.
```jsx
import React from 'react';
import styled from 'styled-components';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
const MessageContainer = styled.div`
padding: 16px;
background: #f5f5f5;
border-radius: 8px;
margin-bottom: 12px;
h1 {
margin-top: 0;
}
`;
export default function ChatMessage({ message }) {
return (
);
}
```
--------------------------------
### Configure Tokenization Strategy (sep)
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/configuration.md
Control how text is split into animatable tokens using the 'sep' prop. Recommended for most use cases is 'word'.
```jsx
// Word-by-word animation
```
```jsx
// Character-by-character animation
```
```jsx
// Incremental streaming (only new text animates)
```
--------------------------------
### Simulating Real Streaming with AI SDK
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/streaming-text.md
Integrates streaming text animation with a chat interface using an AI SDK. Displays assistant messages with token-by-token animation.
```jsx
import StreamingFadeInText from './components/AnimatedText';
import { useChat } from 'ai/react';
export default function ChatWithStreaming() {
const { messages } = useChat();
return (
{messages.map(m => (
{m.role === 'assistant' ? (
) : (
{m.content}
)}
))}
);
}
```
--------------------------------
### Sanitize LLM Output with DOMPurify
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/advanced-usage.md
Sanitize raw LLM output using DOMPurify before rendering it with AnimatedMarkdown to prevent XSS attacks. This example blocks script and iframe components.
```jsx
import React from 'react';
import DOMPurify from 'dompurify';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function SafeLLMOutput({ rawContent }) {
// Sanitize LLM output to prevent XSS
const sanitized = DOMPurify.sanitize(rawContent);
return (
null, // Block script components
iframe: () => null, // Block iframes
}}
/>
);
}
```
--------------------------------
### AnimatedMarkdown with Python Code Block
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/default-code.md
Demonstrates using AnimatedMarkdown to render markdown content containing a Python code block. Includes syntax highlighting and a copy-to-clipboard feature for the code.
```jsx
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function CodeBlockExample() {
const markdown = `
# Python Example
\
\
```python
def hello_world():
print("Hello, World!")
hello_world()
\
```
Try copying the code!
`;
return (
);
}
```
--------------------------------
### Validate Custom Component Props for URLs
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/advanced-usage.md
Validate custom component props, specifically URLs, to ensure they are safe before rendering. This example only allows http and https protocols for the 'href' prop.
```jsx
const ValidatedCustomComponent = ({ children, animateText, href }: any) => {
// Validate URL before rendering
let safeHref = '';
try {
const url = new URL(href);
// Only allow http/https
if (['http:', 'https:'].includes(url.protocol)) {
safeHref = href;
}
} catch {
console.warn('Invalid URL:', href);
}
return (
{animateText(children)}
);
};
export default function SecureCustomComponent() {
return (
Click here`}
customComponents={{ link: ValidatedCustomComponent }}
/>
);
}
```
--------------------------------
### Timing Coordination Logic
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/streaming-text.md
This snippet illustrates the logic used for timing coordination between token animations, ensuring a minimum delay to prevent visual stacking.
```javascript
const delay = 10 - (performance.now() - (lastTokenTime.current || 0));
lastTokenTime.current = Math.max(performance.now() + delay, lastTokenTime.current || 0);
```
--------------------------------
### Custom Streaming Hook with AnimatedMarkdown
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/integration-guide.md
A custom React hook to manage streaming content and display it using AnimatedMarkdown. This example assumes a '/api/stream' endpoint is set up to handle POST requests.
```jsx
import React, { useState, useCallback } from 'react';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
function useStreamingContent() {
const [content, setContent] = useState('');
const [isStreaming, setIsStreaming] = useState(false);
const stream = useCallback(async (prompt: string) => {
setIsStreaming(true);
setContent('');
const response = await fetch('/api/stream', {
method: 'POST',
body: JSON.stringify({ prompt }),
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
setContent(prev => prev + chunk);
}
setIsStreaming(false);
}, []);
return { content, isStreaming, stream };
}
export default function StreamingExample() {
const { content, isStreaming, stream } = useStreamingContent();
return (
{content && (
)}
);
}
```
--------------------------------
### File Organization Structure
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/README.md
This snippet displays the directory structure of the Flowtoken project, highlighting the location of key components and utilities.
```tree
src/
├── components/
│ ├── AnimatedMarkdown.tsx # Main component
│ ├── SplitText.tsx # Tokenization
│ ├── AnimatedImage.tsx # Images
│ ├── AnimatedText.tsx # Streaming tokens
│ ├── DefaultCode.tsx # Code blocks
│ └── CodeRenderer.tsx # Custom renderer
├── utils/
│ └── animations.ts # Animation mapping
├── styles.css # Keyframes
└── index.ts # Public API
```
--------------------------------
### Streaming Animation with Diff Mode
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/tokenized-text.md
Shows how to use AnimatedMarkdown for streaming content with diff mode, updating the content as new chunks arrive. FlowToken CSS must be imported.
```jsx
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function StreamingChat() {
const [fullResponse, setFullResponse] = React.useState('');
const handleStream = (chunk: string) => {
setFullResponse(prev => prev + chunk);
};
return (
);
}
```
--------------------------------
### Import Animations Utility
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/module-structure.md
Demonstrates the internal import path for the animations utility object, used for mapping animation names to CSS classes.
```typescript
// Actually used internally
import { animations } from '../utils/animations';
```
--------------------------------
### Basic AnimatedMarkdown Usage
Source: https://github.com/ephibbs/flowtoken/blob/main/README.md
Import and use the AnimatedMarkdown component to display markdown content with a fade-in animation. Ensure FlowToken CSS is imported for animations to work.
```jsx
import React from 'react';
import { AnimatedMarkdown } from 'flowtoken';
// import the flowtoken css in order to use the animations
import 'flowtoken/dist/styles.css';
const App = () => {
return (
);
};
export default App;
```
--------------------------------
### Code-First Rendering (No Animation on Completion)
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/README.md
Renders markdown content, prioritizing code blocks, and applies an animation until the content is complete, after which animation is disabled.
```APIDOC
### Code-First Rendering (No Animation on Completion)
```jsx
```
```
--------------------------------
### Use AnimatedMarkdown with Vercel AI SDK
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/quick-reference.md
Integrate AnimatedMarkdown with messages from the Vercel AI SDK. Ensure you map through messages and apply appropriate props for rendering.
```jsx
import { useChat } from 'ai/react';
import { AnimatedMarkdown } from 'flowtoken';
const { messages } = useChat();
{messages.map(m => (
))}
```
--------------------------------
### LLM Streaming with AnimatedMarkdown
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/README.md
Integrate FlowToken with the Vercel AI SDK for LLM streaming. Uses the 'diff' tokenization strategy for animating only new content.
```jsx
import { useChat } from 'ai/react';
import { AnimatedMarkdown } from 'flowtoken';
import 'flowtoken/dist/styles.css';
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat();
return (
{messages.map(m => (
{m.role}:
))}
);
}
```
--------------------------------
### Import Flowtoken CSS
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/quick-reference.md
Ensure you import the necessary CSS for Flowtoken styling. This is crucial for animations and layout to render correctly.
```javascript
import 'flowtoken/dist/styles.css'
```
--------------------------------
### Diff-Based Tokenization - Initial Render
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/tokenized-text.md
The initial render in 'diff' mode. This strategy is used for incremental content updates, ensuring only new content is animated.
```jsx
// Initial render
// Output: Hello
```
--------------------------------
### Internal Import of AnimatedMarkdown
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/module-structure.md
Demonstrates the internal import path for the AnimatedMarkdown component within the project.
```typescript
// Internal usage
import AnimatedMarkdown from './components/AnimatedMarkdown';
```
--------------------------------
### Import AnimatedMarkdown in Public API
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/module-structure.md
Shows how to import the AnimatedMarkdown component when using the flowtoken library.
```typescript
// Public import
import { AnimatedMarkdown } from 'flowtoken';
```
--------------------------------
### Build Data Visualization Components
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/advanced-usage.md
Integrate data visualization components by parsing content within the custom component's children. This allows LLM-generated data to be rendered as charts or other visual representations.
```jsx
const ChartComponent = ({ children, animateText, data }: any) => {
// Parse data from children and render chart
const values = children.split('\n').map(line => parseFloat(line));
return (
{values.map((val, i) => (
))}
{animateText(children)}
);
};
export default function ChartExample() {
return (
10
20
15
30
25
`}
customComponents={{ chart: ChartComponent }}
animation="slideUp"
/>
);
}
```
--------------------------------
### Diff-Based Tokenization - Content Update
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/tokenized-text.md
Demonstrates updating content in 'diff' mode. Only the newly added ' world' part will animate, while 'Hello' retains its previous state without re-animating.
```jsx
// Update with additional content
// Output: Hello world
// Only " world" animates, "Hello" does not re-animate
```
--------------------------------
### Static Markdown with Animation
Source: https://github.com/ephibbs/flowtoken/blob/main/_autodocs/README.md
Use this snippet to render static markdown content with a 'slideUp' animation effect. Customize the tokenization strategy and animation duration.
```jsx
```