### Complete Theme Color Setup Example Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/03-color-module.md Demonstrates how to generate a color palette and apply it to CSS variables for a complete theme setup. This is useful for dynamic theming in applications. ```typescript import { getColorPalette, getPaletteColorByNumber } from '@sa/color'; const primaryColor = '#1890ff'; const palette = getColorPalette(primaryColor); // Use in CSS variables const root = document.documentElement; for (let i = 50; i <= 950; i += 50) { const hexColor = palette.get(i as ColorPaletteNumber); root.style.setProperty(`--primary-${i}`, hexColor); } ``` -------------------------------- ### useTable Example with Setup Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/02-hooks-module.md Demonstrates how to use the useTable hook within a Vue 3 setup function, configuring API calls, data transformation, and column definitions. ```typescript import { useTable } from '@sa/hooks'; interface User { id: number; name: string; email: string; } interface ApiResponse { data: User[]; pageNum: number; pageSize: number; total: number; } export default { setup() { const { loading, data, columns, columnChecks, getData } = useTable< ApiResponse, User, DataTableColumn, true >({ api: () => apiService.getUsers(), pagination: true, transform: (response) => ({ data: response.data, pageNum: response.pageNum, pageSize: response.pageSize, total: response.total }), columns: () => [ { key: 'id', title: 'ID' }, { key: 'name', title: 'Name' }, { key: 'email', title: 'Email' } ], getColumnChecks: (cols) => cols.map(col => ({ key: col.key, title: col.title, checked: true, visible: true, fixed: 'unFixed' })), getColumns: (cols, checks) => { const checkMap = new Map(checks.map(c => [c.key, c.checked])); return cols.filter(col => checkMap.get(col.key) !== false); }, onFetched: (data) => { console.log('Data fetched:', data); }, immediate: true }); return { loading, data, columns, columnChecks, getData }; } }; ``` -------------------------------- ### Complete API Example with Axios Module Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/04-axios-module.md Demonstrates a comprehensive setup for the Axios module, including request creation, response transformation, backend error handling, and usage for login and file downloads. Requires importing createRequest from '@sa/axios'. ```typescript import { createRequest } from '@sa/axios'; import type { AxiosError, AxiosResponse } from 'axios'; // Define types interface LoginRequest { username: string; password: string; } interface LoginResponse { code: number; message: string; data: { token: string; user: { id: number; name: string }; }; } interface ApiUser { id: number; name: string; } interface RequestState { token?: string; refreshing?: boolean; } // Create request instance const request = createRequest( { baseURL: 'https://api.example.com', timeout: 15000, withCredentials: true }, { defaultState: { token: localStorage.getItem('token') || '' }, transform: (response) => { // Transform backend response to API data if (response.data.code === 0) { return response.data.data.user; } throw new Error(response.data.message); }, transformBackendResponse: (response) => response.data, onRequest: (config) => { // Add auth token if (request.state.token) { config.headers.set('Authorization', `Bearer ${request.state.token}`); } return config; }, isBackendSuccess: (response) => response.data.code === 0, onBackendFail: async (response, instance) => { // Handle specific error codes if (response.data.code === 401) { // Token expired - refresh token flow if (!request.state.refreshing) { request.state.refreshing = true; try { const refreshResponse = await instance.post('/refresh-token'); const newToken = refreshResponse.data.data.token; request.state.token = newToken; localStorage.setItem('token', newToken); request.state.refreshing = false; // Retry original request return instance(response.config as any); } catch (err) { request.state.refreshing = false; // Redirect to login window.location.href = '/login'; return null; } } } return null; }, onError: (error) => { if (error.response?.status === 500) { // Show error toast console.error('Server error:', error.message); } else if (!error.response) { console.error('Network error:', error.message); } } } ); // Use in component async function login(username: string, password: string) { try { const user = await request({ url: '/login', method: 'POST', data: { username, password } }); console.log('Logged in as:', user.name); } catch (error) { console.error('Login failed:', error); } } // Download file async function downloadFile(fileName: string) { const blob = await request({ url: '/files/' + fileName, method: 'GET', responseType: 'blob' }); // blob is Blob type const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = fileName; a.click(); } ``` -------------------------------- ### Example Soybean Configuration File Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md An example configuration file (soybean.config.ts) demonstrating how to set CLI options such as directories for cleanup, npm-check-updates arguments, and Git commit verification ignores. ```typescript // soybean.config.ts export default { cleanupDirs: ['node_modules', 'dist', 'build', '.turbo'], ncuCommandArgs: ['-u', '-x', '@types/*'], changelogOptions: { // Changelog generation config }, gitCommitVerifyIgnores: ['Merge pull request', 'Merge branch'] } ``` -------------------------------- ### Install Git Hooks Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Command to install Git hooks defined in the project configuration. After running this, the hooks will be active for Git operations. ```bash # Install hooks pnpm prepare ``` -------------------------------- ### Common Patterns with Script Setup Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/02-hooks-module.md Illustrates the use of multiple Soybean Admin hooks, including useBoolean and useLoading, within a Vue 3 ` ``` -------------------------------- ### Workspace Package Dependencies Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/08-project-overview.md Example of how internal packages reference each other using `workspace:*` in package.json for local development and version consistency. ```json { "@sa/utils": "workspace:*", "@sa/hooks": "workspace:*", "@sa/axios": "workspace:*" } ``` -------------------------------- ### Cleanup Directories Before Build Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Command to clean specified directories before starting a build process. Useful for ensuring a fresh build environment. ```bash # Clean and rebuild pnpm sa cleanup --cleanupDir "dist,coverage,.turbo" pnpm build ``` -------------------------------- ### Cancel All Requests Example Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/04-axios-module.md Demonstrates how to cancel all pending requests initiated by a request instance. Ensure the request instance is created using `createRequest`. ```typescript const request = createRequest(config, options); // Later, cancel all pending requests request.cancelAllRequest(); ``` -------------------------------- ### Color Mixing for UI Example Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/03-color-module.md Illustrates mixing primary and danger colors to create a warning color and then finding its CSS name. This is practical for UI element styling. ```typescript import { mixColor, getColorName } from '@sa/color'; const primary = '#1890ff'; const danger = '#ff4d4f'; const warning = mixColor(primary, danger, 0.5); const name = getColorName(warning); ``` -------------------------------- ### Color Validation and Transformation Example Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/03-color-module.md Shows how to validate user input for colors, convert them to hex format, and add alpha transparency. This is essential for handling user-provided color data. ```typescript import { isValidColor, getHex, addColorAlpha } from '@sa/color'; const userColor = userInput; if (!isValidColor(userColor)) { console.error('Invalid color'); } else { const hex = getHex(userColor); const transparent = addColorAlpha(hex, 0.5); } ``` -------------------------------- ### createLocalforage Function Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/01-utils-module.md Creates a typed localforage interface with support for localStorage, IndexedDB, or WebSQL. It provides asynchronous methods for getting, setting, and removing items. ```APIDOC ## createLocalforage Function ### Description Creates a typed localforage interface with support for localStorage, IndexedDB, or WebSQL. It provides asynchronous methods for getting, setting, and removing items. ### Function Signature ```typescript function createLocalforage(driver: LocalforageDriver) ``` #### Parameters - **driver** (`'local' | 'indexedDB' | 'webSQL'`) - Required - The storage driver to use **Returns:** Typed localforage instance ### Supported Methods #### getItem ```typescript getItem(key: K, callback?: (err: any, value: T[K] | null) => void): Promise ``` #### setItem ```typescript setItem(key: K, value: T[K], callback?: (err: any, value: T[K]) => void): Promise ``` #### removeItem ```typescript removeItem(key: keyof T, callback?: (err: any) => void): Promise ``` ### Example ```typescript interface CacheData { userData: { name: string; age: number }; apiResults: unknown; } const cache = createLocalforage('indexedDB'); // Set with promise await cache.setItem('userData', { name: 'John', age: 30 }); // Get with promise const userData = await cache.getItem('userData'); // With callback cache.getItem('userData', (err, value) => { if (err) console.error(err); if (value) console.log(value); }); ``` ``` -------------------------------- ### createStorage Function Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/01-utils-module.md Creates a typed storage interface for either localStorage or sessionStorage with prefix support. It allows setting, getting, removing, and clearing data. ```APIDOC ## createStorage Function ### Description Creates a typed storage interface for either localStorage or sessionStorage with prefix support. It allows setting, getting, removing, and clearing data. ### Function Signature ```typescript function createStorage(type: StorageType, storagePrefix: string) ``` #### Parameters - **type** (`'local' | 'session'`) - Required - The storage type - **storagePrefix** (string) - Required - Prefix for all keys (e.g., 'app_') **Returns:** Storage object with methods ### Storage Object Methods #### set ```typescript set(key: K, value: T[K]): void ``` Sets a value in storage, automatically JSON-serialized. #### get ```typescript get(key: K): T[K] | null ``` Gets a value from storage, automatically JSON-parsed. Returns null if key doesn't exist or parsing fails. #### remove ```typescript remove(key: keyof T): void ``` Removes a key from storage. #### clear ```typescript clear(): void ``` Clears all items from storage. ### Example ```typescript interface AppStorage { theme: 'light' | 'dark'; userId: number; preferences: Record; } const storage = createStorage('local', 'app_'); // Set values storage.set('theme', 'dark'); storage.set('userId', 42); // Get values const theme = storage.get('theme'); // 'dark' const userId = storage.get('userId'); // 42 // Remove storage.remove('theme'); // Clear all storage.clear(); ``` ``` -------------------------------- ### Error Handling: Invalid Directory Pattern for Cleanup Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Example of an error message when an overly complex or invalid glob pattern is provided for the 'cleanup' command's '--cleanupDir' option. ```bash pnpm sa cleanup --cleanupDir "invalid/**/too/**/deep" # Error: Glob pattern too complex ``` -------------------------------- ### Error Handling: Invalid Commit Message Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Example of an error message shown when a commit message does not follow the Conventional Commits format. The 'git-commit-verify' script prevents such commits. ```bash # Will show error and prevent commit pnpm sa git-commit-verify # Error: Commit message must follow Conventional Commits format ``` -------------------------------- ### Production Build Scripts Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/08-project-overview.md Build the project for production or testing environments. Includes a command to preview the built files. ```bash pnpm build # Production build pnpm build:test # Test mode build pnpm preview # Preview built files ``` -------------------------------- ### Complete Development Release Workflow Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Steps for a complete development release, including making and committing changes, testing, and performing a full release with custom scripts. ```bash # 1. Make changes and commit with standard format pnpm sa git-commit # 2. Test everything pnpm test # 3. Release with full workflow pnpm sa release -e "pnpm build && pnpm test" # 4. Automated changelog and version bump ``` -------------------------------- ### Development Server Scripts Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/08-project-overview.md Run the development server for testing and development. Supports both test and production modes. ```bash pnpm dev # Development server (test mode) pnpm dev:prod # Development server (prod mode) ``` -------------------------------- ### CLI Help Text Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Displays the help message for the Soybean Admin CLI, listing available commands and global options. ```bash $ pnpm sa --help soybean-admin Commands: cleanup delete dirs: node_modules, dist, etc. update-pkg update package.json dependencies versions git-commit git commit, generate commit message git-commit-verify verify git commit message changelog generate changelog release release: update version, changelog, commit gen-route generate route Options: -l, --lang display lang of cli (default: en-us) -h, --help Display this message -v, --version Display version number ``` -------------------------------- ### Release Workflow Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Automates the release process by bumping versions, generating changelogs, and committing changes. Supports custom commands and push options. ```bash # Full release workflow with default options pnpm sa release # Release with custom command pnpm sa release --execute "pnpm build && pnpm test" # Release without pushing pnpm sa release --push false ``` -------------------------------- ### Accessing CLI Commands Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Shows how to access the CLI commands provided by the @sa/scripts package. ```bash pnpm sa [command] [options] ``` ```bash pnpm sa --help ``` -------------------------------- ### Get Closest CSS Color Name Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/03-color-module.md Finds the closest CSS color name for a given color string. Useful for mapping arbitrary colors to standard names. ```typescript import { getColorName } from '@sa/color'; getColorName('#ff0000'); // 'red' getColorName('#ff0001'); // 'red' (closest match) ``` -------------------------------- ### Release Workflow Command Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Initiates the release process, including version bumping, executing custom scripts, and committing changes. Use the -e flag to specify custom scripts to run before committing. ```bash pnpm sa release -e "pnpm lint && pnpm build" -p ``` -------------------------------- ### Get Specific Palette Color by Number Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/03-color-module.md Retrieves a specific color from a generated palette using its numerical level (e.g., 100, 500, 900). Useful for accessing individual shades. ```typescript import { getPaletteColorByNumber } from '@sa/color'; const lightColor = getPaletteColorByNumber('#1890ff', 100); const darkColor = getPaletteColorByNumber('#1890ff', 900); ``` -------------------------------- ### CLI Version Display Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Command to display the current version of the Soybean Admin CLI. ```bash $ pnpm sa --version 2.2.0 ``` -------------------------------- ### CLI Commands for Project Management Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/08-project-overview.md Utilize built-in CLI commands for common project tasks such as cleaning directories, committing code, and generating routes. ```bash pnpm sa cleanup # Clean directories pnpm sa git-commit # Commit with standard format pnpm sa release # Release workflow pnpm sa gen-route # Generate routes ``` -------------------------------- ### Vite Configuration Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/08-project-overview.md Configuration file for Vite, setting up the build tool with Vue 3 support, JSX, SVG icons, and progress display. ```typescript import { defineConfig } from "vite" import vue from "@vitejs/plugin-vue" import vueJsx from "@vitejs/plugin-vue-jsx" import svgLoader from "vite-svg-loader" import svgPlugin from "vite-plugin-svgo" import progress from "vite-plugin-progress" import { fileURLToPath, URL } from "node:url" // https://vitejs.dev/config/ export default defineConfig({ plugins: [ vue(), vueJsx(), svgLoader(), svgPlugin(), progress(), ], resolve: { alias: { "@": fileURLToPath(new URL("./src", import.meta.url)), }, }, // optimizeDeps: { // include: [ // 'element-plus', // 'lodash-es', // ], // }, // server: { // host: "0.0.0.0", // port: 3000, // open: true, // proxy: { // // /api: { // // target: "http://127.0.0.1:8080", // // changeOrigin: true, // // rewrite: (path) => path.replace("^/api", ""), // // }, // }, // }, // build: { // terserOptions: { // compress: { // drop_console: true, // drop_debugger: true, // }, // }, // }, }) ``` -------------------------------- ### createFlatRequest Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/04-axios-module.md Creates a request instance that never throws, returning a flat object with data or error. This is useful for scenarios where you want to handle errors directly within the response object. ```APIDOC ## createFlatRequest ### Description Creates a request instance that never throws, returning a flat object with data or error. This is ideal for simplifying error handling by always providing a consistent response structure. ### Method Signature ```typescript function createFlatRequest>( axiosConfig?: CreateAxiosDefaults, options?: Partial> ): FlatRequestInstance ``` ### Parameters #### Arguments - **axiosConfig** (CreateAxiosDefaults) - Optional - Axios configuration object. - **options** (Partial) - Optional - Request options for response transformation and handling. ### Returns - **FlatRequestInstance** - A callable async function that returns a flat object containing data or error. ### Example ```typescript import { createFlatRequest } from '@sa/axios'; const request = createFlatRequest( { baseURL: 'https://api.example.com' }, { transform: (response) => response.data, onRequest: (config) => config, isBackendSuccess: (response) => response.data.code === 0, onBackendFail: async (response) => null, onError: (error) => console.error(error) } ); // Use the request - never throws const { data, error, response } = await request({ url: '/users', method: 'GET' }); if (error) { console.error('Failed:', error.message); } else { console.log('Success:', data); } ``` ``` -------------------------------- ### Check and Update Dependencies Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Commands for managing project dependencies. 'update-pkg' checks for outdated packages, and 'git-commit-verify' ensures commit messages adhere to the standard format. ```bash # Check for outdated packages pnpm sa update-pkg # Verify commits follow standard pnpm sa git-commit-verify ``` -------------------------------- ### AdminLayoutSiderConfig Interface Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/05-materials-module.md Configure the visibility, classes, and widths for the sidebar, including collapsed and mobile states. Defaults to visible and expanded. ```typescript interface AdminLayoutSiderConfig { siderVisible?: boolean; // default: true siderClass?: string; // default: '' mobileSiderClass?: string; // default: '' siderCollapse?: boolean; // default: false siderWidth?: number; // default: 220px siderCollapsedWidth?: number; // default: 64px } ``` -------------------------------- ### Error Handling: Dirty Working Directory During Release Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Illustrates the warning and confirmation prompt when attempting a release with uncommitted changes in the working directory. The 'release' command requires a clean state. ```bash # Will show warning and require confirmation pnpm sa release # Error: Working directory has uncommitted changes ``` -------------------------------- ### AdminLayoutContentConfig Interface Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/05-materials-module.md Configure CSS classes for the main content area or enable full-screen content display. 'fullContent' hides other layout elements. ```typescript export interface AdminLayoutContentConfig { contentClass?: string; // default: '' fullContent?: boolean; // hides other elements if true } ``` -------------------------------- ### AdminLayoutHeaderConfig Interface Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/05-materials-module.md Configure the visibility and height of the admin layout header. Defaults to visible with a height of 56px. ```typescript interface AdminLayoutHeaderConfig { headerVisible?: boolean; // default: true headerHeight?: number; // default: 56px } ``` -------------------------------- ### Simple Git Hooks Configuration Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Configuration for simple-git-hooks to automate Git actions. It sets up commit message verification and pre-commit checks including type checking, linting, and formatting. ```json { "simple-git-hooks": { "commit-msg": "pnpm sa git-commit-verify", "pre-commit": "pnpm typecheck && pnpm lint && pnpm fmt" } } ``` -------------------------------- ### Generate Changelog Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Generates a changelog from git tags and commits. Use the --total flag to generate from all tags. ```bash # Generate changelog from recent commits pnpm sa changelog # Generate complete changelog from all tags pnpm sa changelog --total pnpm sa changelog -t ``` -------------------------------- ### Create Typed Localforage Instance Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/01-utils-module.md Create a typed interface for localforage, supporting drivers like IndexedDB, localStorage, or WebSQL. Provides promise-based and callback-based methods for data operations. Ideal for more complex client-side caching or offline data. ```typescript import localforage from 'localforage'; import { createLocalforage } from '@sa/utils'; interface CacheData { userData: { name: string; age: number }; apiResults: unknown; } const cache = createLocalforage('indexedDB'); // Set with promise await cache.setItem('userData', { name: 'John', age: 30 }); // Get with promise const userData = await cache.getItem('userData'); // With callback cache.getItem('userData', (err, value) => { if (err) console.error(err); if (value) console.log(value); }); ``` -------------------------------- ### TypeScript Configuration for CLI Options Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Defines the structure for CLI configuration options, including directories to clean up, npm-check-updates arguments, changelog settings, and Git commit verification ignores. ```typescript interface CliConfig { cleanupDirs: string[]; ncuCommandArgs: string[]; changelogOptions: ChangelogConfig; gitCommitVerifyIgnores: string[]; } interface ChangelogConfig { // Version template configuration // Release note generation settings } ``` -------------------------------- ### Cleanup Directories Command Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Deletes specified directories like node_modules, dist, etc. Use the --cleanupDir option to specify custom directories. ```bash # Delete default cleanup directories pnpm sa cleanup # Delete specific directories pnpm sa cleanup --cleanupDir "dist,build,coverage" # Multiple patterns pnpm sa cleanup --cleanupDir "**/.turbo,**/.next,**/node_modules" ``` -------------------------------- ### AdminLayoutTabConfig Interface Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/05-materials-module.md Configure the visibility, class, and height of the tab bar for page navigation. Defaults to visible with a height of 48px. ```typescript interface AdminLayoutTabConfig { tabVisible?: boolean; // default: true tabClass?: string; // default: '' tabHeight?: number; // default: 48px } ``` -------------------------------- ### Create Flat Request Instance Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/04-axios-module.md Use `createFlatRequest` to create a request instance that never throws, returning a flat object with `data` or `error`. This is useful for simplifying error handling in components. ```typescript function createFlatRequest>( axiosConfig?: CreateAxiosDefaults, options?: Partial> ): FlatRequestInstance ``` ```typescript import { createFlatRequest } from '@sa/axios'; const request = createFlatRequest( { baseURL: 'https://api.example.com' }, { transform: (response) => response.data, onRequest: (config) => config, isBackendSuccess: (response) => response.data.code === 0, onBackendFail: async (response) => null, onError: (error) => console.error(error) } ); // Use the request - never throws const { data, error, response } = await request({ url: '/users', method: 'GET' }); if (error) { console.error('Failed:', error.message); } else { console.log('Success:', data); } ``` -------------------------------- ### AdminLayoutFooterConfig Interface Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/05-materials-module.md Configure the visibility, fixed positioning, class, height, and placement of the admin layout footer. Defaults to visible, fixed, and with a height of 48px. ```typescript export interface AdminLayoutFooterConfig { footerVisible?: boolean; // default: true fixedFooter?: boolean; // default: true footerClass?: string; // default: '' footerHeight?: number; // default: 48px rightFooter?: boolean; // footer on right side in vertical layout } ``` -------------------------------- ### Export Colord Instance Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/03-color-module.md Exports the colord instance with all extended plugins, including names, mix, and lab functionalities. ```typescript export { colord } ``` -------------------------------- ### Flat Request Pattern with Axios Module Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/04-axios-module.md Utilizes `createFlatRequest` for simplified API calls where errors are returned directly, eliminating the need for try/catch blocks. Requires importing `createFlatRequest` from '@sa/axios'. ```typescript import { createFlatRequest } from '@sa/axios'; const request = createFlatRequest(config, options); // Usage - no try/catch needed async function safeFetch() { const { data, error } = await request({ url: '/api/data' }); if (error) { switch (error.code) { case 'ECONNABORTED': console.log('Request timeout'); break; case 'BACKEND_ERROR_CODE': console.log('Backend error:', error.response?.data); break; default: console.log('Unknown error:', error.message); } } else { console.log('Success:', data); } } ``` -------------------------------- ### getColorPalette Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/03-color-module.md Generates a complete color palette from a base color, providing shades from light to dark. Optionally uses a recommended algorithm for palette generation. ```APIDOC ## getColorPalette ### Description Generates a complete color palette from a base color. ### Method `getColorPalette(color: AnyColor, recommended?: boolean): Map` ### Parameters #### Path Parameters - `color` (AnyColor) - Required - Base color - `recommended` (boolean) - Optional - Use recommended palette algorithm (defaults to false) ### Response #### Success Response - `Map` - Map of palette level to hex color ### Example ```typescript import { getColorPalette } from '@sa/color'; const palette = getColorPalette('#1890ff'); console.log(palette.get(500)); // '#1890ff' (main color) console.log(palette.get(100)); // lighter shade console.log(palette.get(900)); // darker shade ``` ``` -------------------------------- ### Generate Routes After Adding Pages Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Command to regenerate route definitions after adding new page components. This ensures that the type-safe router is updated with the latest routes. ```bash # After creating new page components pnpm sa gen-route # Routes are automatically available in type-safe router ``` -------------------------------- ### Create Typed Local/Session Storage Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/01-utils-module.md Create a typed interface for localStorage or sessionStorage with key prefixing. Automatically handles JSON serialization/deserialization. Useful for structured client-side data storage. ```typescript import { createStorage } from '@sa/utils'; interface AppStorage { theme: 'light' | 'dark'; userId: number; preferences: Record; } const storage = createStorage('local', 'app_'); // Set values storage.set('theme', 'dark'); storage.set('userId', 42); // Get values const theme = storage.get('theme'); // 'dark' const userId = storage.get('userId'); // 42 // Remove storage.remove('theme'); // Clear all storage.clear(); ``` -------------------------------- ### State Management with Axios Module Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/04-axios-module.md Shows how to define and manage state within the Axios request instance, allowing for dynamic modification and usage in request interceptors. Requires defining an `ApiState` interface and using `createRequest`. ```typescript // Define state type interface ApiState { isAuthenticated: boolean; userId?: number; permissions: string[]; } const request = createRequest( config, { defaultState: { isAuthenticated: false, permissions: [] }, // ... other options } ); // Modify state request.state.isAuthenticated = true; request.state.userId = 123; request.state.permissions = ['read', 'write']; // Use state in hooks onRequest: (config) => { if (request.state.isAuthenticated) { config.headers.set('X-User-Id', String(request.state.userId)); } return config; } ``` -------------------------------- ### Create Standard Request Instance Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/04-axios-module.md Use `createRequest` to create a standard request instance that throws on error or returns transformed data. Configure with Axios defaults and request options for response transformation and error handling. ```typescript function createRequest>( axiosConfig?: CreateAxiosDefaults, options?: Partial> ): RequestInstance ``` ```typescript import { createRequest } from '@sa/axios'; const request = createRequest( { baseURL: 'https://api.example.com', timeout: 10000 }, { transform: (response) => response.data, onRequest: (config) => { // Add auth header const token = localStorage.getItem('token'); if (token) { config.headers.set('Authorization', `Bearer ${token}`); } return config; }, isBackendSuccess: (response) => response.data.code === 0, onBackendFail: async (response, instance) => { if (response.data.code === 401) { // Handle token expiry return null; } return null; }, onError: (error) => { console.error('Request failed:', error.message); } } ); // Use the request const data = await request({ url: '/users', method: 'GET' }); ``` -------------------------------- ### RequestOption Interface Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/04-axios-module.md Defines the configuration object for customizing request behavior, including default state, response transformations, and various hooks for request lifecycle events. ```typescript interface RequestOption = Record> { defaultState?: State; transform: ResponseTransform, ApiData>; transformBackendResponse: ResponseTransform, ApiData>; onRequest: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig | Promise; isBackendSuccess: (response: AxiosResponse) => boolean; onBackendFail: (response: AxiosResponse, instance: AxiosInstance) => Promise | Promise; onError: (error: AxiosError) => void | Promise; } ``` -------------------------------- ### Generate Complete Color Palette Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/03-color-module.md Generates a full color palette from a base color, providing shades from light to dark. Use this to create a consistent color scheme. ```typescript import { getColorPalette } from '@sa/color'; const palette = getColorPalette('#1890ff'); console.log(palette.get(500)); // '#1890ff' (main color) console.log(palette.get(100)); // lighter shade console.log(palette.get(900)); // darker shade ``` -------------------------------- ### Generate Routes Command Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Automatically generates Vue Router route definitions based on the file system structure. This command scans the pages directory to create route imports, declarations, and types. ```bash pnpm sa gen-route ``` -------------------------------- ### createRequest Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/04-axios-module.md Creates a standard request instance that throws on error or returns transformed data. It's suitable for most API interactions where error propagation is desired. ```APIDOC ## createRequest ### Description Creates a standard request instance that throws on error or returns transformed data. This function is designed for making API calls where explicit error handling is preferred. ### Method Signature ```typescript function createRequest>( axiosConfig?: CreateAxiosDefaults, options?: Partial> ): RequestInstance ``` ### Parameters #### Arguments - **axiosConfig** (CreateAxiosDefaults) - Optional - Axios configuration object (e.g., baseURL, timeout). - **options** (Partial) - Optional - Request options for response transformation and handling. ### Returns - **RequestInstance** - A callable async function for making requests. ### Example ```typescript import { createRequest } from '@sa/axios'; const request = createRequest( { baseURL: 'https://api.example.com', timeout: 10000 }, { transform: (response) => response.data, onRequest: (config) => { const token = localStorage.getItem('token'); if (token) { config.headers.set('Authorization', `Bearer ${token}`); } return config; }, isBackendSuccess: (response) => response.data.code === 0, onBackendFail: async (response, instance) => { if (response.data.code === 401) { return null; } return null; }, onError: (error) => { console.error('Request failed:', error.message); } } ); // Use the request const data = await request({ url: '/users', method: 'GET' }); ``` ``` -------------------------------- ### Storage Types Definition Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/07-types-reference.md Defines types for storage operations, including storage types, an interface for key-value storage, and supported drivers for localforage. ```typescript type StorageType = 'local' | 'session'; interface StorageInterface { set(key: K, value: T[K]): void; get(key: K): T[K] | null; remove(key: keyof T): void; clear(): void; } type LocalforageDriver = 'local' | 'indexedDB' | 'webSQL'; ``` -------------------------------- ### Supported Response Types Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/04-axios-module.md Defines the supported response types for requests, including 'json', 'blob', 'text', 'arrayBuffer', 'stream', and 'document'. ```typescript type ResponseType = keyof ResponseMap | 'json' ``` -------------------------------- ### Supported Content Types Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/04-axios-module.md Defines the set of supported content types for request bodies in the `@sa/axios` module. ```typescript type ContentType = | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream' ``` -------------------------------- ### Pre-defined Color Palettes Constant Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/03-color-module.md Imports a constant containing pre-defined color palettes for common theme colors. This provides quick access to standard color sets. ```typescript import { colorPalettes } from '@sa/color'; ``` -------------------------------- ### LayoutMode Type Definition Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/05-materials-module.md Defines the possible orientations for the admin layout. Use 'horizontal' for top navigation or 'vertical' for side navigation. ```typescript type LayoutMode = 'horizontal' | 'vertical' ``` -------------------------------- ### AdminLayoutProps Interface Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/05-materials-module.md Defines the complete set of properties for the AdminLayout component, extending various configuration interfaces for header, tab, sider, content, and footer. ```typescript export interface AdminLayoutProps extends AdminLayoutHeaderConfig, AdminLayoutTabConfig, AdminLayoutSiderConfig, AdminLayoutContentConfig, AdminLayoutFooterConfig { mode?: LayoutMode; // 'horizontal' | 'vertical' isMobile?: boolean; scrollMode?: LayoutScrollMode; // 'wrapper' | 'content' scrollElId?: string; // ID of scroll element scrollElClass?: string; scrollWrapperClass?: string; commonClass?: string; // default: 'transition-all-300' fixedTop?: boolean; // default: true maxZIndex?: number; } ``` -------------------------------- ### AES Encryption with Crypto Class Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/01-utils-module.md Use the Crypto class for AES encryption and decryption. Instantiate with a secret key. Ensure the secret key is kept secure. ```typescript import { Crypto } from '@sa/utils'; const crypto = new Crypto('my-secret-key'); const encrypted = crypto.encrypt({ userId: 123, role: 'admin' }); console.log(encrypted); // encrypted string ``` -------------------------------- ### useContext Types Definition Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/07-types-reference.md Defines types related to context management, including context names, values, providers, and consumers. ```typescript type ContextName = string | { name: string; key: string | symbol }; type ContextValue = T extends (...args: any[]) => any ? ReturnType : T; type ContextProvider = T extends (...args: any[]) => any ? T : (arg: T) => T; type ContextConsumer = ( consumerName?: N, defaultValue?: Context ) => N extends null | undefined ? Context | null : Context; ``` -------------------------------- ### Code Quality Scripts Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/08-project-overview.md Scripts for maintaining code quality, including TypeScript type checking, linting, and formatting. ```bash pnpm typecheck # TypeScript type checking pnpm lint # Lint and fix code pnpm fmt # Format code ``` -------------------------------- ### useLoading Return Type Definition Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/07-types-reference.md Defines the structure of the state returned by the useLoading hook, including loading status and functions to start/end loading. ```typescript interface LoadingState { loading: Ref; startLoading: () => void; endLoading: () => void; } ``` -------------------------------- ### Update Package Dependencies Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Updates package.json dependency versions using npm-check-updates. This command runs interactively. ```bash # Interactive update pnpm sa update-pkg ``` -------------------------------- ### RequestInstance Interface Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/04-axios-module.md Represents a callable request function that extends common request instance properties, allowing for API data retrieval with customizable response types. ```typescript interface RequestInstance> extends RequestInstanceCommon { (config: CustomAxiosRequestConfig): Promise>; } ``` -------------------------------- ### Crypto Class Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/01-utils-module.md A generic class for AES encryption and decryption using CryptoJS. It requires a secret key for initialization and provides methods to encrypt and decrypt data. ```APIDOC ## Crypto Class ### Description A generic class for AES encryption and decryption using CryptoJS. It requires a secret key for initialization and provides methods to encrypt and decrypt data. ### Constructor ```typescript constructor(secret: string) ``` #### Parameters - **secret** (string) - Required - The secret key used for encryption/decryption ### Methods #### encrypt ```typescript encrypt(data: T): string ``` Encrypts data object to an encrypted string. #### Parameters - **data** (T (object)) - Required - The data to encrypt **Returns:** `string` - The encrypted data string ### Request Example ```typescript const crypto = new Crypto('my-secret-key'); const encrypted = crypto.encrypt({ userId: 123, role: 'admin' }); console.log(encrypted); // encrypted string ``` #### decrypt ```typescript decrypt(encrypted: string): T | null ``` Decrypts an encrypted string back to the original data object. #### Parameters - **encrypted** (string) - Required - The encrypted string **Returns:** `T | null` - The decrypted object, or null if decryption/parsing fails ### Response Example ```typescript const crypto = new Crypto('my-secret-key'); const decrypted = crypto.decrypt(encryptedString); if (decrypted) { console.log(decrypted.userId); // 123 } ``` ``` -------------------------------- ### Basic Color Types Definition Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/07-types-reference.md Defines types for color palettes, including numbers, indices, and structured palette information. ```typescript type ColorPaletteNumber = 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 950; type ColorIndex = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11; interface ColorPalette { hex: string; number: ColorPaletteNumber; } interface ColorPaletteFamily { name: string; palettes: ColorPalette[]; } interface ColorPaletteWithDelta extends ColorPalette { delta: number; } interface ColorPaletteFamilyWithNearestPalette extends ColorPaletteFamily { nearestPalette: ColorPaletteWithDelta; nearestLightnessPalette: ColorPaletteWithDelta; } interface ColorPaletteMatch extends ColorPaletteFamily { colorMap: Map; main: ColorPalette; match: ColorPalette; } ``` -------------------------------- ### UseTableOptions Type Definition Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/02-hooks-module.md Defines the configuration options for the useTable hook, including API endpoint, data transformation, column definitions, and callbacks. ```typescript interface UseTableOptions { api: () => Promise; pagination?: Pagination; transform: (response: ResponseData) => PaginationData | ApiData[]; columns: () => Column[]; getColumnChecks: (columns: Column[]) => TableColumnCheck[]; getColumns: (columns: Column[], checks: TableColumnCheck[]) => Column[]; onFetched?: (data: PaginationData | ApiData[]) => void | Promise; immediate?: boolean; } ``` -------------------------------- ### transformColorWithOpacity Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/03-color-module.md Transforms a color to an equivalent opaque color, considering a background color and alpha value. Useful for ensuring color visibility on different backgrounds. ```APIDOC ## transformColorWithOpacity ### Description Transforms a color with opacity to a similar opaque color based on background. ### Method `transformColorWithOpacity(color: AnyColor, alpha: number, bgColor?: string): string` ### Parameters #### Path Parameters - `color` (AnyColor) - Required - Color to transform - `alpha` (number) - Required - Alpha value (0 - 1) - `bgColor` (string) - Optional - Background color (defaults to '#ffffff') ### Response #### Success Response - `string` - Opaque color ### Example ```typescript import { transformColorWithOpacity } from '@sa/color'; const opaque = transformColorWithOpacity('#ff0000', 0.5, '#ffffff'); // Returns equivalent opaque red on white background ``` ``` -------------------------------- ### Generate Conventional Commit Message Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/06-scripts-cli.md Generates a commit message following the Conventional Commits standard. Supports English and Chinese. ```bash # English interactive commit pnpm sa git-commit # Chinese interactive commit pnpm sa git-commit --lang zh-cn pnpm sa git-commit -l=zh-cn ``` -------------------------------- ### Mix Two Colors Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/03-color-module.md Mixes two colors together based on a specified ratio. Use this for creating intermediate shades or gradients. ```typescript import { mixColor } from '@sa/color'; const mixed = mixColor('#ff0000', '#0000ff', 0.5); // Mix 50% red and 50% blue = purple ``` -------------------------------- ### isWhiteColor Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/03-color-module.md Checks if a given color is white. This is a simple utility for color comparisons. ```APIDOC ## isWhiteColor ### Description Checks if a color is white. ### Method `isWhiteColor(color: AnyColor): boolean` ### Parameters #### Path Parameters - `color` (AnyColor) - Required - Color to check ### Response #### Success Response - `boolean` - True if color is white ``` -------------------------------- ### useSvgIconRender Types Definition Source: https://github.com/soybeanjs/soybean-admin/blob/main/_autodocs/07-types-reference.md Defines types for configuring and styling SVG icons, including icon properties and CSS style overrides. ```typescript interface IconConfig { icon?: string; localIcon?: string; color?: string; fontSize?: number; } type IconStyle = Partial>; ```