recoil#useRecoilState JavaScript Examples

The following examples show how to use recoil#useRecoilState. 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: ResizeHandler.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function ResizeHandler() {
  const [selectedItems, setSelectedItems] = useRecoilState(selectedItemsSelector);
  const [selectedItemsSnapshot, setSelectedItemsSnapshot] = useState(null);

  const { onMouseDown } = useMove(({ status, offset }) => {
    if (status === 'start') {
      setSelectedItemsSnapshot(selectedItems)
    }

    if (status === 'moving') {
      setSelectedItems(selectedItemsSnapshot.map(item => resizeItem(item, offset)));
    }
  })

  if (selectedItems.length !== 1 || selectedItems[0].type === 'statistics') {
    return null;
  }

  const { x, y, width, height } = selectedItems[0];

  return (
    <View
      style={[styles.resizeHandler, {
        left: x + width,
        top: y + height,
      }]}
      onMouseDown={onMouseDown}
    >
      <View style={styles.resizeHandlerDot} />
    </View>
  )
}
Example #2
Source File: AddRectsButton.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function AddRectsButton() {
  const [itemIds, setItemIds] = useRecoilState(itemIdsState);
  const setSelectedIds = useSetRecoilState(selectedIdsState);

  const handleClick = () => {
    let space = 16;
    let width = 100;
    let height = 100;
    let ids = [];
    let start = itemIds.length;
    for (let i=0; i<100; i++) {
      let count = start + i;
      let row = Math.floor(count / 5);
      let col = count % 5;
      let x = space * (col + 1) + width * col;
      let y = space * (row + 1) + height * row;
      let id = createNewShape({ x, y, width, height });
      ids.push(id);
    }

    setItemIds([...itemIds, ...ids]);
    setSelectedIds([]);
  }


  return (
    <Button style={styles.root} onClick={handleClick}>
      <Text style={styles.text}>Add 100 Rects</Text>
    </Button>
  );
}
Example #3
Source File: DetailPage.js    From app-personium-trails with Apache License 2.0 6 votes vote down vote up
export function DetailPage() {
  const { __id } = useParams();
  const [Id, setId] = useRecoilState(locationId);
  console.log(__id);

  useEffect(() => {
    console.log({ __id });
    setId(__id);
  }, [__id]);

  return (
    <Container>
      <Header as="h3">Detail of #{Id}</Header>
      <LocationDataURLView __id={__id} />
      <LocationODataView __id={__id} />
      <LocationRawDataView __id={__id} />
    </Container>
  );
}
Example #4
Source File: TvShowList.jsx    From recoil-testing with MIT License 6 votes vote down vote up
TvShowList = ({ startTransition }) => {
  const [id, setId] = useRecoilState(atoms.id);

  const onClick = (newId) => {
    // startTransition(() => {
    //   setId(newId);
    // });
    setId(newId)
  };


  const tvMetadata = getTvMetadataResource().read();
  const tvshows = tvMetadata.map(item => (
    <div className="item" key={item.id} onClick={() => onClick(item.id)}>
      <div className="name">{item.name}</div>
      <div className="score">{item.score}</div>
    </div>
  ));
  return <div className="tvshow-list">{tvshows}</div>;
}
Example #5
Source File: ColorPicker.js    From recoil-paint with MIT License 5 votes vote down vote up
export default function ColorPicker() {
  const [shown, setShown] = useState(false);
  const [backgroundColor, setBackgroundColor] = useRecoilState(backgroundColorState);

  const handleChangeComplete = useCallback((color) => {
    setBackgroundColor(color.hex);
  }, [setBackgroundColor]);

  const handleClick = useCallback(() => {
    setShown(true);
  }, []);

  useEffect(() => {
    function hidePopup(e) {
      if (e.target.closest('#color-picker')) {
        return;
      }
      setShown(false);
    }

    document.body.addEventListener('click', hidePopup);

    return () => {
      document.body.removeEventListener('click', hidePopup);
    }
  }, []);

  return (
    <View style={styles.root} onClick={handleClick}>
      <View style={[styles.inner, { backgroundColor: backgroundColor }]} />
      {shown && (
        <View style={styles.popup} nativeID="color-picker">
          <SketchPicker
            color={backgroundColor}
            onChangeComplete={handleChangeComplete}
          />
        </View>
      )}
    </View>
  );
}
Example #6
Source File: NavBar.js    From HealthBridge with GNU General Public License v3.0 5 votes vote down vote up
NavBar = ({ history }) => {
	const [user, setUser] = useRecoilState(userAtom);
	const [, setToken] = useRecoilState(tokenAtom);
	const url = String(history.location.pathname);

	const logOut = () => {
		history.push("/");
		setUser(null);
		setToken(null);
		localStorage.removeItem("user");
		localStorage.removeItem("token");
	};

	return (
		<div className="NavBar">
			<div className="logo">
				<div onClick={() => history.push("/")}>
					<h1>HealthBridge</h1>
				</div>
			</div>
			<div className="links">
				{user ? (
					<React.Fragment>
						<div
							className={
								url === "/dashboard" || url === "/dashboardDoc"
									? "link selected"
									: "link"
							}
							onClick={() => {
								user.type === "doctor"
									? history.push("/dashboardDoc")
									: history.push("/dashboard");
							}}>
							Dashboard
						</div>
						<div
							className={
								url === "/profile" ? "link selected" : "link"
							}
							onClick={() => {
								history.push("/profile");
							}}>
							Profile
						</div>
						<div className="link" onClick={() => logOut()}>
							Logout
						</div>
					</React.Fragment>
				) : (
					<React.Fragment>
						<div
							className={
								url === "/signup" ? "link selected" : "link"
							}
							onClick={() => history.push("/signup")}>
							Register
						</div>
						<div
							className={
								url === "/login" ? "link selected" : "link"
							}
							onClick={() => history.push("/login")}>
							Login
						</div>
					</React.Fragment>
				)}
			</div>
			<DarkToggle/>
		</div>
	);
}
Example #7
Source File: ProfilePage.js    From app-personium-trails with Apache License 2.0 5 votes vote down vote up
export function ProfilePage() {
  const login = useRecoilValue(isLogin);
  const token = useRecoilValue(tokens);
  const [introspection, setIntrospection] = useRecoilState(_introspection);
  const [userData, setUserData] = useState(null);
  const [xmlData, setXMLData] = useState(null);

  useEffect(() => {
    fetch(`${handler.boxUrl}secret.txt`, {
      headers: {
        Authorization: `Bearer ${handler.accessToken.access_token}`,
      },
    })
      .then(res => res.text())
      .then(text => setUserData(text));
    return () => setUserData(null);
  }, [token]);

  useEffect(() => {
    const { access_token } = handler.accessToken;
    statDirectory(`${handler.boxUrl}uploaded/`, access_token).then(res => {
      console.log(res);

      setXMLData(
        Array.from(res.entries()).map(([key, val]) => ({
          file: key,
          acl: Array.from(val.entries()).map(([key, val]) => ({
            principal: key,
            privilege: Array.from(val.keys()),
          })),
        }))
      );
    });
  }, handler.accessToken);

  return (
    <>
      <h1>Profile</h1>
      <Segment>
        <h3>Sample GET</h3>
        <p>Getting secret.txt</p>
        <p>{userData ? userData : 'loading'}</p>
      </Segment>

      <Segment>
        <h3>Sample XML</h3>
        <p>Getting /uploaded</p>
        <p>{xmlData ? JSON.stringify(xmlData) : 'loading'}</p>
      </Segment>

      <Segment>
        <h3>Tokens</h3>
        {login === true ? (
          <TokenView token={token} />
        ) : (
          <p>youre not logged in</p>
        )}
      </Segment>
      <Segment>
        <h3>Token introspection</h3>
        {introspection === null ? (
          <p>loading</p>
        ) : (
          <TokenIntrospect introspection={introspection} />
        )}
      </Segment>
    </>
  );
}
Example #8
Source File: ForceGraph.jsx    From LucidQL with MIT License 5 votes vote down vote up
// The ForceGraph component will be the container for the generated force graph and ForceGraphGenerator will generate the graph using D3
function ForceGraph() {
  // useRef hook to reference the container element (common practice for React + d3)
  const containerRef = useRef(null);
  const [data, setData] = useRecoilState(state);

  const nodeHoverTooltip = React.useCallback((node) => {
    if (node.primary)
      return `<h4>Table: ${node.name}</h4><p>(SQL info)</br>Primary Key : ${node.primaryKey}</br>Columns Count : ${
        node.columnCount
      }</br>Foreign Keys :</br>${node.foreignKeys.length > 0 ? node.foreignKeys : 'N/A'}</br>Referenced by :</br>${
        node.referencedBy.length > 0 ? node.referencedBy : 'N/A'
      }`;
    return `<h5>Column: ${node.name}</h5><p>(SQL info)</br>dataType : ${node.dataType}</br>isNullable : ${node.isNullable}</br>charMaxLength : ${node.charMaxLength}</br>columnDefault : ${node.columnDefault}</p>`;
  }, []);

  const handleDeleteTables = (currentState, tableToExclude) => {
    const { newTables, newSchema, history } = deleteTables(currentState, tableToExclude);
    setData({ ...data, tables: newTables, schema: newSchema, tableModified: true, history });
  };

  const handleDeleteColumns = (currentState, columnToExclude, parentName, foreignKeyToDelete) => {
    const { newTables, newSchema, history } = deleteColumns(currentState, columnToExclude, parentName, foreignKeyToDelete);
    setData({ ...data, tables: newTables, schema: newSchema, tableModified: true, history });
  };

  // useEffect hook to detect successful ref mount, as well as data change
  useEffect(() => {
    if (containerRef.current) {
      if (data.tableModified) {
        // if this is an update, clear up the svg before re-run graph
        d3.select(containerRef.current).html('');
      }
      runForceGraph(containerRef.current, data, nodeHoverTooltip, handleDeleteTables, handleDeleteColumns);
    }
  }, [data.tables]);

  // create a reference to the div which will wrap the generated graph and nothing more.
  return <svg ref={containerRef} className="SVG_container" />;
}
Example #9
Source File: useLocalStorage.js    From airboardgame with MIT License 5 votes vote down vote up
useLocalStorage = (key, initialValue) => {
  const [[loaded, storedValue], setStoredValue] = useRecoilState(
    localStorageFamily(key)
  );

  React.useEffect(() => {
    if (!loaded) {
      try {
        // Get from local storage by key
        const item = window.localStorage.getItem(key);

        if (item === null) {
          // If missing we add it
          window.localStorage.setItem(key, JSON.stringify(initialValue));
          setStoredValue([true, initialValue]);
        }
        setStoredValue([true, JSON.parse(item)]);
      } catch (error) {
        // If error also return initialValue
        console.log(error);
        setStoredValue([true, initialValue]);
      }
    }
  }, [initialValue, key, loaded, setStoredValue]);

  // Return a wrapped version of useState's setter function that ...
  // ... persists the new value to localStorage.
  const setValue = React.useCallback(
    (value) => {
      try {
        // Save state
        setStoredValue(([, prev]) => {
          // Allow value to be a function so we have same API as useState
          const valueToStore = value instanceof Function ? value(prev) : value;

          // Save to local storage
          window.localStorage.setItem(key, JSON.stringify(valueToStore));
          return [true, valueToStore];
        });
      } catch (error) {
        // A more advanced implementation would handle the error case
        console.log(error);
      }
    },
    [key, setStoredValue]
  );

  // React on other tab modifications
  React.useEffect(() => {
    const localStorageChanged = (e) => {
      if (e.key === key) {
        setStoredValue([true, JSON.parse(e.newValue)]);
      }
    };
    window.addEventListener("storage", localStorageChanged);
    return () => {
      window.removeEventListener("storage", localStorageChanged);
    };
  }, [key, setStoredValue]);

  return [storedValue === null ? initialValue : storedValue, setValue];
}
Example #10
Source File: fetch-wrapper.js    From react-recoil-jwt-authentication-example with MIT License 5 votes vote down vote up
function useFetchWrapper() {
    const [auth, setAuth] = useRecoilState(authAtom);

    return {
        get: request('GET'),
        post: request('POST'),
        put: request('PUT'),
        delete: request('DELETE')
    };

    function request(method) {
        return (url, body) => {
            const requestOptions = {
                method,
                headers: authHeader(url)
            };
            if (body) {
                requestOptions.headers['Content-Type'] = 'application/json';
                requestOptions.body = JSON.stringify(body);
            }
            return fetch(url, requestOptions).then(handleResponse);
        }
    }
    
    // helper functions
    
    function authHeader(url) {
        // return auth header with jwt if user is logged in and request is to the api url
        const token = auth?.token;
        const isLoggedIn = !!token;
        const isApiUrl = url.startsWith(process.env.REACT_APP_API_URL);
        if (isLoggedIn && isApiUrl) {
            return { Authorization: `Bearer ${token}` };
        } else {
            return {};
        }
    }
    
    function handleResponse(response) {
        return response.text().then(text => {
            const data = text && JSON.parse(text);
            
            if (!response.ok) {
                if ([401, 403].includes(response.status) && auth?.token) {
                    // auto logout if 401 Unauthorized or 403 Forbidden response returned from api
                    localStorage.removeItem('user');
                    setAuth(null);
                    history.push('/login');
                }
    
                const error = (data && data.message) || response.statusText;
                return Promise.reject(error);
            }
    
            return data;
        });
    }    
}
Example #11
Source File: InfoPane.js    From react-builder with GNU General Public License v3.0 5 votes vote down vote up
InfoPane = () => {
  const mode = useContext(ThemeContext);
  const themeClass = mode.theme === DARK ? mode.theme : null;
  const [,setHighlight] = useRecoilState(highlightAtom);
  const windowSize = useWindowSize();
  const handleHighlight = (num) => {
    setHighlight(num);
    setTimeout(() => {
      setHighlight(0)
    }, 1000);
  }
  return (
    <div className={`InfoPane ${themeClass} ${isMobile && "mobileInfoPane"}`}>
      <div className="header">
        <h1>
          <img src={require("../assets/logo.png")} alt="React-Builder-Logo" />{" "}
          React Builder
        </h1>
        <img
          className={`toggleTheme ${themeClass}`}
          src={require("../assets/day-and-night.svg")}
          alt="Theme-Toggle-Button"
          onClick={mode.toggleTheme}
        ></img>
      </div>
      <div className="container-info">
        <div className="main">
          Want to create a React App Super fast with less steps?
        </div>

        <p>
          You can create a react app with few simple steps. <br />
          <br />
          This is a simple tool that helps you to quikcly create components and
          pages in your react app with your preffered component type(Functional
          or Class Based) <br /> <br />
          You can also integrate Routing with predefined Navigation bar and
          routing done in App{" "}
        </p>

        <div className={`box ${themeClass}`}>
          {!isMobile ? (
            <>
              <h4>Instructions</h4>
              <div className="instruction-cards">
                <div className="instruction-cards-item" onClick={() => handleHighlight(1)}>
                  <div className="instruction-cards-item-subheading">Step 1</div> Choose the desired settings
                  on {windowSize.width <= 768 ? "bottom" : "right"} pane
                </div>
                <div className="instruction-cards-item" onClick={() => handleHighlight(2)}>  
                  <div className="instruction-cards-item-subheading">Step 2</div> When you click the Create App button, a js file and a script will be downloaded and shown.
                </div>
                <div className="instruction-cards-item nopointer">
                  <div className="instruction-cards-item-subheading">Step 3</div>Place that js script in the
                  folder you want to create react app
                </div>
                <div className="instruction-cards-item nopointer">
                  <div className="instruction-cards-item-subheading">Step 4</div>Run that script in that
                  folder.
                </div>
              </div>
            </>
          ) : (
            <h4>Open this website in a desktop browser to access it.</h4>
          )}
        </div>
      </div>
      {isMobile && (
        <div className="githubMetrics">
          <GithubMetrics />
        </div>
      )}
      <h4 className="madeBy">Made with love by Aman Jagdev</h4>
    </div>
  );
}
Example #12
Source File: PlaygroundSettings.js    From basis with MIT License 5 votes vote down vote up
function PlaygroundSettings() {
  const theme = useTheme();
  const [screens, setScreens] = useRecoilState(screensState);
  const setComponentPreviewCounter = useSetRecoilState(
    componentPreviewCounterState
  );

  return (
    <Container bg="grey.t03" height="100%">
      <div
        css={{
          display: "flex",
          flexDirection: "column",
          height: "100%",
          overflowY: "auto",
        }}
      >
        <Text textStyle="subtitle2" margin="4 6 0">
          Screens
        </Text>
        <div css={{ flexGrow: 1, minHeight: 0 }}>
          <List
            lockVertically
            values={screens}
            onChange={({ oldIndex, newIndex }) => {
              setComponentPreviewCounter(
                (componentPreviewCounter) => componentPreviewCounter + 1
              );
              setScreens(arrayMove(screens, oldIndex, newIndex));
            }}
            renderList={({ children, props }) => (
              <ul
                css={{
                  boxSizing: "border-box",
                  margin: 0,
                  padding: `${theme.space[1]} ${theme.space[6]} 0`,
                  overflowY: "auto",
                }}
                {...props}
              >
                {children}
              </ul>
            )}
            renderItem={({ isDragged, value, props }) => (
              <PlaygroundScreenSettings
                isDragged={isDragged}
                id={value.id}
                name={value.name}
                width={value.width}
                {...props}
              />
            )}
          />
          <PlaygroundNewScreenSettings />
        </div>
      </div>
    </Container>
  );
}
Example #13
Source File: SelectionInfo.js    From recoil-paint with MIT License 5 votes vote down vote up
export default function SelectionInfo() {
  const [selectedItems, setSelectedItems] = useRecoilState(selectedItemsSelector);

  const updateSelectedItem = useCallback((name, value) => {
    setSelectedItems([{...selectedItems[0], [name]: value}])
  }, [selectedItems, setSelectedItems]);

  if (selectedItems.length !== 1) {
    return null;
  }

  const selectedItem = selectedItems[0];


  return (
    <View style={styles.root}>
      <View style={styles.row}>
        <Text>Selection:</Text>
      </View>
      <View style={styles.row}>
        <View style={styles.column}>
          <Text style={styles.bold}>X</Text>
          <NumberInput
            value={selectedItem.x}
            style={styles.input}
            onChangeNumber={number => updateSelectedItem('x', number)}
          />
        </View>
        <View style={styles.columnSpace} />
        <View style={styles.column}>
          <Text style={styles.bold}>Y</Text>
          <NumberInput
            value={selectedItem.y}
            style={styles.input}
            onChangeNumber={number => updateSelectedItem('y', number)}
          />
        </View>
      </View>
      {['image'].indexOf(selectedItem.type) === -1 && (
        <View style={styles.labelRow}>
          <Text style={styles.bold}>Label:</Text>
          <TextInput
            value={selectedItem.label}
            style={styles.input}
            onChangeText={text => updateSelectedItem('label', text)}
          />
        </View>
      )}
    </View>
  );
}
Example #14
Source File: Settings.js    From react-builder with GNU General Public License v3.0 4 votes vote down vote up
Settings = () => {
  //State Management
  const [route, setRoute] = useRecoilState(routeAtom);
  const environment = useRecoilValue(environmentAtom);
  const [projectName, setProjetctName] = useRecoilState(projectNameAtom);
  const [components, setComponents] = useRecoilState(componentsAtom);
  const [buildTool, setBuildTool] = useRecoilState(buildToolAtom);
  const [dependencies, setDependencies] = useRecoilState(dependenciesToAddAtom);
  const highlight = useRecoilValue(highlightAtom);
  const [script, setScript] = useState(null);
  const [isCreated, setIsCreated] = useState(false);
  const mode = useContext(ThemeContext);
  const themeClass = mode.theme === DARK ? mode.theme : null;

  const updateUserCount = () => {
    fetch(
      "https://api.countapi.xyz/update/react-builder/usedby/?amount=1"
    ).then(() => setIsCreated(true));
  };

  const handleCreateApp = () => {
    updateUserCount();
    const fileName = shortid.generate();
    createAppHelper({ environment, route, components, projectName, fileName });
    if (buildTool === "yarn") {
      setScript(
        `yarn create react-app ${projectName} && cd ${projectName} && yarn add ${dependencies} && cd .. && node ${fileName}.js && rm ${fileName}.js`
      );
    } else {
      setScript(
        `npx create-react-app ${projectName} && cd ${projectName} && npm install ${dependencies} && cd .. && node ${fileName}.js && rm ${fileName}.js`
      );
    }
  };

  const handleRouteChange = (e) => {
    e.preventDefault();
    setRoute({
      enabled: route.enabled,
      navigation: e.target.value,
    });
  };

  const handleCheckBox = () => {
    setRoute((prevState) => {
      return {
        enabled: !prevState.enabled,
        navigation: prevState.navigation,
      };
    });
  };

  const addEmptyComponent = () => {
    setComponents([
      ...components,
      {
        id: components.length,
        name: "Name",
        type: "FunctionalArrow",
        page: false,
      },
    ]);
  };

  const handleNameChange = (e, id) => {
    setComponents((prevState) => {
      let tempArray = [];
      prevState.forEach((comp) => {
        if (comp.id === id) {
          tempArray.push({
            id: comp.id,
            type: comp.type,
            page: comp.page,
            name: e.target.value,
          });
        } else {
          tempArray.push(comp);
        }
      });
      return tempArray;
    });
  };

  const handleTypeChange = (e, id) => {
    setComponents((prevState) => {
      let tempArray = [];
      prevState.forEach((comp) => {
        if (comp.id === id) {
          tempArray.push({
            id: comp.id,
            type: e.target.value,
            page: comp.page,
            name: comp.name,
          });
        } else {
          tempArray.push(comp);
        }
      });
      return tempArray;
    });
  };

  const handlePageChange = (id) => {
    setComponents((prevState) => {
      let tempArray = [];
      prevState.forEach((comp) => {
        if (comp.id === id) {
          tempArray.push({
            id: comp.id,
            type: comp.type,
            page: !comp.page,
            name: comp.name,
          });
        } else {
          tempArray.push(comp);
        }
      });
      return tempArray;
    });
  };

  const handleDelete = (id) => {
    setComponents((prevState) => {
      let tempArray = [];
      prevState.forEach((comp) => {
        if (comp.id !== id) {
          tempArray.push(comp);
        }
      });
      return tempArray;
    });
  };

  return (
    !isMobile && (
      <div className={`SettingsPane ${themeClass}`}>
        <div className="SettingsHead">
          <div>
            <h1 className="setup-app">
              <img
                src={require("../assets/gear.png")}
                className="gearIcon"
                alt="gear icon"
              />{" "}
              Setup Your App
            </h1>
          </div>
          <GithubMetrics isCreated={isCreated} setIsCreated={setIsCreated} />
        </div>
        <div className={`container-settings ${highlight === 1 && "highlight"}`}>
          <div className="env">
            <div className="form-container">
              <h4 className="head">Environment</h4>
              <select name="environment">
                <option value="create-react-app">Create React App</option>
                <option disabled value="comming-soon">
                  More comming soon
                </option>
              </select>
            </div>
          </div>

          <div className="buildtool">
            <div className="form-container">
              <h4 className="head">Build Tool</h4>
              <select
                name="buildtool"
                value={buildTool}
                onChange={(e) => setBuildTool(e.target.value)}
              >
                <option value="yarn">yarn</option>
                <option value="npx">npx</option>
              </select>
            </div>
          </div>

          <div className="projectname">
            <div className="form-container">
              <div className={`main ${themeClass}`}>
                <h4 className="head">Project Name</h4>
                <p>All small without spaces</p>
              </div>
              <input
                type="text"
                value={projectName}
                onChange={(e) => setProjetctName(e.target.value)}
              />
            </div>
          </div>

          <div className="dependencies">
            <div className="form-container">
              <div className={`main ${themeClass}`}>
                <h4 className="head">Dependencies to be added</h4>
                <p>
                  Seperated by spaces <br /> Do not remove react-router-dom if
                  routing enabled
                </p>
              </div>
              <input
                type="text"
                value={dependencies}
                onChange={(e) => setDependencies(e.target.value)}
              />
            </div>
          </div>

          <div className={`route ${themeClass}`}>
            <h4 className="head">Routing</h4>
            <p>Done using react-router-dom</p>
            <div className="route-flex">
              <div className="enabled">
                <div className="head">Enable </div>
                <input
                  type="checkbox"
                  onChange={() => handleCheckBox()}
                  defaultChecked={route.enabled}
                />
              </div>
              <div className="navigation">
                <div className="head">Navigation Component</div>
                <select
                  value={route.navigation}
                  onChange={(e) => handleRouteChange(e)}
                  name="route"
                >
                  {components.map(({ name, id, page }) => {
                    if (!page) {
                      return (
                        <option key={id} value={name}>
                          {name}
                        </option>
                      );
                    } else {
                      return null;
                    }
                  })}
                </select>
              </div>
            </div>
          </div>

          <div className="components">
            <div className="head-flex">
              <h4 className="head">Components</h4>
              <button onClick={() => addEmptyComponent()}>+</button>
            </div>

            <div className="headers-flex">
              <div className="name">Name</div>
              <div className="type">Type</div>
              <div className="page">Page</div>
              <div className="delete"></div>
            </div>

            <div className="all-comps">
              {components.map(({ id, name, type, page }) => (
                <React.Fragment key={id}>
                  <div className="input-comp">
                    <input
                      type="text"
                      onChange={(e) => handleNameChange(e, id)}
                      value={name}
                    />
                    <select
                      onChange={(e) => handleTypeChange(e, id)}
                      value={type}
                    >
                      <option value="FunctionalArrow">FunctionalArrow</option>
                      <option value="Functional">Functional</option>
                      <option value="ClassStateFul">ClassStateFul</option>
                      <option value="ClassStateLess">ClassStateLess</option>
                    </select>
                    <input
                      type="checkbox"
                      onChange={() => handlePageChange(id)}
                      defaultChecked={page}
                    />
                    <DeleteIcon
                      className="delete-icon"
                      fill="currentColor"
                      onClick={() => handleDelete(id)}
                    />
                  </div>
                </React.Fragment>
              ))}
            </div>
          </div>
        </div>

        <div className="create-app-container">
          <button className={`create-app-btn ${highlight === 2 && "highlight"}`} onClick={() => handleCreateApp()}>
            {" "}
            Create App
          </button>

          {script && (
            <div className={`script ${themeClass}`}>
              <code>{script}</code>
            </div>
          )}
        </div>
      </div>
    )
  );
}
Example #15
Source File: index.js    From basis with MIT License 4 votes vote down vote up
function Playground() {
  const theme = useTheme();
  const [code, setCode] = useRecoilState(codeState);
  const debouncedCode = useDebounce(code, 500);
  const liveProviderProps = useMemo(
    () => ({
      code: debouncedCode,
      noInline: getReactLiveNoInline(debouncedCode),
    }),
    [debouncedCode]
  );
  const [screens, setScreens] = useRecoilState(screensState);
  const initialCodePanelHeight = useLocalStorageValue(
    LOCAL_STORAGE_CODE_PANEL_HEIGHT_KEY,
    "40vh"
  );
  const [codePanelHeight, setCodePanelHeight] = useState(null);
  const codePanelHeightOnResizeStart = useRef();
  const onCodePanelResizeStop = () => {
    try {
      localStorage &&
        localStorage.setItem(
          LOCAL_STORAGE_CODE_PANEL_HEIGHT_KEY,
          JSON.stringify(codePanelHeight)
        );
    } catch (error) {
      console.error(`Saving in localStorage failed: ${error.message}`);
    }
  };

  useEffect(() => {
    if (initialCodePanelHeight !== null) {
      setCodePanelHeight(initialCodePanelHeight);
    }
  }, [initialCodePanelHeight]);

  useEffect(() => {
    const dataFromUrl = getPlaygroundDataFromUrl();
    const initialCode = dataFromUrl.code ?? defaultCode;
    const initialScreens =
      dataFromUrl.settings?.screens ?? Object.entries(theme.breakpoints);

    setCode(initialCode);
    setScreens(
      initialScreens.map(([bp, width]) => ({
        id: bp,
        name: bp,
        width: parseInt(width, 10),
      }))
    );
  }, [theme, setCode, setScreens]);

  if (codePanelHeight === null) {
    return null;
  }

  return (
    <LiveProvider
      {...liveProviderProps}
      transformCode={annotateCodeForPlayground}
      scope={allDesignSystem}
      theme={reactLiveEditorTheme}
    >
      <Grid height="100vh" rows={`1fr ${codePanelHeight}`}>
        <Grid.Item>
          <Container height="100%" bg="grey.t03" overflow="auto">
            <div
              css={{
                display: "flex",
                boxSizing: "border-box",
                padding: theme.space[8],
                width: "min-content", // Without it, right padding is not visible. See also: https://stackoverflow.com/q/10054870/247243
                height: "100%",
              }}
            >
              {screens.map(
                ({ id, name, width, document, componentsLocation }, index) => (
                  <div
                    css={{
                      display: "flex",
                      marginLeft: index === 0 ? null : theme.space[8],
                    }}
                    key={id}
                  >
                    <PlaygroundScreen
                      id={id}
                      name={name}
                      width={width}
                      document={document}
                      componentsLocation={componentsLocation}
                    />
                  </div>
                )
              )}
            </div>
          </Container>
        </Grid.Item>
        {codePanelHeight !== null && (
          <Grid.Item>
            <Resizable
              size={{ height: codePanelHeight }}
              onResizeStart={() => {
                codePanelHeightOnResizeStart.current = codePanelHeight;
              }}
              onResize={(e, direction, ref, d) => {
                setCodePanelHeight(
                  heightToVh(
                    vhToHeight(codePanelHeightOnResizeStart.current) + d.height
                  )
                );
              }}
              onResizeStop={onCodePanelResizeStop}
              minHeight="10vh"
              maxHeight="90vh"
              enable={{
                top: true,
                right: false,
                bottom: false,
                left: false,
                topRight: false,
                bottomRight: false,
                bottomLeft: false,
                topLeft: false,
              }}
            >
              <PlaygroundCodePanel />
            </Resizable>
          </Grid.Item>
        )}
      </Grid>
    </LiveProvider>
  );
}
Example #16
Source File: PlaygroundScreenSettings.js    From basis with MIT License 4 votes vote down vote up
function PlaygroundScreenSettingsRender(
  // eslint-disable-next-line react/prop-types
  { isDragged, id, name, width, ...rest },
  ref
) {
  const { style, ...restWithoutStyle } = rest;
  const theme = useTheme();
  const [screens, setScreens] = useRecoilState(screensState);
  const isNameValid = useCallback(
    (name) => validateScreenName(name, id, screens) === null,
    [id, screens]
  );
  const isWidthValid = (width) => validateScreenWidth(width) === null;
  const [localName, setLocalName] = useState(name);
  const [isLocalNameValid, setIsLocalNameValid] = useState(() =>
    isNameValid(name)
  );
  const [localWidth, setLocalWidth] = useState(String(width));
  const [isLocalWidthValid, setIsLocalWidthValid] = useState(() =>
    isWidthValid(localWidth)
  );
  const onLocalNameChange = (e) => {
    const newName = e.target.value;
    const isValid = isNameValid(newName);

    setLocalName(newName);
    setIsLocalNameValid(isValid);

    if (isValid) {
      setScreens((screens) => updateItemWithId(screens, id, { name: newName }));
    }
  };
  const onLocalWidthChange = (e) => {
    const newWidth = e.target.value;
    const isValid = isWidthValid(newWidth);

    setLocalWidth(newWidth);
    setIsLocalWidthValid(isValid);

    if (isValid) {
      setScreens((screens) =>
        updateItemWithId(screens, id, { width: Number(newWidth) })
      );
    }
  };

  useEffect(() => {
    setLocalName(name);
    setIsLocalNameValid(isNameValid(name));
  }, [name, isNameValid]);

  useEffect(() => {
    const newLocalWidth = String(width);

    setLocalWidth(newLocalWidth);
    setIsLocalWidthValid(isWidthValid(newLocalWidth));
  }, [width]);

  return (
    <li
      css={{
        ...style,
        display: "flex",
        alignItems: "center",
        listStyleType: "none",
        height: "36px",
        borderRadius: 2,
      }}
      ref={ref}
      {...restWithoutStyle}
    >
      <button
        css={{
          display: "flex",
          backgroundColor: "transparent",
          border: 0,
          padding: 0,
          margin: 0,
          cursor: isDragged ? "grabbing" : "grab",
        }}
        data-movable-handle
        tabIndex={-1}
      >
        <svg width="24" height="24" viewBox="0 0 24 24">
          <path
            fill="#777"
            d="M11 18c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2zm-2-8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6 4c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"
          />
        </svg>
      </button>
      <div css={{ marginLeft: theme.space[1] }}>
        <PlaygroundSettingsInput
          value={localName}
          onChange={onLocalNameChange}
          isValid={isLocalNameValid}
          ariaLabel="Screen name"
          width={100}
        />
      </div>
      <div css={{ marginLeft: theme.space[2] }}>
        <PlaygroundSettingsInput
          value={localWidth}
          onChange={onLocalWidthChange}
          isValid={isLocalWidthValid}
          variant="numeric"
          maxLength="4"
          min={MIN_SCREEN_WIDTH}
          max={MAX_SCREEN_WIDTH}
          ariaLabel="Screen width"
          width={50}
        />
      </div>
      <div css={{ display: "flex", marginLeft: theme.space[2] }}>
        <PlaygroundSettingsButton
          width={22}
          title="Remove screen"
          onClick={() => {
            setScreens((screens) => removeItemWithId(screens, id));
          }}
        >
          ✕
        </PlaygroundSettingsButton>
      </div>
    </li>
  );
}
Example #17
Source File: PersoniumAppWrapper.js    From app-personium-trails with Apache License 2.0 4 votes vote down vote up
export function PersoniumAppWrapper(props) {
  const login = useRecoilValue(isLogin);
  const barInstalled = useRecoilValue($barInstalled);
  const [authInfo, setAuthInfo] = useRecoilState($authInfo);
  const setLocalMode = useSetRecoilState($localMode);
  const history = useHistory();

  useEffect(() => {
    console.log('mounted PersoniumAppWrapper');

    // ToDo: Set initialState in RecoilRoot
    const isLocalMode =
      //  false;
      location.hostname === 'localhost' || location.hostname === '127.0.0.1';

    setLocalMode(isLocalMode);

    // Boot Script
    const currentHash = location.hash.replace(/^#\/?/g, '#');
    console.log({ currentHash });

    let targetCell = null;

    if (currentHash.startsWith('#cell')) {
      // boot from Home App
      const [target] = currentHash
        .replace(/^#\/?/g, '')
        .split('&')
        .map(kv => kv.split('='))
        .filter(([k]) => k === 'cell');

      if (target) {
        targetCell = target[1];
        history.push('/');
      } else {
        throw `Something is wrong. Is hash wrong? ${currentHash}`;
      }
    } else {
      // boot directly
      // nextPath = currentHash;
      const lastLoginCell = localStorage.getItem(LS_LAST_LOGIN_CELL);
      targetCell = lastLoginCell ? lastLoginCell : null;
    }

    // oauth redirected
    const url = new URL(location.href);
    if (
      url.searchParams.has('cellUrl') &&
      url.searchParams.has('code') &&
      url.searchParams.has('state')
    ) {
      setAuthInfo({
        cellUrl: url.searchParams.get('cellUrl'),
        code: url.searchParams.get('code'),
        state: url.searchParams.get('state'),
      });
      url.searchParams.delete('cellUrl');
      url.searchParams.delete('code');
      url.searchParams.delete('state');
      window.history.replaceState({}, document.title, url.toString());
    } else {
      setAuthInfo(targetCell !== null ? { cellUrl: targetCell } : null);
    }

    // if (!targetCell) {
    //   // targetCell unknown
    //   setError({ message: 'Launch this app from your Home App again.' });
    //   return () => {};
    // }
  }, []);

  if (login && barInstalled === true) return props.children;

  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        height: '100vh',
        flexDirection: 'column',
      }}
    >
      <div style={{ flexGrow: 1 }} />
      {(() => {
        if (authInfo === null) return <PersoniumCellURL />;

        // attempt to login
        return (
          <>
            <PersoniumLoading />
            {(() => {
              if (!login) return <PersoniumAuthentication />;
              if (!barInstalled) return <PersoniumBarInstaller />;
            })()}
          </>
        );
      })()}
      <div style={{ flexGrow: 1 }} />
    </div>
  );
}
Example #18
Source File: PersoniumBarInstaller.js    From app-personium-trails with Apache License 2.0 4 votes vote down vote up
export function PersoniumBarInstaller() {
  const [installStatus, setInstallStatus] = useRecoilState($installStatus);
  const [installing, setInstalling] = useRecoilState($installing);
  const setBarInstalled = useSetRecoilState($barInstalled);

  const handleClick = useCallback(async () => {
    let pollingStatusID = -1;

    function updateInstallStatus(text) {
      setInstallStatus(c => [...c, { time: Date.now(), text }]);
    }

    if (authState.accessToken.access_token === undefined) {
      setInstalling(true);
      return () => {
        setInstalling(false);
      };
    }
    if (installing) return;

    setInstalling(true);

    const { access_token } = authState.accessToken;

    const res = await fetch(
      'https://app-personium-trails.appdev.personium.io/__/app-personium-trails.bar'
    );
    if (res.status !== 200) {
      throw new Error('Downloading Barfile is failed');
    }

    // download to memory
    const buff = await res.arrayBuffer();
    console.log(`Downloaded ${buff.byteLength} bytes`);

    const boxURL = `${authState._targetCell}app-personium-trails`;

    const sendRes = await fetch(boxURL, {
      method: 'MKCOL',
      body: buff,
      headers: {
        Authorization: `Bearer ${access_token}`,
        'Content-Type': 'application/zip',
      },
      redirect: 'manual',
    });
    if (sendRes.status === 202) {
      // Accepted
      // const boxStatusURL = sendRes.headers.get('location');
      pollingStatusID = setInterval(async () => {
        const boxStatus = await fetch(boxURL, {
          headers: {
            Authorization: `Bearer ${access_token}`,
          },
        }).then(res => res.json());

        const statusText =
          boxStatus.box.status === 'ready'
            ? boxStatus.box.status
            : `${boxStatus.box.status} ${boxStatus.box.progress}`;

        updateInstallStatus(statusText);
        if (boxStatus.box.status === 'ready') {
          clearInterval(pollingStatusID);

          // update boxURL
          authState
            .updateBoxUrl()
            .then(() => {
              console.log('bar installation is done');
              setBarInstalled(true);
            })
            .catch(res => {
              console.log('bar installation is failed', res);
              setBarInstalled(false);
            });
        }
      }, 500);
    } else {
      const err = await sendRes.json();
      updateInstallStatus(err.message.value);
    }
  }, [installing, setInstallStatus, setInstalling, setBarInstalled]);

  if (authState.accessToken === null) {
    return <h1>Login First</h1>;
  }
  return (
    <>
      <h1>Install Application</h1>
      <div>
        <button onClick={handleClick} disabled={installing}>
          Start Install
        </button>
      </div>
      <div>
        {installStatus.map(item => {
          return <p key={`installation-status-${item.time}`}>{item.text}</p>;
        })}
      </div>
    </>
  );
}
Example #19
Source File: PlaygroundNewScreenSettings.js    From basis with MIT License 4 votes vote down vote up
function PlaygroundNewScreenSettings() {
  const theme = useTheme();
  const [screens, setScreens] = useRecoilState(screensState);
  const [name, setName] = useState("");
  const [isNameValid, setIsNameValid] = useState(true);
  const [width, setWidth] = useState("");
  const [isWidthValid, setIsWidthValid] = useState(true);
  const [error, setError] = useState(null);
  const onSubmit = (e) => {
    e.preventDefault();

    const nameError = validateScreenName(name, null, screens);
    const widthError = validateScreenWidth(width);

    setIsNameValid(nameError === null);
    setIsWidthValid(widthError === null);

    if (nameError === null && widthError === null) {
      const cleanName = name.trim();
      const widthInt = Number(width);

      setScreens((screens) =>
        screens.concat({
          id: cleanName,
          name: cleanName,
          width: widthInt,
        })
      );

      setName("");
      setWidth("");
      setError(null);

      return;
    }

    setError(getErrorsFrom([nameError, widthError]));
  };

  return (
    <form
      css={{
        paddingLeft: theme.space[11],
        paddingRight: theme.space[6],
      }}
      onSubmit={onSubmit}
      noValidate
    >
      <div
        css={{
          display: "flex",
          alignItems: "center",
          height: "36px",
        }}
      >
        <div css={{ marginLeft: theme.space[1] }}>
          <PlaygroundSettingsInput
            value={name}
            onChange={(e) => {
              setName(e.target.value);
            }}
            isValid={isNameValid}
            ariaLabel="New screen name"
            width={100}
          />
        </div>
        <div css={{ marginLeft: theme.space[2] }}>
          <PlaygroundSettingsInput
            value={width}
            onChange={(e) => {
              setWidth(e.target.value);
            }}
            isValid={isWidthValid}
            variant="numeric"
            maxLength="4"
            min={MIN_SCREEN_WIDTH}
            max={MAX_SCREEN_WIDTH}
            ariaLabel="New screen width"
            width={50}
          />
        </div>
        <div css={{ display: "flex", marginLeft: theme.space[2] }}>
          <PlaygroundSettingsButton type="submit" width={48}>
            Add
          </PlaygroundSettingsButton>
        </div>
      </div>
      {error && (
        <div css={{ marginLeft: theme.space[1] }}>
          <Text textStyle="body2" color="conditional.negative.text">
            {error}
          </Text>
        </div>
      )}
    </form>
  );
}
Example #20
Source File: PlaygroundCodePanel.js    From basis with MIT License 4 votes vote down vote up
function PlaygroundCodePanel() {
  const theme = useTheme();
  const isCanary = useCanary();
  const [isInspectMode, setIsInspectMode] = useRecoilState(isInspectModeState);
  const [code, setCode] = useRecoilState(codeState);
  const [screens, setScreens] = useRecoilState(screensState);
  const [isSaved, setIsSaved] = useState(false);
  const [areSettingsOpen, setAreSettingsOpen] = useState(false);
  const settingsRef = useRef();
  const updateComponentsLocation = useCallback(() => {
    setScreens((screens) =>
      screens.map((screen) => ({
        ...screen,
        componentsLocation: getComponentsLocation(screen.document),
      }))
    );
  }, [setScreens]);

  useEffect(() => {
    if (isInspectMode) {
      updateComponentsLocation();
    }
  }, [isInspectMode, updateComponentsLocation]);

  return (
    <div
      css={{
        display: "flex",
        flexDirection: "column",
        height: "100%",
        boxSizing: "border-box",
        position: "relative",
      }}
    >
      <div
        css={{
          display: "flex",
          flexShrink: 0,
          padding: `${theme.space[2]} ${theme.space[8]}`,
          backgroundColor: theme.colors.grey.t05,
          borderTop: `${theme.borderWidths[0]} solid ${theme.colors.grey.t16}`,
          borderBottom: `${theme.borderWidths[0]} solid ${theme.colors.grey.t16}`,
        }}
      >
        <Stack direction="horizontal" gap="4">
          {isCanary && (
            <Button
              variant="icon"
              onClick={() => {
                setIsInspectMode((isInspectMode) => !isInspectMode);
              }}
            >
              <Icon
                name="select-object"
                size="24px"
                color={isInspectMode ? "highlight.blue.t100" : "grey.t75"}
                hoverColor={isInspectMode ? "highlight.blue.t100" : "black"}
              />
            </Button>
          )}
          <Button
            variant="secondary"
            width="88"
            onClick={() => {
              setCode(prettify(code));
            }}
          >
            Prettify
          </Button>
          <Button
            variant="secondary"
            width="88"
            disabled={isSaved}
            onClick={() => {
              navigate(
                getPlaygroundUrl({
                  code,
                  settings: {
                    screens: screens.map(({ name, width }) => [name, width]),
                  },
                })
              );

              setIsSaved(true);

              setTimeout(() => {
                setIsSaved(false);
              }, 1000);
            }}
          >
            {isSaved ? "Saved!" : "Save"}
          </Button>
          <Button
            variant="secondary"
            width="88"
            onClick={() => {
              const previewUrl = getPreviewUrl(code);

              window.open(previewUrl, "_blank");
            }}
          >
            Preview
          </Button>
        </Stack>
        <div css={{ flexShrink: 0, marginLeft: "auto" }}>
          <Button
            variant="secondary"
            width="88"
            onClick={() => {
              setAreSettingsOpen((areSettingsOpen) => !areSettingsOpen);
            }}
          >
            Settings
          </Button>
        </div>
      </div>
      <div
        css={{
          display: "flex",
          position: "relative",
          flexGrow: 1,
          minHeight: 0, // This ensures that, when there is a lot of code, this div isn't growing beyond what we want.
        }}
      >
        <div
          css={{
            padding: `${theme.space[4]} ${theme.space[8]}`,
            width: "100%",
            overflow: "auto",
            "textarea:focus": {
              outline: "none",
            },
          }}
        >
          <VisuallyHidden>
            <label htmlFor="code-editor">Code Editor</label>
          </VisuallyHidden>
          <LiveEditor
            textareaId="code-editor"
            padding={0}
            style={{ minHeight: "100%" }}
            onChange={setCode}
          />
        </div>
        {areSettingsOpen && (
          <div
            css={{
              position: "absolute",
              left: 0,
              top: 0,
              right: 0,
              bottom: 0,
              backgroundColor: "rgba(255, 255, 255, 0.7)",
            }}
            role="button"
            tabIndex="0"
            onKeyDown={(e) => {
              if (
                e.target === e.currentTarget &&
                (e.key === " " || e.key === "Enter")
              ) {
                setAreSettingsOpen(false);
              }
            }}
            onClick={(e) => {
              if (!settingsRef.current.contains(e.target)) {
                setAreSettingsOpen(false);
              }
            }}
          >
            <div
              css={{
                position: "absolute",
                top: 0,
                bottom: 0,
                right: 0,
                width: "320px",
                maxWidth: "100vw",
                boxSizing: "border-box",
                borderLeft: `${theme.borderWidths[0]} solid ${theme.colors.grey.t16}`,
              }}
              ref={settingsRef}
            >
              <PlaygroundSettings />
            </div>
          </div>
        )}
      </div>
      <PlaygroundCodeError />
    </div>
  );
}
Example #21
Source File: DashboardDoc.js    From HealthBridge with GNU General Public License v3.0 4 votes vote down vote up
DashboardDoc = ({ history }) => {
	const token = useRecoilValue(tokenAtom);
	const [user, setUser] = useRecoilState(userAtom);

	//State
	const [symptoms, setSymptoms] = useState("");
	const [medicine, setMedicine] = useState("");
	const [comments, setComments] = useState("");
	const [current, setCurrent] = useState("");

	const givePrescription = (pID, objID) => {
		Axios.post(
			`${process.env.REACT_APP_API_URL}/prescription/give`,
			{
				patientId: pID,
				symptoms,
				medicine,
				objID,
				comments,
				date: Date.now(),
			},
			{
				headers: {
					Authorization: "Bearer " + token,
				},
			}
		)
			.then((res) => {
				console.log(res.data, "give pres");
				// setUser(res.data);
				// localStorage.setItem("user", JSON.stringify(res.data));
			})
			.catch((err) => {
				console.error(err);
			});
	};

	useEffect(() => {
		Axios.get(`${process.env.REACT_APP_API_URL}/appointment/upcoming`, {
			headers: {
				Authorization: "Bearer " + token,
			},
		})
			.then((res) => {
				setUser(res.data);
				localStorage.setItem("user", JSON.stringify(res.data));
			})
			.catch((err) => {
				console.error(err);
			});
	}, []);

	const toggleCurrent = (_id) => {
		if (current === _id) {
			setCurrent("");
		} else {
			setCurrent(_id);
		}
	};
	return (
		<div className="DashboardDoc">
			<div className="container">
				<h1>Welcome Doctor</h1>
				<h3>Your Appointments</h3>
				<div className="cards">
					{user.appointments &&
						user.appointments.map((appointment) => (
							<div className="card" key={appointment._id}>
								<div className="head">
									Appointment No :{" "}
									{appointment.patient.substring(14)}
								</div>
								<div className="content">
									<h4> </h4>
									<p>Symptopms : {appointment.symptoms}</p>
								</div>

								<div className="box">
									<div className="box1"></div>
									<div className="box2"></div>
									<div className="box3"></div>
								</div>

								<div className="prescribe-input">
									<div className="edit-prescribe">
										<div className="head">Prescribe</div>{" "}
										<img
											onClick={() =>
												toggleCurrent(appointment._id)
											}
											src="https://img.icons8.com/cotton/2x/edit.png"
											alt="Edit Icon"
										/>
									</div>
									{appointment._id === current && (
										<React.Fragment>
											<label>Symptoms</label>
											<input
												type="text"
												value={symptoms}
												onChange={(e) =>
													setSymptoms(e.target.value)
												}
											/>
											<label>Medicine</label>
											<input
												type="text"
												value={medicine}
												onChange={(e) =>
													setMedicine(e.target.value)
												}
											/>
											<label>Comments</label>
											<input
												type="text"
												value={comments}
												onChange={(e) =>
													setComments(e.target.value)
												}
											/>
											<button
												className="primary"
												onClick={() =>
													givePrescription(
														appointment.patient,
														appointment._id
													)
												}>
												Update
											</button>
										</React.Fragment>
									)}
								</div>
								<div className="box">
									<div className="box1"></div>
									<div className="box2"></div>
									<div className="box3"></div>
								</div>
								{appointment.prescription && (
									<React.Fragment>
										<div className="head">Prescribed</div>
										<div className="prescribed">
											<div className="presc">
												<strong>Symptoms</strong> :{" "}
												{
													appointment.prescription
														.symptoms
												}{" "}
											</div>
											<div className="presc">
												<strong>Medicine</strong> :{" "}
												{
													appointment.prescription
														.medicine
												}{" "}
											</div>
											<div className="presc">
												<strong>Comments</strong> :{" "}
												{
													appointment.prescription
														.comments
												}{" "}
											</div>
										</div>
									</React.Fragment>
								)}
							</div>
						))}
				</div>
			</div>
		</div>
	);
}
Example #22
Source File: Login.js    From HealthBridge with GNU General Public License v3.0 4 votes vote down vote up
Login = ({ history }) => {
	const [email, setEmail] = useState("");
	const [, setUser] = useRecoilState(userAtom);
	const [, setToken] = useRecoilState(tokenAtom);
	const [password, setPassword] = useState("");
	const [errors, setErrors] = useState(null);
	const [selected, setSelected] = useState("user");

	var env = process.env.REACT_APP_API_URL;
	console.log(env);


	const handleLoginUser = () => {
		Axios.post(`${env}/patient/signin`, {
			email,
			password,
		})
			.then((res) => {
				if (res.data.error) {
					setErrors([{ msg: res.data.error }]);
				} else {
					localStorage.setItem(
						"user",
						JSON.stringify(res.data.patient)
					);
					localStorage.setItem("token", res.data.token);
					setUser(res.data.patient);
					setToken(res.data.token);
					history.push("/dashboard");
				}
			})
			.catch((err) => {
				if (Array.isArray(err.response.data.errors)) {
					setErrors(err.response.data.errors);
				} else {
					setErrors([{ msg: err.response.data.error }]);
				}
			});
	};

	const handleLoginDoc = () => {
		Axios.post(`${env}/doctor/signin`, {
			email,
			password,
		})
			.then((res) => {
				if (res.data.error) {
					setErrors([{ msg: res.data.error }]);
				} else {
					console.log(res.data);
					localStorage.setItem(
						"user",
						JSON.stringify(res.data.doctor)
					);
					localStorage.setItem("token", res.data.token);
					setUser(res.data.doctor);
					setToken(res.data.token);
					history.push("/dashboardDoc");
				}
			})
			.catch((err) => {
				if (Array.isArray(err.response.data.errors)) {
					setErrors(err.response.data.errors);
				} else {
					setErrors([{ msg: err.response.data.error }]);
				}
			});
	};
	return (
		<div className="Login">
			<div className="left-bar">
				<div className="top">
					<div onClick={() => history.push("/")}>
						<div className="logo">
							<h1>HealthBridge</h1>
						</div>
					</div>
					<p>
						Welcome to the Unified HealthCare Platform
					</p>
				</div>
				<img
					className="art"
					src={require("../assets/svg/doc2.svg")}
					alt=""
				/>
			</div>
			<div className="main-login">
				<h1>Login</h1>
				<div className="login-form">
					<label htmlFor="email">Email</label>
					<input
						type="text"
						id="email"
						value={email}
						onChange={(e) => setEmail(e.target.value)}
					/>

					<label htmlFor="pass">Password</label>
					<input
						type="password"
						id="pass"
						value={password}
						onChange={(e) => setPassword(e.target.value)}
					/>
					<button
						className="primary"
						onClick={() =>
							selected === "user"
								? handleLoginUser()
								: handleLoginDoc()
						}>
						Log In
					</button>
				</div>
				<div className="error-container">
					{errors &&
						errors.map(({ msg }, index) => (
							<div key={index} className="error">
								{msg}
							</div>
						))}
				</div>
				<div className="selector-container">
					<div className="selector">
						<button
							className="left"
							id={selected === "user" ? "selected" : ""}
							onClick={() => setSelected("user")}>
							User
						</button>
						<button
							className="right"
							id={selected === "doctor" ? "selected" : ""}
							onClick={() => setSelected("doctor")}>
							Doctor
						</button>
					</div>
				</div>
			</div>
		</div>
	);
}
Example #23
Source File: Profile.js    From HealthBridge with GNU General Public License v3.0 4 votes vote down vote up
Appointment = () => {
	const [user, setUser] = useRecoilState(userAtom);
	const [email, setEmail] = useState(user.email);
	const [password, setPassword] = useState("");
	const [fullname, setFullName] = useState(user.name);
	const [age, setAge] = useState(user.phone);
	const [phno, setPhno] = useState(user.age);
	const [address, setAddress] = useState(user.address);
	const [bloodGroup, setBloodGroup] = useState(user.bloodGroup);

	const token = useRecoilValue(tokenAtom);

	const updateProfile = () => {
		const dataTemp = {
			name: fullname,
			email,
			phone: phno,
			age,
			bloodGroup,
			address,
		};
		let updatedProfile;
		if (password === "") {
			updatedProfile = dataTemp;
		} else {
			updatedProfile = { ...dataTemp, password };
		}
		Axios.post(
			`${process.env.REACT_APP_API_URL}/patient/update`,
			updatedProfile,
			{
				headers: {
					Authorization: "Bearer " + token,
				},
			}
		)
			.then((res) => {
				console.log(res.data);
				setUser(res.data);
				localStorage.setItem("user", JSON.stringify(res.data));
			})
			.catch((err) => {
				console.error(err);
			});
	};

	return (
		<div className="Profile">
			<div className="container">
				<div>
					<h1>Your Profile</h1>
				</div>
				<div className="main">
					{/*  APPOINTMENT  */}
					<div className="appointment-info">
						<h3>Your Profile card</h3>
						<div className="cards">
							<div className="card">
								<div className="image">
									<img
										src={require("../assets/icons/profile.png")}
										alt="Image"
									/>
								</div>
								<div className="content">
									<div className="name">{user.name}</div>
									<div className="email">{user.email}</div>
									<div className="box">
										<div className="box1"></div>
										<div className="box2"></div>
										<div className="box3"></div>
									</div>
									<div className="more-details">
										<div className="age">
											<strong>Age</strong> : {user.age}
										</div>
										<div className="bg">
											<strong>Blood Group</strong> :{" "}
											{user.bloodGroup}
										</div>
										<div className="address">
											<strong>Addres </strong> :{" "}
											{user.address}
										</div>
										<div className="phone">
											<strong>Contact </strong>:{" "}
											{user.phone}
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>

					<div className="appointment-submit">
						<h3>Edit Profile</h3>
						<div className="appointment-form">
							<label htmlFor="email">Email</label>
							<input
								type="text"
								id="email"
								value={email}
								defaultValue={user.email}
								onChange={(e) => setEmail(e.target.value)}
							/>

							<label htmlFor="fullname">Full Name</label>
							<input
								type="text"
								id="fullname"
								value={fullname}
								onChange={(e) => setFullName(e.target.value)}
							/>
							<label htmlFor="phone_number">Phone Number</label>
							<input
								type="number"
								id="phone_number"
								value={phno}
								onChange={(e) => setPhno(e.target.value)}
							/>

							<label htmlFor="age">Age</label>
							<input
								type="number"
								id="age"
								value={age}
								onChange={(e) => setAge(e.target.value)}
							/>

							<label htmlFor="blood_group">Blood group</label>
							<select
								name="blood_grp"
								value={bloodGroup}
								onChange={(e) => setBloodGroup(e.target.value)}>
								<option value="AB+">AB+</option>
								<option value="AB-">AB-</option>
								<option value="A+">A+</option>
								<option value="A-">A-</option>
								<option value="B+">B+</option>
								<option value="B-">B-</option>
								<option value="O+">O+</option>
								<option value="O-">O-</option>
							</select>
							<label htmlFor="address">Address</label>
							<input
								type="text"
								id="address"
								value={address}
								onChange={(e) => setAddress(e.target.value)}
							/>
							<label htmlFor="address">New Password</label>
							<input
								type="text"
								id="password"
								value={password}
								onChange={(e) => setPassword(e.target.value)}
							/>
							<div className="helper-text">
								<p>Leave Empty if do not want to change</p>
							</div>
							<button
								className="primary"
								onClick={() => updateProfile()}>
								Update
							</button>
						</div>
					</div>
				</div>
			</div>
		</div>
	);
}
Example #24
Source File: Appointment.js    From HealthBridge with GNU General Public License v3.0 4 votes vote down vote up
Appointment = () => {
	const [doctor, setDoctor] = useState(null);
	const [symptoms, setSymptoms] = useState(null);
	const [department, setDepartment] = useState(null);
	const [appointmentDate, setAppointmentDate] = useState(new Date());

	const [user, setUser] = useRecoilState(userAtom);
	const token = useRecoilValue(tokenAtom);

	const [docs, setDocs] = useState([
		{
			_id: "5435",
			name: "None",
		},
	]);

	useEffect(() => {
		Axios.get(`${process.env.REACT_APP_API_URL}/doctor`)
			.then((res) => {
				setDocs(res.data);
			})
			.catch((err) => {
				console.error(err);
			});
	},[]);

	const handleAppointment = () => {
		Axios.post(
			`${process.env.REACT_APP_API_URL}/appointment/book`,
			{
				symptoms,
				appointmentDate,
				department,
				doctor,
			},
			{
				headers: {
					Authorization: "Bearer " + token,
				},
			}
		)
			.then((res) => {
				console.log(res.data);
				setUser(res.data);
				localStorage.setItem("user", JSON.stringify(res.data));
			})
			.catch((err) => {
				console.error(err);
			});
	};

	useEffect(() => {
		Axios.get(`${process.env.REACT_APP_API_URL}/prescription/get`, {
			headers: {
				Authorization: "Bearer " + token,
			},
		})
			.then((res) => {
				console.log(res.data);
				setUser(res.data);
				localStorage.setItem("user", JSON.stringify(res.data));
			})
			.catch((err) => {
				console.error(err);
			});
	}, []);

	return (
		<div className="Appointment">
			<div className="container">
				<div>
					<h1>Book Appointment</h1>
					<p className="content">
						Patients can book online appointments with a specific
						doctor and can get prescription afterwards.
					</p>
				</div>
				<div className="main">
					{/* FORM  */}
					<div className="appointment-submit">
						<h3>Submit your info</h3>
						<div className="appointment-form">
							<label htmlFor="symptoms">Symptoms</label>
							<input
								type="text"
								id="symptoms"
								value={symptoms}
								onChange={(e) => setSymptoms(e.target.value)}
							/>

							<label htmlFor="doctor">Doctor Name</label>
							<select
								name="blood_grp"
								value={doctor}
								onChange={(e) => setDoctor(e.target.value)}>
								{docs &&
									docs.map((doc) => (
										<option key={doc._id} value={doc.name}>
											{doc.name}
										</option>
									))}
							</select>

							<label htmlFor="department">Department</label>
							<input
								type="text"
								id="dept"
								value={department}
								onChange={(e) => setDepartment(e.target.value)}
							/>
							<label htmlFor="date">Appointment Date</label>
							<div className="date-pick">
								<input
									type="date"
									value={
										appointmentDate
											.getFullYear()
											.toString() +
										"-" +
										(appointmentDate.getMonth() + 1)
											.toString()
											.padStart(2, 0) +
										"-" +
										appointmentDate
											.getDate()
											.toString()
											.padStart(2, 0)
									}
									onChange={(e) =>
										setAppointmentDate(e.target.valueAsDate)
									}
								/>
							</div>
							<button
								className="primary"
								onClick={() => handleAppointment()}>
								Book
							</button>
						</div>
					</div>

					{/*  APPOINTMENT  */}
					{user.appointment && (
						<div className="appointment-info">
							<h3>Your Appointment</h3>
							<div className="cards">
								{user.appointment && (
									<div className="card">
										<div className="image">
											<img
												src={require("../../assets/icons/medicine.png")}
												alt="Image"
											/>
										</div>

										<div className="content">
											<h4>
												Doctor :{" "}
												{user.appointment &&
													user.appointment.doctor}
											</h4>
											<p>
												Symptoms :{" "}
												{user.appointment &&
													user.appointment.symptoms}
											</p>
											<p>
												Date :{" "}
												{user.appointment &&
													user.appointment
														.appointmentDate &&
													user.appointment.appointmentDate.substring(
														0,
														10
													)}
											</p>
											<div className="prescription">
												<div className="pres">
													Prescription From Doctor
												</div>
												<p>
													{user.appointment &&
													user.appointment
														.prescription ? (
														<div className="pres-cont">
															<div>
																<strong>
																	Real
																	Symptoms
																</strong>{" "}
																:{" "}
																{
																	user
																		.appointment
																		.prescription
																		.symptoms
																}{" "}
															</div>
															<div>
																<strong>
																	Medicine
																</strong>{" "}
																:{" "}
																{
																	user
																		.appointment
																		.prescription
																		.medicine
																}{" "}
															</div>
															<div>
																<strong>
																	Comments
																</strong>{" "}
																:{" "}
																{
																	user
																		.appointment
																		.prescription
																		.comments
																}{" "}
															</div>
														</div>
													) : (
														<div>
															<p>
																<strong>
																	Yet To
																	Presctibe
																</strong>
															</p>
														</div>
													)}
												</p>
											</div>
										</div>
									</div>
								)}
							</div>
						</div>
					)}
				</div>
			</div>
		</div>
	);
}