react-redux#shallowEqual JavaScript Examples

The following examples show how to use react-redux#shallowEqual. 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: index.jsx    From react-firebase-admin with MIT License 6 votes vote down vote up
DatePickerStyled = ({ date, onChange }) => {
  const onDateChangedHandler = (value) =>
    onChange(value ? value.toDateString() : new Date().toDateString());

  const { locale } = useSelector(
    (state) => ({
      locale: state.preferences.locale,
    }),
    shallowEqual
  );

  return (
    <DatePicker
      locale={locale}
      dateFormat={dateFormat(locale)}
      selected={date}
      onChange={onDateChangedHandler}
    />
  );
}
Example #2
Source File: AvailableImagesTile.js    From edge-frontend with Apache License 2.0 6 votes vote down vote up
AvailableImageTile = ({ onNewImageClick }) => {
  const { isLoading, hasError, data } = useSelector(
    ({ imagesReducer }) => ({
      isLoading:
        imagesReducer?.isLoading !== undefined
          ? imagesReducer?.isLoading
          : true,
      hasError: imagesReducer?.hasError || false,
      data: imagesReducer?.data || null,
    }),
    shallowEqual
  );

  return (
    <AvailableImageTileBase>
      <CardBody>
        {isLoading ? (
          <Bullseye>
            <Spinner />
          </Bullseye>
        ) : hasError ? (
          data
        ) : (
          <Button variant="link" style={{ paddingLeft: 0 }}>
            {data.meta.count} images
          </Button>
        )}
      </CardBody>
      <CardFooter>
        <Button variant="primary" onClick={() => onNewImageClick()}>
          Create new image
        </Button>
      </CardFooter>
    </AvailableImageTileBase>
  );
}
Example #3
Source File: protected-route.js    From what-front with MIT License 6 votes vote down vote up
ProtectedRoute = ({ roles, ...otherProps }) => {
  const { currentUser } = useSelector(currentUserSelector, shallowEqual);
  const jwt = Cookie.get('jwt');

  if (!jwt) {
    return <Redirect to={paths.AUTH} />;
  }

  if (!roles.includes(currentUser.role)) {
    return <Redirect to={paths.NOT_FOUND} />;
  }
  // eslint-disable-next-line react/jsx-props-no-spreading
  return <Route {...otherProps} />;
}
Example #4
Source File: DocsIndexContainer.js    From signdocs with MIT License 6 votes vote down vote up
DocsIndexContainer = () => {
  const [loading, setLoading] = useState(true);
  const dispatch = useDispatch();

  const docs = useSelector(getAllDocuments, isEqual);

  useEffect(() => {
    (async function getAllDocs() {
      setLoading(true);
      dispatch(fetchDocuments()).done(() => setLoading(false));
    })();
  }, []);

  const docsArray = docs && Object.keys(docs) ? Object.values(docs) : [];

  const currentUser = useSelector(getCurrentUser, shallowEqual);

  const DocsIndexOrNoDocs = () =>
    docsArray.length > 0 ? (
      <DocsIndex docs={docsArray} currentUser={currentUser} />
    ) : (
      <NoDocsCallToCreate />
    );

  return (
    <div id="index-container">
      <Sidebar />
      <div className="index-inbox">
        <div className="search-bar">
          <h2>Inbox</h2>
        </div>
        {loading ? <div>Loading...</div> : <DocsIndexOrNoDocs />}
      </div>
    </div>
  );
}
Example #5
Source File: index.js    From rtk-demo with MIT License 6 votes vote down vote up
export function useHackerNewsArticles({ limit = 20, offset = 0 } = {}) {
  useInjectReducer({ key: name, reducer });
  useInjectSaga({ key: name, saga });

  const dispatch = useDispatch();
  const store = useSelector(makeSelectHackerNewsArticles(), shallowEqual);

  useEffect(() => {
    if (!store?.data?.length && !store?.loading) {
      dispatch(
        actions.fetch({
          offset,
          limit,
        }),
      );
    }
  }, []);

  return store;
}
Example #6
Source File: index.jsx    From react-firebase-admin with MIT License 5 votes vote down vote up
Aside = ({ handleMobileToggle }) => {
  const { isAdmin } = useSelector(
    (state) => ({
      isAdmin: state.auth.userData.isAdmin,
    }),
    shallowEqual
  );

  const usersMessage = useFormatMessage('Aside.users');

  return (
    <aside className="aside is-placed-left is-expanded">
      <Link to={paths.ROOT} className="aside-tools">
        <div className="aside-tools-label">
          <span>
            <b>React</b> Firebase
          </span>
        </div>
      </Link>
      <div className="menu is-menu-main">
        <ul className="menu-list">
          <li>
            <NavLink
              to={paths.ROOT}
              className="has-icon"
              onClick={handleMobileToggle}
            >
              <span className="icon">
                <i className="mdi mdi-home" />
              </span>
              <span className="menu-item-label">
                {useFormatMessage('Aside.home')}
              </span>
            </NavLink>
          </li>
          {isAdmin && (
            <li>
              <NavLink
                to={paths.USERS}
                className="has-icon"
                onClick={handleMobileToggle}
              >
                <span className="icon">
                  <i className="mdi mdi-account-supervisor" />
                </span>
                <span className="menu-item-label">{usersMessage}</span>
              </NavLink>
            </li>
          )}
          <SubMenu label={useFormatMessage('Aside.dropdownMenu')}>
            <li>
              <NavLink
                className={classes.submenuLink}
                to={paths.SUBMENU_1}
                onClick={handleMobileToggle}
              >
                <span>{useFormatMessage('Aside.submenu1')}</span>
              </NavLink>
            </li>
            <li>
              <NavLink
                className={classes.submenuLink}
                to={paths.SUBMENU_2}
                onClick={handleMobileToggle}
              >
                <span>{useFormatMessage('Aside.submenu2')}</span>
              </NavLink>
            </li>
          </SubMenu>
        </ul>
      </div>
    </aside>
  );
}
Example #7
Source File: GuestInfoContainer.js    From airdnd-frontend with MIT License 5 votes vote down vote up
GuestInfoContainer = () => {
  const {
    id,
    hostFirstName,
    profileImg,
    isSupperhost,
    toHostMessage,
    changeInitialMessage,
    checkin,
    checkout,
    adult,
    child,
    infant,
  } = useSelector(
    state => ({
      id: state.home.homeState.home.id,
      hostFirstName: state.home.homeState.home.host.hostFirstName,
      profileImg: state.home.homeState.home.host.profileImg,
      isSupperhost: state.home.homeState.home.host.isSupperhost,
      toHostMessage: state.reservation.toHostMessage,
      changeInitialMessage: state.reservation.changeInitialMessage,
      checkin: state.reservation.checkin,
      checkout: state.reservation.checkout,
      adult: state.reservation.guests.adult,
      child: state.reservation.guests.child,
      infant: state.reservation.guests.infant,
    }),
    shallowEqual,
  );
  const dispatch = useDispatch();
  const history = useHistory();
  const [toggle, setToggle] = useState(false);

  const onToggle = () => setToggle(!toggle);
  const onNextPage = () => {
    if (!changeInitialMessage) dispatch(setChangeInitialMessage());
    if (!toHostMessage) return;
    history.push(
      `/Reservation/Payment/${id}?${checkin && 'checkIn=' + checkin}${
        checkout && '&checkOut=' + checkout
      }${+adult ? '&adult=' + adult : ''}${+child ? '&child=' + child : ''}${
        +infant ? '&infant=' + infant : ''
      }`,
    );
  };

  const onSetMessage = ({ target }) => {
    if (!changeInitialMessage) dispatch(setChangeInitialMessage());
    dispatch(setToHostMessage(target.value));
  };

  return (
    <GuestInfo
      hostFirstName={hostFirstName}
      profileImg={profileImg}
      isSupperhost={isSupperhost}
      onNextPage={onNextPage}
      onSetMessage={onSetMessage}
      onToggle={onToggle}
      toggle={toggle}
      toHostMessage={toHostMessage}
      blankMessage={changeInitialMessage && !toHostMessage}
    />
  );
}
Example #8
Source File: ImageTable.js    From edge-frontend with Apache License 2.0 5 votes vote down vote up
ImageTable = ({ openCreateWizard, openUpdateWizard }) => {
  const { count, data, isLoading, hasError } = useSelector(
    ({ edgeImagesReducer }) => ({
      count: edgeImagesReducer?.data?.count || 0,
      data: edgeImagesReducer?.data?.data || null,
      isLoading:
        edgeImagesReducer?.isLoading === undefined
          ? true
          : edgeImagesReducer.isLoading,
      hasError: edgeImagesReducer?.hasError,
    }),
    shallowEqual
  );

  const isFinalStatus = (status) => status === 'SUCCESS' || status === 'ERROR';

  const actionResolver = (rowData) => {
    const actionsArray = [];
    if (rowData?.isoURL) {
      actionsArray.push({
        title: (
          <Text
            className="force-text-black remove-underline"
            component="a"
            href={rowData.isoURL}
            rel="noopener noreferrer"
            target="_blank"
          >
            Download
          </Text>
        ),
      });
    }
    if (isFinalStatus(rowData.imageStatus)) {
      actionsArray.push({
        title: 'Update Image',
        onClick: (_event, _rowId, rowData) => {
          openUpdateWizard(rowData.id);
        },
      });
    } else if (rowData?.id) {
      actionsArray.push({
        title: '',
      });
    }

    return actionsArray;
  };

  const areActionsDisabled = (rowData) => !isFinalStatus(rowData.imageStatus);

  return (
    <GeneralTable
      apiFilterSort={true}
      filters={defaultFilters}
      loadTableData={loadEdgeImages}
      tableData={{ count, data, isLoading, hasError }}
      columnNames={columnNames}
      rows={data ? createRows(data) : []}
      emptyStateMessage="No images found"
      emptyStateActionMessage="Create new image"
      emptyStateAction={openCreateWizard}
      actionResolver={actionResolver}
      areActionsDisabled={areActionsDisabled}
      defaultSort={{ index: 4, direction: 'desc' }}
      toolbarButtons={[
        {
          title: 'Create new image',
          click: () => openCreateWizard(),
        },
      ]}
    />
  );
}
Example #9
Source File: LogsTable.js    From sed-frontend with Apache License 2.0 5 votes vote down vote up
LogsTable = () => {
  const [opened, setOpened] = useState([]);
  const dispatch = useDispatch();
  const logLoaded = useSelector(
    ({ logReducer }) => logReducer?.loaded || false
  );
  const rows = useSelector(({ logReducer }) => logReducer?.results || []);
  const pagination = useSelector(
    ({ logReducer }) => ({
      itemCount: logReducer?.total,
      perPage: logReducer?.limit,
      page:
        Math.floor((logReducer?.offset || 0) / (logReducer?.limit || 0)) + 1,
    }),
    shallowEqual
  );
  useEffect(() => {
    dispatch(fetchLog());
  }, []);
  const onCollapse = (_e, _key, isOpen, { id }) => {
    setOpened(() =>
      isOpen ? [...opened, id] : opened.filter((openId) => openId !== id)
    );
  };

  const setPage = useCallback(
    (_e, pageNumber) =>
      dispatch(fetchLog({ page: pageNumber, perPage: pagination.perPage })),
    [dispatch, pagination.perPage]
  );

  const setPerPage = useCallback(
    (_e, perPage) => dispatch(fetchLog({ page: 1, perPage })),
    [dispatch]
  );

  return (
    <Fragment>
      <PrimaryToolbar
        pagination={
          logLoaded ? (
            {
              ...pagination,
              onSetPage: setPage,
              onPerPageSelect: setPerPage,
            }
          ) : (
            <Skeleton width="33%" />
          )
        }
      />
      {logLoaded ? (
        <Table
          aria-label="Logs table"
          variant={TableVariant.compact}
          rows={rowsMapper(rows, opened)}
          cells={columns}
          onCollapse={onCollapse}
        >
          <TableHeader />
          <TableBody />
        </Table>
      ) : (
        <SkeletonTable colSize={3} rowSize={10} />
      )}
      <TableToolbar isFooter>
        {logLoaded ? (
          <Pagination
            {...pagination}
            variant={PaginationVariant.bottom}
            onSetPage={setPage}
            onPerPageSelect={setPerPage}
          />
        ) : (
          <Skeleton width="33%" />
        )}
      </TableToolbar>
    </Fragment>
  );
}
Example #10
Source File: download-themes.js    From what-front with MIT License 5 votes vote down vote up
DownloadThemes = () => {
  const { isLoading, isLoaded, error } = useSelector(importThemesSelector, shallowEqual);
  const history = useHistory();
  const downloadThemes = useActions(sendThemes);
  
  useEffect(() => {
    if (!error && isLoaded) {
      history.push(paths.LESSONS);
    }
  }, [error, isLoaded]);
  
  const [fileName, setFileName] = useState('');
  
  const onSubmit = (values) => {
    const formThemes = new FormData();
		formThemes.append('File', values.themes);
    downloadThemes(formThemes);
  };
  
  return (
    <div className="container mt-5">
      <div className="row justify-content-center">
        <div className="col-md-6 col-sm-8 card shadow">
          <Formik
            initialValues={{}}
            onSubmit={onSubmit}
          >
            {({ values, errors, dirty, setFieldValue }) => (
              <Form className="px-2 py-4" name="start-group">
                <h3>Upload Theme</h3>
                <hr />
                <div className="row mb-3">
                  <div className="col d-flex align-items-center">
                    <label className="mb-0 font-weight-bolder" htmlFor="file">Theme('s):</label>
                  </div>
                  <div className='col-md-8'>
                    <input type="file" id="actual-btn" name="themes" accept=".xlsx" onChange={(event) => {
                      setFileName(event.target.files[0].name);
                      setFieldValue("themes", event.currentTarget.files[0]);
                    }} className="form-control" hidden/>
                    <label className={classNames(styles.label, "mr-2 col-md-6")} htmlFor="actual-btn">Choose File</label>
                    <span className='font-weight-bolder'>{fileName}</span>
                  </div>
                </div>
                <div className="row justify-content-end px-4">
                <Button
                            type="submit"
                            className="w-25"
                            variant="info"
                            disabled={!dirty || isLoading || errors.name }
                          >
                            Send
                  </Button>
                </div>
              </Form>
            )}
          </Formik>
        </div>
      </div>
    </div>
  );
}
Example #11
Source File: hooks.js    From frontend-app-course-authoring with GNU Affero General Public License v3.0 5 votes vote down vote up
export function useModel(type, id) {
  return useSelector(
    state => (state.models[type] !== undefined ? state.models[type][id] : undefined),
    shallowEqual,
  );
}
Example #12
Source File: index.jsx    From NeteaseCloudMusic with MIT License 5 votes vote down vote up
BannerComp = memo((props) => {
  const [currIndex, setCurrIndex] = useState(0);
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getBannerListAsyncAction());
  }, [dispatch]);
  const { banners } = useSelector(
    (state) => ({
      banners: state.getIn(["recommendReducer", "bannersList"]),
    }),
    shallowEqual
  );
  const bannerRef = useRef();
  const bannerChange = useCallback((from, to) => {
    // console.log(from);

    setCurrIndex(to);
  }, []);
  const bgImage =
    banners[currIndex] &&
    `${banners[currIndex]["imageUrl"]}?imageView&blur=40x20`;
  return (
    <WrapperContainer bgImage={bgImage}>
      <section className="banner wrap_730_center">
        <LeftContainer>
          <Carousel
            effect="fade"
            beforeChange={bannerChange}
            ref={bannerRef}
            autoplay
          >
            {banners.map((item, index) => {
              return (
                <div className="banner-item" key={item.imageUrl}>
                  <img
                    className="image"
                    src={item.imageUrl}
                    alt={item.typeTitle}
                  />
                </div>
              );
            })}
          </Carousel>
        </LeftContainer>
        <RightContainer></RightContainer>
        <BannerControl>
          <a className="left btn" onClick={(e) => bannerRef.current.prev()}></a>
          <button
            className="right btn"
            onClick={(e) => bannerRef.current.next()}
          ></button>
        </BannerControl>
      </section>
    </WrapperContainer>
  );
})
Example #13
Source File: TreeMenu.js    From ra-treemenu with MIT License 4 votes vote down vote up
Menu = (props) => {
    const {
        className,
        dense,
        hasDashboard,
        onMenuClick,
        logout,
        dashboardlabel,
        resources,
        ...rest
    } = props;

    const classes = useStyles(props);
    const translate = useTranslate();
    const open = useSelector((state) => state.admin.ui.sidebarOpen);
    const pathname = useSelector((state) => state.router.location.pathname);
    const resources = resources || useSelector(getResources, shallowEqual);
    const hasList = (resource) => (resource.hasList);

    const handleToggle = (parent) => {
        /**
         * Handles toggling of parents dropdowns
         * for resource visibility
         */
        setState(state => ({ [parent]: !state[parent] }));
    };

    const isXSmall = useMediaQuery((theme) =>
        /**
         * This function is not directly used anywhere
         * but is required to fix the following error:
         * 
         * Error: Rendered fewer hooks than expected.
         * This may be caused by an accidental early
         * return statement.
         * 
         * thrown by RA at the time of rendering.
         */
        theme.breakpoints.down('xs')
    );

    const isParent = (resource) => (
        /**
         * Check if the given resource is a parent
         * i.e. dummy resource for menu parenting
         */
        resource.options &&
        resource.options.hasOwnProperty('isMenuParent') &&
        resource.options.isMenuParent
    );

    const isOrphan = (resource) => (
        /**
         * Check if the given resource is an orphan
         * i.e. has no parents defined. Needed as
         * these resources are supposed to be rendered
         * as is
         *  
         */
        resource.options &&
        !resource.options.hasOwnProperty('menuParent') &&
        !resource.options.hasOwnProperty('isMenuParent')
    );

    const isChildOfParent = (resource, parentResource) => (
        /**
         * Returns true if the given resource is the
         * mapped child of the parentResource
         */
        resource.options &&
        resource.options.hasOwnProperty('menuParent') &&
        resource.options.menuParent == parentResource.name
    );
    const geResourceName = (slug) => {
        if (!slug) return;
        var words = slug.toString().split('_');
        for (var i = 0; i < words.length; i++) {
            var word = words[i];
            words[i] = word.charAt(0).toUpperCase() + word.slice(1);
        }
        return words.join(' ');
    }

    const getPrimaryTextForResource = (resource) => {
        let resourcename = '';
        if (resource.options && resource.options.label)
            resourcename = resource.options.label;
        else if (resource.name) {
            resourcename = translate(`resources.${resource.name}.name`);
            if (resourcename.startsWith('resources.'))
                resourcename = geResourceName(resource.name);
        }
        return resourcename;
    }

    const MenuItem = (resource) => (
        /**
         * Created and returns the MenuItemLink object component
         * for a given resource.
         */
        <MenuItemLink
            key={resource.name}
            to={`/${resource.name}`}
            primaryText={getPrimaryTextForResource(resource)}
            leftIcon={
                resource.icon
                    ? <resource.icon />
                    : <DefaultIcon />
            }
            onClick={onMenuClick}
            dense={dense}
            sidebarIsOpen={open}
        />
    );

    /**
     * Mapping a "parent" entry and then all its children to the "tree" layout
     */
    const mapParentStack = (parentResource) => (
        <CustomMenuItem
            key={parentResource.name}
            handleToggle={() => handleToggle(parentResource.name)}
            isOpen={state[parentResource.name] || parentActiveResName === parentResource.name}
            sidebarIsOpen={open}
            name={getPrimaryTextForResource(parentResource)}
            icon={parentResource.icon ? <parentResource.icon /> : <LabelIcon />}
            dense={dense}
        >
            {
                // eslint-disable-next-line
                resources
                    .filter((resource) => isChildOfParent(resource, parentResource) && hasList(resource))
                    .map((childResource) => { return MenuItem(childResource); })
            }
        </CustomMenuItem>
    );

    /**
     * Mapping independent (without a parent) entries
     */
    const mapIndependent = (independentResource) => hasList(independentResource) && MenuItem(independentResource);


    /**
     * Initialising the initialExpansionState and
     * active parent resource name at the time of
     * initial menu rendering.
     */
    const initialExpansionState = {};
    let parentActiveResName = null;

    /**
     * Initialise all parents to inactive first.
     * Also find the active resource name.
     */
    resources.forEach(resource => {
        if (isParent(resource)) {
            initialExpansionState[resource.name] = false;
        } else if (pathname.startsWith(`/${resource.name}`) && resource.options.hasOwnProperty('menuParent')) {
            parentActiveResName = resource.options.menuParent;
        }
    });

    const [state, setState] = useState(initialExpansionState);

    /**
     * The final array which will hold the array
     * of resources to be rendered
     */
    const resRenderGroup = [];

    /**
     * Looping over all resources and pushing the menu tree
     * for rendering in the order we find them declared in
     */
    resources.forEach(r => {
        if (isParent(r)) resRenderGroup.push(mapParentStack(r));
        if (isOrphan(r)) resRenderGroup.push(mapIndependent(r));
    });

    return (
        <div>
            <div
                className={classnames(classes.main, className, {
                    [classes.open]: open,
                    [classes.closed]: !open,
                })}
                {...rest}
            >
                {hasDashboard && (
                    <DashboardMenuItem
                        onClick={onMenuClick}
                        dense={dense}
                        sidebarIsOpen={open}
                        primaryText={dashboardlabel}
                    />
                )}
                {resRenderGroup}
            </div>
        </div>
    );
}
Example #14
Source File: index.jsx    From react-firebase-admin with MIT License 4 votes vote down vote up
NavBar = ({ handleMobileToggle, asideMobileActive }) => {
  const [navMobileActive, setNavMobileActive] = useState(false);

  const { userName, logoUrl, locale } = useSelector(
    (state) => ({
      userName: state.auth.userData.name,
      logoUrl: state.auth.userData.logoUrl,
      locale: state.preferences.locale,
    }),
    shallowEqual
  );

  const dispatch = useDispatch();

  const onClickLogoutHandler = () => {
    dispatch(logout());
  };

  const onMobileToggleHandler = useCallback(() => {
    setNavMobileActive(!navMobileActive);
  }, [setNavMobileActive, navMobileActive]);

  const changeLocaleHandler = (local) => {
    dispatch(setUserLocale(local));
  };

  const locales = availableLocales.filter((local) => local !== locale);

  return (
    <nav id="navbar-main" className="navbar is-fixed-top">
      <div className="navbar-brand">
        <a
          className="navbar-item is-hidden-desktop jb-aside-mobile-toggle"
          onClick={handleMobileToggle}
        >
          <span className="icon">
            <i
              className={classNames(
                'mdi',
                'mdi-24px',
                { 'mdi-forwardburger': !asideMobileActive },
                { 'mdi-backburger': asideMobileActive }
              )}
            />
          </span>
        </a>
      </div>
      <div className="navbar-brand is-right">
        <a
          className="navbar-item is-hidden-desktop jb-navbar-menu-toggle"
          data-target="navbar-menu"
          onClick={onMobileToggleHandler}
        >
          <span className="icon">
            <i
              className={classNames(
                'mdi',
                { 'mdi-dots-vertical': !navMobileActive },
                { 'mdi-close': navMobileActive }
              )}
            />
          </span>
        </a>
      </div>
      <div
        className={classNames('navbar-menu', 'fadeIn', 'animated', 'faster', {
          'is-active': navMobileActive,
        })}
        id="navbar-menu"
      >
        <div className="navbar-end">
          <div className="navbar-item has-dropdown has-dropdown-with-icons has-divider has-user-avatar is-hoverable">
            <a className="navbar-link is-arrowless">
              <div className="is-user-avatar">
                <span>
                  <img id={locale} src={flags[locale]} alt={`${locale} flag`} />
                </span>
              </div>
              <span className="icon">
                <i className="mdi mdi-chevron-down" />
              </span>
            </a>
            <div className="navbar-dropdown">
              {locales.map((local) => (
                <a
                  onClick={() => changeLocaleHandler(local)}
                  className="navbar-item"
                  id={local}
                  key={local}
                >
                  <div className="is-user-avatar">
                    <span>
                      <img src={flags[local]} alt={`${local} flag`} />
                    </span>
                  </div>
                </a>
              ))}
            </div>
          </div>
          <div className="navbar-item has-dropdown has-dropdown-with-icons has-divider has-user-avatar is-hoverable">
            <a className="navbar-link is-arrowless">
              <div className="is-user-avatar">
                <img src={logoUrl || defaultLogo} alt="User profile" />
              </div>
              <div className="is-user-name">
                <span>{userName}</span>
              </div>
              <span className="icon">
                <i className="mdi mdi-chevron-down" />
              </span>
            </a>
            <div className="navbar-dropdown">
              <Link to={paths.PROFILE} onClick={onMobileToggleHandler}>
                <span className="icon">
                  <i className="mdi mdi-account" />
                </span>
                <span>{useFormatMessage('NavBar.profile')}</span>
              </Link>
              <hr className="navbar-divider" />
              <a
                className="navbar-item"
                id="logout"
                onClick={onClickLogoutHandler}
              >
                <span className="icon">
                  <i className="mdi mdi-logout" />
                </span>
                <span>{useFormatMessage('NavBar.logOut')}</span>
              </a>
            </div>
          </div>
        </div>
      </div>
    </nav>
  );
}
Example #15
Source File: AsideContainer.js    From airdnd-frontend with MIT License 4 votes vote down vote up
AsideContainer = () => {
  const {
    title,
    subTitle,
    price,
    images,
    reviewCount,
    dateDiff,
    checkin,
    checkout,
    adult,
    child,
  } = useSelector(
    state => ({
      title: state.home.homeState.home.title,
      subTitle: state.home.homeState.home.subTitle,
      price: state.home.homeState.home.price,
      images: state.home.homeState.home.images,
      reviewCount: state.home.homeState.home.host.reviewCount,
      dateDiff: state.reservation.dateDiff,
      checkin: state.reservation.checkin,
      checkout: state.reservation.checkout,
      adult: state.reservation.guests.adult,
      child: state.reservation.guests.child,
    }),
    shallowEqual,
  );

  const checkinDate = new Date(checkin);
  const checkoutDate = new Date(checkout);
  const options = {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  };
  const checkinString = checkinDate.toLocaleDateString('ko-KR', options);
  const checkoutString = checkoutDate.toLocaleDateString('ko-KR', options);

  const image = images[0];

  const regExp = /\d/g;
  const removedCommaPrice = Number(price.match(regExp).join(''));

  const pricePerPerson = removedCommaPrice * (adult + child);

  const pricePerPersonToString = pricePerPerson.toLocaleString(undefined, {
    maximumFractionDigits: 0,
  });

  const multipliedPrice = (pricePerPerson * dateDiff).toLocaleString(
    undefined,
    {
      maximumFractionDigits: 0,
    },
  );

  const percentage = (((pricePerPerson * dateDiff) / 100) * 12).toLocaleString(
    undefined,
    {
      maximumFractionDigits: 0,
    },
  );

  const filteredPercentage = Number(percentage.match(regExp).join(''));

  const totalPrice = (
    pricePerPerson * dateDiff +
    filteredPercentage
  ).toLocaleString(undefined, {
    maximumFractionDigits: 0,
  });

  return (
    <Aside
      title={title}
      subTitle={subTitle}
      price={pricePerPersonToString}
      multipliedPrice={multipliedPrice}
      percentage={percentage}
      totalPrice={totalPrice}
      image={image}
      reviewCount={reviewCount}
      dateDiff={dateDiff}
      checkinString={checkinString}
      checkoutString={checkoutString}
      countGuest={adult + child}
    />
  );
}
Example #16
Source File: UpdateImageModal.js    From edge-frontend with Apache License 2.0 4 votes vote down vote up
UpdateImageModal = ({ updateCveModal, setUpdateCveModal, setReload }) => {
  const dispatch = useDispatch();

  const { getRegistry } = useContext(RegistryContext);
  const { data } = useSelector(
    ({ imageDetailReducer }) => ({
      data: imageDetailReducer?.data || null,
    }),
    shallowEqual
  );

  useEffect(() => {
    const registered = getRegistry().register({
      imageDetailReducer,
    });
    updateCveModal?.imageId &&
      loadImageDetail(dispatch, updateCveModal?.imageId);
    return () => registered();
  }, [dispatch]);

  const handleUpdateModal = () => {
    const payload = {
      Id: data?.image?.ID,
      description: data?.image?.Description,
      name: data?.image?.Name,
      version: data?.image?.Version + 1,
      architecture: 'x86_64',
      credentials: data?.image?.Installer.SshKey,
      username: data?.image?.Installer.Username,
      imageType: data?.image?.OutputTypes,
      'selected-packages': data?.image?.Packages?.map((pack) => ({
        name: pack.Name,
      })),
      release: data?.image?.Distribution,
    };
    handleClose();
    setReload(true);
    createNewImage(dispatch, payload, (resp) => {
      dispatch({
        ...addNotification({
          variant: 'info',
          title: 'Update image',
          description: `${resp.value.Name} image was added to the queue.`,
        }),
        meta: {
          polling: {
            id: `FETCH_IMAGE_${resp.value.ID}_BUILD_STATUS`,
            fetcher: () => getEdgeImageStatus(resp.value.ID),
            condition: (resp) => {
              switch (resp.Status) {
                case 'BUILDING':
                  return [true, ''];
                case 'ERROR':
                  return [false, 'failure'];
                default:
                  return [false, 'success'];
              }
            },
            onEvent: {
              failure: [
                (dispatch) =>
                  dispatch(
                    addNotification({
                      variant: 'danger',
                      title: 'Image build failed',
                      description: `${resp.value.Name} image build is completed unsuccessfully`,
                    })
                  ),
              ],
              success: [
                (dispatch) =>
                  dispatch(
                    addNotification({
                      variant: 'success',
                      title: 'Image is ready',
                      description: `${resp.value.Name} image build is completed`,
                    })
                  ),
                (dispatch) => loadEdgeImageSets(dispatch),
              ],
            },
          },
        },
      });
      loadEdgeImageSets(dispatch);
      dispatch(
        addImageToPoll({ name: data?.image?.Name, id: data?.image?.ID })
      );
    });
  };

  const handleClose = () => {
    setUpdateCveModal((prevState) => ({ ...prevState, isOpen: false }));
  };

  return data ? (
    <Modal
      variant="medium"
      title={`Update image: ${data?.image?.Name}`}
      description="Review the information and click Create image to start the build process"
      isOpen={updateCveModal.isOpen}
      onClose={handleClose}
      //onSubmit={handleUpdateModal}
      actions={[
        <Button key="confirm" variant="primary" onClick={handleUpdateModal}>
          Create Image
        </Button>,
        <Button key="cancel" variant="link" onClick={handleClose}>
          Cancel
        </Button>,
      ]}
    >
      <TextContent>
        <TextListItem component={TextVariants.h3}>
          <Text component={'b'}>Details</Text>
        </TextListItem>
        <TextList component={TextListVariants.dl}>
          <TextListItem component={TextListItemVariants.dt}>Name</TextListItem>
          <TextListItem component={TextListItemVariants.dd}>
            {data?.image?.Name}
          </TextListItem>
          <TextListItem component={TextListItemVariants.dt}>
            Version
          </TextListItem>
          <TextListItem component={TextListItemVariants.dd}>
            {data?.image?.Version + 1}
          </TextListItem>
          <TextListItem component={TextListItemVariants.dt}>
            Description
          </TextListItem>
          <TextListItem component={TextListItemVariants.dd}>
            {data?.image?.Description}
          </TextListItem>
        </TextList>
        <TextListItem component={TextVariants.h3}>
          <Text component={'b'}>Output</Text>
        </TextListItem>
        <TextList component={TextListVariants.dl}>
          <TextListItem component={TextListItemVariants.dt}>
            Release
          </TextListItem>
          <TextListItem component={TextListItemVariants.dd}>
            {releaseMapper[data?.image?.Distribution]}
          </TextListItem>
          <TextListItem component={TextListItemVariants.dt}>
            Output type
          </TextListItem>
          <TextListItem component={TextListItemVariants.dd}>
            {imageTypeMapper[data?.image?.ImageType]}
          </TextListItem>
        </TextList>
        <TextListItem component={TextVariants.h3}>
          <Text component={'b'}>Packages</Text>
        </TextListItem>
        <TextList component={TextListVariants.dl}>
          <TextListItem component={TextListItemVariants.dt}>
            Updated
          </TextListItem>
          <TextListItem
            className="pf-u-pl-lg"
            component={TextListItemVariants.dd}
          >
            {updateCveModal?.cveCount}
          </TextListItem>
        </TextList>
      </TextContent>
    </Modal>
  ) : (
    <Backdrop>
      <Bullseye>
        <Spinner isSVG diameter="100px" />
      </Bullseye>
    </Backdrop>
  );
}
Example #17
Source File: index.js    From sed-frontend with Apache License 2.0 4 votes vote down vote up
SamplePage = () => {
  const history = useHistory();
  const { getRegistry } = useContext(RegistryContext);
  const [confirmChangesOpen, setConfirmChangesOpen] = useState(false);
  const [madeChanges, setMadeChanges] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const dataRef = useRef();
  const dispatch = useDispatch();

  const activeStateLoaded = useSelector(
    ({ activeStateReducer }) => activeStateReducer?.loaded
  );
  const { useOpenSCAP, enableCloudConnector, hasInsights } = useSelector(
    ({ activeStateReducer }) => ({
      useOpenSCAP: activeStateReducer?.values?.useOpenSCAP,
      enableCloudConnector: activeStateReducer?.values?.enableCloudConnector,
      hasInsights: activeStateReducer?.values?.hasInsights,
    }),
    shallowEqual
  );
  const { systemsCount } = useSelector(
    ({ connectedSystemsReducer }) => ({
      systemsLoaded: connectedSystemsReducer?.loaded,
      systemsCount: connectedSystemsReducer?.total,
    }),
    shallowEqual
  );

  useEffect(() => {
    getRegistry().register({
      activeStateReducer,
      logReducer,
      connectedSystemsReducer,
    });
    dispatch(fetchCurrState());
    dispatch(fetchConnectedHosts());
  }, [getRegistry]);

  useEffect(() => {
    insights?.chrome?.appAction?.('cloud-connector-dashboard');
  }, []);

  return (
    <React.Fragment>
      <Route
        exact
        path={paths.logModal}
        render={() => (
          <Suspense
            fallback={
              <Bullseye>
                <Spinner />
              </Bullseye>
            }
          >
            <ConnectLog />
          </Suspense>
        )}
      />
      <PageHeader className="page-header">
        <Split hasGutter className="page-title">
          <SplitItem isFilled>
            <Flex>
              <FlexItem spacer={{ default: 'spacerSm' }}>
                <PageHeaderTitle title="Remote Host Configuration Manager" />
              </FlexItem>
              <FlexItem>
                <AboutRemoteHostConfigPopover />
              </FlexItem>
            </Flex>
          </SplitItem>
          <SplitItem>
            <Button onClick={() => history.push(paths.logModal)} variant="link">
              View log
            </Button>
          </SplitItem>
        </Split>
        <Stack hasGutter>
          <StackItem>
            Selections here affect Red Hat Enterprise Linux (RHEL) systems
            connected to Red Hat with remote host configuration (rhc). Upon
            saving changes, Ansible Playbooks are automatically pushed to
            connected systems to update the configuration of the connection to
            Red Hat.
          </StackItem>
          <StackItem>
            <a
              target="_blank"
              rel="noopener noreferrer"
              href={
                'https://access.redhat.com/documentation/en-us/red_hat_insights/2022/html-single/red_hat_connector_configuration_guide/index'
              }
            >
              Connecting with Red Hat
              {<ExternalLinkAltIcon className="pf-u-ml-sm" />}
            </a>
          </StackItem>
        </Stack>
      </PageHeader>
      <Page>
        <div className="dashboard__content">
          {activeStateLoaded ||
          (useOpenSCAP !== undefined && enableCloudConnector !== undefined) ? (
            <Services
              madeChanges={madeChanges}
              setConfirmChangesOpen={setConfirmChangesOpen}
              setMadeChanges={setMadeChanges}
              setIsEditing={setIsEditing}
              isEditing={isEditing}
              defaults={{
                useOpenSCAP,
                enableCloudConnector,
                hasInsights,
              }}
              onChange={(data) => {
                dataRef.current = data;
              }}
            />
          ) : (
            <Bullseye>
              <Spinner className="pf-u-p-lg" size="xl" />
            </Bullseye>
          )}
        </div>
      </Page>
      <ConfirmChangesModal
        isOpen={confirmChangesOpen}
        handleCancel={() => setConfirmChangesOpen(false)}
        systemsCount={systemsCount}
        data={dataRef.current}
        handleConfirm={() => {
          setConfirmChangesOpen(false);
          (async () => {
            const saveAction = saveCurrState(dataRef.current);
            dispatch(saveAction);
            await saveAction.payload;
            dispatch(
              addNotification({
                variant: 'success',
                title: 'Changes saved',
                description:
                  'Your service enablement changes were applied to connected systems',
              })
            );
            setMadeChanges(false);
            setIsEditing(false);
          })();
        }}
      />
    </React.Fragment>
  );
}
Example #18
Source File: auth.js    From what-front with MIT License 4 votes vote down vote up
Auth = () => {
  const {
    isLoading,
    error: requestError,
    loaded,
    currentUser,
  } = useSelector(currentUserSelector, shallowEqual);
  const dispatchLogIn = useActions(login);
  const history = useHistory();
  const jwt = Cookie.get('jwt');

  useEffect(() => {
    if (jwt) {
      history.push(paths.NOT_FOUND);
    }
  }, [history, jwt]);

  const submitHandler = (values) => {
    const {email, password} = values;
    dispatchLogIn({ email: email.trim(), password});
  };

  useEffect(() => {
    if (loaded && !requestError && currentUser) {
      history.push(homepages[currentUser.role]);
    }
  }, [currentUser, history, loaded, requestError]);

  return (
    <div className={styles.wrapper}>
      <div className="container">
        <div className="row justify-content-center">
          <div className="col-xl-6 col-md-8 col-sm-10 col-12">
            <div className={classNames(styles.form, 'card', 'shadow')}>
              <Formik
                initialValues={{
                  email: '',
                  password: '',
                }}
                onSubmit={submitHandler}
                validationSchema={authValidation}
              >
                {({
                  errors,
                  touched,
                }) => (
                  <Form className="p-3" noValidate>
                    <h3 className="text-center">Sign in to WHAT</h3>
                    <hr />
                    <div className="form-group">
                      <label htmlFor="email">Email address</label>
                      <Field
                        type="email"
                        className={classNames('form-control', { 'border-danger': errors.email && touched.email })}
                        name="email"
                        placeholder="Email address"
                        id="email"
                      />
                      <p className="text-danger">{touched.email && errors.email}</p>
                    </div>
                    <div className="form-group">
                      <label htmlFor="password">Password</label>
                      <Field
                        type="password"
                        className={classNames('form-control', { 'border-danger': errors.password && touched.password })}
                        name="password"
                        placeholder="Password"
                        id="password"
                        autoComplete="on"
                      />
                      <p className="text-danger">{touched.password && errors.password}</p>
                    </div>
                    <div className="d-flex justify-content-center">
                      <WithLoading isLoading={isLoading} variant="info" className="d-block mx-auto">
                        <Button type="submit" className={styles['form-button']}>Sign in</Button>
                      </WithLoading>
                    </div>
                    {requestError && <p className="text-center text-danger mt-2">{requestError}</p>}
                    <div className="d-flex justify-content-between mt-3">
                      <div className="text-center">
                        <p><Link to={paths.FORGOT_PASSWORD} className={styles['form-link']}>Forgot Password?</Link></p>
                      </div>
                      <div className="text-right">
                        <p>Don&apos;t have an account? <Link to={paths.REGISTRATION} className={styles['form-link']}>Registration</Link></p>
                      </div>
                    </div>
                  </Form>
                )}
              </Formik>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
Example #19
Source File: index.jsx    From NeteaseCloudMusic with MIT License 4 votes vote down vote up
Recommend = memo(() => {
  const [tabsState, setTabsState] = useState([
    {
      name: "华语",
    },
    {
      name: "流行",
    },
    {
      name: "摇滚",
    },
    {
      name: "民谣",
    },
    {
      name: "电子",
    },
  ]);
  const dispatch = useDispatch();
  const { listData } = useSelector(
    (state) => ({
      listData: state.getIn(["recommendReducer", "personalizedList"]),
    }),
    shallowEqual
  );
  useEffect(() => {
    dispatch(fetchPersonalizedAsyncAction());
  }, [dispatch]);
  return (
    <>
      <BannerComp />
      <section className="recommend_container wrap_980_center">
        <section className="container_left">
          <NRcmdTitleComp title="热门推荐" tabs={tabsState} />
          <section className="lists">
            {listData.map((item) => {
              return <CommonItem key={item.id} itemData={item} />;
            })}
          </section>
          <NRcmdTitleComp title="新碟上架" tag="new" />
          <NewDis />
          <NRcmdTitleComp title="榜单" tag="new" />
          {/* 榜单的主要内容 */}
          <section className="n-bilst">
            <dl className="blk">
              <dt className="top">
                <div className="cover">
                  <img
                    src="http://p3.music.126.net/DrRIg6CrgDfVLEph9SNh7w==/18696095720518497.jpg?param=100y100"
                    data-src="http://p3.music.126.net/DrRIg6CrgDfVLEph9SNh7w==/18696095720518497.jpg?param=100y100"
                    alt=""
                    className="j-img"
                  />
                  <a
                    href="/discover/toplist?id=19723756"
                    className="msk"
                    title="云音乐飙升榜"
                  ></a>
                </div>
                <div className="tit">
                  <a href="/discover/toplist?id=19723756" title="云音乐飙升榜">
                    <h3 className="fs1">云音乐飙升榜</h3>
                  </a>
                  <div className="btn">
                    <a href="" className="play ">
                      播放
                    </a>
                    <a href="" className="favorites">
                      收藏
                    </a>
                  </div>
                </div>
              </dt>
              <dd className="list-container">
                <ol className="">
                  <li>
                    <span className="no no-top">1</span>
                    <a href="" className="nm">
                      是想你的声音啊
                    </a>
                    <div className="oper">
                      <a href="" className="btn play"></a>
                      <a href="" className="btn add"></a>
                      <a href="" className="btn shou"></a>
                    </div>
                  </li>
                </ol>
              </dd>
            </dl>
            <dl className="blk">
              <dt className="top">
                <div className="cover">
                  <img
                    src="http://p3.music.126.net/N2HO5xfYEqyQ8q6oxCw8IQ==/18713687906568048.jpg?param=100y100"
                    data-src="http://p3.music.126.net/DrRIg6CrgDfVLEph9SNh7w==/18696095720518497.jpg?param=100y100"
                    alt=""
                    className="j-img"
                  />
                  <a
                    href="/discover/toplist?id=19723756"
                    className="msk"
                    title="云音乐飙升榜"
                  ></a>
                </div>
                <div className="tit">
                  <a href="/discover/toplist?id=19723756" title="云音乐飙升榜">
                    <h3 className="fs1">云音乐新歌榜</h3>
                  </a>
                  <div className="btn">
                    <a href="" className="play ">
                      播放
                    </a>
                    <a href="" className="favorites">
                      收藏
                    </a>
                  </div>
                </div>
              </dt>
              <dd className="list-container">
                <ol className="">
                  <li>
                    <span className="no no-top">1</span>
                    <a href="" className="nm">
                      是想你的声音啊
                    </a>
                    <div className="oper">
                      <a href="" className="btn play"></a>
                      <a href="" className="btn add"></a>
                      <a href="" className="btn shou"></a>
                    </div>
                  </li>
                </ol>
              </dd>
            </dl>
            <dl className="blk blk1">
              <dt className="top">
                <div className="cover">
                  <img
                    src="http://p3.music.126.net/sBzD11nforcuh1jdLSgX7g==/18740076185638788.jpg?param=100y100"
                    data-src="http://p3.music.126.net/DrRIg6CrgDfVLEph9SNh7w==/18696095720518497.jpg?param=100y100"
                    alt=""
                    className="j-img"
                  />
                  <a
                    href="/discover/toplist?id=19723756"
                    className="msk"
                    title="云音乐飙升榜"
                  ></a>
                </div>
                <div className="tit">
                  <a href="/discover/toplist?id=19723756" title="云音乐飙升榜">
                    <h3 className="fs1">网易原创歌曲榜</h3>
                  </a>
                  <div className="btn">
                    <a href="" className="play ">
                      播放
                    </a>
                    <a href="" className="favorites">
                      收藏
                    </a>
                  </div>
                </div>
              </dt>
              <dd className="list-container">
                <ol className="">
                  <li>
                    <span className="no no-top">1</span>
                    <a href="" className="nm">
                      是想你的声音啊
                    </a>
                    <div className="oper">
                      <a href="" className="btn play"></a>
                      <a href="" className="btn add"></a>
                      <a href="" className="btn shou"></a>
                    </div>
                  </li>
                </ol>
              </dd>
            </dl>
          </section>
        </section>
        <section className="container_right">
          <UserLoginComp />
        </section>
      </section>
    </>
  );
})