Using getBoundingClientRect to position React component (x,y position)

I’m using portals in react to render my popovers so they appear above all other content. I have it working but they don’t appear next to the button that triggers them.

I’ve been playing around with getBoundingClientRect() using getBoundingClientRect().top/getBoundingClientRect().bottom and getBoundingClientRect().x/y, but what I noticed is that these values change if you load the page at a different scroll position. This means that everytime you load the page the popovers appear in different places and not below the button like they’re supposed to.

import React from 'react' import { string } from 'prop-types' import ReactDOM from 'react-dom'  import Modal from './Modal.jsx' import classNames from 'classnames'  class PopoverWithModal extends React.Component {   constructor (props) {     super(props)      this.state = {       showModal: false,       showPopover: false     }      this.openModal = this.openModal.bind(this)     this.closeModal = this.closeModal.bind(this)     this.handleClick = this.handleClick.bind(this)      this.domNode = null     this.selector = React.createRef()   }    componentDidMount () {     this.domNode = document.getElementById('popover-root')     const buttonTop = this.selector.current.getBoundingClientRect().y     const buttonLeft = this.selector.current.getBoundingClientRect().x     const styles = {       'top': buttonTop,       'left': buttonLeft,       'display': 'block'     }     console.log(this.selector.current.getBoundingClientRect())     this.setState({       styles     })   }    handleClick () {     this.setState((prevState, props) => {       return { showPopover: !prevState.showPopover }     })   }    openModal () {     this.setState({ showModal: true })   }    closeModal () {     this.setState({ showModal: false })   }    render () {     const { id, buttonText, modalContent } = this.props     const { showPopover, showModal } = this.state     const classesAndStuff = classNames({       'hidden': !showPopover,       'popover': true,       'popover-body': true     })     return (       <React.Fragment>         <button ref={this.selector}         className='btn' tabIndex='0' data-toggle='popover' data-trigger='focus' data-popover-content={`#$  {id}`} data-placement='bottom' onClick={this.handleClick}>{buttonText}</button>         { showPopover && ReactDOM.createPortal(           <div id={id} data-container='body' style={this.state.styles} className={classesAndStuff}>             <div className='popover-trigger-text'>               <p>{modalContent}</p>               <span className='btn' onClick={this.openModal}>Read more</span>             </div>           </div>,           this.domNode         )}         <Modal open={showModal} closeModal={this.closeModal}>           <div className='modal-main'>             <h2>Modal Stuff</h2>             <p>{modalContent}</p>           </div>         </Modal>       </React.Fragment>     )   } }  PopoverWithModal.propTypes = {   buttonText: string.isRequired,   modalContent: string.isRequired }  export default PopoverWithModal 

Angular 7 child routes import component usando modules


Estou tentando setar algumas rotas filhas na minha aplicação angular 7 porém elas não funcionam, tenho o seguinte cenário:

Possuo um base-home.component e um home.component, encapsulei os dois components em modules específicos de cada um, base-home.module e home.module, importei os dois módulos no app.module, e setei no app-routing.module umas rota '/' que chama o base-home.component, e uma rota filha '/home' que chama o home.component, porém ele não carrega a página, porém se eu importar os components direto no app.module em vez de importar os modules eles funciona, segue como estão os arquivos:

// app.module.ts  import { BrowserModule } from '@angular/platform-browser'; import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core';  import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component';  import { HomeModule } from './home/home.module'; import { BaseHomeModule } from './base-home/base-home.module';  @NgModule({   declarations: [     AppComponent   ],   imports: [     BrowserModule,     CommonModule,     AppRoutingModule,     BaseHomeModule,     HomeModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { }  
// app-routing.module.ts  import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router';  import { HomeComponent } from './home/home.component'; import { BaseHomeComponent } from './base-home/base-home.component';  const routes: Routes = [   {     path: '',     component: BaseHomeComponent,     children: [       {         path: 'home',         component: HomeComponent        }     ]   } ];  @NgModule({   imports: [RouterModule.forRoot(routes)],   exports: [RouterModule] }) export class AppRoutingModule { }  
// base-home.module.ts  import { NgModule } from '@angular/core';  import { BaseHomeComponent } from './base-home.component';  @NgModule({   declarations: [       BaseHomeComponent   ],   exports: [       BaseHomeComponent     ] }) export class BaseHomeModule {}  
// home.module.ts  import { NgModule } from '@angular/core';  import { HomeComponent } from './home.component';  @NgModule({   declarations: [       HomeComponent   ],   exports: [       HomeComponent     ] }) export class HomeModule { }  

Dessa maneira acima ele não funciona, mas se eu importar o base-home.component direto no no app.module ele funciona, dessa forma:

// app.module.ts  import { BrowserModule } from '@angular/platform-browser'; import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core';  import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component';  import { HomeModule } from './home/home.module'; import { BaseHomeComponent } from './base-home/base-home.component';  @NgModule({   declarations: [     AppComponent,     BaseHomeComponent   ],   imports: [     BrowserModule,     CommonModule,     AppRoutingModule,     HomeModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { }  

Alguém sabe como eu posso fazer as child routes funcionar importando apenas os modules com os components encapsulados sem precisar importar o component direto no app-module ?

Unbounded Component of the Fredholm Domain

Let $ X$ be a Banach space and $ T \in \mathcal L(X)$ .

The authors Engel and Nagel introduce in their book “One-Parameter Semigroups for Linear Evolution Equations” on p. 248 the concept of the Fredholm domain of $ T$ defined by $ $ \rho_F(T) := \{\lambda \in \mathbb C: \lambda – T \text{ is a Fredholm operator} \}.$ $ On the next page the following is stated:

“Here, we only recall that the poles of $ R(\cdot, T)$ with finite algebraic multiplicity belong to $ \rho_F(T)$ . Conversely, an element of the unbounded connected component of $ \rho_F(T)$ either belongs to $ \rho(T)$ or is a pole of finite algebraic multiplicity.”

I can prove the first statement very elementary just by using properties of spectral projections and some very basic functional calculus. But the second statement seems to be quite difficult to prove. In the cited literature I found a proof of the stament (cf. the proof Corollary XI.8.5 in “Classes of Linear Operators Vol. I” by Gohberg, Goldberg and Kaashoek). But it seems to rely on quite some theorems about Fredholm operator valued functions.

So my question is whether there is a more elementary way to see that the statement holds, maybe just by using some basic facts on spectral projections? I thought quite some time about I couldn’t prove it. So is there maybe a reference for the statement which uses more elementary arguments? Or does someone know another way how to prove it? I am looking forward to your answers.

Facing difficulty in initialize i18next react component with fetch response data?

I am using i18next to do the internalization.

Default fetch request used to get a data from server and the language information available in response data. Based on language info the page has to be loaded with corresponding language

import i18n from 'i18next'; import { reactI18nextModule } from 'react-i18next'; import LanguageDetector from 'i18next-browser-languagedetector'; import translationEN from './locales/en/translation.json'; import translationDE from './locales/de/translation.json';  // the translations let language; function sendRequest(resources) {   console.log('resources', resources);   i18n     .use(reactI18nextModule) // passes i18n down to react-i18next     .init(       {         resources,         lng: language,         fallbackLng: 'en',         keySeparator: false, // we do not use keys in form messages.welcome          interpolation: {           escapeValue: false // react already safes from xss         }       },       function() {         fetch('http://localhost:3100/getLang')           .then(data => data.json())           .then(res => {             console.log(res);             language = res.lang;             i18n.changeLanguage(language, (err, t) => {               if (err)                 return console.log(                   'something went wrong loading the language',                   err                 );             });           });       }     );   return i18n; } function i18() {   const resources = {     en: {       translation: translationEN     },     de: {       translation: translationDE     }   };   return sendRequest(resources); } export default i18(); 

Language variable is undefined initially. For the very first time i18n init method setup with “fallbackLng” variable instead of “lng”. After that fetch request goes in callback of init method. That will have the response of language need to used. Then i18n changeLanguage method will help to change language.

I am just wondering how can i execute fetch request prior to i18n initialization. I don’t like the approach of initialize the i18next with some default language first and then moved to different language. When i tried to initialize i18n in then part of fetch request doesn’t works for me.

Is there any alternative way available to execute fetch request first and then setup i18n before exporting the component?

Thanks in advance for any suggestion!

How would I do component testing if my component requires access to a database

I created an electron app which persists data in NeDB which displays data through the app. I’m trying to test my component which displays the data with jest and enzyme, but my simple test fails because one of my module that is imported to the file requires access to a property that is only defined when I run the electron app.

I’m new to creating electron app so my architecture might be bad.

The main issue is when I try to run my test I get the error,

 TypeError: Cannot read property 'app' of undefined    1 | const remote = require('electron').remote; > 2 | const app = remote.app; 

How would I go about fixing this? Some possible things I thought might work was to use jest to mock SchoolAPI, but I’m not sure how to go about doing this.

SchoolList.js

import React from "react"; // @material-ui/core components import withStyles from "@material-ui/core/styles/withStyles"; import List from "@material-ui/core/List"; import ListItem from "@material-ui/core/ListItem"; import ListItemText from "@material-ui/core/ListItemText"; import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction'; import IconButton from '@material-ui/core/IconButton'; import DeleteIcon from '@material-ui/icons/Delete';  import { Link } from "react-router-dom";  import * as SchoolAPI from "../../utils/SchoolAPI.js"  class SchoolList extends React.Component {     constructor(props) {         super(props);     };      handleDelete = (id) => {         SchoolAPI.deleteSchool(id).then(() => {             this.props.onLoadData();         });     };     render() {         const { classes } = this.props;         const listSchools = this.props.schoolsData.map((school, i) =>             <div key={i}>                 <ListItem button component={Link} to={`/orders/$  {i}`}>                     <ListItemText primary={school.name}/>                     <ListItemSecondaryAction onClick={() => this.handleDelete(school["_id"])}>                         <IconButton aria-label="Delete" >                             <DeleteIcon />                         </IconButton>                     </ListItemSecondaryAction>                 </ListItem>             </div>         );         return (             <List className="schoolList">                 {listSchools}             </List>         );     }; } 

SchoolAPI.js

import db from "../db.js" ...a bunch of API(e.g. db.insert(..)) 

db.js

const remote = require('electron').remote; const app = remote.app; const path = require('path'); const Datastore = require('nedb-promises');  const dbFactory = (fileName) => Datastore.create({   filename: `$  {process.env.NODE_ENV === 'dev' ? '.' : app.getPath('userData')}/data/$  {fileName}`,    timestampData: true,   autoload: true });  const db = {   schools: dbFactory('schools.db') };  module.exports = db; 

test.spec.js

describe("SchoolList component", () => {     it("renders without throwing an error", () => {         const SchoolListComponent = renderer.create(<SchoolList schoolsData={schoolsData/>).toJson();         expect(SchoolListComponent).toMatchSnapshot();     }); }); 

Do we need the Axiom of Choice to prove component = quasicomponent in every compact Hausdorff space?

The following is a well-known theorem:

Let $ X$ be a compact Hausdorff space. Then $ x$ and $ y$ belong to the same quasicomponent if and only if they belong to the same component of $ X$ .

In Munkre’s Topology Exercise 38.4, he presents an argument using the Zorn’s Lemma:

(a) Let $ \mathscr A$ be the collection of all closed subspaces of $ X$ such that $ x$ and $ y$ lie in the same quasicomponent of $ A$ . Let $ \mathscr B$ be a collection of $ \mathscr A$ that is simply ordered by proper inclusion. Show that the intersection of the elements of $ \mathscr B$ belongs to $ \mathscr A$ .

(b) Show $ \mathscr A$ has a minimal element $ D$ .

(c) Show $ D$ is connected.

However, I’ve found a proof here which apparently doesn’t use the Axiom of Choice:

We just need to prove that the quasicomponent $ Q$ is connected. Suppose that $ Q = X_1 \cup X_2$ , where $ X_1, X_2$ are two disjoint closed subsets of the space $ Q$ . Then $ X_1$ and $ X_2$ are closed in $ X$ , since $ Q$ is closed in $ X$ . By normality of compact Hausdorff spaces, there exist disjoint open subsets $ U,V$ of $ X$ containing $ X_1, X_2$ , respectively. Hence, we have $ Q \subseteq U \cup V$ and, by compactness, there exist closed-open sets $ F_1, \ldots, F_k$ such that

$ $ Q \subseteq \bigcap_{i=1}^k F_i \subseteq U \cup V.$ $

$ F = \bigcap_{i=1}^k F_i$ is clearly closed-open. Since $ \overline{U \cap F} \subseteq \overline{U} \cap F = \overline{U} \cap (U \cup V) \cap F = U \cap F$ , the intersection $ U \cap F$ is also closed-open. As $ x \in U \cap F$ , we have $ Q \subseteq U \cap F$ and $ X_2 \subseteq Q \subseteq U \cap F \subseteq U$ . It follows that $ X_2 \subseteq U \cap V = \emptyset$ , which shows that the set $ Q$ is connected.

Question 1:

Do we really need AC to prove component = quasicomponent in every compact Hausdorff space?

Question 2 (soft-question):

If not, what is the advantage of the first proof over the second?

What is the best way to display a destructive action on this component?

The final assignment from my course is to create a mobile application similar to AnkiDroid where the user can create flashcards to study.

I’m not sure about how to display a destructive action on the flashcard component.

Is there a better way to show that? I currently enabled a swipe left action. I don’t know if is that ok, though.

enter image description here

Swipe action enter image description here

different collision geometries in a component based game engine

I’m writing a simple game engine and after a lot of rethinking/refactoring I settled with sort of a component based architecture (not strictly ECS, but it isn’t inheritance based anymore either). So everything in my world is an entity, and each entity has got a bunch of components. Every system/subsystem in my game scans an entity for a series of components it’s interested in, and performs some relevant computations.

So far so good. The engine basic architecture can be seen here:

Now, every entity that is collidable with has a collision component (along with position/movement/rigidbody components), so the physics system needs to get that component and use it to feed its collision detection algorithms, in order to generate contact data to be used to resolve the collision.

I’m stuck on the following issue: the collison detection algorithms deal with different geometries: boxes,spheres,planes and rays (as of now), but I don’t want to have a spherecollisioncomponent and a boxcollisioncomponent, at least I don’t want them to be unrelated but I’d like them to share some common base class.

class Sphere  { public:     Sphere(float radius);     ~Sphere();     float GetRadius() { return mRadius; }  private:     float mRadius; };  class Box  : public BoundingVolume { public:     Box(const XMFLOAT3 &halfSize);     ~Box();     XMFLOAT3 const &GetHalfSize() const { return mHalfSize; } private:     XMFLOAT3 mHalfSize; }; 

Obviously each component has a different interface (boxes have halfsizes, spheres have a radius and so on), and the different collision detection functions deal very differently with each of them (box-box, box-sphere, sphere-sphere..).

void CollisionSystem::BoxAndBoxCollision(const Box &box1, const Box &box2) {     // contact data     XMFLOAT3 contactPoint;     XMFLOAT3 contactNormal;     float minOverlap = 100.0f;      // get axes for SAT test     std::vector<XMFLOAT3> axes = GetSATAxes(box1, box2);      int axisIndex = 0;     int index = 0;      for (XMFLOAT3 axis : axes)     {         if (XMVectorGetX(XMVector3Length(XMLoadFloat3(&axis))) < 0.01f)         {             index++;             continue;         }          float overlap = PerformSAT(axis, box1, box2);          if (overlap < 0)  // found separating axis - early out             return;          if (overlap < minOverlap)         {             minOverlap = overlap;             axisIndex = index;         }          index++;     }      // other collision detection/generation code.....       // store contact     mContacts.push_back(new Contact(box1->GetRigidBody(), box2->GetRigidBody(), contactPoint, contactNormal, minOverlap, coefficientOfRestitution)); } 

So how can I solve this in an elegant and robust way?