mobx-react-lite#Observer TypeScript Examples
The following examples show how to use
mobx-react-lite#Observer.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConnectedAvatar.tsx From binaural-meet with GNU General Public License v3.0 | 6 votes |
ConnectedAvatar: React.FC<ConnectedAvatarProps> = (props) => {
const participant = props.participant
// console.log('ConnectedAvatar is rendered.')
return <Observer>{() => {
const colors = participant.getColor()
const {avatarSrc, name} = participant.information
const args = {colors, avatarSrc, name}
return <ComposedAvatar {...args}
stream={participant.showVideo && !(participant instanceof PlaybackParticipant) ?
participant.tracks.avatarStream : undefined}
blob={participant.showVideo && (participant instanceof PlaybackParticipant) ?
participant.videoBlob: undefined}
colors={colors} size={props.size} style={{pointerEvents:'none'}}
mirror={props.isLocal}
/>
}}</Observer>
}
Example #2
Source File: RelationalDatabaseConnectionEditor.tsx From legend-studio with Apache License 2.0 | 6 votes |
GCPWorkloadIdentityFederationAuthenticationStrategyEditor = observer(
(props: {
authSpec: GCPWorkloadIdentityFederationAuthenticationStrategy;
isReadOnly: boolean;
}) => {
const { authSpec, isReadOnly } = props;
const GCPScopes = authSpec.additionalGcpScopes.join('\n');
return (
<>
<ConnectionEditor_StringEditor
isReadOnly={isReadOnly}
value={authSpec.serviceAccountEmail}
propertyName={'Service Account Email'}
update={(value: string | undefined): void =>
gcpWorkloadIdentityFederationAuthenticationStrategy_setServiceAccountEmail(
authSpec,
value ?? '',
)
}
/>
<ConnectionEditor_StringEditor
isReadOnly={isReadOnly}
value={GCPScopes}
propertyName={'Additional GCP Scopes'}
update={(value: string | undefined): void =>
gcpWorkloadIdentityFederationAuthenticationStrategy_setAdditionalGcpScopes(
authSpec,
value ? [value] : [],
)
}
/>
</>
);
},
)
Example #3
Source File: ImageAvatar.tsx From binaural-meet with GNU General Public License v3.0 | 6 votes |
RawImageAvatar: React.FC<ImageAvatarProps> = (props: ImageAvatarProps) => {
const classes = useStyles(props)
return <Observer>{()=>{
//console.log(`render ImageAvatar src=${props.avatarSrc}`)
let initial = ''
if (!props.avatarSrc){
const nameArray = props.name.split(' ')
nameArray.forEach(s => initial += s ? s.substring(0,1) : '')
initial = initial.substring(0,2)
}
const size = props.border ? props.size * BORDER_CONTENT : props.size
return props.avatarSrc ?
<Avatar src={props.avatarSrc} className={classes.imageAvatar} /> :
<Avatar className={classes.textAvatar} >
<div style={{height:size, width:size, textAlign:'center',
verticalAlign:'middle', display:'table-cell', whiteSpace:'nowrap'}}>
{initial}</div></Avatar>
}
}</Observer>
}
Example #4
Source File: DataTableSettings.tsx From jmix-frontend with Apache License 2.0 | 6 votes |
DataTableSettings = observer(<T, >({ columns, fieldsVisibility, onChange }: DataTableSettingsProps<T>) => { const intl = useIntl(); const content = <List dataSource={columns} renderItem={item => ( <List.Item> <Checkbox checked = {fieldsVisibility.get(item.key as string)} onChange={ev => onChange(item.key as string, ev.target.checked)} > {item.title} </Checkbox> </List.Item> )} />; return <Popover placement="bottom" title={intl.formatMessage({id: 'jmix.dataTable.fieldsVisibility'})} content={content} trigger="click" > <Button> <SettingOutlined /> </Button> </Popover> })
Example #5
Source File: index.tsx From hubble-ui with Apache License 2.0 | 6 votes |
run = async () => {
ui.setCSSVars(ui.sizes);
const routes: Route[] = [Route.new('service-map', { path: '(/:namespace)' })];
const Screen = observer(() => {
useHooksOnDataManager();
return (
<Router>
<App key="service-map" api={api} path="/*appPath" />
</Router>
);
});
// NOTE: we don't have another option to take notifier from except from inside
const onFeatureFetchError = (err: Error, notifier: Notifier) => {
console.error('features fetch error: ', err);
notifier.showError(`Failed to load UI settings: ${err.message}`);
};
const elems = (
<NotifierProvider>
<StoreProvider historySource={RouteHistorySourceKind.URL} routes={routes}>
<DataManagerProvider api={api}>
<FeatureFlagsFetcher api={api.v1} onError={onFeatureFetchError}>
<Screen />
</FeatureFlagsFetcher>
</DataManagerProvider>
</StoreProvider>
</NotifierProvider>
);
ReactDOM.render(elems, document.getElementById('app'));
}
Example #6
Source File: ActionAlert.tsx From legend-studio with Apache License 2.0 | 6 votes |
ActionAlert = observer(() => {
const applicationStore = useApplicationStore();
const actionAlertInfo = applicationStore.actionAlertInfo;
if (!actionAlertInfo) {
return null;
}
return <ActionAlertInner info={actionAlertInfo} />;
})
Example #7
Source File: FaceControl.tsx From binaural-meet with GNU General Public License v3.0 | 6 votes |
FaceControl: React.FC<BMProps> = (props: BMProps) => {
const local = props.stores.participants.local
const faceSwitch = <Observer>{ () =>
<Switch checked={local.information.faceTrack} name="face"
onChange={event => {
local.information.faceTrack = !local.information.faceTrack
local.saveInformationToStorage()
local.sendInformation()
} } />
}</Observer>
const {t} = useTranslation()
return <Container>
<FormControlLabel
control={faceSwitch}
label={t('showTrackedFace')}
/>
</Container>
}
Example #8
Source File: BasicValueSpecificationEditor.tsx From legend-studio with Apache License 2.0 | 6 votes |
NumberPrimitiveInstanceValueEditor = observer(
(props: {
valueSpecification: PrimitiveInstanceValue;
isInteger: boolean;
className?: string | undefined;
resetValue: () => void;
}) => {
const { valueSpecification, isInteger, className, resetValue } = props;
const value = valueSpecification.values[0] as number;
const changeValue: React.ChangeEventHandler<HTMLInputElement> = (event) => {
let inputVal = isInteger
? parseInt(event.target.value, 10)
: parseFloat(event.target.value);
inputVal = isNaN(inputVal) ? 0 : inputVal;
instanceValue_changeValue(valueSpecification, inputVal, 0);
};
return (
<div className={clsx('value-spec-editor', className)}>
<input
className="panel__content__form__section__input value-spec-editor__input"
spellCheck={false}
type="number"
value={value}
onChange={changeValue}
/>
<button
className="value-spec-editor__reset-btn"
title="Reset"
onClick={resetValue}
>
<RefreshIcon />
</button>
</div>
);
},
)
Example #9
Source File: ShareLayer.tsx From binaural-meet with GNU General Public License v3.0 | 6 votes |
ShareLayer = React.memo<MapProps>(
(props) => {
const contents = props.stores.contents
const classes = useStyles()
const {transparent, ...contentProps} = props
return <div className={classes.slContainer} >
<Observer>{
()=>{
const all = Array.from(contents.all)
const filtered = props.transparent ? all.filter(c => !isContentWallpaper(c)) : all
return <>{
filtered.map(val =>
<SharedContent key={val.id} content={val} {...contentProps} />)
}</>
}
}</Observer>
<PastedContent {...contentProps} />
</div>
},
(prev, next) => {
return _.isEqual(prev.stores.contents.all, next.stores.contents.all) && prev.transparent === next.transparent
},
)
Example #10
Source File: BasicValueSpecificationEditor.tsx From legend-studio with Apache License 2.0 | 6 votes |
DateInstanceValueEditor = observer(
(props: {
valueSpecification: PrimitiveInstanceValue | SimpleFunctionExpression;
graph: PureModel;
typeCheckOption: TypeCheckOption;
className?: string | undefined;
updateValue: (val: ValueSpecification) => void;
resetValue: () => void;
}) => {
const {
valueSpecification,
updateValue,
graph,
typeCheckOption,
resetValue,
} = props;
return (
<div className="value-spec-editor">
<CustomDatePicker
valueSpecification={valueSpecification}
graph={graph}
typeCheckOption={typeCheckOption}
updateValue={updateValue}
/>
<button
className="value-spec-editor__reset-btn"
title="Reset"
onClick={resetValue}
>
<RefreshIcon />
</button>
</div>
);
},
)
Example #11
Source File: Background.tsx From binaural-meet with GNU General Public License v3.0 | 6 votes |
Background: React.FC<MapProps> = (props) => {
const roomInfo = props.stores.roomInfo
const styleProps = {
color: [0,0,0],
fill: [0,0,0],
...props
}
useObserver(()=>{
styleProps.color = roomInfo.backgroundColor
styleProps.fill = roomInfo.backgroundFill
})
const classes = useStyles(styleProps)
return <Observer>{() => {
return <div className={classes.img}>
<img className={classes.logo} src={jitsiIcon} alt="jitsi icon"/>
</div>
}}</Observer>
}
Example #12
Source File: BlockingAlert.tsx From legend-studio with Apache License 2.0 | 6 votes |
BlockingAlert = observer(() => {
const applicationStore = useApplicationStore();
const info = applicationStore.blockingAlertInfo;
if (!info) {
return null;
}
return (
<Dialog
open={Boolean(info)}
onClose={noop} // disallow closing dialog by using Esc key or clicking on the backdrop
classes={{
root: 'blocking-alert__root-container',
container: 'blocking-alert__container',
}}
>
<div className="modal modal--dark blocking-alert">
<PanelLoadingIndicator isLoading={Boolean(info.showLoading)} />
<div className="modal__body">
<div className="blocking-alert__message">{info.message}</div>
{info.prompt && (
<div className="blocking-alert__message__prompt">{info.prompt}</div>
)}
</div>
</div>
</Dialog>
);
})
Example #13
Source File: HistoryList.tsx From lightning-terminal with MIT License | 5 votes |
HistoryList: React.FC = () => {
const { swapStore } = useStore();
const { Wrapper } = Styled;
return (
<Wrapper>
<HistoryRowHeader />
<ListContainer>
<AutoSizer disableHeight>
{({ width }) => (
<WindowScroller>
{({ height, isScrolling, onChildScroll, scrollTop, registerChild }) => (
<Observer>
{() => (
<div ref={ref => ref && registerChild(ref)}>
<List
autoHeight
height={height}
isScrolling={isScrolling}
onScroll={onChildScroll}
rowCount={swapStore.sortedSwaps.length}
rowHeight={ROW_HEIGHT}
rowRenderer={({ index, key, style }) => (
<HistoryRow
key={key}
style={style}
swap={swapStore.sortedSwaps[index]}
/>
)}
scrollTop={scrollTop}
width={width}
/>
</div>
)}
</Observer>
)}
</WindowScroller>
)}
</AutoSizer>
</ListContainer>
</Wrapper>
);
}
Example #14
Source File: LegendStudioApplication.tsx From legend-studio with Apache License 2.0 | 5 votes |
LegendStudioApplicationRoot = observer(() => {
const studioStore = useLegendStudioStore();
const applicationStore = useApplicationStore<LegendStudioConfig>();
const extraApplicationPageRenderEntries = studioStore.pluginManager
.getStudioPlugins()
.flatMap((plugin) => plugin.getExtraApplicationPageRenderEntries?.() ?? []);
useEffect(() => {
flowResult(studioStore.initialize()).catch(
applicationStore.alertUnhandledError,
);
}, [applicationStore, studioStore]);
return (
<div className="app">
{!studioStore.isSDLCAuthorized && (
<div className="app__page">
<PanelLoadingIndicator isLoading={true} />
</div>
)}
{studioStore.isSDLCAuthorized && (
<>
{/* TODO: consider moving this to `LegendApplicationComponentFrameworkProvider` */}
<VirtualAssistant />
<Switch>
<Route
exact={true}
path={[
LEGEND_STUDIO_ROUTE_PATTERN.VIEW,
LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_GAV,
LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_GAV_ENTITY,
LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_ENTITY,
LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_REVISION,
LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_VERSION,
LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_REVISION_ENTITY,
LEGEND_STUDIO_ROUTE_PATTERN.VIEW_BY_VERSION_ENTITY,
]}
component={Viewer}
/>
<Route
exact={true}
path={LEGEND_STUDIO_ROUTE_PATTERN.REVIEW}
component={Review}
/>
<Route
exact={true}
strict={true}
path={[
LEGEND_STUDIO_ROUTE_PATTERN.EDIT_GROUP,
LEGEND_STUDIO_ROUTE_PATTERN.EDIT,
]}
component={Editor}
/>
<Route
exact={true}
path={[
// root path will lead to setup page (home page)
'/',
LEGEND_STUDIO_ROUTE_PATTERN.SETUP,
LEGEND_STUDIO_ROUTE_PATTERN.SETUP_GROUP,
]}
component={Setup}
/>
{extraApplicationPageRenderEntries.map((entry) => (
<Route
key={entry.key}
exact={true}
path={entry.urlPatterns.map(generateExtensionUrlPattern)}
component={entry.component as React.ComponentType<unknown>}
/>
))}
<Route>
<LegendStudioNotFoundRouteScreen />
</Route>
</Switch>
</>
)}
</div>
);
})
Example #15
Source File: BatchList.tsx From lightning-terminal with MIT License | 5 votes |
BatchList: React.FC = () => {
const { batchStore } = useStore();
const { Wrapper, Content, More } = Styled;
return (
<Wrapper>
<BatchRowHeader />
<Content>
<AutoSizer>
{({ width, height }) => (
<Observer>
{() => (
<List
rowCount={batchStore.sortedBatches.length}
rowHeight={ROW_HEIGHT}
rowRenderer={({ index, key, style }) => (
<BatchRow
key={key}
style={style}
batch={batchStore.sortedBatches[index]}
/>
)}
width={width}
height={height}
/>
)}
</Observer>
)}
</AutoSizer>
</Content>
{batchStore.hasMoreBatches && (
<More>
{batchStore.loading ? (
<LoaderLines />
) : (
<Button
borderless
ghost
onClick={batchStore.fetchBatches}
disabled={batchStore.loading}
>
Load Older Batches
</Button>
)}
</More>
)}
</Wrapper>
);
}
Example #16
Source File: QuerySetup.tsx From legend-studio with Apache License 2.0 | 5 votes |
QuerySetupLandingPage = observer(() => {
const setupStore = useQuerySetupStore();
const queryStore = useLegendQueryStore();
const extraQuerySetupOptions = queryStore.pluginManager
.getQueryPlugins()
.flatMap(
(plugin) =>
plugin.getExtraQuerySetupOptionRendererConfigurations?.() ?? [],
)
.filter(isNonNullable)
.map((config) => (
<Fragment key={config.key}>{config.renderer(setupStore)}</Fragment>
));
const editQuery = (): void =>
setupStore.setSetupState(new ExistingQuerySetupState(setupStore));
const loadServiceQuery = (): void =>
setupStore.setSetupState(new ServiceQuerySetupState(setupStore));
const createQuery = (): void =>
setupStore.setSetupState(new CreateQuerySetupState(setupStore));
useEffect(() => {
setupStore.initialize();
}, [setupStore]);
return (
<div className="query-setup__landing-page">
<div className="query-setup__landing-page__title">
What do you want to do today
<QuestionCircleIcon
className="query-setup__landing-page__title__question-mark"
title="Choose one of the option below to start"
/>
</div>
<div className="query-setup__landing-page__options">
<button
className="query-setup__landing-page__option query-setup__landing-page__option--existing-query"
onClick={editQuery}
>
<div className="query-setup__landing-page__option__icon">
<PencilIcon className="query-setup__landing-page__icon--edit" />
</div>
<div className="query-setup__landing-page__option__label">
Load an existing query
</div>
</button>
{extraQuerySetupOptions}
<button
className="query-setup__landing-page__option query-setup__landing-page__option--advanced query-setup__landing-page__option--service-query"
onClick={loadServiceQuery}
>
<div className="query-setup__landing-page__option__icon">
<RobotIcon />
</div>
<div className="query-setup__landing-page__option__label">
Load query from a service
</div>
</button>
<button
className="query-setup__landing-page__option query-setup__landing-page__option--advanced query-setup__landing-page__option--create-query"
onClick={createQuery}
>
<div className="query-setup__landing-page__option__icon">
<PlusIcon />
</div>
<div className="query-setup__landing-page__option__label">
Create a new query
</div>
</button>
</div>
</div>
);
})
Example #17
Source File: App.tsx From Cleanarr with MIT License | 5 votes |
App = () => {
const serverInfoStore = React.useContext(serverInfoContext);
useEffect(() => {
serverInfoStore.loadServerInfo();
serverInfoStore.loadDeletedSizes();
});
const onClickServerLink = () => {
window.open(serverInfoStore.serverUrl, '_blank');
}
return (
<Pane>
<Pane
background="tint2"
borderRadius={0}
elevation={1}
border="muted"
padding={majorScale(2)}
display={"flex"}
alignItems={"center"}
justifyContent={"center"}
>
<Pane flex={1}>
<Heading >
Cleanarr
</Heading>
</Pane>
<Observer>
{() => (
<Pane display="flex" alignItems="center" justifyContent={"center"}>
<Pane marginRight={20}>
<Badge color="blue">
Lifetime Space Saved:
{Object.keys(serverInfoStore.deletedSizes).map((key) => {
return (
<span className={"deleted-size"} key={key}>{key}: {bytesToSize(serverInfoStore.deletedSizes[key])}</span>
)
})}
</Badge>
</Pane>
</Pane>
)}
</Observer>
<Observer>
{() => (
<>
{serverInfoStore.serverUrl && (
<Button onClick={onClickServerLink}>
{serverInfoStore.serverName}
<Icon icon={"share"} size={10} marginLeft={majorScale(1)} />
</Button>
)}
</>
)}
</Observer>
</Pane>
<ContentPage />
</Pane>
);
}
Example #18
Source File: SessionList.tsx From lightning-terminal with MIT License | 5 votes |
SessionList: React.FC = () => {
const { sessionStore } = useStore();
if (sessionStore.sortedSessions.length === 0) return null;
const { Wrapper } = Styled;
return (
<Wrapper>
<SessionRowHeader />
<ListContainer>
<AutoSizer disableHeight>
{({ width }) => (
<WindowScroller>
{({ height, isScrolling, onChildScroll, scrollTop, registerChild }) => (
<Observer>
{() => (
<div ref={ref => ref && registerChild(ref)}>
<List
autoHeight
height={height}
isScrolling={isScrolling}
onScroll={onChildScroll}
rowCount={sessionStore.sortedSessions.length}
rowHeight={ROW_HEIGHT}
rowRenderer={({ index, key, style }) => (
<SessionRow
key={key}
style={style}
session={sessionStore.sortedSessions[index]}
/>
)}
scrollTop={scrollTop}
width={width}
/>
</div>
)}
</Observer>
)}
</WindowScroller>
)}
</AutoSizer>
</ListContainer>
</Wrapper>
);
}
Example #19
Source File: QueryEditor.tsx From legend-studio with Apache License 2.0 | 5 votes |
QueryExportInner = observer(
(props: { queryExportState: QueryExportState }) => {
const { queryExportState } = props;
const applicationStore = useApplicationStore();
const allowCreate = queryExportState.allowPersist;
const allowSave =
queryExportState.allowPersist && queryExportState.allowUpdate;
const create = applicationStore.guardUnhandledError(() =>
queryExportState.persistQuery(true),
);
const save = applicationStore.guardUnhandledError(() =>
queryExportState.persistQuery(false),
);
// name
const nameInputRef = useRef<HTMLInputElement>(null);
const changeName: React.ChangeEventHandler<HTMLInputElement> = (event) =>
queryExportState.setQueryName(event.target.value);
useEffect(() => {
nameInputRef.current?.focus();
}, []);
return (
<>
<div className="modal__body">
<PanelLoadingIndicator
isLoading={queryExportState.persistQueryState.isInProgress}
/>
<input
ref={nameInputRef}
className="input input--dark"
spellCheck={false}
value={queryExportState.queryName}
onChange={changeName}
/>
</div>
<div className="modal__footer">
{allowSave && (
<button
className="btn modal__footer__close-btn btn--dark"
onClick={save}
>
Save
</button>
)}
<button
className="btn modal__footer__close-btn btn--dark"
disabled={!allowCreate}
onClick={create}
>
Create
</button>
</div>
</>
);
},
)
Example #20
Source File: Text.tsx From binaural-meet with GNU General Public License v3.0 | 5 votes |
TextEdit: React.FC<TextEditProps> = (props:TextEditProps) => {
const [text, setText] = React.useState(props.text.message)
const sendTextLaterRef = useRef<any>(undefined)
useEffect(() => {
sendTextLaterRef.current = _.throttle(sendText, 1000, {leading: false})
}, [])
const sendTextLater = sendTextLaterRef.current
return <Observer>{() =>
<div style={{...props.css, position:'relative', margin:0, border:0, padding:0, backgroundColor:'none'}}>
<div style={{...props.css, color:'red', position:'relative', width:'100%',
overflow: 'hidden', visibility:'hidden'}}>{text+'\u200b'}</div>
<textarea value={text} autoFocus={props.autoFocus}
style={{...props.css, font: 'inherit', verticalAlign:'baseline', resize:'none',
position:'absolute', top:0, left:0, width:'100%', height:'100%', border:'none',
letterSpacing: 'inherit', overflow: 'hidden'
}}
onChange={(ev) => {
setText(ev.currentTarget.value)
if (sendTextLater){
sendTextLater(ev.currentTarget.value, props)
}
}}
onBlur={()=>{
if (sendTextLater){ sendTextLater.cancel() }
sendText(text, props)
}}
onFocus={()=>{
}}
onKeyDown={(ev) => {
if (ev.key === 'Escape' || ev.key === 'Esc') {
ev.stopPropagation()
ev.preventDefault()
if (sendTextLater){ sendTextLater.cancel() }
sendText(text, props)
props.stores.contents.setEditing('')
}
}}
/>
</div>}</Observer>
}
Example #21
Source File: QueryBuilderPostFilterPanel.tsx From legend-studio with Apache License 2.0 | 5 votes |
QueryBuilderPostFilterTreeNodeView = observer(
(
props: TreeNodeViewProps<
QueryBuilderPostFilterTreeNodeData,
{
queryBuilderState: QueryBuilderState;
}
>,
) => {
const {
node,
level,
onNodeSelect,
getChildNodes,
stepPaddingInRem,
innerProps,
} = props;
return (
<div className="tree-view__node__block">
<QueryBuilderPostFilterTreeNodeContainer
node={node}
level={level + 1}
stepPaddingInRem={stepPaddingInRem}
onNodeSelect={onNodeSelect}
innerProps={innerProps}
/>
{node.isOpen &&
getChildNodes(node).map((childNode) => (
<QueryBuilderPostFilterTreeNodeView
key={childNode.id}
node={childNode}
level={level + 1}
onNodeSelect={onNodeSelect}
getChildNodes={getChildNodes}
innerProps={innerProps}
/>
))}
</div>
);
},
)