How to use useMemo method in root

Best JavaScript code snippet using root

OutgoiongWebhookForm.js

Source:OutgoiongWebhookForm.js Github

copy

Full Screen

...62 handleRetryDelay,63 handleTriggerWordAnywhere,64 handleRunOnEdits,65 } = formHandlers;66 const retryDelayOptions = useMemo(67 () => [68 ['powers-of-ten', t('powers-of-ten')],69 ['powers-of-two', t('powers-of-two')],70 ['increments-of-two', t('increments-of-two')],71 ],72 [t],73 );74 const eventOptions = useMemo(75 () => Object.entries(outgoingEvents).map(([key, val]) => [key, t(val.label)]),76 [t],77 );78 const showChannel = useMemo(() => outgoingEvents[event].use.channel, [event]);79 const showTriggerWords = useMemo(() => outgoingEvents[event].use.triggerWords, [event]);80 const showTargetRoom = useMemo(() => outgoingEvents[event].use.targetRoom, [event]);81 const additionalFields = useMemo(82 () => ({83 ...(alias && { alias }),84 ...(emoji && { emoji }),85 ...(avatarUrl && { avatar: avatarUrl }),86 }),87 [alias, avatarUrl, emoji],88 );89 const [exampleData] = useExampleData({90 additionalFields,91 url: null,92 });93 const hilightedExampleJson = useHighlightedCode('json', JSON.stringify(exampleData, null, 2));94 return (95 <Page.ScrollableContentWithShadow96 pb='x24'97 mi='neg-x24'98 is='form'99 onSubmit={useCallback((e) => e.preventDefault(), [])}100 qa-admin-user-edit='form'101 {...props}102 >103 <Margins block='x16'>104 <Accordion width='x600' alignSelf='center'>105 <FieldGroup>106 {useMemo(107 () => (108 <Field>109 <Field.Label>{t('Event_Trigger')}</Field.Label>110 <Field.Row>111 <Select112 flexGrow={1}113 value={event}114 options={eventOptions}115 onChange={handleEvent}116 />117 </Field.Row>118 <Field.Hint>{t('Event_Trigger_Description')}</Field.Hint>119 </Field>120 ),121 [event, eventOptions, handleEvent, t],122 )}123 {useMemo(124 () => (125 <Field>126 <Field.Label display='flex' justifyContent='space-between' w='full'>127 {t('Enabled')}128 <ToggleSwitch checked={enabled} onChange={handleEnabled} />129 </Field.Label>130 </Field>131 ),132 [enabled, handleEnabled, t],133 )}134 {useMemo(135 () => (136 <Field>137 <Field.Label>{t('Name_optional')}</Field.Label>138 <Field.Row>139 <TextInput flexGrow={1} value={name} onChange={handleName} />140 </Field.Row>141 <Field.Hint>142 {t('You_should_name_it_to_easily_manage_your_integrations')}143 </Field.Hint>144 </Field>145 ),146 [handleName, name, t],147 )}148 {useMemo(149 () =>150 showChannel && (151 <Field>152 <Field.Label>{t('Channel')}</Field.Label>153 <Field.Row>154 <TextInput155 flexGrow={1}156 value={channel}157 onChange={handleChannel}158 addon={<Icon name='at' size='x20' />}159 />160 </Field.Row>161 <Field.Hint>{t('Channel_to_listen_on')}</Field.Hint>162 <Field.Hint163 dangerouslySetInnerHTML={{164 __html: t(165 'Start_with_s_for_user_or_s_for_channel_Eg_s_or_s',166 '@',167 '#',168 '@john',169 '#general',170 ),171 }}172 />173 <Field.Hint174 dangerouslySetInnerHTML={{ __html: t('Integrations_for_all_channels') }}175 />176 </Field>177 ),178 [showChannel, t, channel, handleChannel],179 )}180 {useMemo(181 () =>182 showTriggerWords && (183 <Field>184 <Field.Label>{t('Trigger_Words')}</Field.Label>185 <Field.Row>186 <TextInput flexGrow={1} value={triggerWords} onChange={handleTriggerWords} />187 </Field.Row>188 <Field.Hint>189 {t('When_a_line_starts_with_one_of_there_words_post_to_the_URLs_below')}190 </Field.Hint>191 <Field.Hint>{t('Separate_multiple_words_with_commas')}</Field.Hint>192 </Field>193 ),194 [handleTriggerWords, showTriggerWords, t, triggerWords],195 )}196 {useMemo(197 () =>198 showTargetRoom && (199 <Field>200 <Field.Label>{t('TargetRoom')}</Field.Label>201 <Field.Row>202 <TextInput flexGrow={1} value={targetRoom} onChange={handleTargetRoom} />203 </Field.Row>204 <Field.Hint>{t('TargetRoom_Description')}</Field.Hint>205 <Field.Hint206 dangerouslySetInnerHTML={{207 __html: t(208 'Start_with_s_for_user_or_s_for_channel_Eg_s_or_s',209 '@',210 '#',211 '@john',212 '#general',213 ),214 }}215 />216 </Field>217 ),218 [handleTargetRoom, showTargetRoom, t, targetRoom],219 )}220 {useMemo(221 () => (222 <Field>223 <Field.Label>{t('URLs')}</Field.Label>224 <Field.Row>225 <TextAreaInput226 rows={10}227 flexGrow={1}228 value={urls}229 onChange={handleUrls}230 addon={<Icon name='permalink' size='x20' />}231 />232 </Field.Row>233 </Field>234 ),235 [handleUrls, t, urls],236 )}237 {useMemo(238 () => (239 <Field>240 <Field.Label display='flex' justifyContent='space-between' w='full'>241 {t('Impersonate_user')}242 <ToggleSwitch checked={impersonateUser} onChange={handleImpersonateUser} />243 </Field.Label>244 </Field>245 ),246 [handleImpersonateUser, impersonateUser, t],247 )}248 {useMemo(249 () => (250 <Field>251 <Field.Label>{t('Post_as')}</Field.Label>252 <Field.Row>253 <TextInput254 flexGrow={1}255 value={username}256 onChange={handleUsername}257 addon={<Icon name='user' size='x20' />}258 />259 </Field.Row>260 <Field.Hint>261 {t('Choose_the_username_that_this_integration_will_post_as')}262 </Field.Hint>263 <Field.Hint>{t('Should_exists_a_user_with_this_username')}</Field.Hint>264 </Field>265 ),266 [handleUsername, t, username],267 )}268 {useMemo(269 () => (270 <Field>271 <Field.Label>{`${t('Alias')} (${t('optional')})`}</Field.Label>272 <Field.Row>273 <TextInput274 flexGrow={1}275 value={alias}276 onChange={handleAlias}277 addon={<Icon name='edit' size='x20' />}278 />279 </Field.Row>280 <Field.Hint>281 {t('Choose_the_alias_that_will_appear_before_the_username_in_messages')}282 </Field.Hint>283 </Field>284 ),285 [alias, handleAlias, t],286 )}287 {useMemo(288 () => (289 <Field>290 <Field.Label>{`${t('Avatar_URL')} (${t('optional')})`}</Field.Label>291 <Field.Row>292 <TextInput293 flexGrow={1}294 value={avatarUrl}295 onChange={handleAvatar}296 addon={<Icon name='user-rounded' size='x20' alignSelf='center' />}297 />298 </Field.Row>299 <Field.Hint>{t('You_can_change_a_different_avatar_too')}</Field.Hint>300 <Field.Hint>{t('Should_be_a_URL_of_an_image')}</Field.Hint>301 </Field>302 ),303 [avatarUrl, handleAvatar, t],304 )}305 {useMemo(306 () => (307 <Field>308 <Field.Label>{`${t('Emoji')} (${t('optional')})`}</Field.Label>309 <Field.Row>310 <TextInput311 flexGrow={1}312 value={emoji}313 onChange={handleEmoji}314 addon={<Icon name='emoji' size='x20' alignSelf='center' />}315 />316 </Field.Row>317 <Field.Hint>{t('You_can_use_an_emoji_as_avatar')}</Field.Hint>318 <Field.Hint dangerouslySetInnerHTML={{ __html: t('Example_s', ':ghost:') }} />319 </Field>320 ),321 [emoji, handleEmoji, t],322 )}323 {useMemo(324 () => (325 <Field>326 <Field.Label>{`${t('Token')} (${t('Optional')})`}</Field.Label>327 <Field.Row>328 <TextInput329 flexGrow={1}330 value={token}331 onChange={handleToken}332 addon={<Icon name='key' size='x20' />}333 />334 </Field.Row>335 </Field>336 ),337 [handleToken, t, token],338 )}339 {useMemo(340 () => (341 <Field>342 <Field.Label display='flex' justifyContent='space-between' w='full'>343 {t('Script_Enabled')}344 <ToggleSwitch checked={scriptEnabled} onChange={handleScriptEnabled} />345 </Field.Label>346 </Field>347 ),348 [handleScriptEnabled, scriptEnabled, t],349 )}350 {useMemo(351 () => (352 <Field>353 <Field.Label>{t('Script')}</Field.Label>354 <Field.Row>355 <TextAreaInput356 rows={10}357 flexGrow={1}358 value={script}359 onChange={handleScript}360 addon={<Icon name='code' size='x20' alignSelf='center' />}361 />362 </Field.Row>363 </Field>364 ),365 [handleScript, script, t],366 )}367 {useMemo(368 () => (369 <Field>370 <Field.Label>{t('Responding')}</Field.Label>371 <Field.Hint>{t('Response_description_pre')}</Field.Hint>372 <Field.Row>373 <Box fontScale='p1' withRichContent flexGrow={1}>374 <pre>375 <code dangerouslySetInnerHTML={{ __html: hilightedExampleJson }}></code>376 </pre>377 </Box>378 </Field.Row>379 <Field.Hint>{t('Response_description_post')}</Field.Hint>380 </Field>381 ),382 [hilightedExampleJson, t],383 )}384 </FieldGroup>385 <Accordion.Item title={t('Integration_Advanced_Settings')}>386 <FieldGroup>387 {useMemo(388 () => (389 <Field>390 <Field.Label display='flex' justifyContent='space-between' w='full'>391 {t('Integration_Retry_Failed_Url_Calls')}392 <ToggleSwitch checked={retryFailedCalls} onChange={handleRetryFailedCalls} />393 </Field.Label>394 <Field.Hint>{t('Integration_Retry_Failed_Url_Calls_Description')}</Field.Hint>395 </Field>396 ),397 [handleRetryFailedCalls, retryFailedCalls, t],398 )}399 {useMemo(400 () => (401 <Field>402 <Field.Label>{t('Retry_Count')}</Field.Label>403 <Field.Row>404 <TextInput flexGrow={1} value={retryCount} onChange={handleRetryCount} />405 </Field.Row>406 <Field.Hint>{t('Integration_Retry_Count_Description')}</Field.Hint>407 </Field>408 ),409 [handleRetryCount, retryCount, t],410 )}411 {useMemo(412 () => (413 <Field>414 <Field.Label>{t('Integration_Retry_Delay')}</Field.Label>415 <Field.Row>416 <Select417 flexGrow={1}418 value={retryDelay}419 options={retryDelayOptions}420 onChange={handleRetryDelay}421 />422 </Field.Row>423 <Field.Hint424 dangerouslySetInnerHTML={{ __html: t('Integration_Retry_Delay_Description') }}425 />426 </Field>427 ),428 [handleRetryDelay, retryDelay, retryDelayOptions, t],429 )}430 {useMemo(431 () =>432 event === 'sendMessage' && (433 <FieldGroup>434 <Field>435 <Field.Label display='flex' justifyContent='space-between' w='full'>436 {t('Integration_Word_Trigger_Placement')}437 <ToggleSwitch438 checked={triggerWordAnywhere}439 onChange={handleTriggerWordAnywhere}440 />441 </Field.Label>442 <Field.Hint>443 {t('Integration_Word_Trigger_Placement_Description')}444 </Field.Hint>...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...80}) {81 const {82 strapi: { fieldApi },83 } = useStrapi();84 const attribute = useMemo(() => get(layout, ['schema', 'attributes', name], {}), [layout, name]);85 const metadatas = useMemo(() => get(layout, ['metadatas', name, 'edit'], {}), [layout, name]);86 const disabled = useMemo(() => !get(metadatas, 'editable', true), [metadatas]);87 const type = useMemo(() => get(attribute, 'type', null), [attribute]);88 const regexpString = useMemo(() => get(attribute, 'regex', null), [attribute]);89 const temporaryErrorIdUntilBuffetjsSupportsFormattedMessage = 'app.utils.defaultMessage';90 const errorId = useMemo(() => {91 return get(formErrors, [keys, 'id'], temporaryErrorIdUntilBuffetjsSupportsFormattedMessage);92 }, [formErrors, keys]);93 const fieldName = useMemo(() => {94 return getFieldName(keys);95 }, [keys]);96 const isChildOfDynamicZone = useMemo(() => {97 const attributes = get(currentContentTypeLayout, ['schema', 'attributes'], {});98 const foundAttributeType = get(attributes, [fieldName[0], 'type'], null);99 return foundAttributeType === 'dynamiczone';100 }, [currentContentTypeLayout, fieldName]);101 const validations = useMemo(() => {102 return omit(103 attribute,104 shouldNotRunValidations ? [...validationsToOmit, 'required', 'minLength'] : validationsToOmit105 );106 }, [attribute, shouldNotRunValidations]);107 const isRequired = useMemo(() => get(validations, ['required'], false), [validations]);108 const inputType = useMemo(() => {109 return getInputType(type);110 }, [type]);111 const inputValue = useMemo(() => {112 // Fix for input file multipe113 if (type === 'media' && !value) {114 return [];115 }116 return value;117 }, [type, value]);118 const step = useMemo(() => {119 let step;120 if (type === 'float' || type === 'decimal') {121 step = 0.01;122 } else if (type === 'time' || type === 'datetime') {123 step = 30;124 } else {125 step = 1;126 }127 return step;128 }, [type]);129 const isMultiple = useMemo(() => {130 return get(attribute, 'multiple', false);131 }, [attribute]);132 const isUserAllowedToEditField = useMemo(() => {133 const joinedName = fieldName.join('.');134 if (allowedFields.includes(joinedName)) {135 return true;136 }137 if (isChildOfDynamicZone) {138 return allowedFields.includes(fieldName[0]);139 }140 const isChildOfComponent = fieldName.length > 1;141 if (isChildOfComponent) {142 const parentFieldName = take(fieldName, fieldName.length - 1).join('.');143 return allowedFields.includes(parentFieldName);144 }145 return false;146 }, [allowedFields, fieldName, isChildOfDynamicZone]);147 const isUserAllowedToReadField = useMemo(() => {148 const joinedName = fieldName.join('.');149 if (readableFields.includes(joinedName)) {150 return true;151 }152 if (isChildOfDynamicZone) {153 return readableFields.includes(fieldName[0]);154 }155 const isChildOfComponent = fieldName.length > 1;156 if (isChildOfComponent) {157 const parentFieldName = take(fieldName, fieldName.length - 1).join('.');158 return readableFields.includes(parentFieldName);159 }160 return false;161 }, [readableFields, fieldName, isChildOfDynamicZone]);162 const shouldDisplayNotAllowedInput = useMemo(() => {163 return isUserAllowedToReadField || isUserAllowedToEditField;164 }, [isUserAllowedToEditField, isUserAllowedToReadField]);165 const shouldDisableField = useMemo(() => {166 if (!isCreatingEntry) {167 const doesNotHaveRight = isUserAllowedToReadField && !isUserAllowedToEditField;168 if (doesNotHaveRight) {169 return true;170 }171 return disabled;172 }173 return disabled;174 }, [disabled, isCreatingEntry, isUserAllowedToEditField, isUserAllowedToReadField]);175 const options = useMemo(() => {176 return get(attribute, 'enum', []).map(v => {177 return (178 <option key={v} value={v}>179 {v}180 </option>181 );182 });183 }, [attribute]);184 const otherFields = useMemo(() => {185 return fieldApi.getFields();186 }, [fieldApi]);187 if (regexpString) {188 const regexp = new RegExp(regexpString);189 if (regexp) {190 validations.regex = regexp;191 }192 }193 const { description, visible } = metadatas;194 if (visible === false) {195 return null;196 }197 if (!shouldDisplayNotAllowedInput) {198 return <NotAllowedInput label={metadatas.label} />;...

Full Screen

Full Screen

PreferencesMessagesSection.js

Source:PreferencesMessagesSection.js Github

copy

Full Screen

...55 handleClockMode,56 handleSendOnEnter,57 handleMessageViewMode,58 } = handlers;59 const timeFormatOptions = useMemo(60 () => [61 [0, t('Default')],62 [1, t('12_Hour')],63 [2, t('24_Hour')],64 ],65 [t],66 );67 const sendOnEnterOptions = useMemo(68 () => [69 ['normal', t('Enter_Normal')],70 ['alternative', t('Enter_Alternative')],71 ['desktop', t('Only_On_Desktop')],72 ],73 [t],74 );75 const messageViewModeOptions = useMemo(76 () => [77 [0, t('Normal')],78 [1, t('Cozy')],79 [2, t('Compact')],80 ],81 [t],82 );83 commitRef.current.messages = commit;84 // TODO: Weird behaviour when saving clock mode, and then changing it.85 return (86 <Accordion.Item title={t('Messages')} {...props}>87 <FieldGroup>88 {useMemo(89 () => (90 <Field display='flex' flexDirection='row' justifyContent='spaceBetween' flexGrow={1}>91 <Field.Label>{t('Unread_Tray_Icon_Alert')}</Field.Label>92 <Field.Row>93 <ToggleSwitch checked={unreadAlert} onChange={handleUnreadAlert} />94 </Field.Row>95 </Field>96 ),97 [handleUnreadAlert, t, unreadAlert],98 )}99 {useMemo(100 () => (101 <Field display='flex' flexDirection='row' justifyContent='spaceBetween' flexGrow={1}>102 <Field.Label>{t('Show_Message_In_Main_Thread')}</Field.Label>103 <Field.Row>104 <ToggleSwitch105 checked={showMessageInMainThread}106 onChange={handleShowMessageInMainThread}107 />108 </Field.Row>109 </Field>110 ),111 [handleShowMessageInMainThread, showMessageInMainThread, t],112 )}113 {useMemo(114 () => (115 <Field>116 <Field.Label>{t('Message_TimeFormat')}</Field.Label>117 <Field.Row>118 <Select value={clockMode} onChange={handleClockMode} options={timeFormatOptions} />119 </Field.Row>120 </Field>121 ),122 [clockMode, handleClockMode, t, timeFormatOptions],123 )}124 {useMemo(125 () => (126 <Field display='flex' flexDirection='row' justifyContent='spaceBetween' flexGrow={1}>127 <Field.Label>{t('Use_Emojis')}</Field.Label>128 <Field.Row>129 <ToggleSwitch checked={useEmojis} onChange={handleUseEmojis} />130 </Field.Row>131 </Field>132 ),133 [handleUseEmojis, t, useEmojis],134 )}135 {useMemo(136 () => (137 <Field display='flex' flexDirection='row' justifyContent='spaceBetween' flexGrow={1}>138 <Field.Label>{t('Convert_Ascii_Emojis')}</Field.Label>139 <Field.Row>140 <ToggleSwitch checked={convertAsciiEmoji} onChange={handleConvertAsciiEmoji} />141 </Field.Row>142 </Field>143 ),144 [convertAsciiEmoji, handleConvertAsciiEmoji, t],145 )}146 {useMemo(147 () => (148 <Field display='flex' flexDirection='row' justifyContent='spaceBetween' flexGrow={1}>149 <Field.Label>{t('Auto_Load_Images')}</Field.Label>150 <Field.Row>151 <ToggleSwitch checked={autoImageLoad} onChange={handleAutoImageLoad} />152 </Field.Row>153 </Field>154 ),155 [autoImageLoad, handleAutoImageLoad, t],156 )}157 {useMemo(158 () => (159 <Field display='flex' flexDirection='row' justifyContent='spaceBetween' flexGrow={1}>160 <Field.Label>{t('Save_Mobile_Bandwidth')}</Field.Label>161 <Field.Row>162 <ToggleSwitch checked={saveMobileBandwidth} onChange={handleSaveMobileBandwidth} />163 </Field.Row>164 </Field>165 ),166 [handleSaveMobileBandwidth, saveMobileBandwidth, t],167 )}168 {useMemo(169 () => (170 <Field display='flex' flexDirection='row' justifyContent='spaceBetween' flexGrow={1}>171 <Field.Label>{t('Collapse_Embedded_Media_By_Default')}</Field.Label>172 <Field.Row>173 <ToggleSwitch174 checked={collapseMediaByDefault}175 onChange={handleCollapseMediaByDefault}176 />177 </Field.Row>178 </Field>179 ),180 [collapseMediaByDefault, handleCollapseMediaByDefault, t],181 )}182 {useMemo(183 () => (184 <Field display='flex' flexDirection='row' justifyContent='spaceBetween' flexGrow={1}>185 <Field.Label>{t('Hide_usernames')}</Field.Label>186 <Field.Row>187 <ToggleSwitch checked={hideUsernames} onChange={handleHideUsernames} />188 </Field.Row>189 </Field>190 ),191 [handleHideUsernames, hideUsernames, t],192 )}193 {useMemo(194 () =>195 showRoles && (196 <Field display='flex' flexDirection='row' justifyContent='spaceBetween' flexGrow={1}>197 <Field.Label>{t('Hide_roles')}</Field.Label>198 <Field.Row>199 <ToggleSwitch checked={hideRoles} onChange={handleHideRoles} />200 </Field.Row>201 </Field>202 ),203 [handleHideRoles, hideRoles, showRoles, t],204 )}205 {useMemo(206 () => (207 <Field display='flex' flexDirection='row' justifyContent='spaceBetween' flexGrow={1}>208 <Field.Label>{t('Hide_flextab')}</Field.Label>209 <Field.Row>210 <ToggleSwitch checked={hideFlexTab} onChange={handleHideFlexTab} />211 </Field.Row>212 </Field>213 ),214 [handleHideFlexTab, hideFlexTab, t],215 )}216 {useMemo(217 () => (218 <Field display='flex' flexDirection='row' justifyContent='spaceBetween' flexGrow={1}>219 <Field.Label>{t('Display_avatars')}</Field.Label>220 <Field.Row>221 <ToggleSwitch checked={displayAvatars} onChange={handleDisplayAvatars} />222 </Field.Row>223 </Field>224 ),225 [handleDisplayAvatars, displayAvatars, t],226 )}227 {useMemo(228 () => (229 <Field>230 <Field.Label>{t('Enter_Behaviour')}</Field.Label>231 <Field.Row>232 <Select233 value={sendOnEnter}234 onChange={handleSendOnEnter}235 options={sendOnEnterOptions}236 />237 </Field.Row>238 <Field.Hint>{t('Enter_Behaviour_Description')}</Field.Hint>239 </Field>240 ),241 [handleSendOnEnter, sendOnEnter, sendOnEnterOptions, t],242 )}243 {useMemo(244 () => (245 <Field>246 <Field.Label>{t('View_mode')}</Field.Label>247 <Field.Row>248 <Select249 value={messageViewMode}250 onChange={handleMessageViewMode}251 options={messageViewModeOptions}252 />253 </Field.Row>254 <Field.Hint>{t('Message_view_mode_info')}</Field.Hint>255 </Field>256 ),257 [handleMessageViewMode, messageViewMode, messageViewModeOptions, t],...

Full Screen

Full Screen

player_token_info.react.js

Source:player_token_info.react.js Github

copy

Full Screen

...16import TokenPreview from '../token_preview.react';17const PlayerTokenInfo = props => {18 const [open, SetOpen] = useState(() => false);19 const player = GameRoom.player;20 const token = useMemo(() => GameRoom.tokens.find(t => t.name == player.name));21 const color = player.color;22 const [url, urlValid, handleURL] = useUrl(player);23 const run = useMemo(() => player.run);24 const fly = useMemo(() => player.fly);25 const runDistance = e => (player.run = Math.max(0, e.target.value));26 const flyDistance = e => (player.fly = Math.max(0, e.target.value));27 const intent = useMemo(() =>28 token && token.over ? Intent.PRIMARY : Intent.NONE29 );30 const gradient = useMemo(31 () => `linear-gradient(90deg,${color} 10px, rgba(0,0,0,0) 35px)`,32 [color]33 );34 const style = useMemo(() => {35 let s = {};36 Object.assign(s, props.style);37 Object.assign(s, {38 backgroundImage: `${gradient}`,39 });40 return s;41 });42 const result = useMemo(() => (token ? token.current_roll[0] : 0));43 const roll = useMemo(() => (token ? token.current_roll[1] : 0));44 const add = useMemo(() => (token ? token.current_roll[2] : 0));45 const roll_string = useMemo(() => `${result} = ${roll}(d20) + ${add}`);46 return (47 <Callout icon={null} className='token-callout' style={style}>48 <input49 className='bp3-button token-color'50 type='color'51 value={color}52 onChange={player.OnChangeColor}53 />54 <TokenPreview token={player} />55 <FormGroup>56 <div className='space-between'>57 <ButtonGroup>58 <SButton59 title={player.name}60 onClick={() => SetOpen(!open)}61 className='token-list-name'62 text={player.name}63 />64 <SButton65 title='Move to center'66 onClick={token ? token.MoveToCenter : undefined}67 icon='inheritance'68 disabled={!token}69 />70 <SButton71 title='Zoom to'72 onClick={token ? token.CenterOn : undefined}73 icon='locate'74 disabled={!token}75 />76 <SButton77 title='Roll Initiative'78 onClick={token ? token.RollInitiative : () => {}}79 icon='random'80 />81 </ButtonGroup>82 <Tag title={roll_string}>{result}</Tag>83 </div>84 <Collapse isOpen={open} className='layer-info'>85 <FormGroup inline={false} label='Image URL'>86 <SInput87 onChange={handleURL}88 placeholder='url...'89 type='text'90 value={url}91 intent={Intent.NONE}92 />93 </FormGroup>94 <PlayerVisionInfo {...props} />95 <FormGroup96 className='formatted double-num'97 inline={false}98 label='Travel'99 >100 <SInputDistance101 value={run}102 onChange={runDistance}103 className='small-number'104 leftIcon='walk'105 />106 <SInputDistance107 value={fly}108 onChange={flyDistance}109 className='small-number'110 leftIcon='airplane'111 />112 </FormGroup>113 </Collapse>114 </FormGroup>115 </Callout>116 );117};118const PlayerVisionInfo = props => {119 const player = GameRoom.player;120 const light = useMemo(() => player.vision[0]);121 const dim = useMemo(() => player.vision[1]);122 const dark = useMemo(() => player.vision[2]);123 const lightDistance = e => (player.vision[0] = Math.max(0, e.target.value));124 const dimDistance = e => (player.vision[1] = Math.max(0, e.target.value));125 const darkDistance = e => (player.vision[2] = Math.max(0, e.target.value));126 const light_color = Player.vision_colors[0];127 const dim_color = Player.vision_colors[1];128 const dark_color = Player.vision_colors[2];129 return (130 <>131 <FormGroup className='formatted double-num' inline={false} label='Vision'>132 <SInputDistance133 value={light}134 onChange={lightDistance}135 className='small-number3'136 leftIcon='circle'...

Full Screen

Full Screen

token_info.react.js

Source:token_info.react.js Github

copy

Full Screen

...14import SInput, { SInputNumber } from '../../components/small_input.react';15import TokenPreview from '../token_preview.react';16const TokenInfo = props => {17 const [open, SetOpen] = useState(() => false);18 const token = useMemo(() => props.token);19 const name = useMemo(() => token.name, [token.name]);20 const x = useMemo(() => token.x, [token.x]);21 const y = useMemo(() => token.y, [token.y]);22 const size = useMemo(() => token.size, [token.size]);23 const visible = useMemo(() => token.visible, [token.visible]);24 const color = useMemo(() => token.color, [token.color]);25 const [url, urlValid, handleURL] = useUrl(token);26 const intent = useMemo(() => (token.over ? Intent.PRIMARY : Intent.NONE), [27 token.over,28 ]);29 const gradient = useMemo(30 () => `linear-gradient(90deg,${color} 10px, rgba(0,0,0,0) 35px)`,31 [color]32 );33 const style = useMemo(() => ({34 backgroundImage: `${gradient}`,35 }));36 const result = useMemo(() => token.current_roll[0]);37 const roll = useMemo(() => token.current_roll[1]);38 const add = useMemo(() => token.current_roll[2]);39 const roll_string = useMemo(() => `${result} = ${roll}(d20) + ${add}`);40 return (41 <Callout42 intent={intent}43 icon={null}44 className='token-callout'45 style={style}46 >47 <input48 className='bp3-button token-color'49 type='color'50 value={color}51 onChange={token.OnChangeColor}52 />53 <TokenPreview token={token} />...

Full Screen

Full Screen

UseMemoH.jsx

Source:UseMemoH.jsx Github

copy

Full Screen

2import ReactCode from "../../../../components/ReactCode";3export default function UseMemoH() {4 const [x, setx] = useState(0);5 const [y, sety] = useState(100);6 const multiplication = useMemo(() => {7 alert("Multiplication of x function with useMemo hook");8 return x * 200;9 }, [x]);10 return (11 <>12 <h1>useMemo hook</h1>13 <ul data-ul="what is useMemo hook">14 <li>useMemo hook is same like pure component but only for function component</li>15 <li>useMemo hook is prevent to unnecessary calling functions in component</li>16 </ul>17 <ul data-ul="useMemo syntax"></ul>18 <ReactCode19 file="Syntax"20 dot="jsx"21 code={`22 const variableName = useMemo(() => {23 //code here24 },[state (or) props variableName]);25 `}26 />27 <ul data-ul="how to use useMemo hook"></ul>28 <ReactCode29 file="Example"30 dot="jsx"31 code={`32 import React, { useState, useMemo } from "react";33 34 export default function Example() {35 const [x, setx] = useState(0);36 const [y, sety] = useState(100);37 //function without useMemo: calling every time ,every state (x,y)38 const multi = () => {39 return x * 200;40 };41 //function with useMemo: calling only x state change42 const multi = useMemo(() => {43 return x * 200;44 }, [x]);45 return (46 <>47 <p>x : {x}</p>48 <p>y : {y}</p> 49 <p>without useMemo x : {multi()}</p>50 <p>with useMemo x : {multi}</p>51 <button onClick={() => setx(x + 1)}>change x value</button>52 <button onClick={() => sety(y + 1)}>change y value</button>53 </>54 )55 }56 ...

Full Screen

Full Screen

App.js

Source:App.js Github

copy

Full Screen

...17const App = () => {18 const [count, setCount] = useState(0);19 const click = () => setCount(count + 1);20 //21 const memoChild = useMemo(() => {22 return <Child />;23 // add a state in this dependency and it will re-render as normal24 }, []);25 const normalChild = <Child />;26 //27 return (28 <div className="App">29 <div>30 <Button onClick={click}>Increase count</Button> <>count : {count}</>31 </div>32 <header>33 <h3>Use Memo: <>{memoChild}</></h3>34 <h3>Normal Render: <>{normalChild}</></h3>35 </header>...

Full Screen

Full Screen

register.js

Source:register.js Github

copy

Full Screen

...6 return;7 }8 registerForm({9 useCustomFieldsAdditionalForm: () =>10 useMemo(() => lazy(() => import('./CustomFieldsAdditionalFormContainer')), []),11 });12 registerForm({13 useMaxChatsPerAgent: () => useMemo(() => lazy(() => import('./MaxChatsPerAgentContainer')), []),14 });15 registerForm({16 useMaxChatsPerAgentDisplay: () =>17 useMemo(() => lazy(() => import('./MaxChatsPerAgentDisplay')), []),18 });19 registerForm({20 useEeNumberInput: () => useMemo(() => lazy(() => import('./EeNumberInput')), []),21 });22 registerForm({23 useEeTextAreaInput: () => useMemo(() => lazy(() => import('./EeTextAreaInput')), []),24 });25 registerForm({ useEeTextInput: () => useMemo(() => lazy(() => import('./EeTextInput')), []) });26 registerForm({27 useBusinessHoursMultiple: () =>28 useMemo(() => lazy(() => import('./BusinessHoursMultipleContainer')), []),29 });30 registerForm({31 useBusinessHoursTimeZone: () =>32 useMemo(() => lazy(() => import('./BusinessHoursTimeZone')), []),33 });34 registerForm({35 useContactManager: () => useMemo(() => lazy(() => import('./ContactManager')), []),36 });37 registerForm({38 useCurrentChatTags: () => useMemo(() => lazy(() => import('../tags/CurrentChatTags')), []),39 });40 registerForm({41 useDepartmentBusinessHours: () =>42 useMemo(() => lazy(() => import('./DepartmentBusinessHours')), []),43 });44 registerForm({45 useDepartmentForwarding: () => useMemo(() => lazy(() => import('./DepartmentForwarding')), []),46 });47 registerForm({48 usePrioritiesSelect: () => useMemo(() => lazy(() => import('./PrioritiesSelect')), []),49 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import React, { useState, useMemo } from "react";2import "./styles.css";3export default function App() {4 const [count, setCount] = useState(0);5 const [count1, setCount1] = useState(0);6 const [count2, setCount2] = useState(0);7 const increment = useMemo(() => {8 return () => {9 setCount(count + 1);10 };11 }, [count]);12 const increment1 = useMemo(() => {13 return () => {14 setCount1(count1 + 1);15 };16 }, [count1]);17 const increment2 = useMemo(() => {18 return () => {19 setCount2(count2 + 1);20 };21 }, [count2]);22 return (23 <button onClick={increment}>Count - {count}</button>24 <button onClick={increment1}>Count - {count1}</button>25 <button onClick={increment2}>Count - {count2}</button>26 );27}28import React, { useMemo } from "react";29export default function ChildComponent({ count }) {30 const increment = useMemo(() => {31 return () => {32 console.log("increment");33 };34 }, [count]);35 const decrement = useMemo(() => {36 return () => {37 console.log("decrement");38 };39 }, [count]);40 return (41 <button onClick={increment}>Increment</button>42 <button onClick={decrement}>Decrement</button>43 );44}45React.memo() method46React.memo() method is used to optimize the

Full Screen

Using AI Code Generation

copy

Full Screen

1import { createStore, combineReducers, applyMiddleware, compose } from "redux";2import thunk from "redux-thunk";3import { composeWithDevTools } from "redux-devtools-extension";4import { productListReducer, productDetailsReducer } from "./reducers/productReducers";5import { cartReducer } from "./reducers/cartReducers";6import {7} from "./reducers/userReducers";8import {9} from "./reducers/orderReducers";10const reducer = combineReducers({11});12const cartItemsFromStorage = localStorage.getItem("cartItems")13 ? JSON.parse(localStorage.getItem("cartItems"))14 : [];15const userInfoFromStorage = localStorage.getItem("userInfo")16 ? JSON.parse(localStorage.getItem("userInfo"))17 : null;18const shippingAddressFromStorage = localStorage.getItem("shippingAddress")19 ? JSON.parse(localStorage.getItem("shippingAddress"))20 : {};21const initialState = {22 cart: {23 },24 userLogin: { userInfo: userInfoFromStorage },25};26const middleware = [thunk];27const store = createStore(28 composeWithDevTools(applyMiddleware(...middleware))29);30export default store;31export const cartReducer = (state = { cartItems: [], shippingAddress: {} }, action) => {32 switch (action.type) {33 const item = action.payload;34 const existItem = state.cartItems.find((x) => x.product === item.product);35 if (existItem) {36 return {37 cartItems: state.cartItems.map((x) =>38 };39 } else {40 return {

Full Screen

Using AI Code Generation

copy

Full Screen

1import React, { useState, useMemo } from "react";2import { render } from "react-dom";3import { useFetch } from "./useFetch";4const App = () => {5 const [count, setCount] = useState(0);6 const { data } = useFetch(7 );8 const computeLongestWord = (arr) => {9 if (!arr) {10 return [];11 }12 console.log("computing longest word");13 let longestWord = "";14 JSON.parse(arr).forEach((sentence) =>15 sentence.split(" ").forEach((word) => {16 if (word.length > longestWord.length) {17 longestWord = word;18 }19 })20 );21 return longestWord;22 };23 const longestWord = useMemo(() => computeLongestWord(data), [data]);24 return (25 <div>count: {count}</div>26 <button onClick={() => setCount((c) => c + 1)}>increment</button>27 <div>{longestWord}</div>28 );29};30render(<App />, document.getElementById("root"));31import { useState, useEffect } from "react";32export const useFetch = (url) => {33 const [data, setData] = useState(null);34 useEffect(() => {35 const fetchData = async () => {36 const response = await fetch(url);37 const data = await response.json();38 setData(data);39 };40 fetchData();41 }, [url]);42 return { data };43};

Full Screen

Using AI Code Generation

copy

Full Screen

1import React, { useState, useMemo } from "react";2import ReactDOM from "react-dom";3import { useCounter } from "./useCounter";4const Test = () => {5 const [count, setCount] = useState(0);6 const [count2, setCount2] = useState(0);7 const increment = () => {8 setCount(count + 1);9 };10 const increment2 = () => {11 setCount2(count2 + 1);12 };13 const isEven = useMemo(() => {14 let i = 0;15 while (i < 2000000000) i++;16 return count % 2 === 0;17 }, [count]);18 return (19 <button onClick={increment}>Count 1 - {count}</button>20 <span>{isEven ? "Even" : "Odd"}</span>21 <button onClick={increment2}>Count 2 - {count2}</button>22 );23};24ReactDOM.render(<Test />, document.getElementById("root"));25import React, { useState, useEffect, useMemo } from "react";26export const useCounter = () => {27 const [count, setCount] = useState(0);28 const increment = () => {29 setCount(count + 1);30 };31 const decrement = () => {32 setCount(count - 1);33 };34 const reset = () => {35 setCount(0);36 };37 const isEven = useMemo(() => {38 let i = 0;39 while (i < 2000000000) i++;40 return count % 2 === 0;41 }, [count]);42 return { count, increment, decrement, reset, isEven };43};44import React, { useState, useCallback } from "react";45import ReactDOM from "react-dom";46import { useCounter } from "./useCounter";47const Test = () => {48 const [count, setCount] = useState(0);49 const [count2, setCount2] = useState(0);50 const increment = useCallback(() => {51 setCount(count + 1);52 }, [count]);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { useMemo } from 'react';2import { useRootHook } from './rootHook';3const useTestHook = () => {4 const { state, setState } = useRootHook();5 const { test } = state;6 const { setTest } = setState;7 const testValue = useMemo(() => test, [test]);8 return { testValue, setTest };9};10export default useTestHook;11import { useState, useCallback } from 'react';12const useRootHook = () => {13 const [state, setState] = useState({14 });15 const setTest = useCallback((value) => {16 setState((prevState) => ({17 }));18 }, []);19 return { state, setState, setTest };20};21export default useRootHook;22import React from 'react';23import useTestHook from './test';24const App = () => {25 const { testValue, setTest } = useTestHook();26 return (27 <h1>{testValue}</h1>28 <button onClick={() => setTest('test2')}>Click me</button>29 );30};31export default App;

Full Screen

Using AI Code Generation

copy

Full Screen

1import { useMemo } from 'react';2const myFunction = () => {3 const myValue = useMemo(() => {4 return 'myValue';5 }, []);6};7import React from 'react';8const myFunction = () => {9 const myValue = React.useMemo(() => {10 return 'myValue';11 }, []);12};13import { useRef } from 'react';14const myFunction = () => {15 const myRef = useRef();16};17import React from 'react';18const myFunction = () => {19 const myRef = React.useRef();20};21import { useReducer } from 'react';22const myFunction = () => {23 const [state, dispatch] = useReducer((state, action) => {24 switch (action.type) {25 return { ...state, count: state.count + action.payload };26 return { ...state, count: state.count - action.payload };27 return state;28 }29 }, { count: 0 });30};31import React from 'react';32const myFunction = () => {33 const [state, dispatch] = React.useReducer((state, action) => {34 switch (action.type) {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful