@reach/router#navigate JavaScript Examples

The following examples show how to use @reach/router#navigate. 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: randomshop.jsx    From emprezzo with MIT License 6 votes vote down vote up
RandomShop = ({ data }) => {
  const { edges } = data.allMysqlMainView;
  const combinedEdges = edges;
  /*
  const rowRankViewEdges = data.allMysqlRankView.edges;
  //Creating a new dataset with original nodes and required columns from DataView
  edges.map((edge) => {
    const inputInstaID = edge.node.UserName;
    var resultRankView = _.filter(rowRankViewEdges, ({ node }) => node.UserName == inputInstaID)
    if (resultRankView.length > 0) {
      combinedEdges.push(edge);
    }
  })
  */

  //console.log("Total Shops with Rank View = ",combinedEdges.length,combinedEdges);
  const randomnumber = Math.round(Math.random() * combinedEdges.length);
  //console.log("Generated Random Number = "+randomnumber);
  const edge = combinedEdges[randomnumber-1] ? combinedEdges[randomnumber-1] : combinedEdges[0];
  //console.log(edge)
  const randomshopurl = "/shops/"+edge.node.emprezzoID+"/";
  //console.log("Random URL = "+randomshopurl);
  navigate(randomshopurl);

  return (
    <Helmet title={'Random Shop'} />
  );

}
Example #2
Source File: Utils.js    From cord-19 with Apache License 2.0 6 votes vote down vote up
onSearch = params => {
  const urlParams = new URLSearchParams(window.location.search);

  for (let [key, value] of Object.entries(params)) {
    urlParams.delete(key);
    if (Array.isArray(value)) value.forEach(v => urlParams.append(key, v));
    else if (value) urlParams.set(key, value);
  }
  // Offset must be reset whenever result set changes, which we assume may be
  // every time the URL changes due to other interactions than with pagination.
  if (!params.hasOwnProperty('offset')) urlParams.delete('offset');

  // No query or filters specified
  if (urlParams.entries().next().done) return;
  navigate('/search?' + urlParams);
}
Example #3
Source File: index.js    From gatsby-shopify-course with BSD Zero Clause License 6 votes vote down vote up
export function Search() {
  const [searchTerm, setSearchTerm] = React.useState('');
  const { search } = useLocation();
  const c = queryString.parse(search)?.c || '';

  const handleSubmit = e => {
    e.preventDefault();

    if (c) {
      navigate(
        `/all-products?s=${encodeURIComponent(
          searchTerm
        )}&c=${encodeURIComponent(c)}`
      );
    } else {
      navigate(`/all-products?s=${encodeURIComponent(searchTerm)}`);
    }
  };

  return (
    <SearchForm onSubmit={handleSubmit}>
      <Input
        value={searchTerm}
        onChange={e => setSearchTerm(e.currentTarget.value)}
        placeholder="Search"
      />
      <Button>
        <FaSearch />
      </Button>
    </SearchForm>
  );
}
Example #4
Source File: Logout.js    From PyLot with MIT License 6 votes vote down vote up
Logout = () => {
  const [signInState, setSignInState] = useContext(SignInContext);
  if (signInState[0] === "Signed In") {
    setSignInState(["Signed Out", "None", "None"]);
    navigate("/");
    return <h1>Signing out</h1>;
  } else {
    return <h1>Signed Out</h1>;
  }
}
Example #5
Source File: header.js    From aws-amplify-gatsby-auth with MIT License 6 votes vote down vote up
Header = ({ siteTitle }) => (
  <div
    style={{
      background: 'rebeccapurple',
      marginBottom: '1.45rem',
    }}
  >
    <div
      style={{
        margin: '0 auto',
        maxWidth: 960,
        padding: '1.45rem 1.0875rem',
      }}
    >
      <h1 style={{ margin: 0 }}>
        <Link
          to="/"
          style={styles.headerTitle}
        >
          {siteTitle}
        </Link>
      </h1>
      {
        isLoggedIn() && (
          <p
            onClick={
              () => Auth.signOut().then(logout(() => navigate('/app/login'))).catch(err => console.log('eror:', err))
            }
            style={styles.link}
          >Sign Out</p>
        )
      }
    </div>
  </div>
)
Example #6
Source File: Login.js    From aws-amplify-gatsby-auth with MIT License 6 votes vote down vote up
render() {
    if (isLoggedIn()) navigate('/app/profile')
    return (
      <div>
        <h1>Sign In</h1>
        {this.state.error && <Error errorMessage={this.state.error}/>}
        <div style={styles.formContainer}>
         <input
            onChange={this.handleUpdate}
            placeholder='Username'
            name='username'
            value={this.state.username}
            style={styles.input}
          />
          <input
            onChange={this.handleUpdate}
            placeholder='Password'
            name='password'
            value={this.state.password}
            type='password'
            style={styles.input}
          />
          <div style={styles.button} onClick={this.login}>
            <span style={styles.buttonText}>Sign In</span>
          </div>
        </div>
        <Link to="/app/signup">Sign Up</Link><br />
      </div>
    )
  }
Example #7
Source File: View.jsx    From PyLot with MIT License 5 votes vote down vote up
backToNotebook(){
        navigate(`/notebooks/${window.location.href.split("/")[window.location.href.split("/").length-3]}/${window.location.href.split("/")[window.location.href.split("/").length-2]}`)
    }
Example #8
Source File: Signupin.js    From PyLot with MIT License 5 votes vote down vote up
Signupin = () => {
  const [username, setUsername] = useState("username");
  const [password, setPassword] = useState("*******");
  const [signInState, setSignInState] = useContext(SignInContext);
  function verifyDetails() {
    if (username === "" || password === "") {
      alert("Form missing information.");
    } else {
      const formData = {
        username: username,
        password: password,
      };
      axios.post("/users/signin", formData).then((response) => {
        if (response.data === "Authentication Successful") {
          setSignInState(["Signed In", username, password]);
          navigate("/");
        } else {
          alert("Authentication failed.");
        }
      });
    }
  }
  return (
    <div className="form-page-container">
      <div className="form-container">
        <form
          onSubmit={(e) => {
            e.preventDefault();
            verifyDetails();
          }}
        >
          <label htmlFor="username" className="teal-text text-accent-3">
            Username
            <input
              id="username"
              onChange={(event) => setUsername(event.target.value)}
              className="teal-text text-accent-3"
            />
          </label>
          <label htmlFor="password" className="teal-text text-accent-3">
            Password
            <input
              id="password"
              type="password"
              onChange={(event) => setPassword(event.target.value)}
              className="teal-text text-accent-3"
            />
          </label>
          <button className="teal white-text accent-3">submit</button>
          <Link
            to="/signup"
            style={{ textDecoration: "none", color: "#4c5357" }}
          >
            <span className="teal-text text-accent-3">Sign Up</span>
          </Link>
        </form>
      </div>
    </div>
  );
}
Example #9
Source File: Profile.jsx    From PyLot with MIT License 5 votes vote down vote up
render(){
        if(this.state.loading){
            return (
                <div className="serverDetailsPageMainContainer">
          <CircularProgress style={{color:"#42f5bf"}}/>
        </div>
            )
        }else{
            const {servers} = this.state;
            return (
                <div className="server-page-container">
                    <div className="server-page-controls">
                        <h2>{this.state.username}'s Servers</h2>
                        <Button
                         variant="contained"
                         color="seagreen"
                         startIcon={<AddIcon/>}
                         onClick={()=>{navigate("/addServer")}}
                        >
                            Add Server
                        </Button>
                        <Button
                         variant="contained"
                         color="seagreen"
                         startIcon={<MenuBookIcon/>}
                         onClick={()=>{navigate(`/notebooks/${this.state.username}`)}}
                        >
                            Notebooks
                        </Button>
                    </div>
                    <div className="servers-container">
                        <List>
                        {servers.map(({serverName,ipAddr,sshKey,user,password},index)=>{
                            return (
                            <Link key={index} to={`/serverDetails/${this.state.username}/${serverName}/${ipAddr}/${user}/${password}`} style={{ textDecoration: "none", color: "white" }}>
                            <ListItem button>
                                <ListItemIcon>
                                    <DnsIcon/>
                                </ListItemIcon>
                                <ListItemText primary={serverName} secondary={`${user} | ${ipAddr}`}/>
                            </ListItem>
                            <Divider/>
                            </Link>
                            )
                        })}
                        </List>
                    </div>
                </div>
            )
        }
    }
Example #10
Source File: NotebooksDisplay.jsx    From PyLot with MIT License 5 votes vote down vote up
render(){
        return (
            <div className="notebooks-container">
                <div className = "notebooks-page-controls">
                <h2>{this.state.username}'s Notebooks</h2>
                        <Button
                         variant="contained"
                        //  color="seagreen"
                         startIcon={<AddIcon/>}
                         onClick={()=>{navigate("/addNotebook")}}
                        >
                            Add Notebook
                        </Button>
                        <Button
                         variant="contained"
                        //  color="seagreen"
                         startIcon={<RemoveIcon/>}
                         onClick={()=>{navigate("/deleteNotebook")}}
                        >
                            Delete Notebook
                        </Button>
                </div>
                <div className="servers-container">
                    <List>
                        {
                            this.state.notebooks.map(({notebookName,createdOn,_id},index)=>{
                                return(
                                    <Link key={index} to={`/notebooks/${this.state.username}/${notebookName}`} style={{ textDecoration: "none", color: "white" }}>
                                    <ListItem button>
                                        <ListItemIcon>
                                            <MenuBookIcon/>
                                        </ListItemIcon>
                                        <ListItemText primary={notebookName} secondary={createdOn}/>
                                    </ListItem>
                                    <Divider/>
                                    </Link>
                                )
                            })
                        }
                    </List>
                </div>
            </div>
        )
    }
Example #11
Source File: Notebook.jsx    From PyLot with MIT License 5 votes vote down vote up
render() {
    const username = this.state.username;
    const notebookName = this.state.notebookName;
    const servers = this.state.servers;
    return (
      <div className="notebook-container">
        {/* <h1>{this.state.connectionStatus}</h1> */}
        <h3 className="teal-text text-accent-3">
          {username}'s Notebook [{notebookName}]
        </h3>
        <div id="notebook-buttons-container">
          <button id="add-tile-button">Add tile</button>
          <button id="remove-tile-button">Remove tile</button>
          <button id="bind-button">Bind Tiles</button>
          <button id="save-notebook">Save Notebook</button>
          {/* <button id="edit-tile-code" onClick={this.editTileHandler}>Edit Tile Code</button> */}
          <button id="edit-tile-code">Edit Tile Code</button>
          <button
            id="back-button"
            onClick={() => navigate(`/notebooks/${username}`)}
          >
            Back
          </button>
          <button id="run-tile-code">Run Tile Code</button>
          <button id="view-tile-output">View Tile Output</button>
          <button id="schedule-dag-button">Schedule DAG</button>
          <button id="cancel-job-button">Cancel DAG Execution</button>
          <div
            className="connection-status-display"
            style={{
              backgroundColor:
                this.state.connectionStatus === "Connected to PyLot runtime"
                  ? "green"
                  : "red",
              width: "40%",
            }}
          >
            <p
              style={{
                color: "white",
              }}
            >
              {this.state.connectionStatus}
            </p>
          </div>
        </div>
        <P5Wrapper sketch={sketch}></P5Wrapper>
        <div className="tile-info">
          <p id="tile-name"></p>
          <p></p>
        </div>
      </div>
    );
  }
Example #12
Source File: PrivateRoute.js    From aws-amplify-gatsby-auth with MIT License 5 votes vote down vote up
render() {
    const { component: Component, location, ...rest } = this.props
    if (!isLoggedIn()) {
      navigate(`/app/login`)
      return null
    }
    return <Component {...rest} />
  }
Example #13
Source File: Editor.jsx    From PyLot with MIT License 5 votes vote down vote up
backToNotebook(){
        navigate(`/notebooks/${window.location.href.split("/")[window.location.href.split("/").length-3]}/${window.location.href.split("/")[window.location.href.split("/").length-2]}`)
    }
Example #14
Source File: DeleteNotebook.js    From PyLot with MIT License 5 votes vote down vote up
DeleteNotebook = () => {
  const [context, setSignInstate] = useContext(SignInContext);
  const [notebookName, setNotebookName] = useState("");
  function verifyAndSendDetails() {
    const ssh = false;
    const formData = {
      username: context[1],
      name: notebookName,
    };
    if (formData.username === "None") {
      navigate("/");
    }
    if (formData.username === "") {
      alert("please enter a name.");
    }
    axios
      .post("/deleteNotebook", formData)
      .then(({ data: { message } }) => console.log(message));
    console.log(formData);
    // navigate(`/notebooks/${context[1]}`);
    navigate(`/`);
  }
  return (
    <div className="form-container">
      <form
        onSubmit={(e) => {
          e.preventDefault();
          verifyAndSendDetails();
        }}
      >
        <label htmlFor="notebookName" className="teal-text text-accent-3">
          Notebook Name (DELETE)
          <input
            id="notebookName"
            onChange={(event) => setNotebookName(event.target.value)}
            className="teal-text text-accent-3"
          />
        </label>
        <button className="teal accent-3">
          <span className="white-text">submit</span>
        </button>
      </form>
    </div>
  );
}
Example #15
Source File: AddServer.jsx    From PyLot with MIT License 5 votes vote down vote up
AddServer=()=>{
    const [context,setSignInstate]=useContext(SignInContext);
    const [serverName,setServerName]=useState("");
    const [ipAddr,setIpAddr]=useState("");
    const [sshKey,setSSH]=useState(false);
    const [serverPassword,setServerPassword]=useState("")
    const [serverUser,setServerUser]=useState("")
    function verifyAndSendDetails(){
        const ssh=false;
        const formData={
            username:context[1],
            serverName:serverName,
            ipAddr:ipAddr,
            sshKey:ssh,
            user:serverUser,
            password:serverPassword
        }
        axios.post("/users/addserver",formData).then((response)=>{
            if(response.data==="Added server." || response.data==="Added user's first server!"){
                navigate('/')
            }else{
                alert("An error ocurred");
            }
        })
    }
    return (
        <div className="form-container">
            <form
             onSubmit={(e)=>{
                 e.preventDefault();
                 verifyAndSendDetails()
             }}
            >
                <label htmlFor="serverName" className="teal-text text-accent-3">
                Server Name
                <input 
                    id="serverName"
                    onChange={(event)=>setServerName(event.target.value)}
                    className="teal-text text-accent-3"
                />
                </label>
                <label htmlFor="ipAddress" className="teal-text text-accent-3">
                IP Address
                <input 
                    id="ipAddress"
                    onChange={(event)=>setIpAddr(event.target.value)}
                    className="teal-text text-accent-3"
                />
                </label>
                <label htmlFor="serverUser" className="teal-text text-accent-3">
                User account on server
                <input 
                    id="serverUser"
                    onChange={(event)=>setServerUser(event.target.value)}
                    className="teal-text text-accent-3"
                />
                </label>
                <label htmlFor="serverPassword" className="teal-text text-accent-3">
                Password for server user account
                <input 
                    id="serverPassword"
                    onChange={(event)=>setServerPassword(event.target.value)}
                    className="teal-text text-accent-3"
                />
                </label>
                <button className="teal accent-3"><span className="white-text">submit</span></button>
            </form>
        </div>
    )
}
Example #16
Source File: AddNotebook.js    From PyLot with MIT License 5 votes vote down vote up
AddNotebook = () => {
  const [context, setSignInstate] = useContext(SignInContext);
  const [notebookName, setNotebookName] = useState("");
  function verifyAndSendDetails() {
    const ssh = false;
    const formData = {
      username: context[1],
      name: notebookName,
    };
    if (formData.username === "None") {
      navigate("/");
    }
    if (formData.username === "") {
      alert("please enter a name.");
    }
    axios.post("/addNotebook", formData); //.then(({data:{message}})=>alert(message));
    // navigate(`/notebooks/${context[1]}`);
    navigate("/")
  }
  return (
    <div className="form-container">
      <form
        onSubmit={(e) => {
          e.preventDefault();
          verifyAndSendDetails();
        }}
      >
        <label htmlFor="notebookName" className="teal-text text-accent-3">
          Notebook Name
          <input
            id="notebookName"
            onChange={(event) => setNotebookName(event.target.value)}
            className="teal-text text-accent-3"
          />
        </label>
        <button className="teal accent-3">
          <span className="white-text">submit</span>
        </button>
      </form>
    </div>
  );
}
Example #17
Source File: index.js    From gatsby-shopify-course with BSD Zero Clause License 5 votes vote down vote up
export function CartContents() {
  const { checkout, updateLineItem } = React.useContext(CartContext);

  const handleAdjustQuantity = ({ quantity, variantId }) => {
    updateLineItem({ quantity, variantId });
  };

  return (
    <section>
      <h1>Your cart</h1>
      {!!checkout?.lineItems && (
        <CartHeader>
          <div>Product</div>
          <div>Unit price</div>
          <div>Quantity</div>
          <div>Amount</div>
        </CartHeader>
      )}
      {checkout?.lineItems?.map(item => (
        <CartItem key={item.variant.id}>
          <div>
            <div>{item.title}</div>
            <div>
              {item.variant.title === 'Default Title' ? '' : item.variant.title}
            </div>
          </div>
          <div>£{item.variant.price}</div>
          <div>
            <QuantityAdjuster item={item} onAdjust={handleAdjustQuantity} />
          </div>
          <div>£{(item.quantity * item.variant.price).toFixed(2)}</div>
          <div>
            <RemoveLineItem lineItemId={item.id} />
          </div>
        </CartItem>
      ))}
      {!!checkout?.lineItems && (
        <CartFooter>
          <div>
            <strong>Total:</strong>
          </div>
          <div>
            <span>£{checkout?.totalPrice}</span>
          </div>
        </CartFooter>
      )}
      {!checkout?.lineItems && <h4>You cart is empty.</h4>}
      <Footer>
        <div>
          <Button onClick={() => navigate(-1)}>Continue shopping</Button>
        </div>
        <div>
          {!!checkout?.webUrl && (
            <Button
              onClick={() => {
                window.location.href = checkout.webUrl;
              }}
            >
              Checkout
            </Button>
          )}
        </div>
      </Footer>
    </section>
  );
}
Example #18
Source File: index.js    From gatsby-shopify-course with BSD Zero Clause License 5 votes vote down vote up
export function CategoryFilterItem({ title, id }) {
  const { search } = useLocation();
  const qs = queryString.parse(search);
  const collectionIds = qs.c?.split(',').filter(c => !!c) || [];
  const checked = collectionIds?.find(cId => cId === id);
  const searchTerm = qs.s;

  const onClick = () => {
    let navigateTo = '/all-products';

    let newIds = [];

    if (checked) {
      newIds = collectionIds
        .filter(cId => cId !== id)
        .map(cId => encodeURIComponent(cId));
    } else {
      collectionIds.push(id);
      newIds = collectionIds.map(cId => encodeURIComponent(cId));
    }

    if (newIds.length && !searchTerm) {
      navigate(`${navigateTo}?c=${newIds.join(',')}`);
    } else if (newIds.length && !!searchTerm) {
      navigate(
        `${navigateTo}?c=${newIds.join(',')}&s=${encodeURIComponent(
          searchTerm
        )}`
      );
    } else if (!newIds.length && !!searchTerm) {
      navigate(`${navigateTo}?s=${encodeURIComponent(searchTerm)}`);
    } else {
      navigate(`${navigateTo}`);
    }
  };
  return (
    <CategoryFilterItemWrapper onClick={onClick}>
      <Checkbox checked={checked} />
      <div>{title}</div>
    </CategoryFilterItemWrapper>
  );
}
Example #19
Source File: profile.js    From create-magic-app with MIT License 5 votes vote down vote up
export default function Profile() {
  const [userMetadata, setUserMetadata] = useState();

  useEffect(() => {
    // On mount, we check if a user is logged in.
    // If so, we'll retrieve the authenticated user's profile.
    magic.user.isLoggedIn().then(magicIsLoggedIn => {
      if (magicIsLoggedIn) {
        magic.user.getMetadata().then(setUserMetadata);
      } else {
        // If no user is logged in, redirect to `/login`
        navigate(`/app/login`);
      }
    });
  }, []);

  /**
   * Perform logout action via Magic.
   */
  const logout = useCallback(() => {
    magic.user.logout().then(() => {
      navigate(`/app/login`);
    })
  }, []);

  return userMetadata ?
    <Layout>
      <Seo title="Profile" />
      <h1>Current user: {userMetadata.email}</h1>
      <h6>User ID: {userMetadata.issuer}</h6>
      <h6>Public Address: {userMetadata.publicAddress}</h6>
      <button onClick={logout} style={{
        background: `rebeccapurple`,
        color: 'white',
        cursor: 'pointer'
      }}>Logout</button>
      <p style={{ marginTop: '20px' }}>
        <Link to="/">Home</Link>
      </p>
    </Layout>
    : <Loading />;
}
Example #20
Source File: login.js    From create-magic-app with MIT License 5 votes vote down vote up
Login = () => {
  const [email, setEmail] = useState("");
  const [isLoggingIn, setIsLoggingIn] = useState(false);

  useEffect(() => {
    // On mount, we check if a user is logged in.
    // If so, we'll retrieve the authenticated user's profile.
    magic.user.isLoggedIn().then(magicIsLoggedIn => {
      if (magicIsLoggedIn) {
        navigate(`/app/profile`);
      } else {
        // If no user is logged in, redirect to `/login`
        navigate(`/app/login`);
      }
    });
    
  }, []);

  /**
   * Perform login action via Magic's passwordless flow. Upon successuful
   * completion of the login flow, a user is redirected to the homepage.
   */
  const login = useCallback(async () => {
    setIsLoggingIn(true);

    try {
      await magic.auth.loginWithMagicLink({
        email
      });
      navigate(`/app/profile`);
    } catch {
      setIsLoggingIn(false);
    }
  }, [email]);

  /**
   * Saves the value of our email input into component state.
   */
  const handleInputOnChange = useCallback(event => {
    setEmail(event.target.value);
  }, []);

  return (
    <Layout>
      <Seo title="Login" />
      <h1>Please sign up or login</h1>
      <input
        type="email"
        name="email"
        required="required"
        placeholder="Enter your email"
        onChange={handleInputOnChange}
        disabled={isLoggingIn}
      />
      <button onClick={login} disabled={isLoggingIn} style={{ marginLeft: '10px' }}>Send</button>

      <p style={{ marginTop: '20px' }}>
        <Link to="/">Home</Link>
      </p>
    </Layout>
  )
}
Example #21
Source File: AppSubBar.js    From docs with BSD Zero Clause License 5 votes vote down vote up
AppSubBar = ({ location, navItems }) => {
  const currentNavItem = navItems.find(({ root }) => location.pathname.includes(root)) || {};
  const { sections = [] } = currentNavItem;
  const currentSection = sections.find(({ root }) => location.pathname.includes(root)) || {};
  const { items = [] } = currentSection;

  const allItems = [
    ...items,
    ...items.map(({ subItems }) => subItems || []).reduce((acc, cur) => [...cur, ...acc], []),
  ];

  const currentItem = allItems.find(({ path }) => location.pathname.includes(path)) || {};

  const handleNavItemChange = (e) => {
    navigate(e.currentTarget.value);
  };

  const handleSectionChange = (e) => {
    navigate(e.currentTarget.value);
  };

  return (
    <Mobile>
      <Container>
        <Wrapper>
          <NavItemDropdownWrapper>
            <NavItemDropdown onChange={handleNavItemChange} value={currentNavItem.defaultPath}>
              {
                navItems.map(({ defaultPath, name }) => (
                  <NavItemDropdownItem key={name} value={defaultPath}>
                    {name}
                  </NavItemDropdownItem>
                ))
              }
            </NavItemDropdown>
          </NavItemDropdownWrapper>
          <SectionDropdownWrapper>
            <SectionDropdown onChange={handleSectionChange} value={currentItem.path}>
              {
                (currentNavItem.sections || []).map(({ name, items: sectionItems }) => (
                  <Section key={name} label={name}>
                    {
                      (sectionItems || []).map(({ name: itemName, path, subItems }) => (
                        <Fragment key={itemName}>
                          <Item value={path}>{itemName}</Item>
                          {
                            subItems && subItems.sort((a, b) => a.idx - b.idx).map(({ name: subItemName, path: subItemPath }) => (
                              <Item key={subItemName} value={subItemPath}>
                                &nbsp;&nbsp;&nbsp;-&nbsp;
                                {subItemName}
                              </Item>
                            ))
                          }
                        </Fragment>
                      ))
                    }
                  </Section>
                ))
              }
            </SectionDropdown>
          </SectionDropdownWrapper>
        </Wrapper>
      </Container>
    </Mobile>
  );
}
Example #22
Source File: index.js    From cord-19 with Apache License 2.0 5 votes vote down vote up
function Article({ id }) {
  const url = new URL(window.location);
  const { loading, response, error } = Get(
    `/document/v1/covid-19/doc/docid/${id}`
  ).state();

  if (loading) return <Loading message="Loading..." />;
  if (error)
    return <Error message={error.message || `Failed to load article #${id}`} />;

  console.log(response);

  const citations = uniq([
    ...(response.fields.cited_by || []),
    ...(response.fields.citations_inbound || [])
      .map(c => c.source_id)
      .filter(c => !isNaN(c)),
  ]);

  const panes = [
    {
      menuItem: 'Similar articles by Sent-SciBERT',
      render: () => <Related id={response.fields.id} specter={false} />,
    },
    {
      menuItem: 'Similar articles by SPECTER',
      render: () => <Related id={response.fields.id} specter={true} />,
    },
    {
      menuItem: {
        key: 'citations',
        content: `${citations.length} citing articles`,
        disabled: citations.length === 0,
      },
      render: () => (
        <CitedBy
          citedBy={citations}
          offset={parseInt(url.searchParams.get('offset')) || 0}
          total={citations.length}
          onOffsetChange={offset => {
            url.searchParams.set('offset', offset);
            navigate(url);
          }}
        />
      ),
    },
  ];

  return (
    <React.Fragment>
      <ContainerContent>
        <Content {...response.fields} />
        <Tab
          panes={panes}
          defaultActiveIndex={url.searchParams.get('tab') || 0}
          onTabChange={(e, tabInfo) => {
            // Reset all query params when changing tab
            [...url.searchParams.keys()].forEach(k =>
              url.searchParams.delete(k)
            );
            url.searchParams.set('tab', tabInfo.activeIndex);
            navigate(url);
          }}
        />
      </ContainerContent>
      <Footer />
    </React.Fragment>
  );
}
Example #23
Source File: index.js    From gatsby-shopify-course with BSD Zero Clause License 4 votes vote down vote up
export default function ProductTemplate(props) {
  const { getProductById } = React.useContext(CartContext);
  const [product, setProduct] = React.useState(null);
  const [selectedVariant, setSelectedVariant] = React.useState(null);
  const { search, origin, pathname } = useLocation();
  const variantId = queryString.parse(search).variant;

  React.useEffect(() => {
    getProductById(props.data.shopifyProduct.shopifyId).then(result => {
      setProduct(result);
      setSelectedVariant(
        result.variants.find(({ id }) => id === variantId) || result.variants[0]
      );
    });
  }, [
    getProductById,
    setProduct,
    props.data.shopifyProduct.shopifyId,
    variantId,
  ]);

  const handleVariantChange = e => {
    const newVariant = product?.variants.find(v => v.id === e.target.value);
    setSelectedVariant(newVariant);
    navigate(
      `${origin}${pathname}?variant=${encodeURIComponent(newVariant.id)}`,
      {
        replace: true,
      }
    );
  };

  return (
    <Layout>
      <SEO
        description={props.data.shopifyProduct.description}
        title={props.data.shopifyProduct.title}
      />
      <Button onClick={() => navigate(-1)}>Back to products</Button>
      <Grid>
        <div>
          <h1>{props.data.shopifyProduct.title}</h1>
          <p>{props.data.shopifyProduct.description}</p>
          {product?.availableForSale && !!selectedVariant && (
            <>
              {product?.variants.length > 1 && (
                <SelectWrapper>
                  <strong>Variant</strong>
                  <select
                    value={selectedVariant.id}
                    onChange={handleVariantChange}
                  >
                    {product?.variants.map(v => (
                      <option key={v.id} value={v.id}>
                        {v.title}
                      </option>
                    ))}
                  </select>
                </SelectWrapper>
              )}
              {!!selectedVariant && (
                <>
                  <Price>£{selectedVariant.price}</Price>
                  <ProductQuantityAdder
                    available={selectedVariant.available}
                    variantId={selectedVariant.id}
                  />
                </>
              )}
            </>
          )}
        </div>
        <div>
          <ImageGallery
            selectedVariantImageId={selectedVariant?.image.id}
            images={props.data.shopifyProduct.images}
          />
        </div>
      </Grid>
    </Layout>
  );
}
Example #24
Source File: index.js    From inboxzero-web with MIT License 4 votes vote down vote up
PageContent = props => {
  const { tagId = "all", tipId } = props;

  const tagsValues = Object.keys(tags);
  const tagNames = Object.values(tags).map(v => v.name);

  const handleSelectTag = tag => {
    if (tag === "all") {
      navigate("/");
    } else {
      navigate(`/${tag}`);
    }
  };

  const handleSelectTip = tip => {
    if (tipId) {
      if (tagId && tagId !== "all") {
        navigate(`/${tagId}`);
      } else {
        navigate("/");
      }
    } else {
      if (tagId && tagId !== "all") {
        navigate(`/${tagId}/${tip.id}`);
      } else {
        navigate(`t/${tip.id}`);
      }
    }
  };

  const selectedTip = tipId ? content.find(tip => tip.id === tipId) : null;

  if ((tagId && !tags[tagId]) || (tipId && !selectedTip)) {
    window.location = "/404";
    return;
  }

  return (
    <Fragment>
      <Section width="56rem" center>
        <Spacer size="xxxl" />
        <Logo />
        <Spacer />
        <H2 align="center">Inbox Zero</H2>
        <H3 align="center" style={{ maxWidth: "48rem" }}>
          Here’s how the most productive people manage their inbox. A&nbsp;collection of <Highlight>tips</Highlight>,{" "}
          <Highlight>apps</Highlight> and <Highlight>workflows</Highlight>.
        </H3>
        <Grid width="22em">
          <StyledA
            href="https://github.com/superlinear-hq/inboxzero-web/edit/master/content.js"
            icon="github"
            type="primary"
            target="_blank"
            rel="noopener"
          >
            Contribute
          </StyledA>
          <DropDownMenu
            buttonWidth="100%"
            fullWidth
            innerIcon="chevronDown"
            iconSide="right"
            label={tags[tagId].name}
            options={tagsValues}
            optionsNames={tagNames}
            onSelect={handleSelectTag}
          />
        </Grid>
        <Spacer />
        <P2>
          Made by{" "}
          <a href="https://twitter.com/linuz90" target="_blank" rel="noopener noreferrer">
            Fabrizio
          </a>{" "}
          and{" "}
          <a href="https://twitter.com/frankdilo" target="_blank" rel="noopener noreferrer">
            Francesco
          </a>
          . Privacy Policy <Link to="/privacy-policy">here</Link>.
        </P2>
      </Section>
      <Section width="100%">
        <Columns
          queries={[
            {
              columns: 1,
              query: "min-width: 0px",
            },
            {
              columns: 2,
              query: "min-width: 680px",
            },
            {
              columns: 3,
              query: "min-width: 1250px",
            },
            {
              columns: 4,
              query: "min-width: 1800px",
            },
          ]}
          gap="10px"
        >
          {content.map(tip => {
            const key = tip.id;
            const tag = tip.tag;
            const show = tagId === tag || tagId === "all";

            return (
              <ContentCard
                isCurrentCard={false}
                key={key}
                show={show}
                element={tip}
                onTagClick={() => handleSelectTag(tag === tagId ? "all" : tag)}
                onLinkClick={() => handleSelectTip(tip)}
              />
            );
          })}
        </Columns>
        <Spacer size="xxxl" />
        <P2 align="center">
          Made by{" "}
          <a href="https://twitter.com/linuz90" target="_blank" rel="noopener noreferrer">
            Fabrizio
          </a>{" "}
          and{" "}
          <a href="https://twitter.com/frankdilo" target="_blank" rel="noopener noreferrer">
            Francesco
          </a>{" "}
          with{" "}
          <a href="https://www.gatsbyjs.org/" target="_blank" rel="noopener noreferrer">
            Gatsby
          </a>
          ,{" "}
          <a href="https://www.framer.com/motion/" target="_blank" rel="noopener noreferrer">
            Framer Motion
          </a>{" "}
          and{" "}
          <a href="https://zeit.co/" target="_blank" rel="noopener noreferrer">
            Zeit
          </a>
          .
        </P2>
        <P2 align="center">
          Thanks{" "}
          <a href="https://twitter.com/thepatwalls" target="_blank" rel="noopener noreferrer">
            Pat Walls
          </a>{" "}
          for the feedback and support.
        </P2>
      </Section>
      <AnimatePresence>
        {selectedTip && (
          <Fragment>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              style={{
                position: "fixed",
                top: 0,
                left: 0,
                bottom: 0,
                right: 0,
                zIndex: 0,
                background: "rgba(40,40,40,.5)",
              }}
            />
            <motion.div
              style={{
                position: "fixed",
                top: 0,
                left: 0,
                bottom: 0,
                right: 0,
                display: "flex",
                zIndex: 3,
                overflow: "scroll",
                WebkitOverflowScrolling: "touch",
                padding: "3em 1em",
              }}
            >
              <ContentCard
                id={selectedTip.id}
                isCurrentCard={true}
                show={selectedTip}
                element={selectedTip}
                style={{
                  margin: "auto",
                  pointerEvents: "auto",
                  width: "36em",
                  maxWidth: "100%",
                }}
                onLinkClick={handleSelectTip}
              />
            </motion.div>
          </Fragment>
        )}
      </AnimatePresence>
    </Fragment>
  );
}
Example #25
Source File: production-app.js    From cybsec with GNU Affero General Public License v3.0 4 votes vote down vote up
// Let the site/plugins run code very early.
apiRunnerAsync(`onClientEntry`).then(() => {
  // Let plugins register a service worker. The plugin just needs
  // to return true.
  if (apiRunner(`registerServiceWorker`).length > 0) {
    require(`./register-service-worker`)
  }

  class RouteHandler extends React.Component {
    render() {
      let { location } = this.props

      return (
        <EnsureResources location={location}>
          {({ pageResources, location }) => (
            <RouteUpdates location={location}>
              <ScrollContext
                location={location}
                shouldUpdateScroll={shouldUpdateScroll}
              >
                <PageRenderer
                  {...this.props}
                  location={location}
                  pageResources={pageResources}
                  {...pageResources.json}
                />
              </ScrollContext>
            </RouteUpdates>
          )}
        </EnsureResources>
      )
    }
  }

  const { page, location: browserLoc } = window
  if (
    // Make sure the window.page object is defined
    page &&
    // The canonical path doesn't match the actual path (i.e. the address bar)
    __PATH_PREFIX__ + page.path !== browserLoc.pathname &&
    // ...and if matchPage is specified, it also doesn't match the actual path
    (!page.matchPath ||
      !match(__PATH_PREFIX__ + page.matchPath, browserLoc.pathname)) &&
    // Ignore 404 pages, since we want to keep the same URL
    page.path !== `/404.html` &&
    !page.path.match(/^\/404\/?$/) &&
    // Also ignore the offline shell (since when using the offline plugin, all
    // pages have this canonical path)
    !page.path.match(/^\/offline-plugin-app-shell-fallback\/?$/)
  ) {
    navigate(
      __PATH_PREFIX__ + page.path + browserLoc.search + browserLoc.hash,
      { replace: true }
    )
  }

  loader.getResourcesForPathname(browserLoc.pathname).then(() => {
    const Root = () =>
      createElement(
        Router,
        {
          basepath: __PATH_PREFIX__,
        },
        createElement(RouteHandler, { path: `/*` })
      )

    const WrappedRoot = apiRunner(
      `wrapRootElement`,
      { element: <Root /> },
      <Root />,
      ({ result }) => {
        return { element: result }
      }
    ).pop()

    let NewRoot = () => WrappedRoot

    const renderer = apiRunner(
      `replaceHydrateFunction`,
      undefined,
      ReactDOM.hydrate
    )[0]

    domReady(() => {
      renderer(
        <NewRoot />,
        typeof window !== `undefined`
          ? document.getElementById(`___gatsby`)
          : void 0,
        () => {
          postInitialRenderWork()
          apiRunner(`onInitialClientRender`)
        }
      )
    })
  })
})
Example #26
Source File: sketch.js    From PyLot with MIT License 4 votes vote down vote up
sketch = (p) => {
  let current = "None";
  const addTileButton = document.querySelector("#add-tile-button");
  const removeTileButton = document.querySelector("#remove-tile-button");
  const bindButton = document.querySelector("#bind-button");
  const saveNotebookButton = document.querySelector("#save-notebook");
  const editTileButton = document.querySelector("#edit-tile-code");
  const runTileButton = document.querySelector("#run-tile-code");
  const viewTileOutputButton = document.querySelector("#view-tile-output");
  const scheduleDAGButton = document.querySelector("#schedule-dag-button");
  const cancelDAGButton = document.querySelector("#cancel-job-button");
  let noteBook;
  let canvasWidth = p.windowWidth / 1.15;
  let canvasHeight = p.windowHeight / 1.35;
  
  let socket="No socket";
  axios.post("/getIp",{
    username:"testpilot",
    serverName:"Local Test Server"
  }).then(({data})=>{
    const ip = data;
    socket = openConnection(`http://${ip}:5000/`);
    socket.on("connect",()=>console.log("sketch socket connected to runtime"));
    socket.on("disconnect",()=>console.log("sketch socket disconnected from runtime"));
    socket.on("scheduled-dag",({message})=>{
      alert(message)
    })
    socket.on("cancelled-job",({message})=>alert(message))
    socket.on("ran-tile",(response)=>{
      if(Object.keys(response).includes("error")){
        alert(response.error)
      }else{
        console.log(response);
        alert(`Executed tile code successfully.`)
      }
    });
  })
  
  const notebookName = window.location.href.split("/")[
    window.location.href.split("/").length - 1
  ];
  const username = window.location.href.split("/")[
    window.location.href.split("/").length - 2
  ];

  class Tile {
    constructor(name, canvasWidth, canvasHeight) {
      this.information = {
        name: name,
        canvasWidth: canvasWidth,
        canvasHeight: canvasHeight,
        xPos: canvasWidth / 2,
        yPos: canvasHeight / 2,
        tileWidth: canvasWidth / 10,
        tileHeight: canvasHeight / 10,
        // outputs: [],
        // inputs: [],
        outputTileNames: [],
        inputTileNames: [],
        code: "",
      };
    }

    addOutput(someTile) {
      // this.information.outputs.push(someTile);
      this.information.outputTileNames.push(someTile.information.name);
    }
    addInput(someTile) {
      // this.information.inputs.push(someTile);
      this.information.inputTileNames.push(someTile.information.name);
    }
    show() {
      if (
        p.mouseIsPressed &&
        (current === "None" || current === this.information.name)
      ) {
        const { tileWidth, tileHeight, xPos, yPos } = this.information;
        const leftWall = xPos - tileWidth / 2;
        const rightWall = xPos + tileWidth / 2;
        const bottomWall = yPos + tileHeight / 2;
        const topWall = yPos - tileHeight / 2;
        if (
          p.mouseX > leftWall &&
          p.mouseX < rightWall &&
          p.mouseY < bottomWall &&
          p.mouseY > topWall
        ) {
          current = this.information.name;
          this.information.xPos = p.mouseX;
          this.information.yPos = p.mouseY;
          p.strokeWeight(5);
          p.stroke("green");
        }
      }
      const {
        name,
        xPos,
        yPos,
        canvasWidth,
        canvasHeight,
        tileWidth,
        tileHeight,
        outputTileNames,
      } = this.information;
      p.rectMode(p.CENTER);
      p.fill("#42f5bf"); //teal fill for tile
      p.rect(xPos, yPos, tileWidth, tileHeight);
      p.stroke("black");
      p.strokeWeight(1);
      p.text(name, xPos - 20, yPos);
      p.point(xPos, yPos);
      const { outputs } = this.information;
      p.stroke("white");

      if (outputTileNames.length > 0) {
        // console.log(noteBook);
        outputTileNames.forEach((outputTileName, index) => {
          let outputTile;
          for (let i = 0; i < noteBook.tiles.length; i++) {
            if (noteBook.tiles[i].information.name === outputTileName) {
              outputTile = noteBook.tiles[i];
            }
          }
          p.line(
            xPos + tileWidth / 2,
            yPos,
            outputTile.information.xPos - tileWidth / 2,
            outputTile.information.yPos
          );
        });
      }
    }
  }

  class Notebook {
    constructor() {
      this.name = "Untitled-Notebook";
      this.tiles = [];
      this.tileNames = [];
      // localStorage.setItem("test","sketch set this value")
    }
    viewTileCode(name){
      if (!name) {
        alert("Please enter a tile name.");
      } else if (this.tileNames.includes(name)) {
        saveNotebookButton.click();//save notebook before editing tile code.
        navigate(`/view/${username}/${notebookName}/${name}`);
      } else {
        alert("Tile with that name does not exists.");
      }
    }
    editTileCode(name) {
      if (!name) {
        alert("Please enter a tile name.");
      } else if (this.tileNames.includes(name)) {
        saveNotebookButton.click();//save notebook before editing tile code.
        navigate(`/editor/${username}/${notebookName}/${name}`);
      } else {
        alert("Tile with that name does not exists.");
      }
    }

    addTile(name, canvasWidth, canvasHeight) {
      // console.log(name);
      if (!name) {
        alert("No name added to tile.");
      } else if (this.tileNames.includes(name)) {
        alert("Tile already exists, cannot create tile.");
      } else {
        const newTile = new Tile(name, canvasWidth, canvasHeight);
        this.tiles.push(newTile);
        this.tileNames.push(name);
        saveNotebookButton.click();
      }
    }

    display() {
      this.tiles.forEach((element, index) => {
        element.show();
      });
    }

    bind(nodeName, outputTileName) {
      const nodeIndex = this.tileNames.indexOf(nodeName);
      const outputTileIndex = this.tileNames.indexOf(outputTileName);
      if (nodeIndex === -1 || outputTileIndex === -1) {
        alert("Invalid tile names");
      } else {
        const nodeTile = this.tiles[nodeIndex];
        const outputTile = this.tiles[outputTileIndex];
        let alreadyOutput = false;
        for (let i = 0; i < nodeTile.information.outputTileNames.length; i++) {
          if (nodeTile.information.outputTileNames[i] === outputTileName) {
            alreadyOutput = true;
          }
        }
        console.log(alreadyOutput);
        if (alreadyOutput) {
          alert("Tiles already bound.");
          console.log(nodeTile.information.outputTileNames);
        } else {
          nodeTile.addOutput(outputTile);
          outputTile.addInput(nodeTile);
        }
      }
    }

    removeTile(tileName) {
      const tileIndex = this.tileNames.indexOf(tileName);
      this.tileNames.splice(tileIndex, 1);
      this.tiles.splice(tileIndex, 1);
      this.tiles.forEach((tile, index) => {
        tile.information.outputTileNames = tile.information.outputTileNames.filter(
          // (el) => el.information.name !== tileName
          (el) => el !== tileName
        );
        tile.information.inputTileNames = tile.information.inputTileNames.filter(
          // (el) => el.information.name !== tileName
          (el) => el !== tileName
        );
      });
      saveNotebookButton.click();
    }
  }
  cancelDAGButton.addEventListener("click",()=>{
    // alert("Cancel DAG button not implemented.")
    const nbName = window.location.href.split("/")[window.location.href.split("/").length-1];
    socket.emit("cancel-job",{notebookName:nbName});
  });
  scheduleDAGButton.addEventListener("click",()=>{
    const nbName = window.location.href.split("/")[window.location.href.split("/").length-1];
    const minutes = parseInt(prompt("Minutes(?)"));
    if(minutes===NaN){
      alert("Invalid input for minutes")
    }else{
      socket.emit("schedule-dag",{notebookName:nbName,minutes:minutes});
    }
  });
  viewTileOutputButton.addEventListener("click",()=>{
    const name = prompt("Enter name of tile you wish to view:");
    noteBook.viewTileCode(name)
  })
  editTileButton.addEventListener("click", () => {
    const name = prompt("Enter name of new tile:");
    noteBook.editTileCode(name);
  });
  addTileButton.addEventListener("click", () => {
    const name = prompt("Enter name of new tile:");
    noteBook.addTile(name, canvasWidth, canvasHeight);
  });
  removeTileButton.addEventListener("click", () => {
    const name = prompt("Enter name of the tile you wish to remove:");
    noteBook.removeTile(name, canvasWidth, canvasHeight);
  });
  bindButton.addEventListener("click", () => {
    const tile1 = prompt("Enter name of input tile:");
    const tile2 = prompt("Enter name of output tile:");
    if (
      !noteBook.tileNames.includes(tile1) ||
      !noteBook.tileNames.includes(tile2)
    ) {
      alert("One of the two tile names entered does not exist.");
    } else {
      noteBook.bind(tile1, tile2);
      saveNotebookButton.click();
    }
  });
  saveNotebookButton.addEventListener("click", () => {
    // console.log(socket) write code here to send notebook object to the runtime.js file 
    // socket.emit("test-sketch-socket",{message:"hello from sketch"})
    while (noteBook.name === "Untitled-Notebook" || noteBook.name == null) {
      const newName = window.location.href.split("/")[
        window.location.href.split("/").length - 1
      ];
      noteBook.name = newName;
    }
    const username = window.location.href.split("/")[
      window.location.href.split("/").length - 2
    ];
    axios
      .post("/users/test", { notebook: noteBook, user: username })
      .then(({ data: { message } }) => console.log(message));
    //This function is where all the communication with server takes place.
    // console.log(noteBook);
    socket.emit("test-sketch-socket",{ notebook: noteBook, user: username })
  });
  runTileButton.addEventListener("click",()=>{
    const tileName = prompt("Please enter tile name: ");
    if(!noteBook.tileNames.includes(tileName)){
      alert(`${tileName} not found in notebook: ${noteBook.name}`);
    }else{
      socket.emit("run-tile",{notebookName:noteBook.name,tileName:tileName})
    }
    //maybe add savebutton.click to save before running
  })
  let loadNotebook;
  p.preload = () => {
    axios
      .post("/loadNotebook", { notebook: notebookName, user: username })
      .then(({ data: { message, data } }) => {
        if (
          message === "Database connection error." ||
          message === "Username not found." ||
          message === "Notebook not found."
        ) {
          alert(message);
          loadNotebook = false;
        } else {
          // console.log("data");
          // console.log(data);
          const notebookName = data.name;
          const notebookTileNames = data.tileNames;
          const notebookTiles = [];
          if (notebookTileNames.length === 0) {
            console.log("Empty notebook, no data to load.");
            loadNotebook = false;
          } else {
            //POPULATING A NOTEBOOK OBJECT.
            // console.log(data.tiles);
            for (let i = 0; i < data.tiles.length; i++) {
              // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
              // console.log(data.tiles[i].information);
              const tileInfo = data.tiles[i].information;
              const newTile = new Tile(
                tileInfo.name,
                tileInfo.canvasWidth,
                tileInfo.canvasHeight
              );
              newTile.information.code = tileInfo.code;
              newTile.information.inputTileNames = tileInfo.inputTileNames;
              newTile.information.outputTileNames = tileInfo.outputTileNames;
              newTile.information.tileHeight = tileInfo.tileHeight;
              newTile.information.tileWidth = tileInfo.tileWidth;
              newTile.information.xPos = tileInfo.xPos;
              newTile.information.yPos = tileInfo.yPos;
              // console.log(newTile);
              // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
              notebookTiles.push(newTile);
            }
            // console.log(notebookTiles);
            noteBook = new Notebook();
            noteBook.name = notebookName;
            noteBook.tileNames = notebookTileNames;
            noteBook.tiles = notebookTiles;
            loadNotebook = true;
          }
        }
      });
  };
  p.setup = () => {
    p.createCanvas(canvasWidth, canvasHeight);
    p.background("grey");
    if (!loadNotebook) {
      noteBook = new Notebook();
    }
  };
  p.mouseReleased = () => {
    current = "None";
  };
  p.draw = () => {
    p.background(220);
    noteBook.display();
  };
}
Example #27
Source File: ServerDetail.js    From PyLot with MIT License 4 votes vote down vote up
render() {
    if (this.state.loading) {
      return (
        <div className="serverDetailsPageMainContainer ">
          <CircularProgress />
        </div>
      );
    } else {
      const { serverName, username, socketRunning } = this.state;
      function RemoveServer() {
        const sName = prompt(
          "Please enter name of the server to continue server deletion."
        );
        if (sName === serverName) {
          axios
            .post("/users/removeserver", {
              username: username,
              serverName: sName,
            })
            .then((response) => {
              if (
                response.data ===
                `Server : ${serverName} was deleted successfully.`
              ) {
                alert("Server deleted successfully.");
                navigate("/");
              } else {
                alert("Failed to delete server.[Internal Issue]");
              }
            });
        } else {
          alert("Did not delete server.");
        }
      }
      function startHealthReportingService() {
        if (socketRunning) {
          alert("Health reporting service already running on remote server.");
        } else {
          const data = {
            username: username,
            serverName: serverName,
          };
          axios.post("/health/setupserver", data).then((response) => {
            console.log(response);
            alert("Done.");
          });
        }
      }
      function openTerminal() {
        // alert(`Open new window to ${ipAddr}`)
        navigate(`/terminal/${username}/${serverName}`);
      }
      function openNotebook() {
        navigate(`/notebooks/${username}`);
      }
      const { ipAddr } = this.state;
      const healthData = this.state.health;
      return (
        <Card style={{ maxHeight: "30%", minHeight: "50%" }}>
          <CardContent>
            <Typography variant="h5">{this.state.serverName}</Typography>
            <Typography>{this.state.data.operatingSystem}</Typography>
            <Typography>User: {this.state.user}</Typography>
            <Typography>Uptime: {this.state.data.uptime}</Typography>
            <Typography>{this.state.data.cpuUsage}?</Typography>
            <Typography>
              Memory Usage: {this.state.data.memoryUsedPercent}?
            </Typography>
            <Typography>
              {this.state.socketRunning
                ? "Health Reporting Service is online ?"
                : "Health reporting service is offline on remote server ?"}
            </Typography>
            <p
              className="waves-effect btn remove-server teal accent-3"
              onClick={RemoveServer}
            >
              REMOVE SERVER
            </p>
            <p
              className="waves-effect btn remove-server teal accent-3"
              onClick={startHealthReportingService}
            >
              Setup Health Reporting Service
            </p>
            <p
              className="waves-effect btn remove-server teal accent-3"
              onClick={openTerminal}
            >
              Open Terminal
            </p>
            <p
              className="waves-effect btn remove-server teal accent-3"
              onClick={openNotebook}
            >
              Notebooks
            </p>
          </CardContent>
        </Card>
      );
    }
  }
Example #28
Source File: index.js    From devrel-kpis with MIT License 4 votes vote down vote up
PageContent = props => {
  const { tagId = "all", tipId } = props;

  const tagsValues = Object.keys(tags);
  const tagNames = Object.values(tags).map(v => v.name);

  const handleSelectTag = tag => {
    if (tag === "all") {
      navigate("/");
    } else {
      navigate(`/${tag}`);
    }
  };

  const handleSelectTip = tip => {
    if (tipId) {
      if (tagId && tagId !== "all") {
        navigate(`/${tagId}`);
      } else {
        navigate("/");
      }
    } else {
      if (tagId && tagId !== "all") {
        navigate(`/${tagId}/${tip.id}`);
      } else {
        navigate(`t/${tip.id}`);
      }
    }
  };

  const selectedTip = tipId ? content.find(tip => tip.id === tipId) : null;

  if ((tagId && !tags[tagId]) || (tipId && !selectedTip)) {
    window.location = "/404";
    return;
  }

  return (
    <Fragment>
      <Section width="56rem" center>
        <Spacer size="xxxl" />
        {<Logo />}
        <Spacer />
        <H2 align="center">DevRel KPIs</H2>
        <H3 align="center" style={{ maxWidth: "48rem" }}>
          <Highlight>Metrics and methods for proving ROI </Highlight> through data + story. Advice from around the
          DevRel and Community world.
        </H3>
        <Grid width="22em">
          <StyledA
            href="https://github.com/orbit-love/devrel-kpis"
            icon="github"
            type="primary"
            target="_blank"
            rel="noopener"
          >
            Contribute
          </StyledA>
          <DropDownMenu
            buttonWidth="100%"
            fullWidth
            innerIcon="chevronDown"
            iconSide="right"
            label={tags[tagId].name}
            options={tagsValues}
            optionsNames={tagNames}
            onSelect={handleSelectTag}
          />
        </Grid>
        <Spacer />
        <P2>
          Made by{" "}
          <a href="https://orbit.love" target="_blank" rel="noopener noreferrer">
            the team at Orbit
          </a>
          .
        </P2>
      </Section>
      <Section width="100%">
        <Columns
          queries={[
            {
              columns: 1,
              query: "min-width: 0px",
            },
            {
              columns: 2,
              query: "min-width: 680px",
            },
            {
              columns: 3,
              query: "min-width: 1250px",
            },
            {
              columns: 4,
              query: "min-width: 1800px",
            },
          ]}
          gap="10px"
        >
          {content.map(tip => {
            const key = tip.id;
            const tag = tip.tag;
            const show = tagId === tag || tagId === "all";

            return (
              <ContentCard
                isCurrentCard={false}
                key={key}
                show={show}
                element={tip}
                onTagClick={() => handleSelectTag(tag === tagId ? "all" : tag)}
                onLinkClick={() => handleSelectTip(tip)}
              />
            );
          })}
        </Columns>
        <Spacer size="xxxl" />
        <P2 align="center">
          Made by{" "}
          <a href="https://twitter.com/OrbitModel" target="_blank" rel="noopener noreferrer">
            Orbit
          </a>{" "}
          with{" "}
          <a href="https://www.gatsbyjs.org/" target="_blank" rel="noopener noreferrer">
            Gatsby
          </a>
          ,{" "}
          <a href="https://www.framer.com/motion/" target="_blank" rel="noopener noreferrer">
            Framer Motion
          </a>{" "}
          and{" "}
          <a href="https://zeit.co/" target="_blank" rel="noopener noreferrer">
            Zeit
          </a>
          .
        </P2>
        <P2 align="center">
          Inspired by and forked from{" "}
          <a href="https://inboxze.ro/" target="_blank" rel="noopener noreferrer">
            Inbox Zero
          </a>
          .
        </P2>
        <P2 align="center">
          Privacy Policy <Link to="/privacy-policy">here</Link>.
        </P2>
      </Section>
      <AnimatePresence>
        {selectedTip && (
          <Fragment>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              style={{
                position: "fixed",
                top: 0,
                left: 0,
                bottom: 0,
                right: 0,
                zIndex: 0,
                background: "rgba(40,40,40,.5)",
              }}
            />
            <motion.div
              style={{
                position: "fixed",
                top: 0,
                left: 0,
                bottom: 0,
                right: 0,
                display: "flex",
                zIndex: 3,
                overflow: "scroll",
                WebkitOverflowScrolling: "touch",
                padding: "3em 1em",
              }}
            >
              <ContentCard
                id={selectedTip.id}
                isCurrentCard={true}
                show={selectedTip}
                element={selectedTip}
                style={{
                  margin: "auto",
                  pointerEvents: "auto",
                  width: "36em",
                  maxWidth: "100%",
                }}
                onLinkClick={handleSelectTip}
              />
            </motion.div>
          </Fragment>
        )}
      </AnimatePresence>
    </Fragment>
  );
}
Example #29
Source File: index.jsx    From gsoc-organizations with GNU General Public License v3.0 4 votes vote down vote up
IndexPage = ({ data, location }) => {
  const dispatch = useAppDispatch()
  const searchQuery = useAppSelector(getSearch)
  const filters = useAppSelector(getFilters)

  // Any url would work here.
  const currentURL = new URL("https://www.gsocorganizations.dev/")

  try {
    currentURL.search = location.search
  } catch (err) {}

  const getSearchQueryInUrl = () => {
    return currentURL.searchParams.get("search") || ""
  }

  const getFiltersFromUrl = () => {
    return (
      JSON.parse(currentURL.searchParams.get("filters")) || {
        years: [],
        categories: [],
        technologies: [],
        topics: [],
      }
    )
  }

  useEffect(() => {
    dispatch(setSearch(getSearchQueryInUrl()))
    dispatch(setFilters(getFiltersFromUrl()))
  }, [])

  useEffect(() => {
    // Don't append search params if there is no filter or searchQurey.
    if (searchQuery !== "") {
      currentURL.searchParams.set("search", searchQuery)
    } else {
      currentURL.searchParams.delete("search")
    }
    if (Object.values(filters).filter(arr => arr.length !== 0).length !== 0) {
      currentURL.searchParams.set("filters", JSON.stringify(filters))
    } else {
      currentURL.searchParams.delete("filters")
    }
    navigate(currentURL.search === "" ? "/" : currentURL.search)
  }, [searchQuery, filters])

  const [orgCards, setOrgCards] = React.useState([])

  React.useEffect(() => {
    let filteredOrganizations = getFilteredOrganizations(
      data,
      searchQuery,
      filters
    )

    const cards = []
    for (const organization of filteredOrganizations) {
      cards.push(
        <Grid.Column>
          <OrgCard data={organization} />
        </Grid.Column>
      )
    }

    setOrgCards(cards)
  }, [searchQuery, filters])

  const metaDescription =
    "View and analyse the info of the organizations participating in Google Summer of Code and filter them by various parameters."
  const meta = [
    {
      name: "description",
      content: metaDescription,
    },
    {
      name: "keywords",
      content:
        "gsoc, analysis, organizations, statistics, filter, years, google summer of code, technologies, topics, categories, projects",
    },
    {
      property: "og:type",
      content: "website",
    },
    {
      property: "og:title",
      content: data.site.siteMetadata.title,
    },
    {
      property: "og:description",
      content: metaDescription,
    },
    {
      property: "og:image",
      content: `${data.site.siteMetadata.siteUrl}/images/screenshot.png`,
    },
    {
      property: "og:site_name",
      content: data.site.siteMetadata.title,
    },
    {
      property: "og:url",
      content: data.site.siteMetadata.siteUrl,
    },
    {
      name: "twitter:card",
      content: "summary_large_image",
    },
    {
      name: "twitter:title",
      content: data.site.siteMetadata.title,
    },
    {
      name: "twitter:description",
      content: metaDescription,
    },
    {
      name: "twitter:image",
      content: `${data.site.siteMetadata.siteUrl}/images/screenshot.png`,
    },
  ]

  const cardColumns = useBreakpoint().l ? 3 : 4

  React.useEffect(() => {
    setTimeout(() => {
      ;(window.adsbygoogle = window.adsbygoogle || []).push({})
    }, 2000)
  }, [])

  return (
    <Layout>
      <SEO title={"Home"} meta={meta} />
      <Grid className="index-org-cards-grid">
        <Notification />
      </Grid>
      <div style={{ marginTop: "1rem", textAlign: "center" }}>
        <a className="ui orange label">{orgCards.length} results</a>
      </div>
      <Grid className="index-org-cards-grid" stackable columns={cardColumns}>
        {orgCards}
      </Grid>
      <div style={{ padding: "1rem" }}>
        <ins
          className="adsbygoogle"
          style={{ display: "block" }}
          data-ad-client="ca-pub-9769516184087442"
          data-ad-slot="5525920548"
          data-ad-format="auto"
          data-full-width-responsive="false"
        ></ins>
      </div>
    </Layout>
  )
}