### Run the Server Source: https://github.com/fangpenlin/avataaars-generator/blob/master/README.md Use this command to start the web app locally for development. ```bash yarn start ``` -------------------------------- ### Avataaars React Component Example Source: https://context7.com/fangpenlin/avataaars-generator/llms.txt This is an example of a generated React component for a configured avatar. It shows the necessary props to customize the avatar's appearance. Installation instructions for the avataaars npm package are also provided. ```tsx // Generated code example for a configured avatar: ``` ```bash // Installation instructions displayed with code: // yarn add avataaars // or // npm install avataaars --save ``` -------------------------------- ### Avataaars Image API Examples Source: https://context7.com/fangpenlin/avataaars-generator/llms.txt Examples of embedding avatars as images using the external avataaars.io API with URL query parameters. Supports basic and fully customized avatars, including transparent backgrounds. ```html ``` -------------------------------- ### Manage Avatar Options with OptionContext Source: https://context7.com/fangpenlin/avataaars-generator/llms.txt Initializes and interacts with the OptionContext to manage avatar customization state. This includes setting initial data, getting and setting option values, and listening for changes. Ensure 'avataaars' and 'lodash' are imported. ```tsx import { OptionContext, allOptions } from 'avataaars' // Create option context with all available options const optionContext = new OptionContext(allOptions) // Set avatar data from URL params or state optionContext.setData({ topType: 'LongHairStraight', hairColor: 'BrownDark', eyeType: 'Default', mouthType: 'Smile' }) // Get current value for an option const hairColor = optionContext.getValue('hairColor') // Returns: 'BrownDark' // Set a specific option value optionContext.setValue('eyeType', 'Happy') // Get option state including available choices const optionState = optionContext.getOptionState('topType') // Returns: { available: number, options: string[] } // Listen for value changes optionContext.addValueChangeListener((key, value) => { console.log(`Option ${key} changed to ${value}`) }) // Listen for state changes optionContext.addStateChangeListener(() => { console.log('Option states updated') }) ``` -------------------------------- ### Prerender.io Integration Snippet Source: https://github.com/fangpenlin/avataaars-generator/blob/master/public/index.html This snippet is used to inform prerender.io that the page is not yet ready for rendering. It should be placed in the HTML head. ```javascript // tell prerender.io that the page is not loaded // https://prerender.io/documentation/best-practices window.prerenderReady = false ``` -------------------------------- ### Render Basic Avataaars Source: https://context7.com/fangpenlin/avataaars-generator/llms.txt Renders a basic avatar with either a circular or transparent background using the Avatar component. Ensure the 'avataaars' library is imported. ```tsx import { Avatar, AvatarStyle } from 'avataaars' // Basic avatar with circular background // Avatar with transparent background ``` -------------------------------- ### Integrate Avataaars with URL Query Parameters Source: https://context7.com/fangpenlin/avataaars-generator/llms.txt Configures react-url-query to synchronize avatar customization state with URL query parameters. This enables shareable links and browser history support. Requires 'react-url-query', 'history', and 'lodash' libraries. ```tsx import { UrlQueryParamTypes, UrlUpdateTypes, addUrlProps } from 'react-url-query' import { configureUrlQuery } from 'react-url-query' import { allOptions } from 'avataaars' import { fromPairs } from 'lodash' import { createBrowserHistory } from 'history' // Configure URL query with browser history const history = createBrowserHistory() configureUrlQuery({ history }) // Build URL props config for all avatar options const urlPropsQueryConfig = { ...fromPairs( allOptions.map((option) => [ option.key, { type: UrlQueryParamTypes.string, updateType: UrlUpdateTypes.pushIn, }, ]) ), avatarStyle: { type: UrlQueryParamTypes.string, updateType: UrlUpdateTypes.pushIn, }, } // Wrap component to sync props with URL const MainWithUrlProps = addUrlProps({ urlPropsQueryConfig })(Main) // Example shareable URL // http://getavataaars.com/?avatarStyle=Circle&topType=LongHairStraight&hairColor=BrownDark ``` -------------------------------- ### Download Avatar as SVG Source: https://context7.com/fangpenlin/avataaars-generator/llms.txt Directly exports the avatar as a vector SVG file using FileSaver. Requires an Avatar component reference. ```tsx import * as FileSaver from 'file-saver' import * as ReactDOM from 'react-dom' const onDownloadSVG = (avatarRef: Avatar) => { // Get SVG element from Avatar component const svgNode = ReactDOM.findDOMNode(avatarRef) as Element // Convert SVG to blob and download const data = svgNode.outerHTML const svg = new Blob([data], { type: 'image/svg+xml' }) FileSaver.saveAs(svg, 'avataaars.svg') } ``` -------------------------------- ### AvatarForm Component Usage Source: https://context7.com/fangpenlin/avataaars-generator/llms.txt Demonstrates the usage of the AvatarForm component, which provides a UI for customizing avatar attributes. It accepts various props for managing avatar style, options, and download/toggle functionalities. ```tsx import { AvatarStyle, OptionContext } from 'avataaars' interface AvatarFormProps { avatarStyle: AvatarStyle optionContext: OptionContext displayingCode: boolean displayingImg: boolean onDownloadPNG?: () => void onDownloadSVG?: () => void onAvatarStyleChange?: (avatarStyle: AvatarStyle) => void onToggleCode?: () => void onToggleImg?: () => void } // Usage ``` -------------------------------- ### Download Avatar as PNG Source: https://context7.com/fangpenlin/avataaars-generator/llms.txt Converts an SVG avatar to a canvas element and exports it as a PNG file using FileSaver. Requires Avatar and HTMLCanvasElement references. Scales the image 2x for retina quality. ```tsx import * as FileSaver from 'file-saver' import * as ReactDOM from 'react-dom' const onDownloadPNG = (avatarRef: Avatar, canvasRef: HTMLCanvasElement) => { // Get SVG element from Avatar component const svgNode = ReactDOM.findDOMNode(avatarRef) as Element const canvas = canvasRef const ctx = canvas.getContext('2d')! // Clear canvas (528x560 dimensions) ctx.clearRect(0, 0, canvas.width, canvas.height) const DOMURL = window.URL || (window as any).webkitURL // Convert SVG to blob const data = svgNode.outerHTML const img = new Image() const svg = new Blob([data], { type: 'image/svg+xml' }) const url = DOMURL.createObjectURL(svg) img.onload = () => { // Scale 2x for retina quality ctx.save() ctx.scale(2, 2) ctx.drawImage(img, 0, 0) ctx.restore() DOMURL.revokeObjectURL(url) // Download as PNG canvas.toBlob((imageBlob) => { FileSaver.saveAs(imageBlob!, 'avataaars.png') }) } img.src = url } ``` -------------------------------- ### Configure Renderer Mode in React App Source: https://context7.com/fangpenlin/avataaars-generator/llms.txt This code snippet configures the application to either run in normal interactive mode or a special server-side render mode based on URL parameters. It handles rendering the main App component or a Renderer component accordingly. ```tsx // index.tsx - Application entry point const params = new URL(document.location.href).searchParams if (params.get('__render__') !== '1') { // Normal interactive mode configureUrlQuery({ history }) ReactDOM.render(, document.getElementById('root')) registerServiceWorker() } else { // Server render mode - just the avatar ReactDOM.render(, document.body) } ``` -------------------------------- ### Capitalize First Letter Helper Source: https://github.com/fangpenlin/avataaars-generator/blob/master/tools/component-extractor.html A utility function to capitalize the first letter of a string. Used for transforming kebab-case or colon-separated attribute names into camelCase. ```javascript function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } ``` -------------------------------- ### Customize Avataaars with Props Source: https://context7.com/fangpenlin/avataaars-generator/llms.txt Renders a fully customized avatar by passing various attribute props to the Avatar component. All necessary types and components should be imported from 'avataaars'. ```tsx import { Avatar, AvatarStyle } from 'avataaars' // Avatar with custom styling ``` -------------------------------- ### Generate React Component from SVG Source: https://github.com/fangpenlin/avataaars-generator/blob/master/tools/component-extractor.html An event listener that runs on DOMContentLoaded. It collects SVG definitions, converts them, generates unique IDs, and constructs a complete React component string, including imports and render method. ```javascript document.addEventListener('DOMContentLoaded', () => { var top = document.getElementById('Top') var defs = new Set() var treeNode = {} collectDefs(top, defs, treeNode) var defsNodes = [] for (var id of defs) { var node = document.getElementById(id) var defTreeNode = {} convertDef(node, defTreeNode) defsNodes.push(defTreeNode) } var typeCount = {} var idMap = {} var idProps = [] const sortedDefs = Array.from(defs) var newIDs = [] sortedDefs.sort() for (var id of sortedDefs) { var parts = id.split('-') var type = parts[0] var num = parts[1] if (!(type in typeCount)) { typeCount[type] = 1 } else { typeCount[type] += 1 } const newID = type + typeCount[type] newIDs.push(newID) idProps.push(` private ${newID} = uniqueId('react-${type}-')`) idMap[id] = newID } //console.info('$$$$$', defsNodes) // console.info('$$$$$', defsStr) // console.info(defs, treeNode) treeNode.childNodes.unshift({ nodeName: 'defs', attrs: [], childNodes: defsNodes.filter(n => n.nodeName !== 'mask') }) newIDs.sort() const dom = outputNode(treeNode, idMap) const output = ` import * as React from 'react' import { uniqueId } from 'lodash' import FacialHair from './facialHair' import HairColor from './HairColor' export default class FIXME extends React.Component { static optionValue = 'FIXME' ${idProps.join('\n')} render () { const { ${newIDs.join(', ')} } = this return ( ${dom} ) } } ` document.getElementById('output-text').value = output }) ``` -------------------------------- ### Output React Node Source: https://github.com/fangpenlin/avataaars-generator/blob/master/tools/component-extractor.html Generates a React JSX string representation of an SVG node. It handles attribute transformation, including mapping IDs and converting names to camelCase, and recursively processes child nodes. ```javascript function outputNode(node, idMap) { var result = `<${node.nodeName} ` var attrs = [] for (var attr of node.attrs) { var { name, value } = attr var nameParts = name.split('-') if (nameParts.length > 1) { name = nameParts[0] + nameParts.slice(1).map(n => capitalizeFirstLetter(n)) } var nameParts2 = name.split(':') if (nameParts2.length > 1) { name = nameParts2[0] + nameParts2.slice(1).map(n => capitalizeFirstLetter(n)) } if (typeof value === 'function') { value = value(idMap) attrs.push(`${name}={${value}}`) } else { if (name === 'id' && value.startsWith('Top/_Resources/')) { return '{this.props.children}' } else if (name === 'id' && value.startsWith('Facial-Hair/')) { return '' } else if (name === 'id' && value.startsWith('Color/Hair/')) { return "" } attrs.push(`${name}='${value}'`) } } result += attrs.join(' ') + '>' for (var child of node.childNodes) { result += outputNode(child, idMap) } result += `` return result } ``` -------------------------------- ### Collect SVG Definitions Source: https://github.com/fangpenlin/avataaars-generator/blob/master/tools/component-extractor.html Recursively traverses SVG nodes to collect all referenced IDs from attributes like 'xlink:href' and 'id'. This function is crucial for identifying all unique SVG elements that need to be mapped to new IDs. ```javascript function collectDefs (node, defs, treeNode) { if (node.nodeName === '#text') { return } treeNode.nodeName = node.nodeName var re = /^url\(#(.\*)\)/i; var attrs = [] var color = false for (var attr of node.attributes) { var value = attr.value if (attr.name === 'xlink:href') { var id = value.substr(1) defs.add(id) value = (idMap) => "'#" + idMap[id] + "'" } else if (attr.name === 'id' && node.nodeName === 'mask') { var id = attr.value defs.add(id) value = (idMap) => idMap[id] } else { var found = value.match(re); if (found) { var id = found[1] value = (idMap) => '`url(#${' + idMap[id] + '})`' defs.add(id) } } /* if (color && attr.name === 'fill') { value = () => 'color' } // xxx: it's possible id comes after color, but we didn't see it so far if (attr.name === 'id' && attr.value.startsWith('Color/Hair/')) { color = true }*/ attrs.push({ name: attr.name, value }) } treeNode.attrs = attrs var children = [] for (var child of node.childNodes) { var childNode = {} collectDefs(child, defs, childNode) if (childNode.nodeName) { children.push(childNode) } } treeNode.childNodes = children } ``` -------------------------------- ### Generate Random Avatar Source: https://context7.com/fangpenlin/avataaars-generator/llms.txt Generates random avatars by sampling available options for each customizable attribute. Updates the context and URL query parameters. ```tsx import { sample } from 'lodash' import { UrlUpdateTypes } from 'react-url-query' const onRandom = ( optionContext: OptionContext, avatarStyle: AvatarStyle, onChangeUrlQueryParams: (params: any, updateType: string) => void ) => { let values: { [index: string]: string } = { avatarStyle: avatarStyle, } // Sample random values for each option for (const option of optionContext.options) { if (option.key in values) continue const optionState = optionContext.getOptionState(option.key)! if (!optionState.options.length) continue // Pick random value from available options values[option.key] = sample(optionState.options)! } // Update context and URL optionContext.setData(values) onChangeUrlQueryParams(values, UrlUpdateTypes.push) } ``` -------------------------------- ### Convert SVG Definition Node Source: https://github.com/fangpenlin/avataaars-generator/blob/master/tools/component-extractor.html Converts an SVG node into a tree structure, processing attributes and child nodes. It specifically handles 'id' attributes by creating a mapping function. ```javascript function convertDef (node, treeNode) { if (node.nodeName === '#text') { return } treeNode.nodeName = node.nodeName var attrs = [] for (var attr of node.attributes) { var value = attr.value if (attr.name === 'id') { var id = attr.value value = (idMap) => idMap[id] } attrs.push({ name: attr.name, value }) } treeNode.attrs = attrs var children = [] for (var child of node.childNodes) { var childNode = {} convertDef(child, childNode) if (childNode.nodeName) { children.push(childNode) } } treeNode.childNodes = children } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.