recoil#useRecoilValue JavaScript Examples

The following examples show how to use recoil#useRecoilValue. 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: Canvas.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function Canvas() {
  const ref = useRef();
  const itemIds = useRecoilValue(itemIdsState);
  const setLayoutState = useSetRecoilState(canvasLayoutState);

  const onLayout = ({
    nativeEvent: {
      layout: { x, y, width, height }
    }
  }) => setLayoutState({ x, y, width, height });

  return (
    <View style={styles.root} ref={ref} onLayout={onLayout}>
      <View style={styles.container}>
        <CanvasBackground />
        {itemIds.map(id => <CanvasItem key={`item-${id}`} id={id} />)}
        <Selection />
      </View>
    </View>
  );
}
Example #2
Source File: CanvasBackground.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function CanvasBackground(props) {
  const setSelectedIds = useSetRecoilState(selectedIdsState);
  const backgroundColor = useRecoilValue(backgroundColorState);

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

  return (
    <View style={[StyleSheet.absoluteFill, { backgroundColor }]} onClick={handleClick} />
  );
}
Example #3
Source File: CanvasItem.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function CanvasItem({ id }) {
  const [itemSnapshot, setItemSnapshot] = useState(null);
  const itemState = useRecoilValue(itemWithId(id));
  const setSelectedIds = useSetRecoilState(selectedIdsState);
  const updatePosition = useUpdateItem();

  const { onMouseDown } = useMove(({ status, origin, offset }) => {
    if (status === 'start') {
      setItemSnapshot(itemState);
    }

    if (status === 'moving' && itemSnapshot) {
      updatePosition({
        ...itemSnapshot,
        x: itemSnapshot.x + offset.x,
        y: itemSnapshot.y + offset.y,
      })
    }

    if (status === 'end') {
      setItemSnapshot(null);
      setSelectedIds(ids => {
        if (origin.metaKey || origin.shiftKey) {
          return [...ids, id];
        }
        return [id];
      });
    }
  });

  const Shape = createShape(itemState);
  if (!Shape) {
    return null;
  }

  return <Shape {...itemState} onMouseDown={onMouseDown} />;
}
Example #4
Source File: ItemInfo.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function ItemInfo({ id }) {
  const itemState = useRecoilValue(itemWithId(id));
  const { label, x, y } = itemState;

  return (
    <View style={styles.root}>
      {label ? <Text style={styles.label}>{label}</Text> : null}
      <Text style={styles.subLabel}>{`(x = ${x} y = ${y})`}</Text>
    </View>
  )
}
Example #5
Source File: ItemInfoList.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function ItemInfoList() {
  const itemIds = useRecoilValue(itemIdsState);

  return (
    <View style={styles.root}>
      {itemIds.map(id => <ItemInfo key={`item-info-${id}`} id={id} />)}
    </View>
  );
}
Example #6
Source File: useMoveItems.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function useMoveItems(func) {
  const [movingItemsSnapshot, setMovingItemsSnapshot] = useState([]);
  const movingItemIds = useRecoilValue(movingItemIdsState);

  const loadMovingItems = useLoadItems();
  const updateItemsPosition = useUpdateItems();

  const updateSnpashot = useCallback(async () => {
    const items = await loadMovingItems(movingItemIds);
    setMovingItemsSnapshot(items);
  }, [loadMovingItems, movingItemIds]);

  const { onMouseDown } = useMove((params) => {
    const { status, offset } = params;
    func(params);

    if (status === 'moving' && movingItemsSnapshot.length) {
      const newMovingItems = movingItemsSnapshot.map(item => {
        return {
          ...item,
          x: item.x + offset.x,
          y: item.y + offset.y,
        }
      });
      updateItemsPosition(newMovingItems);
    }
  });

  useEffect(() => {
    updateSnpashot();
  }, [movingItemIds, updateSnpashot]);

  return {
    onMouseDown
  }
}
Example #7
Source File: Nav.jsx    From react-recoil-jwt-authentication-example with MIT License 6 votes vote down vote up
function Nav() {
    const auth = useRecoilValue(authAtom);
    const userActions = useUserActions();

    // only show nav when logged in
    if (!auth) return null;
    
    return (
        <nav className="navbar navbar-expand navbar-dark bg-dark">
            <div className="navbar-nav">
                <NavLink exact to="/" className="nav-item nav-link">Home</NavLink>
                <a onClick={userActions.logout} className="nav-item nav-link">Logout</a>
            </div>
        </nav>
    );
}
Example #8
Source File: PrivateRoute.jsx    From react-recoil-jwt-authentication-example with MIT License 6 votes vote down vote up
function PrivateRoute({ component: Component, ...rest }) {
    const auth = useRecoilValue(authAtom);
    return (
        <Route {...rest} render={props => {
            if (!auth) {
                // not logged in so redirect to login page with the return url
                return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
            }

            // authorized so return component
            return <Component {...props} />
        }} />
    );
}
Example #9
Source File: Home.jsx    From react-recoil-jwt-authentication-example with MIT License 6 votes vote down vote up
function Home() {
    const auth = useRecoilValue(authAtom);
    const users = useRecoilValue(usersAtom);
    const userActions = useUserActions();

    useEffect(() => {
        userActions.getAll();
        
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return (
        <div>
            <h1>Hi {auth?.firstName}!</h1>
            <p>You're logged in with React + Recoil & JWT!!</p>
            <h3>Users from secure api end point:</h3>
            {users &&
                <ul>
                    {users.map(user =>
                        <li key={user.id}>{user.firstName} {user.lastName}</li>
                    )}
                </ul>
            }
            {!users && <div className="spinner-border spinner-border-sm"></div>}
        </div>
    );
}
Example #10
Source File: TvShowDetails.jsx    From recoil-testing with MIT License 6 votes vote down vote up
Comments = () => {

  const id = useRecoilValue(atoms.id);

  const commentsResource = getCommentsResource(id).read();
  const comments = commentsResource.map(comment => (
    <div className="comment" key={comment.id}>
      <h4>{comment.title}</h4>
      <div className="text">{comment.text}</div>
    </div>
  ));

  return (
    <div className="flex flex-col comments">
      <h3>Comments</h3>
      {comments}
    </div>
  );
}
Example #11
Source File: TvShowDetails.jsx    From recoil-testing with MIT License 6 votes vote down vote up
Details = () => {

  const id = useRecoilValue(atoms.id);

  const tvShowResource = getTvDataResource(id).read();
  return (
    <div className="flex">
      <div>
        <h2>{tvShowResource.name}</h2>
        <div className="details">{tvShowResource.description}</div>
      </div>
      <div>
        <img
          src={`https://res.cloudinary.com/dqsubx7oc/image/upload/w_200/v1582908284/tv-shows/${id}.jpg`}
          alt={tvShowResource.name}
        />
      </div>
    </div>
  );
}
Example #12
Source File: Navigation.jsx    From recoil-testing with MIT License 6 votes vote down vote up
export default function Navigation() {
    const recoilValue = useRecoilValue(textState);
    const Fetch = () => {
        fetch('/api')
        .then(data => console.log(data));
    }
    return (
        <div>
            <Suspense>
                <Fetch />
            </Suspense>
            <h1>This is my nested root component</h1>
            {recoilValue}
        </div>
    )
}
Example #13
Source File: DetailPage.js    From app-personium-trails with Apache License 2.0 6 votes vote down vote up
function LocationDataURLViewChild({ __id, locationUrl }) {
  const { updateLocationACL } = useLocationACLSubscribe(__id, locationUrl);
  const aclStatus = useRecoilValue(locationACLStatusState(__id));
  const isLoading = aclStatus === 'loading';

  const refInput = useRef(null);

  useEffect(() => {
    updateLocationACL();
  }, []);

  const onClick = useCallback(() => {
    refInput.current.select();
    document.execCommand('copy');
  }, []);

  return (
    <Form.Field disabled={isLoading}>
      <label>This location is set as `{aclStatus}`</label>
      <Input
        fluid
        disabled={aclStatus === 'private'}
        ref={refInput}
        value={locationUrl}
        action={{
          color: 'teal',
          icon: 'copy',
          labelPosition: 'right',
          content: 'Copy',
          onClick: onClick,
        }}
      />
    </Form.Field>
  );
}
Example #14
Source File: PrivateRoute.js    From HealthBridge with GNU General Public License v3.0 6 votes vote down vote up
PrivateRoute = ({ component: Component, doc, ...rest }) => {
	const user = useRecoilValue(userAtom);

	return (
		<Route
			{...rest}
			render={(props) =>
				user ? (
					doc ? (
						user.type === "doctor" ? (
							<Component {...props} />
						) : (
							<Redirect to="/" />
						)
					) : user.type === "user" ? (
						<Component {...props} />
					) : (
						<Redirect to="/" />
					)
				) : (
					<Redirect to="/login" />
				)
			}
		/>
	);
}
Example #15
Source File: Dashboard.js    From HealthBridge with GNU General Public License v3.0 6 votes vote down vote up
Dashboard = () => {
	const user = useRecoilValue(userAtom);
	return (
		<div className="Dashboard">
			<div className="container">
				<h1>Hi {user.name}</h1>
				<div className="cards">
					{services.map(({ imageAlt, title, image, desc, link }) => (
						<Card
							key={title}
							title={title}
							image={image}
							imageAlt={imageAlt}
							desc={desc}
							link={link}
						/>
					))}
					<div
						className="card"
						onClick={() => window.open("https://ambulance-on-demand.vercel.app")}>
						<div className="image">
							<img
								src={require("../assets/icons/ambulance.png")}
								alt="Ambulance"
							/>
						</div>
						<div className="content">
							<h4>Ambulance</h4>
							<p>
								A service to provide low latency and live location based ambulance service on demand.
							</p>
						</div>
					</div>
				</div>
			</div>
		</div>
	);
}
Example #16
Source File: StateProvider.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
export default function StateProvider({ children }) {
  const authentication = useRecoilValue(authenticationState);

  useEffect(() => {
    const persistenceItems = createStore(authentication);
    store = persistenceItems.store;
    persistor = persistenceItems.persistor;

    store.dispatch({
      type: actionTypes.SET_AUTH,
      payload: authentication,
    });
    return () => {
      persistor.flush().then(() => {
        persistor.pause();
        store.dispatch({
          type: actionTypes.CLEAR_PATIENT_DATA,
        });
        store = null;
        persistor = null;
      });
    };
  }, [authentication]);

  if (!store) {
    return <LoadingIndicator />;
  }

  return (
    <Provider store={store}>
      <PersistGate
        loading={<LoadingIndicator />}
        persistor={persistor}
      >
        { children }
      </PersistGate>
    </Provider>
  );
}
Example #17
Source File: Selection.js    From recoil-paint with MIT License 5 votes vote down vote up
export default function Selection() {
  const selectedIds = useRecoilValue(selectedIdsState);
  const selection = useRecoilValue(selectionBoundingBox);
  const setMovingItemIds = useSetRecoilState(movingItemIdsState);

  const { onMouseDown } = useMoveItems(({ status }) => {
    if (!selection) {
      return null;
    }

    if (status === 'start') {
      setMovingItemIds(selectedIds)
    }

    if (status === 'end') {
      setMovingItemIds([])
    }
  })

  if (!selection) {
    return null;
  }

  const { x, y, width, height } = selection;

  return (
    <>
      <View
        style={[styles.selection, {
          left: x,
          top: y,
          width,
          height
        }]}
        onMouseDown={onMouseDown}
      />
      <ResizeHandler />
    </>
  )
}
Example #18
Source File: NewItemButton.js    From recoil-paint with MIT License 5 votes vote down vote up
export default function NewItemButton({ newShapeProps = {}, ...others }) {
  const [newItem, setNewItem] = useState(null);
  const setItemIds = useSetRecoilState(itemIdsState);
  const setSelectedIds = useSetRecoilState(selectedIdsState);
  const canvasLayout = useRecoilValue(canvasLayoutState);
  const createNewItem = useNewItem();
  const updatePosition = useUpdateItem();

  const { onMouseDown } = useMove(({ status, origin, offset }) => {
    if (status === 'start') {
      setNewItem(null);
      createNewItem({
        ...newShapeProps,
        x: origin.clientX - canvasLayout.x,
        y: origin.clientY - canvasLayout.y
      })
        .then(item => {
          setNewItem(item);
          setItemIds(items => [...items, item.id]);
          setSelectedIds([]);
        });
    }

    if (status === 'moving') {
      if (newItem) {
        updatePosition({
          ...newItem,
          x: origin.clientX + offset.x - canvasLayout.x,
          y: origin.clientY + offset.y - canvasLayout.y
        })
      }
    }

    if (status === 'end') {
      if (newItem) {
        setNewItem(null);
        setSelectedIds([newItem.id]);
      }
    }
  })



  return <Button {...others} onMouseDown={onMouseDown} />;
}
Example #19
Source File: Login.jsx    From react-recoil-jwt-authentication-example with MIT License 5 votes vote down vote up
function Login({ history }) {
    const auth = useRecoilValue(authAtom);
    const userActions = useUserActions();

    useEffect(() => {
        // redirect to home if already logged in
        if (auth) history.push('/');

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // form validation rules 
    const validationSchema = Yup.object().shape({
        username: Yup.string().required('Username is required'),
        password: Yup.string().required('Password is required')
    });
    const formOptions = { resolver: yupResolver(validationSchema) };

    // get functions to build form with useForm() hook
    const { register, handleSubmit, setError, formState } = useForm(formOptions);
    const { errors, isSubmitting } = formState;

    function onSubmit({ username, password }) {
        return userActions.login(username, password)
            .catch(error => {
                setError('apiError', { message: error });
            });
    }

    return (
        <div className="col-md-6 offset-md-3 mt-5">
            <div className="alert alert-info">
                Username: test<br />
                Password: test
            </div>
            <div className="card">
                <h4 className="card-header">Login</h4>
                <div className="card-body">
                    <form onSubmit={handleSubmit(onSubmit)}>
                        <div className="form-group">
                            <label>Username</label>
                            <input name="username" type="text" {...register('username')} className={`form-control ${errors.username ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.username?.message}</div>
                        </div>
                        <div className="form-group">
                            <label>Password</label>
                            <input name="password" type="password" {...register('password')} className={`form-control ${errors.password ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.password?.message}</div>
                        </div>
                        <button disabled={isSubmitting} className="btn btn-primary">
                            {isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
                            Login
                        </button>
                        {errors.apiError &&
                            <div className="alert alert-danger mt-3 mb-0">{errors.apiError?.message}</div>
                        }
                    </form>
                </div>
            </div>
        </div>
    )
}
Example #20
Source File: DetailPage.js    From app-personium-trails with Apache License 2.0 5 votes vote down vote up
function LocationRawDataViewChild({ __id }) {
  const locationUrl = useRecoilValue(locationURLFromId(__id));
  const [locationInfo, setLocationInfo] = useState({});

  useEffect(() => {
    let unmounted = false;
    fetch(locationUrl, {
      headers: {
        Authorization: `Bearer ${authState.accessToken.access_token}`,
      },
    })
      .then(res => res.json())
      .then(jsonDat => {
        if (!unmounted) setLocationInfo(jsonDat);
      });

    return function cleanup() {
      unmounted = true;
    };
  }, [locationUrl]);

  return (
    <Table>
      <Table.Header>
        <Table.Row>
          <Table.HeaderCell>Name</Table.HeaderCell>
          <Table.HeaderCell>Value</Table.HeaderCell>
        </Table.Row>
      </Table.Header>

      <Table.Body>
        {Object.entries(locationInfo).map(([key, val]) => {
          const _val = typeof val === 'object' ? JSON.stringify(val) : val;
          return (
            <Table.Row key={key}>
              <Table.Cell>{key}</Table.Cell>
              <Table.Cell style={{ overflowWrap: 'anywhere' }}>
                {_val}
              </Table.Cell>
            </Table.Row>
          );
        })}
      </Table.Body>
    </Table>
  );
}
Example #21
Source File: LocationPage.js    From app-personium-trails with Apache License 2.0 5 votes vote down vote up
function LocationItem({ item }) {
  const timems = parseInt(item.startTime.match(/\/Date\((\d+)\)\//)[1]);
  const filename = `${'placeId' in item ? 's' : 'm'}_${timems}.json`;
  const folder = `${authState.boxUrl}locations/${getYMD(timems)}/`;
  const filepath = `${folder}${filename}`;

  const {
    setLocationACLPrivate,
    setLocationACLPublic,
  } = useLocationACLSubscribe(item.__id, filepath);
  const aclStatus = useRecoilValue(locationACLStatusState(item.__id));

  const onClick = useCallback(() => {
    if (aclStatus === 'loading') return;
    if (aclStatus === 'public') {
      setLocationACLPrivate();
    } else {
      setLocationACLPublic();
    }
  }, [aclStatus]);

  if ('placeId' in item) {
    return (
      <StayItem
        dat={item}
        key={`list-${item.__id}`}
        isPublic={aclStatus === 'public'}
        isLoading={aclStatus === 'loading'}
        onClick={onClick}
      />
    );
  } else {
    return (
      <MoveItem
        dat={item}
        key={`list-${item.__id}`}
        isPublic={aclStatus === 'public'}
        isLoading={aclStatus === 'loading'}
        onClick={onClick}
      />
    );
  }
}
Example #22
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 #23
Source File: Medicine.js    From HealthBridge with GNU General Public License v3.0 5 votes vote down vote up
Medicine = () => {
	const token = useRecoilValue(tokenAtom);
	const [enteredName, setEnteredName] = useState("");
	const [commonNames, setCommonNames] = useState(null);

	const getBrandNames = () => {
		Axios.post(
			`https://eureka-scrapper-radioactive11.herokuapp.com/generic_name`,
			{
				generic_name: enteredName,
			},
			{
				headers: {
					Authorization: "Bearer " + token,
				},
			}
		)
			.then((res) => {
				console.log(res.data);
				setCommonNames(res.data);
			})
			.catch((err) => {
				console.log(err);
			});
	};

	return (
		<div className="Medicine">
			<div className="container">
				<div className="top">
					<h1>Common Medicine Names</h1>
					<p>
						Making brand names of medicines available to the patient
						by providing a generic name of the medicine, which are
						far cheaper and easily available.
					</p>
				</div>

				<div className="main">
					<div className="entered-name">
						<label htmlFor="medicine">Medicine Name</label>
						<input
							type="text"
							value={enteredName}
							onChange={(e) => setEnteredName(e.target.value)}
						/>
					</div>
					<button className="primary" onClick={() => getBrandNames()}>
						Get Results
					</button>
					{commonNames && (
						<div className="commons">
							<label htmlFor="commons">Common Medicines</label>
							<div className="result">
								<table>
									<thead>
										<tr>
											<th>Name</th>
											<th>General Price</th>
											<th>Source</th>
										</tr>
									</thead>
									<tbody>
										{commonNames.map((med) => (
											<tr>
												<td>{med.name}</td>
												<td>{med.price}</td>
												<td>{med.source}</td>
											</tr>
										))}
									</tbody>
								</table>
							</div>
						</div>
					)}
				</div>
			</div>
		</div>
	);
}
Example #24
Source File: useCubeStore.js    From minecraft-react with MIT License 5 votes vote down vote up
useCube = () => useRecoilValue($cubes)
Example #25
Source File: LoginScreen.js    From discovery-mobile-ui with MIT License 5 votes vote down vote up
LoginScreen = () => {
  const baseUrl = useRecoilValue(baseUrlState);

  return (
    <SafeAreaView style={styles.root}>
      <StatusBar backgroundColor={Colors.primary} barStyle="dark-content" />
      <View style={styles.screen}>
        <View style={styles.topScreen}>
          <TouchableOpacity
            style={styles.navlink}
            onPress={() => Linking.openURL('https://syncfor.science/')}
          >
            <View style={styles.fullLogoContainer}>
              <FullLogo height={105} width={225} fill="black" />
            </View>
          </TouchableOpacity>
          <Suspense fallback={(<View style={styles.loading}><LoadingIndicator /></View>)}>
            <Login />
          </Suspense>
        </View>
        <View style={styles.midScreen} />
        <View style={styles.bottomScreen}>
          {!!baseUrl && <LoginButton baseUrl={baseUrl} />}
          <ResetAsyncStorageButton />
          <Text style={styles.powered}>Powered By</Text>
          <TouchableOpacity
            style={styles.navlink}
            onPress={() => Linking.openURL('https://dbmi.hms.harvard.edu')}
          >
            <Image
              style={styles.harvard}
              source={harvardLogo}
              resizeMode="contain"
            />
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.navlink}
            onPress={() => Linking.openURL('https://vermonster.com')}
          >
            <Image
              style={styles.vermonster}
              source={vermonsterLogo}
              resizeMode="contain"
            />
          </TouchableOpacity>
        </View>
      </View>
    </SafeAreaView>
  );
}
Example #26
Source File: PlaygroundScreen.js    From basis with MIT License 4 votes vote down vote up
function PlaygroundScreen({ id, name, width, document, componentsLocation }) {
  const componentPreviewCounter = useRecoilValue(componentPreviewCounterState);
  const setScreens = useSetRecoilState(screensState);
  const isInspectMode = useRecoilValue(isInspectModeState);
  const [componentsAtMouse, setComponentsAtMouse] = useState({});
  const setScreenWidth = (width) => {
    setScreens((screens) => updateItemWithId(screens, id, { width }));
  };
  const setScreenDocument = (document) => {
    setScreens((screens) => updateItemWithId(screens, id, { document }));
  };
  const [mousePosition, mouseMoveRef] = useMousePosition(
    0, // enterDelay
    0, // leaveDelay
    10 // fps
  );
  const lastMousePosition = useRef();
  const widthOnResizeStart = useRef();

  useEffect(() => {
    const { x, y } = mousePosition;

    if (
      x !== null &&
      y !== null &&
      (!lastMousePosition.current ||
        lastMousePosition.current.x !== x ||
        lastMousePosition.current.y !== y)
    ) {
      const { scrollX, scrollY } = document.defaultView;
      const componentsAtMouse = getComponentsAtPoint(
        {
          x: x - scrollX,
          y: y - scrollY,
        },
        componentsLocation
      );

      setComponentsAtMouse(componentsAtMouse);
    }

    lastMousePosition.current = mousePosition;
  }, [mousePosition, document, componentsLocation]);

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

  return (
    <Resizable
      size={{ width }}
      onResizeStart={() => {
        widthOnResizeStart.current = width;
      }}
      onResize={(e, direction, ref, d) => {
        setScreenWidth(widthOnResizeStart.current + d.width);
      }}
      minWidth={MIN_SCREEN_WIDTH}
      maxWidth={MAX_SCREEN_WIDTH}
      enable={{
        top: false,
        right: true,
        bottom: false,
        left: false,
        topRight: false,
        bottomRight: false,
        bottomLeft: false,
        topLeft: false,
      }}
    >
      <div
        css={{
          display: "flex",
          flexDirection: "column-reverse",
          width,
          height: "100%",
          overflowY: "hidden",
        }}
      >
        <Text color="grey.t75" margin="1 1 0">
          <strong>{name}</strong> – {width}px
        </Text>
        <ComponentPreview
          iframeTitle={`${name} screen preview`}
          iframeStyle={{
            flexGrow: 1,
            backgroundColor: "white",
            boxShadow:
              "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",
          }}
          hasBodyMargin={false}
          setDocument={setScreenDocument}
          containerRef={isInspectMode ? mouseMoveRef : undefined}
          highlightedComponents={componentsAtMouse}
          onMouseLeave={() => {
            setComponentsAtMouse({});
          }}
          key={
            componentPreviewCounter /* See: https://github.com/ryanseddon/react-frame-component/issues/170 */
          }
        />
      </div>
    </Resizable>
  );
}
Example #27
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 #28
Source File: PersoniumAppWrapper.js    From app-personium-trails with Apache License 2.0 4 votes vote down vote up
function PersoniumAuthentication() {
  const isLocalMode = useRecoilValue($localMode);
  const authInfo = useRecoilValue($authInfo);
  const setLogin = useSetRecoilState(isLogin);
  const setToken = useSetRecoilState(tokens);
  const setBarInstalled = useSetRecoilState($barInstalled);
  const [error, setError] = useState(null);

  useEffect(() => {
    let unmounted = false;
    let autoRefreshID = -1;

    const appUrlSplit = `${location.origin}${location.pathname}`.split('/');
    const appCellUrl = isLocalMode
      ? 'https://app-personium-trails.appdev.personium.io/'
      : `${appUrlSplit.slice(0, 3).join('/')}/`;
    // const appCellUrl = 'https://app-personium-trails.appdev.personium.io/';
    const targetCell = authInfo.cellUrl;

    const handler = isLocalMode
      ? new PersoniumLoginROPC(
          targetCell,
          localStorage.getItem('USERNAME_FOR_DEVELOPMENT'),
          localStorage.getItem('PASSWORD_FOR_DEVELOPMENT'),
          'https://app-personium-trails.appdev.personium.io/'
        )
      : new PersoniumLoginHandler(targetCell);

    // subscribe authentication state
    localStorage.setItem(LS_LAST_LOGIN_CELL, targetCell);
    console.log(appCellUrl, authInfo);
    handler
      .loginAsync(appCellUrl, authInfo)
      .catch(res => {
        // ToDo: change handling depending on situation.
        console.log(JSON.stringify(res));
        localStorage.removeItem(LS_LAST_LOGIN_CELL);
        if (res.status === 404) {
          setError({
            message: 'Authentication failed',
            body: `Cell not found: ${targetCell}`,
            // ToDo: refactoring
            bodyUrl: 'javascript: location.reload();',
          });
        } else {
          setError({
            message: 'Authentication failed',
            body: 'Please login from your Home App',
            bodyUrl: targetCell,
          });
        }
        return Promise.reject(res);
      })
      .then(authState => {
        // sined in successfully
        console.log('logged in');
        if (!unmounted) {
          setToken(authState.accessToken);
        }
        // start refreshing access_token (per 3000 sec)
        autoRefreshID = setInterval(() => handler.refreshAsync(), 3000 * 1000);

        // check bar installed;
        return authState
          .updateBoxUrl() // ToDo: refactoring Promise chain
          .then(() => {
            setBarInstalled(true);
          })
          .catch(res => {
            if (res.status === 403) {
              console.log('bar not installed');
              setBarInstalled(false);
            }
          });
      })
      .then(res => {
        if (!unmounted) {
          setLogin(true);
        }
      })
      .catch(reason => {
        console.log('error happened', reason);
      });

    return () => {
      // unsubscribe
      unmounted = true;
      if (autoRefreshID != -1) {
        clearInterval(autoRefreshID);
      }
    };
  }, [authInfo, isLocalMode, setToken, setLogin, setError, setBarInstalled]);

  return error ? (
    <>
      <h1>{error.message || 'Oops, you cannot sign in'}</h1>
      <p>
        <a href={error.bodyUrl}>{error.body || 'click'}</a>
      </p>
    </>
  ) : null;
}
Example #29
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>
  );
}