### Getting Started with List v2 LLMs Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v2/llms.md A basic example to get started with List v2 LLMs. This demonstrates initializing a list and rendering its items. ```javascript import React from 'react'; import { List } from '@legendapp/list'; const SimpleList = () => { const data = new List(['Apple', 'Banana', 'Cherry']); return ( (
{item}
)} /> ); }; export default SimpleList; ``` -------------------------------- ### Getting Started with List v1 LLMs Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v1/llms.md Basic setup for using List v1 LLMs. This snippet shows the minimal code required to render a list. ```javascript import React from 'react'; import { List } from '@legendapp/list'; const MyListComponent = () => { const data = [ { id: 'a', value: 'Apple' }, { id: 'b', value: 'Banana' }, { id: 'c', value: 'Cherry' }, ]; return ( (
{item.value}
)} /> ); }; export default MyListComponent; ``` -------------------------------- ### Full Example: Configure Synced State with Keel Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v3/llms/sync/keel.md A comprehensive example demonstrating the setup of Legend-State with Keel, including authentication, persistence, and observable configuration. ```typescript import { observable } from '@legendapp/state' import { ObservablePersistLocalStorage } from '@legendapp/state/persist-plugins/local-storage' import { configureSynced } from '@legendapp/state/sync' import KSUID from 'ksuid' import { syncedKeel } from '@legendapp/state/sync-plugins/keel' import { APIClient } from './keelClient' const client = new APIClient({ baseUrl: process.env.API_BASE_URL }) const isAuthed$ = observable(false); // Set defaults const sync = configureSynced(syncedKeel, { client, persist: { plugin: ObservablePersistLocalStorage, retrySync: true }, debounceSet: 500, retry: { infinite: true, }, changesSince: 'last-sync', waitFor: isAuthed$ }) // enable sync after authentication succeeds async function doAuth() { // authenticate the client await keel.auth.authenticateWithPassword(email, pass) // check that the client is authenticated const isAuthenticated = await keel.auth.isAuthenticated() // Set isAuthed$ to start syncing isAuthed$.set(true) } // Set up your observables with Keel queries const { mutations, queries } = client.api // create an observable with the action functions const messages$ = observable(sync({ list: queries.getMessages, create: mutations.createMessage, update: mutations.updateMessage, delete: mutations.deleteMessage, persist: { name: 'messages' }, })) // get() activates and starts syncing const messages = messages$.get() function addMessage(text: string) { const id = KSUID.randomSync().string // Add keyed by id to the messages$ observable to trigger the create action messages$[id].set({ id, text, createdAt: undefined, updatedAt: undefined }) } function updateMessage(id: string, text: string) { // Just set valudes in the observable to trigger the update action messages$[id].text.set(text) } ``` -------------------------------- ### Animated List Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v2/llms.md Demonstrates how to implement animated transitions for list items using List v2 LLMs. Ensure proper setup for animations. ```javascript import React from 'react'; import { List } from '@legendapp/list'; const MyAnimatedList = () => { const list = new List([1, 2, 3]); return ( (
Item {item}
)} /> ); }; export default MyAnimatedList; ``` -------------------------------- ### Observing Context Examples Source: https://github.com/legendapp/legend-docs/blob/main/docs/content/state/v2/usage/reactivity.mdx Demonstrates how `get()` tracks observables within an observing context. It also shows examples of what is and is not tracked, including shallow tracking with `map()` and `Object.keys()`. ```javascript const state$ = observable({ settings: { theme: "dark", }, chats: { messages: [{ id: 0, text: "hi" }], }, }); observe(() => { // Example 1: const theme = state$.settings.theme.get(); // ✅ Tracking [state$.settings.theme] because of get() // Example 2: const settings = state$.settings; // ❌ Not tracking because it's an object const theme = settings.theme.get(); // ✅ Tracking [state$.settings.theme] because of get() // Example 3: const theme$ = state$.settings.theme; // ❌ Not tracking with no get() // Example 4: state$.chats.messages.map((m) => ); // ✅ Tracking [state$.chats.messages (shallow)] because of map() // Example 5: Object.keys(state$.settings); // ✅ Tracking [state$.settings (shallow)] }); ``` -------------------------------- ### Run Legend State Locally Source: https://github.com/legendapp/legend-docs/blob/main/README.md Follow these steps to run the Legend State documentation locally. Ensure you have bun installed. This will install dependencies and start the development server. ```bash cd packages/state bun i bun dev ``` -------------------------------- ### Full Supabase Integration Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v3/llms/sync/supabase.md This example demonstrates a complete setup for syncing data with Supabase using Legend-State. It includes client creation, type generation, observable configuration with filters, actions, persistence, and real-time settings. It also shows how to add and update messages. ```typescript import { createClient } from '@supabase/supabase-js' import { Database } from './database.types' import { observable } from '@legendapp/state' import { configureSyncedSupabase, syncedSupabase } from '@legendapp/state/sync-plugins/supabase' import { v4 as uuidv4 } from "uuid" const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY) // provide a function to generate ids locally const generateId = () => uuidv4() configureSyncedSupabase({ generateId }) const uid = '' const messages$ = observable(syncedSupabase({ supabase, collection: 'messages', // Optional: // Select only id and text fields select: (from) => from.select('id,text'), // Filter by the current user filter: (select) => select.eq('user_id', uid), // Don't allow delete actions: ['read', 'create', 'update'], // Realtime filter by user_id realtime: { filter: `user_id=eq.${uid}` }, // Persist data and pending changes locally persist: { name: 'messages', retrySync: true }, // Sync only diffs changesSince: 'last-sync' })) // get() activates and starts syncing const messages = messages$.get() function addMessage(text: string) { const id = generateId() // Add keyed by id to the messages$ observable to trigger a create in Supabase messages$[id].set({ id, text, created_at: null, updated_at: null }) } function updateMessage(id: string, text: string) { // Just set values in the observable to trigger an update to Supabase messages$[id].text.set(text) } ``` -------------------------------- ### Getting Started with React Native LLMs Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v3/llms.txt Basic setup instructions for integrating LLMs into a React Native project. Ensure you have the necessary dependencies installed. ```javascript import { LLM } from "@legendapp/llms"; // Initialize LLM const llm = new LLM(); // Use LLM const response = await llm.generate("Hello, world!"); console.log(response); ``` -------------------------------- ### Animated List v1 LLM Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v1/llms.txt Demonstrates how to implement animated lists using List v1 LLMs. Ensure proper setup for animations. ```javascript import React from 'react'; import { List } from 'legend-list'; const AnimatedList = () => { const items = [ { id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' }, { id: 3, text: 'Item 3' }, ]; return ( (
{item.text}
)} animation={{ type: 'fade' }} /> ); }; export default AnimatedList; ``` -------------------------------- ### Install Legend-Motion Source: https://github.com/legendapp/legend-docs/blob/main/docs/content/motion/v2/getting-started/introduction.mdx Install the Legend-Motion library using npm. ```bash npm install @legendapp/motion ``` -------------------------------- ### Start FumaDocs Production Server Source: https://github.com/legendapp/legend-docs/blob/main/CLAUDE.md Start the production server for the FumaDocs application. ```bash cd docs bun start ``` -------------------------------- ### Infinite Scroll Example with Legend List Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v2/llms-full.txt Demonstrates implementing infinite scrolling in both directions (up and down) using LegendList. Requires setup for fetching more data when the user reaches the start or end of the list. Ensure `fetchMoreItems` and `fetchPreviousItems` are defined elsewhere. ```tsx import { LegendList } from "@legendapp/list"; import { useState, useCallback } from "react"; export function InfiniteScrollExample() { const [data, setData] = useState(initialData); const [loading, setLoading] = useState(false); const loadMoreAtEnd = useCallback(async () => { if (loading) return; setLoading(true); try { const newItems = await fetchMoreItems(data.length); setData(prev => [...prev, ...newItems]); } finally { setLoading(false); } }, [data.length, loading]); const loadMoreAtStart = useCallback(async () => { if (loading) return; setLoading(true); try { const newItems = await fetchPreviousItems(data[0]?.id); setData(prev => [...newItems, ...prev]); } finally { setLoading(false); } }, [data, loading]); return ( } keyExtractor={item => item.id} onEndReached={loadMoreAtEnd} onStartReached={loadMoreAtStart} onEndReachedThreshold={0.5} onStartReachedThreshold={0.5} recycleItems /> ); } ``` -------------------------------- ### NPM Installation Source: https://github.com/legendapp/legend-docs/blob/main/docs/content/state/v2/intro/introduction.mdx Installs the Legend-State library using npm. This is the first step to using Legend-State in your project. ```bash npm install @legendapp/state ``` -------------------------------- ### Basic SVG Animation Setup Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/motion/v2/llms/usage/svg.md Import `MotionSvg` to animate SVG elements. This example shows a basic setup for animating a rectangle's properties with custom transitions for different attributes. ```jsx import { MotionSvg } from '@legendapp/motion/svg'; ``` -------------------------------- ### Install Legend List Source: https://github.com/legendapp/legend-docs/blob/main/docs/content/list/v2/getting-started.mdx Install the Legend List package using npm. ```bash npm install @legendapp/list ``` -------------------------------- ### Install ksuid Library Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v3/llms/sync/keel.md Install the ksuid library, which the Keel plugin uses for local ID generation. ```bash npm install ksuid ``` -------------------------------- ### Install next-transpile-modules Source: https://github.com/legendapp/legend-docs/blob/main/docs/content/motion/v2/resources/next-js.mdx Install the `next-transpile-modules` package using npm. This is required to transpile Legend-Motion and its dependencies. ```bash npm install next-transpile-modules ``` -------------------------------- ### Observable Basics with get() and set() Source: https://github.com/legendapp/legend-docs/blob/main/docs/content/state/v2/intro/why.mdx Demonstrates the fundamental usage of observables for state management, including getting and setting values, and automatic tracking of changes with observe. ```jsx const state$ = observable({ value: 1 }); state$.value.get(); state$.value.set(2); // Tracks automatically and runs on every change observe(() => { console.log(state$.value.get()); }); ``` -------------------------------- ### Chat Interface Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v1/llms.md Illustrates how to build a chat interface with List v1 LLMs. This example focuses on rendering messages and handling user input. ```javascript import React, { useState } from 'react'; import { List } from '@legendapp/list'; const ChatInterface = () => { const [messages, setMessages] = useState([]); const [inputValue, setInputValue] = useState(''); const handleSendMessage = () => { if (inputValue.trim()) { setMessages([...messages, { id: Date.now(), text: inputValue }]); setInputValue(''); } }; return (
(
{item.text}
)} style={{ flexGrow: 1, overflowY: 'auto', padding: '10px' }} />
setInputValue(e.target.value)} placeholder='Type a message...' style={{ flexGrow: 1, marginRight: '10px', padding: '8px' }} />
); }; export default ChatInterface; ``` -------------------------------- ### React Product Shelf Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v3/llms.txt Example of a product shelf component using LLMs in React. Useful for displaying a curated list of products. ```javascript import React from "react"; import { View, Text, Image, ScrollView } from "react-native"; // Assuming React Native context import { LLM } from "@legendapp/llms"; const ProductCard = ({ product }) => ( {product.name} ${product.price.toFixed(2)} {product.description} ); const ProductShelf = () => { const products = [ { id: "1", name: "Product A", price: 19.99, description: "A great product.", imageUrl: "https://via.placeholder.com/180x120" }, { id: "2", name: "Product B", price: 29.99, description: "Another amazing product.", imageUrl: "https://via.placeholder.com/180x120" }, { id: "3", name: "Product C", price: 9.99, description: "Simple and effective.", imageUrl: "https://via.placeholder.com/180x120" }, ]; return ( Featured Products {products.map((product) => ( ))} ); }; export default ProductShelf; ``` -------------------------------- ### Install Expo Linear Gradient Source: https://github.com/legendapp/legend-docs/blob/main/docs/content/motion/v2/usage/linear-gradient.mdx Install the expo-linear-gradient package for Expo projects. ```bash npm install expo-linear-gradient ``` -------------------------------- ### Basic SectionList Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v3/llms/api.md A quick example demonstrating how to use the SectionList component with sample data and render functions. ```tsx import { Text } from "react-native"; import { SectionList } from "@legendapp/list/section-list"; const sections = [ { title: "A", data: ["Apple", "Avocado"] }, { title: "B", data: ["Banana", "Blueberry"] }, ]; const Header = ({ title }: { title: string }) => {title}; const Row = ({ label }: { label: string }) => {label}; export function MySectionList() { return ( item} renderSectionHeader={({ section }) =>
} renderItem={({ item }) => } stickySectionHeadersEnabled estimatedItemSize={48} /> ); } ``` -------------------------------- ### Installing Keyboard Controller Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v3/llms-full.md Provides the npm command to install the required version of react-native-keyboard-controller and react-native-reanimated for KeyboardAwareLegendList. ```npm npm install react-native-keyboard-controller@^1.21.7 react-native-reanimated ``` -------------------------------- ### Install React Native Storage Dependencies Source: https://github.com/legendapp/legend-docs/blob/main/docs/content/state/v2/guides/persistence.mdx Install either `react-native-mmkv` or `@react-native-async-storage/async-storage` if you are using React Native. ```bash react-native-mmkv ``` ```bash @react-native-async-storage/async-storage ``` -------------------------------- ### Chat Interface Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v2/llms.md Provides a basic structure for building a chat interface using List v2 LLMs. This example focuses on rendering messages efficiently. ```javascript import React from 'react'; import { List } from '@legendapp/list'; const ChatInterface = () => { const messages = new List([ { id: 1, text: 'Hello!', sender: 'user' }, { id: 2, text: 'Hi there!', sender: 'bot' }, ]); return (
(
{message.text}
)} />
); }; export default ChatInterface; ``` -------------------------------- ### Install Legend-State Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v3/llms/intro/getting-started.md Install the Legend-State package using npm. It is recommended to use the beta version for the latest features. ```bash npm install @legendapp/state@beta ``` -------------------------------- ### React Directory Component Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v3/llms.txt Example of a directory structure display using LLMs in React. This can be used for navigating through hierarchical data. ```javascript import React from "react"; import { View, Text, FlatList } from "react-native"; // Assuming React Native context import { LLM } from "@legendapp/llms"; const Directory = () => { const directoryData = [ { id: "1", name: "Folder A", type: "folder" }, { id: "2", name: "File 1.txt", type: "file" }, { id: "3", name: "Folder B", type: "folder" }, { id: "4", name: "File 2.doc", type: "file" }, ]; const renderItem = ({ item }) => ( {item.name} ({item.type}) ); return ( Directory item.id} /> ); }; export default Directory; ``` -------------------------------- ### Run Development Server Source: https://github.com/legendapp/legend-docs/blob/main/docs/README.md Commands to start the development server using npm, pnpm, or yarn. ```bash npm run dev # or pnpm dev # or yarn dev ``` -------------------------------- ### Other Frameworks: Vanilla JS Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v2/llms.txt Demonstrates using the library with plain JavaScript without any framework. ```javascript import { observable, observe } from "@legendapp/state"; const count = observable(0); observe(() => { document.getElementById('count').innerText = count.get(); }); document.getElementById('increment').addEventListener('click', () => { count.set(count.get() + 1); }); ``` -------------------------------- ### Run FumaDocs Development Server Source: https://github.com/legendapp/legend-docs/blob/main/CLAUDE.md Navigate to the docs directory and run the development server using bun. ```bash cd docs bun dev ``` -------------------------------- ### onStartReachedThreshold Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v2/llms/props.md Defines the distance from the start, as a percentage of the screen size, that triggers the `onStartReached` callback. For example, a value of 0.5 will call `onStartReached` when the user scrolls to half a screen's distance from the start. ```APIDOC ## onStartReachedThreshold ### Description The distance from the start as a percentage that the scroll should be from the end to trigger `onStartReached`. It is multiplied by screen size, so a value of 0.5 will trigger `onStartReached` when scrolling to half a screen from the start. ### Type ```ts onStartReachedThreshold?: number | null | undefined; ``` ``` -------------------------------- ### Run Legacy Astro Package Docs Source: https://github.com/legendapp/legend-docs/blob/main/CLAUDE.md Install dependencies and run the development server for individual legacy Astro documentation packages. ```bash cd packages/state bun i && bun dev ``` ```bash cd packages/motion bun i && bun dev ``` ```bash cd packages/list bun i && bun dev ``` -------------------------------- ### Get Legend List State Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v3/llms/api.md Returns a live snapshot API for advanced integrations. Refer to the documentation for the full type, fields, listener channels, caveats, and examples. ```typescript getState(): LegendListState; ``` -------------------------------- ### KeyboardAwareLegendList with useKeyboardChatComposerInset Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v3/llms-full.txt Example of using `contentInsetEndAdjustment` with `KeyboardAwareLegendList` and `useKeyboardChatComposerInset` for React Native. This setup is ideal for floating composers or input bars that overlay the list's end. ```tsx const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(listRef, composerRef); ``` -------------------------------- ### Keyboard Aware Legend List Setup Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v3/llms/react-native/keyboard-and-animated.md Imports necessary components for keyboard-aware scrolling and inset management in React Native lists. Ensure `react-native-reanimated` and `react-native-keyboard-controller` (v1.21.7+) are installed. ```ts import { KeyboardAwareLegendList, useKeyboardChatComposerInset, useKeyboardScrollToEnd, } from "@legendapp/list/keyboard"; ``` -------------------------------- ### Simple Legend-Motion Animation Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/content/blog/2022-05-23-react-and-native.mdx Install Legend-Motion to easily add animations to your React Native components. This snippet shows a basic animating view that changes position, opacity, and scale. ```jsx function SimpleExample() { const [value, setValue] = useState(0) useInterval(() => { setValue(v => v === 0 ? 1 : 0) }, 1000) return ( Animating View ) } ``` -------------------------------- ### Enable React Tracking for Observables Source: https://github.com/legendapp/legend-docs/blob/main/docs/content/state/v2/react/react-introduction.mdx Use enableReactTracking to make components re-render when observable values change. This is recommended for getting started and rapid prototyping. It acts like a hook and should not be used conditionally or within loops. ```jsx import { observable } from "@legendapp/state"; import { enableReactTracking } from "@legendapp/state/config/enableReactTracking"; enableReactTracking({ auto: true, }); const name$ = observable("Annyong"); function Component() { // The component re-renders when name changes const name = name$.get(); return
{name}
; } ``` -------------------------------- ### Animated List Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v1/llms.md Demonstrates how to create an animated list using List v1 LLMs. Ensure the necessary animation libraries are imported. ```javascript import React from 'react'; import { List } from '@legendapp/list'; const AnimatedList = () => { const items = [ { id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' }, { id: 3, text: 'Item 3' }, ]; return ( (
{item.text}
)} animation={{ type: 'slideIn', duration: 300 }} /> ); }; export default AnimatedList; ``` -------------------------------- ### Get Observable Value with get() Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v3/llms/usage/observable.md Use the `get()` method to retrieve the underlying value of an observable. Calling `get()` within a tracking context automatically tracks the observable. ```javascript const profile = { name: "Test user" } const state$ = observable({ profile, test: 0 }) // get the underlying value from the observable const name = state$.profile.name.get() ``` ```javascript const state$ = observable({ data: someHugeThing }) const { data } = state$.get() // Nothing special happens when working with the raw data processData(data) ``` ```javascript state$.get(true) // Create a shallow listener ``` -------------------------------- ### Get Observable Value Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v3/llms-full.txt Use `get()` to retrieve the underlying value of an observable. Accessing properties directly creates proxies, but `get()` on raw data avoids this. ```javascript const profile = { name: "Test user" } const state$ = observable({ profile, test: 0 }) // get the underlying value from the observable const name = state$.profile.name.get() ``` ```javascript const state$ = observable({ data: someHugeThing }) const { data } = state$.get() // Nothing special happens when working with the raw data processData(data) ``` -------------------------------- ### Custom Sync Plugin Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v3/llms/sync/persist-sync.md This example shows how to create a custom sync plugin for a 'user' entity. It defines fetch logic for listing, creating, updating, and deleting users, and configures persistence and authentication. Use this pattern when your backend has specific API endpoints for these operations. ```typescript import { observable } from '@legendapp/state' import { synced } from '@legendapp/state/sync' const isAuthed$ = observable(false); // Create a custom synced that just needs a name in your API const customSynced = ({ name }) => { const basePath = 'https://url/api/v1/' const doFetch = (path) => { return fetch(basePath + path).then((res) => res.json()) } return synced({ get: () => doFetch(`list-${name}s`), set: ({ value }) => { if (value === null || value === undefined) { return doFetch('delete-' + name) } else { return doFetch('upsert-' + name) } }, retry: { infinite: true }, persist: { name }, waitFor: isAuthed$, subscribe: ({ refresh }) => { // Subscribe to realtime service }, }) } const store$ = observable({ users: customSynced('user') }) ``` -------------------------------- ### React Media Rails Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v3/llms.txt Demonstrates how to implement media rails (e.g., carousels of images or videos) using LLMs in React. This is useful for showcasing related media. ```javascript import React from "react"; import { View, Text, ScrollView, Image } from "react-native"; // Assuming React Native context import { LLM } from "@legendapp/llms"; const MediaRail = ({ title, mediaItems }) => ( {title} {mediaItems.map((item, index) => ( ))} ); const MediaRails = () => { const images1 = [ { url: "https://via.placeholder.com/120" }, { url: "https://via.placeholder.com/120" }, { url: "https://via.placeholder.com/120" }, ]; const images2 = [ { url: "https://via.placeholder.com/120" }, { url: "https://via.placeholder.com/120" }, { url: "https://via.placeholder.com/120" }, ]; return ( ); }; export default MediaRails; ``` -------------------------------- ### Install React Native Linear Gradient Source: https://github.com/legendapp/legend-docs/blob/main/docs/content/motion/v2/usage/linear-gradient.mdx Install the react-native-linear-gradient package for React Native projects. ```bash npm install react-native-linear-gradient ``` -------------------------------- ### List v2 LLM Props Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v2/llms.md Demonstrates the usage of various props available for List v2 LLMs to customize its behavior and appearance. Refer to the documentation for a full list of props. ```javascript import React from 'react'; import { List } from '@legendapp/list'; const PropsExample = () => { const items = new List([1, 2, 3, 4, 5]); return ( (
{item}
)} /> ); }; export default PropsExample; ``` -------------------------------- ### Other Frameworks: Qwik Integration Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v2/llms.txt Shows an example of integrating the library with Qwik for reactive state management. ```typescript import { observable } from "@legendapp/state"; import { component$, useStore } from '@builder.io/qwik'; const count = observable(0); export const Counter = component$(() => { const state = useStore(count); return (

Count: {state.get()}

); }); ``` -------------------------------- ### Get Profile with syncedKeel Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v3/llms/sync/keel.md Use `syncedKeel` with a `get` action to observe a single profile. The observable's value will be the profile returned by the `get` query. Create, update, and delete operations are configured similarly to how they would be for a list. ```typescript const { mutations, queries } = client.api const profile$ = observable(syncedKeel({ get: queries.getProfile, create: mutations.createProfile, update: mutations.updateProfile, delete: mutations.deleteProfile, })) // profile$.get() is a Profile ``` -------------------------------- ### List v1 LLM Properties Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v1/llms.txt Illustrates the usage of various properties available for List v1 LLMs. This example shows basic item rendering and styling. ```javascript import React from 'react'; import { List } from 'legend-list'; const ListWithProps = () => { const data = [ { id: 'a', value: 'Apple' }, { id: 'b', value: 'Banana' }, { id: 'c', value: 'Cherry' }, ]; return ( (
{item.value}
)} itemKey="id" className="custom-list-class" style={{ maxHeight: '300px', overflowY: 'auto' }} /> ); }; export default ListWithProps; ``` -------------------------------- ### Helper Function: `get` Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v2/llms.txt Illustrates using the `get` helper function to retrieve the current value of an observable. ```typescript import { observable, get } from "@legendapp/state"; const count = observable(10); console.log(get(count)); // 10 ``` -------------------------------- ### React Gallery Grid Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v3/llms.txt Implementation of a responsive image gallery grid using LLMs in React. Suitable for displaying collections of images. ```javascript import React from "react"; import { View, Image, FlatList, Dimensions } from "react-native"; // Assuming React Native context import { LLM } from "@legendapp/llms"; const { width } = Dimensions.get("window"); const numColumns = 3; const imageSize = width / numColumns; const GalleryGrid = () => { const images = [ { id: "1", url: "https://via.placeholder.com/150" }, { id: "2", url: "https://via.placeholder.com/150" }, { id: "3", url: "https://via.placeholder.com/150" }, { id: "4", url: "https://via.placeholder.com/150" }, { id: "5", url: "https://via.placeholder.com/150" }, { id: "6", url: "https://via.placeholder.com/150" }, ]; const renderItem = ({ item }) => ( ); return ( item.id} numColumns={numColumns} /> ); }; export default GalleryGrid; ``` -------------------------------- ### Configuring Observable with Persistence and Sync Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v3/llms/intro/why.md Sets up an observable state with initial data, custom get/set functions for data fetching and updates, and local persistence using Local Storage. This example is useful for applications requiring offline support and data synchronization. ```js import { ObservablePersistLocalStorage } from '@legendapp/state/persist-plugins/local-storage' import { synced } from '@legendapp/state/sync' import { observable } from '@legendapp/state' const state$ = observable({ initial: { { bigObject: { ... } } }, get: () => fetch('url').then(res => res.json()), set: ({ value }) => fetch('https://url.to.set', { method: 'POST', data: JSON.stringify(value) }), persist: { name: 'test' } }) ``` -------------------------------- ### Example: Scaling from Top-Left and Bottom-Right Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/motion/v2/llms/usage/transform-origin.md This example demonstrates scaling two components from different origins. The first scales from the top-left (0, 0) and the second from the bottom-right (100%, 100%). ```jsx { (value) => ( )} ``` -------------------------------- ### Install Legend List v2 Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/list/v2/llms-full.txt Use npm to install the latest version of the Legend List package. ```bash npm @legendapp/list ``` -------------------------------- ### TanStack-Query Persistence Plugin Example Source: https://github.com/legendapp/legend-docs/blob/main/docs/content/blog/2023-10-17-legend-state-v2.mdx Demonstrates integrating Legend-State's persistence with TanStack-Query for remote data synchronization. It shows how to configure local storage and a remote query client, with the query key dynamically updating based on an observable page number. ```javascript import { observable } from "@legendapp/state" import { persistObservable } from "@legendapp/state/persist" import { persistPluginQuery } from "@legendapp/state/persist-plugins/query" import { ObservablePersistLocalStorage } from "@legendapp/state/persist-plugins/local-storage" import { QueryClient } from "@tanstack/react-query" const queryClient = new QueryClient(); const page$ = observable(1) const obs$ = persistObservable( { initialValue: "hello" }, { pluginLocal: ObservablePersistLocalStorage, local: { name: "user", }, pluginRemote: persistPluginQuery({ queryClient, query: { // queryKey is a computed function that updates the query when page$ changes queryKey: () => ["key", page$.get()], queryFn: () => { return fetch("https://url.to.get?page=" + page$.get()).then((res) => res.json() ) }, }, }), } ) ``` -------------------------------- ### Reactive Animations with Framer Motion Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v3/llms/react/react-examples.md This example showcases how to integrate Legend App's reactive state management with Framer Motion for animating components based on reactive props. It utilizes `reactive` to create a `MotionDiv` that animates its background color and 'x' position based on a boolean observable. The `useComputed` hook is implicitly used within the `$animate` prop to derive animation values from the observable state. Ensure `framer-motion` and `@legendapp/state/react` are installed. ```jsx import { reactive } from "@legendapp/state/react" import { motion } from "framer-motion" import { useRef } from "react" import { observable } from "@legendapp/state" import { useComputed, useObservable, Memo } from "@legendapp/state/react" const MotionDiv = reactive(motion.div) function Toggle({ $value }) { return ( ({ backgroundColor: $value.get() ? '#6ACB6C' : '#515153' })} style={{ width: 64, height: 32 }} onClick={$value.toggle} > ({ x: $value.get() ? 34 : 4 })} /> ) } const settings$ = observable({ enabled: false }) function App() { const renderCount = ++useRef(0).current // Computed text value const text$ = useObservable(() => ( settings$.enabled.get() ? 'Yes' : 'No' )) return (
Renders: {renderCount}
Enabled: {text$}
) } ``` -------------------------------- ### Get Current Time Observable Source: https://github.com/legendapp/legend-docs/blob/main/docs/content/state/v2/react/helpers-and-hooks.mdx Use `currentTime` to get an observable that updates every minute. Import from `@legendapp/state/helpers/time`. ```javascript import { currentTime } from "@legendapp/state/helpers/time" observe(() => { console.log('The time is is': currentTime.get()) }) ``` -------------------------------- ### Basic Observable Usage in React Source: https://github.com/legendapp/legend-docs/blob/main/docs/public/state/v2/llms/intro/introduction.md Demonstrates creating an observable object, getting and setting its values, and using `observe` to log changes. It also shows how to enable React tracking for automatic component re-renders when observable values change. ```jsx const state$ = observable({ settings: { theme: "dark" } }); const theme = state$.settings.theme.get(); state$.settings.theme.set("light"); observe(() => { console.log(state$.settings.theme.get()); }); enableReactTracking({ auto: true }); const Component = function Component() { const theme = state$.settings.theme.get(); return
Theme: {theme}
; }; ```