### Run Demo Server Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/README.md Start a local HTTP server to view examples. Navigate to the specified URL to access the demo. ```bash yarn demo ``` -------------------------------- ### Install pixi-tagged-text Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/GETTING_STARTED.md Install the library and its peer dependency pixi.js using npm or yarn. ```bash npm install pixi-tagged-text pixi.js # or yarn add pixi-tagged-text pixi.js ``` -------------------------------- ### Minimal Example Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/GETTING_STARTED.md A basic example demonstrating how to create and add a TaggedText object to a Pixi application stage. ```typescript import * as PIXI from 'pixi.js'; import TaggedText from 'pixi-tagged-text'; // Create Pixi app const app = new PIXI.Application(); document.body.appendChild(app.view as HTMLCanvasElement); // Define styles for tags const styles = { bold: { fontSize: 32, fontWeight: 'bold', fill: 0xFF0000 }, italic: { fontSize: 20, fontStyle: 'italic', fill: 0x0000FF } }; // Create tagged text const taggedText = new TaggedText( 'Hello World!', styles ); // Add to stage app.stage.addChild(taggedText); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/README.md Install project dependencies using Yarn. This command is essential for setting up the development environment. ```bash yarn install ``` -------------------------------- ### TypeScript Code Example with Comment and Result Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/INDEX.md Shows the expected format for code examples, including descriptive comments and the expected result of the code execution. ```typescript // Descriptive comment const result = functionName(value); // Result: expected output ``` -------------------------------- ### Animated Multistyle Text Setup Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/demo/index.html Defines the text content with tags and styles for animation. Includes setup for a PixiJS application and the TaggedText instance. ```javascript const animatedText = "Now have fun making some\nB E A U T I F U L\nmultistyle\ntext!"; let animatedStyles = { default: { fontFamily: "Recursive, Arial", fontSize: "48px", fontWeight: 900, fill: "#cccccc", strokeThickness: 1, stroke: "#aaaaaa", dropShadow: true, dropShadowBlur: 15, dropShadowDistance: 15, dropShadowAngle: 0, wordWrapWidth: 500, lineSpacing: 40, align: "center", }, blue: { fill: 0x4488ff, stroke: 0x2244cc, fontSize: 22, }, red: { fill: 0xff8888, stroke: 0xcc4444 }, }; let animated = new TaggedText(animatedText, animatedStyles, { splitStyle: "characters", }); const app = createDemo("animated", animated); ``` -------------------------------- ### Markdown Table Format Example Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/INDEX.md Provides an example of a standard Markdown table structure with headers and rows. ```markdown | Header | Header | Header | |--------|--------|--------| | Value | Value | Value | ``` -------------------------------- ### options Property Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/TaggedText.md Gets the current configuration options for the TaggedText instance. ```APIDOC ## options Property ### Description Returns the current configuration options. ### Method - **GET** `options` ### Return Value - **TaggedTextOptions** - The configuration options object. ### Example Usage ```typescript const currentOptions = taggedText.options; console.log(currentOptions.debug); ``` ``` -------------------------------- ### Common Style Properties Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/GETTING_STARTED.md Example of defining styles using standard Pixi.js TextStyle properties and custom extensions. ```typescript const styles = { heading: { // Standard Pixi.js properties fontSize: 32, fontFamily: 'Georgia', fill: 0x000000, fontWeight: 'bold', // Extended properties valign: 'middle', // Vertical alignment textTransform: 'uppercase', // Text transformation textDecoration: 'underline', // Text decoration paragraphSpacing: 10, // Space after paragraph fontScaleWidth: 0.8, // Scale width to 80% iconScale: 1.5 // Scale inline images to 150% } }; ``` -------------------------------- ### Initialize PIXI Application and Setup Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/demo/memory.html Sets up the PIXI application, appends the view to the DOM, and defines initial configurations for text styles and options. This is the boilerplate for running the demo. ```javascript PIXI.settings.RESOLUTION = 2; const app = new PIXI.Application({ width: 600, height: 600, backgroundColor: 0x333333, }); document.getElementById("basic").appendChild(app.view); let tt; let plainText; const iconImage = PIXI.Sprite.from("./icon.png"); const style = { fontSize: 40, textDecoration: "underline", wordWrap: true, wordWrapWidth: 400, fill: 0xffffff, }; const options = { imgMap: { icon: iconImage }, debug: false, drawWhitespace: false, }; const text = "Hello my baby, hello my honey, hello my ragtime gal!\n" + (TEST_ICON ? `` : ``); const styleSet = { default: style, }; const makeTaggedText = (total) => { try { tt = new TaggedText(text + " " + total, styleSet, options); tt.x = 50; tt.y = 50; app.stage.addChild(tt); } catch (error) { console.warn("Failed to create TaggedText"); console.error(error); } }; const destroyTaggedText = () => { if (tt && tt.destroyed === false) { app.stage.removeChild(tt); // tt.destroyImgMap(); tt.destroy(); tt = null; } }; const makePlainText = () => { plainText = new PIXI.Text(text + " " + total, style); plainText.x = 50; plainText.y = 350; app.stage.addChild(plainText); }; const destroyPlainText = () => { app.stage.removeChild(plainText); plainText.destroy(); plainText = null; }; const instructions = new PIXI.Text("See console for results", { fontSize: 12, fill: 0xffff00, }); instructions.x = 50; instructions.y = 10; app.stage.addChild(instructions); ``` -------------------------------- ### TypeScript Function Signature Example Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/INDEX.md Demonstrates the standard format for function signatures in TypeScript, including parameter types, optional parameters, and return types. ```typescript functionName(param1: Type1, param2?: Type2): ReturnType ``` -------------------------------- ### Defining Text Styles with Tags Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/README.md Illustrates how to define styles for different tags, including a default style that applies to all text. This setup is used to style specific text segments. ```typescript const text = 'Bold italic'; const styles = { bold: { fontSize: 32, fontWeight: 'bold' }, italic: { fontSize: 20, fontStyle: 'italic' }, default: { fontSize: 16 } // Applied to all text }; ``` -------------------------------- ### TypeScript Type Notation Examples Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/INDEX.md Illustrates various TypeScript type notations used within the documentation, such as primitive types, arrays, objects, unions, intersections, generics, and constraints. ```typescript string - Primitive type string[] - Array type Record - Object mapping strings to T T | U - Union type T & U - Intersection type Partial - All properties optional T extends U - Generic constraint ``` -------------------------------- ### updateOffsetForNewLine Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/layout.md Calculates the position for the start of the next line based on the current offset, the largest line height, and line spacing. ```APIDOC ## updateOffsetForNewLine ### Description Calculates the position for the start of the next line. ### Method ```typescript export const updateOffsetForNewLine = ( offset: Point, largestLineHeight: number, lineSpacing: number ): Point ``` ### Parameters #### Path Parameters - **offset** (Point) - Required - Current position - **largestLineHeight** (number) - Required - Height of the current line - **lineSpacing** (number) - Required - Extra space between lines ### Returns New Point at start of next line ### Example ```typescript const currentPos = { x: 0, y: 0 }; const lineHeight = 20; const spacing = 4; const nextLine = updateOffsetForNewLine(currentPos, lineHeight, spacing); // Result: { x: 0, y: 24 } (20 + 4) ``` ``` -------------------------------- ### lineWidth Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/layout.md Calculates the total width of a line by summing the widths of its constituent bounds from the start of the first word to the end of the last word. ```APIDOC ## lineWidth ### Description Calculates the total width of a line from first word start to last word end. ### Method ```typescript export const lineWidth = (wordsInLine: Bounds[]): number ``` ### Parameters #### Path Parameters - **wordsInLine** (Bounds[]) - Required - Word bounds in the line ### Returns Total line width ### Example ```typescript const words = [ { x: 0, y: 0, width: 50, height: 20 }, { x: 55, y: 0, width: 60, height: 20 } ]; const width = lineWidth(words); // Result: 115 (55 + 60) ``` ``` -------------------------------- ### alignLeft Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/layout.md Positions words in a line starting from x=0, each word immediately following the previous. ```APIDOC ## alignLeft() ### Description Positions words in a line starting from x=0, each word immediately following the previous. ### Method N/A (Function Signature) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters - **line** (Bounds[]) - Required - Word bounds to align ### Returns Aligned word bounds ``` -------------------------------- ### tagStyles Property Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/TaggedText.md Gets or sets the complete set of styles used for different tags. This includes the default style. ```APIDOC ## tagStyles Property ### Description Gets or sets the complete style set. All tag styles, including `default`, are stored here. ### Method - **GET** `tagStyles` - **SET** `tagStyles` ### Parameters #### Path Parameters - **styles** (TextStyleSet) - Required - The new set of tag styles. ### Example Usage ```typescript taggedText.tagStyles = { default: { fontSize: 26, fill: 0x000000 }, bold: { fontWeight: 'bold' }, italic: { fontStyle: 'italic' } }; ``` ``` -------------------------------- ### Extended TextStyle Properties Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/README.md Shows an example of TextStyleExtended, which includes standard PIXI.TextStyle properties along with custom properties for advanced text styling and layout. ```typescript { // Standard PIXI.TextStyle fontSize: 16, fontFamily: 'Arial', fill: 0x000000, fontWeight: 'bold', // Extended properties valign: 'baseline', // Vertical alignment textTransform: 'uppercase', // Case transformation textDecoration: 'underline', // Decorations paragraphSpacing: 10, // Space after paragraph fontScaleWidth: 0.8, // Scale width breakLines: true, // Enable word wrapping // Image properties imgSrc: 'icon', // Image reference key imgDisplay: 'icon', // How to display: icon, inline, block iconScale: 1.5 } ``` -------------------------------- ### defaultStyles Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/TaggedText.md Provides access to the built-in default styles that are applied to all new instances of TaggedText, ensuring a consistent starting appearance. ```APIDOC ## Static Properties ### defaultStyles #### Description Returns the built-in default styles applied to all new instances. #### Method ```typescript static get defaultStyles(): TextStyleSet ``` #### Returns - **TextStyleSet** - Frozen `TextStyleSet` object (cannot be modified) ``` -------------------------------- ### Example Usage of parseTagsNew Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/tags.md Demonstrates how to use the parseTagsNew function to parse a string containing nested bold and italic tags. It specifies which tags to recognize and shows the resulting token tree structure. ```typescript const text = 'Bold and italic normal'; const tokens = parseTagsNew( text, ['bold', 'italic'], // Only recognize these tags false, // Don't wrap emoji console.warn ); // Result: { // children: [ // { // tag: 'bold', // children: [ // 'Bold ', // { // tag: 'italic', // children: ['and italic'] // } // ] // }, // ' normal' // ] // } ``` -------------------------------- ### Calculate Next Line Offset Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/layout.md Calculates the position for the start of the next line based on the current position, line height, and line spacing. ```typescript export const updateOffsetForNewLine = ( offset: Point, largestLineHeight: number, lineSpacing: number ): Point ``` ```typescript const currentPos = { x: 0, y: 0 }; const lineHeight = 20; const spacing = 4; const nextLine = updateOffsetForNewLine(currentPos, lineHeight, spacing); // Result: { x: 0, y: 24 } (20 + 4) ``` -------------------------------- ### Calculate Line Width Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/layout.md Calculates the total width of a line by summing the start position of the first word and the end position of the last word. ```typescript export const lineWidth = (wordsInLine: Bounds[]): number ``` ```typescript const words = [ { x: 0, y: 0, width: 50, height: 20 }, { x: 55, y: 0, width: 60, height: 20 } ]; const width = lineWidth(words); // Result: 115 (55 + 60) ``` -------------------------------- ### Development Build Commands Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/README.md Provides essential commands for setting up the development environment, building the project, running tests, and enabling watch mode for continuous development. ```bash # Install dependencies npm install # Build distribution npm run build # Run tests npm test # Watch mode npm run dev # Linting npm run lint # Format code npm run fix:prettier ``` -------------------------------- ### Main Export and Instantiation Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/README.md Demonstrates how to import the TaggedText class and create a new instance with initial text and options. This is the primary way to begin using the library. ```typescript import TaggedText from 'pixi-tagged-text'; // Only export is the TaggedText class const text = new TaggedText('Text', {}); ``` -------------------------------- ### Get Style for Tag Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/style.md Retrieves the style associated with a tag name from a set of styles, optionally applying inline attributes. Use this to get the computed style for a specific HTML-like tag. ```typescript export const getStyleForTag = ( tagName: string, tagStyles: TextStyleSet, attributes: AttributesList = {} ): TextStyleExtended | undefined ``` ```typescript const styles = { bold: { fontWeight: 'bold', fontSize: 20 }, italic: { fontStyle: 'italic' } }; const style1 = getStyleForTag('bold', styles); // Result: { fontWeight: 'bold', fontSize: 20 } const style2 = getStyleForTag('bold', styles, { fontSize: 24 }); // Result: { fontWeight: 'bold', fontSize: 24 } (attribute overrides) const style3 = getStyleForTag('unknown', styles); // Result: undefined ``` -------------------------------- ### Build the Project Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/README.md Build the project using Yarn. This command compiles the source code into a distributable format. ```bash yarn build ``` -------------------------------- ### Get Untagged Text Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/GETTING_STARTED.md Retrieve the plain text content without any applied tags. ```typescript const text = new TaggedText('Hello world'); console.log(text.untaggedText); // "Hello world" ``` -------------------------------- ### Initialize TaggedText Component Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/README.md Instantiate the TaggedText component with text, styles, and optional configuration. All parameters are optional. ```javascript new TaggedText(text, styles, options); ``` -------------------------------- ### Get Untagged Text Content Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/TaggedText.md Retrieves the plain text content from a TaggedText instance, with all styling tags removed. ```typescript console.log(taggedText.untaggedText); // "Hello world!" (if text is "Hello world!") ``` -------------------------------- ### Get Nested Bounds Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/layout.md Calculates the bounding box of a nested token structure by flattening and merging all individual bounds. ```typescript export const getBoundsNested: Unary, Bounds> ``` -------------------------------- ### Get Last Element of an Array Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/pixiUtils.md Retrieves the last element from an array. Ensure the array is not empty before calling to avoid errors. ```typescript export const last = (a: T[]): T => a[a.length - 1] ``` -------------------------------- ### Get First Element of an Array Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/pixiUtils.md Retrieves the first element from an array. Ensure the array is not empty before calling to avoid errors. ```typescript export const first = (a: T[]): T => a[0] ``` -------------------------------- ### Create and Add TaggedText Instance Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/TaggedText.md Demonstrates how to create a new TaggedText instance with custom text, tag styles, and options, and then add it to the Pixi application stage. ```typescript import TaggedText from 'pixi-tagged-text'; const taggedText = new TaggedText( 'Hello world!', { bold: { fontSize: 32, fill: 0xFF0000 }, small: { fontSize: 14, fill: 0x0000FF } }, { debug: false, splitStyle: 'words' } ); app.stage.addChild(taggedText); ``` -------------------------------- ### Text Transformations with TaggedText Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/demo/index.html Shows how to apply text transformations like lowercase, uppercase, and capitalize using TaggedText. Also demonstrates the 'small-caps' font variant. ```javascript const textTransformText = `

Text transformations:

textTransform: "lowercase" lowerCASE text textTransform: "uppercase" upperCASE text textTransform: "capitalize" capitalized text fontVariant: "small-caps" Small Caps `; const textTransformStyle = { default: { fontFamily: "Arial", fontSize: "24px", fill: "#FFCC22", align: "center", }, h1: { fontSize: "36px", fill: "#CCCCCC" }, code: { fontFamily: "courier", fontSize: 12, fill: "#FFFFFF" }, upper: { textTransform: "uppercase" }, lower: { textTransform: "lowercase" }, capitalize: { textTransform: "capitalize" }, smallcaps: { fontVariant: "small-caps" }, }; let textTransform = new TaggedText( textTransformText, textTransformStyle ); createDemo("textTransform", textTransform); ``` -------------------------------- ### defaultStyle Property Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/TaggedText.md Gets or sets the default style that is applied to all text segments unless overridden by a specific tag. This is a shortcut to `tagStyles.default`. ```APIDOC ## defaultStyle Property ### Description Gets or sets the default style applied to all text. Shortcut to `tagStyles.default`. ### Method - **GET** `defaultStyle` - **SET** `defaultStyle` ### Parameters #### Path Parameters - **defaultStyles** (TextStyleExtended) - Required - The new default style object. ### Example Usage ```typescript taggedText.defaultStyle = { fontSize: 20, fill: 0x333333, fontFamily: 'Arial' }; ``` ``` -------------------------------- ### Basic TaggedText Usage Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/README.md Demonstrates how to create a TaggedText object with different styles applied to specific parts of the text using HTML-like tags and a style definition object. ```typescript new TaggedText( 'Bold and italic', { bold: { fontSize: 32, fill: 0xFF0000 }, italic: { fontSize: 16, fill: 0x0000FF } } ); ``` -------------------------------- ### Default Constructor Options Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/configuration.md Shows the default configuration object passed to the TaggedText constructor. ```typescript const taggedText = new TaggedText( text, styles, { debug: false, debugConsole: false, splitStyle: "words", imgMap: {}, scaleIcons: true, skipUpdates: false, skipDraw: false, drawWhitespace: false, wrapEmoji: true, errorHandler: undefined, supressConsole: false, overdrawDecorations: 0, adjustFontBaseline: undefined } ); ``` -------------------------------- ### text Property Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/TaggedText.md Gets or sets the text content of the TaggedText instance. Setting this property automatically triggers an update and draw cycle. ```APIDOC ## text Property ### Description Gets or sets the text content with optional tags. Setting text automatically triggers an update and draw cycle (unless `skipUpdates` option is enabled). ### Method - **GET** `text` - **SET** `text` ### Parameters #### Path Parameters - **text** (string) - Required - The new text content with optional tags. ### Example Usage ```typescript taggedText.text = 'New text'; ``` ``` -------------------------------- ### Align Left Function Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/layout.md Positions words in a line starting from x=0, with each word immediately following the previous. Use this for left-aligned text. ```typescript export const alignLeft: AlignFunction = (line) => [...] ``` -------------------------------- ### Choose Efficient Split Style Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/GETTING_STARTED.md Use the default `splitStyle: 'words'` for better performance. Only use `splitStyle: 'characters'` if per-character control is strictly necessary. ```typescript // Fast (default) new TaggedText(text, styles, { splitStyle: 'words' }); // Slower - only use if you need per-character control new TaggedText(text, styles, { splitStyle: 'characters' }); ``` -------------------------------- ### Run Performance Test Loop Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/demo/memory.html Continuously runs tests to measure iterations, heap size, and texture cache usage. The loop stops when a predefined limit is reached. ```javascript let total = 0; let heapSize = 0; const firstHeapSize = window.performance.memory.usedJSHeapSize / 1024 / 1024; let lastHeapSize = firstHeapSize; const firstTextureCacheSize = Object.keys( PIXI.utils.TextureCache ).length; let lastTextureCacheSize = firstTextureCacheSize; let textureCacheSize = 0; const firstBaseTextureCacheSize = Object.keys( PIXI.utils.BaseTextureCache ).length; let lastBaseTextureCacheSize = firstBaseTextureCacheSize; let baseTextureCacheSize = 0; const runTest = () => { let i = SET_SIZE; while (i > 0) { total += 1; if (TEST_TT) { if (tt) { destroyTaggedText(); } makeTaggedText(total); } if (TEST_PLAIN_TEXT) { if (plainText) { destroyPlainText(); } makePlainText(total); } i--; } console.log(`\nIterations: ${total}`); if (TEST_HEAP) { heapSize = Math.ceil( window.performance.memory.usedJSHeapSize / 1024 / 1024 ); console.log( ` Heap • size: ${heapSize}MB • change: ${ heapSize - lastHeapSize } indIndex` ); lastHeapSize = heapSize; } if (TEST_TEXTURE_CACHE) { textureCacheSize = Object.keys(PIXI.utils.TextureCache).length; console.log( ` TextureCache • size: ${textureCacheSize} • change: ${ textureCacheSize - lastTextureCacheSize } indIndex` ); lastTextureCacheSize = textureCacheSize; } if (TEST_BASE_TEXTURE_CACHE) { baseTextureCacheSize = Object.keys( PIXI.utils.BaseTextureCache ).length; console.log( ` BaseTextureCache • size: ${baseTextureCacheSize} • change: ${ baseTextureCacheSize - lastBaseTextureCacheSize } indIndex` ); lastBaseTextureCacheSize = baseTextureCacheSize; } if (total >= LIMIT) { clearInterval(loop); console.log(`\nFINISHED!`); if (TEST_HEAP) { const total = (heapSize - firstHeapSize).toFixed(2); const each = ( ((heapSize - firstHeapSize) * 1024) / LIMIT ).toFixed(2); console.log( ` Heap • Total gain: ${total}MB (${each}KB/iteration)` ); } if (TEST_TEXTURE_CACHE) { const total = textureCacheSize - firstTextureCacheSize; const each = ( (textureCacheSize - firstTextureCacheSize) / LIMIT ).toFixed(2); console.log( ` TextureCache • Total gain: ${total} (${each}/iteration)` ); } if (TEST_BASE_TEXTURE_CACHE) { const total = baseTextureCacheSize - firstBaseTextureCacheSize; const each = ( (baseTextureCacheSize - firstBaseTextureCacheSize) / LIMIT ).toFixed(2); console.log( ` BaseTextureCache • Total gain: ${total} (${each}/iteration)` ); } } }; var loop = setInterval(runTest, INTERVAL); ``` -------------------------------- ### Nesting Tags Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/demo/index.html Demonstrates nesting multiple text styles within a single string. Ensure all styles are defined in the style object. ```javascript const nestedText = `You can nest tags as deeply as you'd like, dude! `; const nestedStyle = { default: { fontFamily: "Arial", fontSize: "24px", fill: "#cccccc", wordWrapWidth: 500, wordWrap: true, align: "left", valign: "baseline", }, outline: { stroke: "#000000", strokeThickness: 2 }, b: { fontWeight: 700 }, red: { fill: "#ff8888" }, blue: { fill: "#8888FF" }, i: { fontStyle: "italic" }, thicker: { stroke: "#002266", strokeThickness: 10 }, large: { fontSize: "36px" }, }; let nested = new TaggedText(nestedText, nestedStyle); createDemo("nested", nested); ``` -------------------------------- ### decorations Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/TaggedText.md Returns an array of all PIXI.Graphics objects used for text decorations. ```APIDOC ## decorations ### Description Array of all text decoration graphics. ### Type `PIXI.Graphics[]` ``` -------------------------------- ### TaggedText Constructor Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/TaggedText.md Creates a new TaggedText instance. You can provide initial text content, a set of tag styles, configuration options, and a base texture. ```APIDOC ## TaggedText Constructor ### Description Creates a new TaggedText instance with optional text, styles, and configuration options. ### Parameters #### Path Parameters - **text** (string) - Optional - Text content with optional HTML-like tags - **tagStyles** (TextStyleSet) - Optional - Object mapping tag names to `TextStyleExtended` objects - **options** (TaggedTextOptions) - Optional - Configuration options - **texture** (PIXI.Texture) - Optional - Base texture for the Sprite parent class ### Example Usage ```typescript import TaggedText from 'pixi-tagged-text'; const taggedText = new TaggedText( 'Hello world!', { bold: { fontSize: 32, fill: 0xFF0000 }, small: { fontSize: 14, fill: 0x0000FF } }, { debug: false, splitStyle: 'words' } ); app.stage.addChild(taggedText); ``` ``` -------------------------------- ### Common Configuration Options Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/GETTING_STARTED.md Set various options for TaggedText, including debug visualization, splitting behavior, whitespace rendering, emoji wrapping, performance settings, and error handling. ```typescript const text = new TaggedText( 'Text content', { default: { fontSize: 20 } }, { // Debug visualization debug: false, // Show layout boundaries debugConsole: false, // Log token structure // Splitting splitStyle: 'words', // 'words' or 'characters' // Whitespace drawWhitespace: false, // Render spaces/tabs as objects // Emoji wrapEmoji: true, // Auto-wrap emoji with styling // Performance skipUpdates: false, // Don't auto-update on changes skipDraw: false, // Don't auto-draw after update // Error handling supressConsole: false, // Don't log to console errorHandler: (err) => { console.log(`[${err.code}] ${err.message}`); }, // Images imgMap: {}, // Image reference map scaleIcons: true // Scale icon images with font scaling } ); ``` -------------------------------- ### Error Handling: Unclosed Tags Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/tags.md Illustrates how the parseTagsNew function handles unclosed tags by logging a warning. This example shows a bold tag opened but not closed. ```typescript const text = 'Bold text without closing'; parseTagsNew(text, ['bold']); // Warning: "unclosed-tags: Found 1 unclosed tags in bold" ``` -------------------------------- ### Basic Multiline and Multistyle Text Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/demo/index.html Demonstrates creating text with multiple styles and line breaks using HTML-like tags. Requires the TaggedText class. ```javascript function createPixiApp( id, width = 600, height = 600, backgroundColor = 0x333333 ) { PIXI.settings.RESOLUTION = 2; const app = new PIXI.Application({ width, height, backgroundColor }); document.getElementById(id).appendChild(app.view); return app; } function createDemo(id, TaggedTextExample) { const app = createPixiApp(id); if (TaggedTextExample !== undefined) { TaggedTextExample.x = 30; TaggedTextExample.y = 30; app.stage.addChild(TaggedTextExample); } return app; } // Basics const basicText = `Let's make some multiline and multistyle text for Pixi.js!`; const basicStyle = { default: { fontSize: "24px", fill: "#cccccc", align: "center", }, ml: { fontStyle: "italic", color: "#ff8888", fontSize: "40px", }, ms: { fontWeight: "bold", fill: "#4488ff", fontSize: "40px", }, pixi: { fontSize: "64px", fill: "#efefef", }, }; const basic = new TaggedText(basicText, basicStyle, {}); createDemo("basic", basic); ``` -------------------------------- ### Get Style for a Tag Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/TaggedText.md Retrieves the style associated with a given tag. You can also merge inline attributes with the tag's style by providing an optional attributes object. ```typescript const boldStyle = taggedText.getStyleForTag('bold'); const customBold = taggedText.getStyleForTag('bold', { fontSize: 20 }); ``` -------------------------------- ### Text Alignment Options Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/demo/index.html Illustrates how to apply different text alignments (left, right, center, justify) to text elements. Alignment is controlled via the 'align' property in the default style. ```javascript // Alignment. const alignText = `You can align text left, right, center or even justify.\n\nHowever, alignment can only be set on the default style.`; const alignStyle = { default: { wordWrapWidth: 250, }, b: { fontWeight: "700", fill: "white", }, }; const alignOptions = {}; let left = new TaggedText( alignText.replace("left", "left"), { ...alignStyle, default: { ...alignStyle.default, align: "left", fill: "teal" } }, alignOptions ); let right = new TaggedText( alignText.replace("right", "right"), { ...alignStyle, default: { ...alignStyle.default, align: "right", fill: "orange" } }, alignOptions ); right.x = 330; right.y = 30; let center = new TaggedText( alignText.replace("center", "center"), { ...alignStyle, default: { ...alignStyle.default, align: "center", fill: "yellow" } }, alignOptions ); center.x = 30; center.y = 330; let justify = new TaggedText( alignText.replace("justify", "justify"), { ...alignStyle, default: { ...alignStyle.default, align: "justify", fill: "pink" } }, alignOptions ); justify.x = 330; justify.y = 330; const alignApp = createDemo("align", left); alignApp.stage.addChild(right); alignApp.stage.addChild(center); alignApp.stage.addChild(justify); ``` -------------------------------- ### Configure Word Wrapping Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/GETTING_STARTED.md Enable and configure word wrapping by setting `wordWrap` to true and specifying `wordWrapWidth` in the default style. ```typescript const text = new TaggedText( 'Long text that will wrap to multiple lines', { default: { wordWrap: true, // Enable word wrapping (default: true) wordWrapWidth: 200 // Wrap at 200 pixels (default: 500) } } ); ``` -------------------------------- ### Error Handling: Mismatched Tags Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/tags.md Demonstrates the error thrown by parseTagsNew when tags are mismatched (not closed in LIFO order). This example shows a bold tag closed before an inner italic tag. ```typescript const text = 'Mixed'; parseTagsNew(text, ['bold', 'italic']); // Error: "Unexpected tag nesting. Found a closing tag \"bold\" that doesn't match..." ``` -------------------------------- ### INITIAL_FONT_PROPS Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/pixiUtils.md Default font metrics used as fallback when measurements haven't been calculated yet. This is a constant object. ```APIDOC ## INITIAL_FONT_PROPS ### Description Default font metrics used as fallback when measurements haven't been calculated yet. ### Response #### Success Response (200) - **ascent** (number) - Default ascent value - **descent** (number) - Default descent value - **fontSize** (number) - Default font size value ``` -------------------------------- ### combineAllStyles() Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/style.md Combines an array of TextStyleExtended objects into a single style. Later styles in the array override earlier ones, and undefined styles are ignored. ```APIDOC ## combineAllStyles() ### Description Combines multiple styles in order, with later styles overriding earlier ones. Filters out undefined styles. ### Method ```typescript combineAllStyles(styles: (TextStyleExtended | undefined)[]): TextStyleExtended ``` ### Parameters #### Arguments - **styles** (Array) - Required - Array of styles to combine ### Returns Single combined TextStyleExtended object ### Example ```typescript const defaultStyle = { fontSize: 16, fill: 0x000000 }; const tagStyle = { fontWeight: 'bold' }; const attrStyle = { fill: 0xFF0000 }; const combined = combineAllStyles([defaultStyle, tagStyle, attrStyle]); // Result: { fontSize: 16, fontWeight: 'bold', fill: 0xFF0000 } ``` ``` -------------------------------- ### Get Font Properties from PIXI.Text Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/pixiUtils.md Extracts font metrics from a PIXI.Text object. Optionally forces an update before measuring. Throws an error if the text field hasn't been updated and forceUpdate is false. ```typescript export const getFontPropertiesOfText = ( textField: PIXI.Text, forceUpdate?: boolean ): IFontMetrics ``` ```typescript const textField = new PIXI.Text("Hello", { fontSize: 20 }); textField.updateText(false); // Must update first const metrics = getFontPropertiesOfText(textField); // Result: { ascent: ~16, descent: ~4, fontSize: 20 } // Or force update: const metrics2 = getFontPropertiesOfText(textField, true); ``` -------------------------------- ### Source Code Structure Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/INDEX.md Lists the main source files for the pixi-tagged-text library, indicating the purpose of each file. ```text src/ ├── TaggedText.ts # Main class ├── types.ts # Type definitions ├── style.ts # Style functions ├── layout.ts # Layout algorithm ├── tags.ts # Tag parsing ├── defaultStyle.ts # Default styles ├── defaultOptions.ts # Default options ├── pixiUtils.ts # Utilities ├── stringUtil.ts # String utilities ├── functionalUtils.ts # Functional utilities ├── errorMessaging.ts # Error handling └── InteractionEvents.ts # Event names ``` -------------------------------- ### Get Combined Styles for Multiple Tags Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/TaggedText.md Combines the styles from an array of tags, respecting their nesting order. This method is useful for determining the final style of text elements with multiple applied tags. ```typescript const combinedStyle = taggedText.getStyleForTags([{ tag: 'bold', attributes: {} }, { tag: 'italic', attributes: {} }]); ``` -------------------------------- ### Get Combined Style for Nested Tags with Caching Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/style.md Combines styles from an array of nested TagWithAttributes objects, applying them in order and utilizing a cache for performance. This is essential for efficiently rendering text with multiple, potentially overlapping styles. ```typescript export const getStyleForTags = ( tags: TagWithAttributes[], tagStyles: TextStyleSet, styleCache: TextStyleSet ): TextStyleExtended ``` ```typescript const tags = [ { tagName: 'bold', attributes: {} }, { tagName: 'large', attributes: { fontSize: 30 } } ]; const styles = { default: { fill: 0x000000 }, bold: { fontWeight: 'bold' }, large: { fontSize: 20 } }; const cache = {}; const result = getStyleForTags(tags, styles, cache); // Result: { fill: 0x000000, fontWeight: 'bold', fontSize: 30 } // Second call with same tags uses cache const result2 = getStyleForTags(tags, styles, cache); // Retrieved from cache ``` -------------------------------- ### draw() Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/TaggedText.md Creates and positions all display objects based on the current tokens. This method is normally called automatically by `update()` unless `skipDraw` is true, allowing for manual control over the rendering process. ```APIDOC ## draw() ### Description Creates and positions all display objects based on the current tokens. Normally called automatically by `update()` unless `skipDraw` is true. ### Method ```typescript draw(): void ``` ### Side Effects - Clears and recreates `textFields`, `sprites`, and `decorations` arrays - Updates `textContainer`, `spriteContainer`, `decorationContainer` children - Renders debug overlays if `debug` option is true - Logs warnings if decorations are used without `drawWhitespace` enabled ### Example ```typescript taggedText.options.skipDraw = true; taggedText.text = 'Text content'; taggedText.update(); // Updates tokens but doesn't draw taggedText.draw(); // Now create display objects ``` ``` -------------------------------- ### center Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/layout.md Calculates the necessary offset to center a given value within a specified context width. ```APIDOC ## center ### Description Calculates offset to center a value within a context. ### Method ```typescript export const center = (x: number, context: number): number => (context - x) / 2 ``` ### Parameters #### Path Parameters - **x** (number) - Required - Value to center - **context** (number) - Required - Context width ### Returns Offset to apply for centering ### Example ```typescript center(50, 200); // Result: 75 ((200 - 50) / 2) center(100, 200); // Result: 50 ((200 - 100) / 2) ``` ``` -------------------------------- ### HTML-like Tags Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/GETTING_STARTED.md Decorate text with HTML-like tags for basic formatting. ```typescript const text = new TaggedText( 'Bold text and italic text', { bold: { fontWeight: 'bold' }, italic: { fontStyle: 'italic' } } ); ``` -------------------------------- ### Type Imports Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/README.md Shows how to import various type definitions from the 'pixi-tagged-text' package for use in TypeScript projects. This allows for better type checking and code completion. ```typescript import { TextStyleExtended, TaggedTextOptions, SegmentToken, ParagraphToken, // ... etc } from 'pixi-tagged-text'; ``` -------------------------------- ### Image Display Modes Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/GETTING_STARTED.md Configure how images are displayed within the text using `imgDisplay` and `iconScale` in styles. Options include 'icon', 'inline', and 'block'. ```typescript const styles = { // icon: Scales to match line height inline_icon: { imgDisplay: 'icon', iconScale: 1.0 }, // inline: Inline with text, no scaling inline_img: { imgDisplay: 'inline' }, // block: Forces line break before and after block_img: { imgDisplay: 'block' } }; ``` -------------------------------- ### sprites Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/TaggedText.md Returns an array of all sprite clones that were created from the imgMap. ```APIDOC ## sprites ### Description Array of all sprite clones created from `imgMap`. ### Type `PIXI.Sprite[]` ``` -------------------------------- ### cloneSprite Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/_autodocs/api-reference/pixiUtils.md Creates a new PIXI.Sprite with the same texture as the original. Modifications to the clone do not affect the original. ```APIDOC ## cloneSprite() ### Description Creates a new sprite with the same texture as the original. ### Parameters #### Path Parameters - **sprite** (PIXI.Sprite) - Required - Sprite to clone ### Returns - **clonedSprite** (PIXI.Sprite) - New PIXI.Sprite instance ### Note Creates a new sprite object but shares the texture. Modifications to position, scale, etc. don't affect the original. ### Request Example ```typescript const original = PIXI.Sprite.from('image.png'); original.scale.set(0.5); const clone = cloneSprite(original); clone.scale.set(2.0); // Doesn't affect original // Both sprites show the same image but with different scales ``` ``` -------------------------------- ### Underline, Overline, and Strikethrough with TaggedText Source: https://github.com/mimshwright/pixi-tagged-text/blob/main/demo/index.html Illustrates text decorations including underline, overline, and strikethrough, with options for custom thickness, offset, and color. Supports combining multiple decorations. ```javascript const underlineText = `

Underline, overline and strikethru:

textDecoration: "underline" A cumque ea quia vel. textDecoration: "overline" Est labore quibusdam laborum facere. textDecoration: "line-through" Veritatis aut ducimus occaecati illo. underlineThickness, underlineOffset, underlineColor Est labore quibusdam laborum facere. textDecoration: "underline overline" maiores fugiat quae voluptas eaque modi. nested tags (note, textDecoration will override in nested styles) maiores fugiat quae voluptas eaque modi. multiple custom decorations consequuntur odit in excepturi perspiciatis dolores commodi aliquam exercitationem at `; const underlineStyle = { default: { fontFamily: "Arial", fontSize: "22px", align: "center", }, h1: { fill: "#CCCCCC" }, code: { fontFamily: "courier", fontSize: 12, fill: "#FFFFFF" }, purple: { fill: "#6600FF" }, underline: { textDecoration: "underline", fill: "#FF0000" }, overline: { textDecoration: "overline", fill: "#FFFF00" }, lineThrough: { textDecoration: "line-through", fill: "#0066FF" }, underOver: { textDecoration: "underline overline", fill: "#FF9900", }, underlineCustom: { underlineThickness: 3, underlineOffset: 4, underlineColor: "#FF00FF", fill: "#66FF66", }, custom: { fill: "#FFCCFF", textStyle: "italic", underlineThickness: 4, underlineColor: "#FFFF00", underlineOffset: 5, overlineColor: "#00FFFF", overlineThickness: 4, overlineOffset: -3, lineThroughThickness: 2, lineThroughColor: "#FF0000", }, }; let underline = new TaggedText(underlineText, underlineStyle, { // When using text decoration, it's recommended you use drawWhitespace: true // so that spaces will have underlines. drawWhitespace: true, // When overdrawDecorations is set, // the width of the decorations is extended by this amount on either side. overdrawDecorations: 2, }); createDemo("underline", underline); ```