import * as _ from "lodash" ; import * as React from "react" ; import ReactMarkdown = require ( "react-markdown" ) ; import * as ReactReplace from "react-string-replace-recursively" ; import { Spell } from "../../common/Spell" ; import { concatenatedStringRegex , toModifierString } from "../../common/Toolbox" ; import { Listing } from "../Library/Listing" ; import { Conditions } from "../Rules/Conditions" ; import { Dice } from "../Rules/Dice" ; import { IRules , DefaultRules } from "../Rules/Rules" ; import { CounterOrBracketedText } from "./Counter" ; interface ReplaceConfig { [ name ] : { pattern : RegExp ; matcherFn : ( rawText : string , processed : string , key : string ) => JSX . Element ; ignore ? : string [ ] ; } ; } export class TextEnricher { constructor ( private rollDice , private referenceSpellListing , private referenceCondition , private getSpellListings , private getSpellsByNameRegex , private rules ) { } private referenceSpell = ( spellName ) => { const name = spellName . toLocaleLowerCase ( ) ; const listing = _ . find ( this . getSpellListings ( ) , s => s . Meta ( ) . Name . toLocaleLowerCase ( ) == name ) ; if ( listing ) { this . referenceSpellListing ( listing ) ; } } ; public GetEnrichedModifierFromAbilityScore = ( score ) => { const modifier = this . rules . GetModifierFromScore ( score ) ; return this . EnrichModifier ( modifier ) ; } ; public EnrichModifier = ( modifier ) => { const modifierString = toModifierString ( modifier ) ; return ( < span className = "rollable" onClick = { ( ) => this . rollDice ( modifierString ) } > { modifierString } < /span>); } ; public EnrichText = ( text , updateTextSource ? ) => { const replacer = this . buildReactReplacer ( ) ; const renderers = { text : props => replacer ( props . children ) , linkReference : CounterOrBracketedText ( text , updateTextSource ) } ; return < ReactMarkdown source = { text } renderers = { renderers } rawSourcePos / > ; } ; private buildReactReplacer ( ) { const replaceConfig = { diceExpression : { pattern : Dice . GlobalDicePattern , matcherFn : ( rawText , processed , key ) => ( < span className = "rollable" key = { key } onClick = { ( ) => this . rollDice ( rawText ) } > { rawText } < /span>) } , spells : { pattern : this . getSpellsByNameRegex ( ) , matcherFn : ( rawText , processed , key ) => ( < span className = "spell-reference" key = { key } onClick = { ( ) => this . referenceSpell ( rawText ) } > { rawText } < /span>) } , conditions : { pattern : concatenatedStringRegex ( _ . keys ( Conditions ) ) , matcherFn : ( rawText , processed , key ) => ( < span className = "condition-reference" key = { key } onClick = { ( ) => this . referenceCondition ( rawText ) } > { rawText } < /span>) } } ; return ReactReplace ( replaceConfig ) ; } } export const TextEnricherContext = React . createContext ( new TextEnricher ( ( ) => { } , ( ) => { } , ( ) => { } , ( ) => [ ] , ( ) => new RegExp ( "$^" ) , new DefaultRules ( ) ) ) ;