color-formatter.tsx (1427B)
1 import { TextStyle, TextProperties } from 'react-native'; 2 3 import { WeeChatProtocol } from './parser'; 4 import { ceb, cwb, cob, cef, cwf, cof } from './colors'; 5 6 type AttributedStringNode = { 7 attrs: { 8 name: string | null; 9 override: any; 10 }; 11 bgColor: WeechatColorAttribute; 12 fgColor: WeechatColorAttribute; 13 text: string; 14 }; 15 16 type WeechatColorAttribute = { 17 name: string; 18 type: 'option' | 'weechat' | 'ext'; 19 }; 20 21 const getBgColor = ( 22 colorAttr: WeechatColorAttribute 23 ): TextStyle | undefined => { 24 if (colorAttr.type === 'ext') { 25 return { backgroundColor: ceb[colorAttr.name] }; 26 } else if (colorAttr.type === 'weechat') { 27 return { backgroundColor: cwb[colorAttr.name] }; 28 } else if (colorAttr.type === 'option') { 29 return cob[colorAttr.name]; 30 } 31 }; 32 33 const getFgColor = ( 34 colorAttr: WeechatColorAttribute 35 ): TextStyle | undefined => { 36 if (colorAttr.type === 'ext') { 37 return { color: cef[colorAttr.name] }; 38 } else if (colorAttr.type === 'weechat') { 39 return { color: cwf[colorAttr.name] }; 40 } else if (colorAttr.type === 'option') { 41 return cof[colorAttr.name]; 42 } 43 }; 44 45 export const renderWeechatFormat = (input: string): TextProperties[] => { 46 const formattedNode = WeeChatProtocol.rawText2Rich( 47 input 48 ) as AttributedStringNode[]; 49 50 return formattedNode.map((node) => ({ 51 children: node.text, 52 style: [getBgColor(node.bgColor), getFgColor(node.fgColor)] 53 })); 54 };