react-bootstrap#DropdownButton JavaScript Examples

The following examples show how to use react-bootstrap#DropdownButton. 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: Export.js    From anutimetable with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
Export = ({ API, year, session }) => {
  const [path, setPath] = useState('')
  const encoded = encodeURIComponent('http://'+path)
  const name = `ANU Timetable ${session} ${year}`

  return <DropdownButton
    style={{flexGrow: 1}}
    as={InputGroup.Append}
    alignRight
    title='Export'
    variant='outline-primary'
    id='export-button'
    onClick={() => setPath(`${API}/GetICS${window.location.search}`)}
  >
    <Dropdown.Item eventKey="web" target={"_blank"} rel={"noreferrer"}
      href={`webcal://${path}`}>
      <SiApple /> WebCal (eg iOS)
    </Dropdown.Item>
    <Dropdown.Item eventKey="gcal" target={"_blank"} rel={"noreferrer"}
      href={`https://www.google.com/calendar/render?cid=${encoded}`}>
      <SiGooglecalendar /> Google Calendar
    </Dropdown.Item>
    <Dropdown.Item eventKey="msol" target={"_blank"} rel={"noreferrer"}
      // undocumented OWA MSOL/AAD deeplinks. removing the 0 is supposed to work and could be necessary for some accounts
      // but in our case it drops all but the first qs param during parsing (maybe need double-encode?) and adds a 10s+ delay
      // source code - /owa/node_modules/calendar-bootstrap-config/src/routing/browseDiscoverCalendarsRouteHandler.ts
      href={`https://outlook.live.com/calendar/0/addfromweb?name=${name}&url=${encoded}`}>
      <SiMicrosoftoutlook /> Outlook.com
    </Dropdown.Item>
    <Dropdown.Item eventKey="aad" target={"_blank"} rel={"noreferrer"}
      href={`https://outlook.office.com/calendar/0/addfromweb?name=${name}&url=${encoded}`}>
      <SiMicrosoftexchange /> Office 365
    </Dropdown.Item>
    <Dropdown.Divider />
    <Dropdown.Item eventKey="ics" download={`${name} as of ${new Date().toLocaleDateString().replace(/(\/|\\)/g,'.')}.ics`} href={`${window.location.protocol}//${path}`}>
      <RiCalendar2Fill /> Download ICS file
    </Dropdown.Item>
  </DropdownButton>
}
Example #2
Source File: editor-dropdown.jsx    From codeinterview-frontend with Apache License 2.0 6 votes vote down vote up
editorDropdown = ({ defaultItem, items, handler }) => {
  return (
    <DropdownButton
      alignRight
      id="dropdown-basic-button"
      className="ml-auto mr-2"
      title={defaultItem}
      size="sm"
      variant="dark"
    >
      {items.map(item => {
        return (
          <Dropdown.Item
            as="button"
            key={item}
            onClick={e => handler(e, item)}
          >
            {item}
          </Dropdown.Item>
        );
      })}
    </DropdownButton>
  );
}
Example #3
Source File: ChartSelector.js    From indeplot with GNU General Public License v3.0 6 votes vote down vote up
render() {
        const { selected, color, colorPickerOn } = this.state;
        const { data, labels } = this.props;
        return (
            <Container>
                <Form inline className="justify-content-center mb-3">
                    <Form.Label className="mr-2">
                        Select Chart Type
                    </Form.Label>
                    <DropdownButton className="chart-type-selector" title={selected} variant="outline-dark" onSelect={this.handleSelect}>
                        {chartTypes.map((item, i) =>
                            <Dropdown.Item key={i} eventKey={item} >{chartTypeIcons[item]}{item}</Dropdown.Item>
                        )}
                    </DropdownButton>
                    <span>&nbsp;</span>
                    <Button as="input" type="button" value="Color Picker" variant="outline-dark" onClick={this.handleColorPicker} />
                    <Button type="button" variant="outline-dark" onClick={this.refreshData} className="ml-1">Refresh</Button>
                    <Modal show={colorPickerOn} onHide={this.handleModalClose}>
                        <Modal.Header closeButton>
                            Color Picker
                        </Modal.Header>
                        <Modal.Body>
                            <SketchPicker
                                width="95%"
                                color={this.state.color}
                                onChangeComplete={this.handleColor}
                            />
                        </Modal.Body>
                    </Modal>
                </Form>
                <Row>
                    <Col>
                        <Charts chartType={selected} chartColor={color} labels={labels} title="Sample" data={data} options={{}} />
                    </Col>
                </Row>
            </Container>
        )
    }
Example #4
Source File: index.js    From wedding-planner with MIT License 5 votes vote down vote up
function DropdownButtonAll(props) {
  return (
    <DropdownButton
      id="dropdown-basic-button"
      title="States"
      className="btn-md m-auto px-5 mb-5 text-white mt-3"
      size="md=auto"
      variant="outline-secondary light"
    >
      <Dropdown.Item href="#">Alabama</Dropdown.Item>
      <Dropdown.Item href="#">Alaska</Dropdown.Item>
      <Dropdown.Item href="#">Arizona</Dropdown.Item>
      <Dropdown.Item href="#">Arkansas</Dropdown.Item>
      <Dropdown.Item href="#">California</Dropdown.Item>
      <Dropdown.Item href="#">Colorado</Dropdown.Item>
      <Dropdown.Item href="#">Connecticut</Dropdown.Item>
      <Dropdown.Item href="#">Delaware</Dropdown.Item>
      <Dropdown.Item href="#">Florida</Dropdown.Item>
      <Dropdown.Item href="#">Georgia</Dropdown.Item>
      <Dropdown.Item href="#">Hawaii</Dropdown.Item>
      <Dropdown.Item href="#">Idaho</Dropdown.Item>
      <Dropdown.Item href="#">Illinois</Dropdown.Item>
      <Dropdown.Item href="#">Indiana</Dropdown.Item>
      <Dropdown.Item href="#">Iowa</Dropdown.Item>
      <Dropdown.Item href="#">Kansas</Dropdown.Item>
      <Dropdown.Item href="#">Kentucky</Dropdown.Item>
      <Dropdown.Item href="#">Louisiana</Dropdown.Item>
      <Dropdown.Item href="#">Maine</Dropdown.Item>
      <Dropdown.Item href="#">Maryland</Dropdown.Item>
      <Dropdown.Item href="#">Massachusetts</Dropdown.Item>
      <Dropdown.Item href="#">Michigan</Dropdown.Item>
      <Dropdown.Item href="#">Minnesota</Dropdown.Item>
      <Dropdown.Item href="#">Mississippi</Dropdown.Item>
      <Dropdown.Item href="#">Missouri</Dropdown.Item>
      <Dropdown.Item href="#">Montana</Dropdown.Item>
      <Dropdown.Item href="#">Nebraska</Dropdown.Item>
      <Dropdown.Item href="#">Nevada</Dropdown.Item>
      <Dropdown.Item href="#">New Hampshire</Dropdown.Item>
      <Dropdown.Item href="#">New Jersey</Dropdown.Item>
      <Dropdown.Item href="#">New Mexico</Dropdown.Item>
      <Dropdown.Item href="#">New York</Dropdown.Item>
      <Dropdown.Item href="#">North Carolina</Dropdown.Item>
      <Dropdown.Item href="#">North Dakota</Dropdown.Item>
      <Dropdown.Item href="#">Ohio</Dropdown.Item>
      <Dropdown.Item href="#">Oklahoma</Dropdown.Item>
      <Dropdown.Item href="#">Oregon</Dropdown.Item>
      <Dropdown.Item href="#">Pennsylvania</Dropdown.Item>
      <Dropdown.Item href="#">Rhode Island</Dropdown.Item>
      <Dropdown.Item href="#">South Carolina</Dropdown.Item>
      <Dropdown.Item href="#">South Dakota</Dropdown.Item>
      <Dropdown.Item href="#">Tennessee</Dropdown.Item>
      <Dropdown.Item href="#">Texas</Dropdown.Item>
      <Dropdown.Item href="#">Utah</Dropdown.Item>
      <Dropdown.Item href="#">Vermont</Dropdown.Item>
      <Dropdown.Item href="#">Virginia</Dropdown.Item>
      <Dropdown.Item href="#">Washington</Dropdown.Item>
      <Dropdown.Item href="#">West Virginia</Dropdown.Item>
      <Dropdown.Item href="#">Wisconsin</Dropdown.Item>
      <Dropdown.Item href="#">Wyoming</Dropdown.Item>
    </DropdownButton>
  );
}
Example #5
Source File: Settings.js    From viade_en1b with MIT License 4 votes vote down vote up
export function Settings(props) {
  const { changeLanguage, locale } = props;

  const handleLanguageChange = (lang) => {
    changeLanguage(lang);
  };
  return (
    <div className={style.settings}>
      <h2 className={style.settingsTitle} data-testid="settings-title">
        <FormattedMessage id="SettingsTitle" />
      </h2>

      <div className={style.language}>
        <h2 data-testid="settings-language">
          <FormattedMessage id="Language" />
        </h2>
        <DropdownButton
          data-testid="settings-language-dropdown"
          id="dropdown-basic-button"
          title={<FormattedMessage id={locale.id} />}
        >
          <Dropdown.Item
            data-testid="settings-language-english"
            onClick={() => {
              handleLanguageChange({
                id: "English",
                text: "English",
                locale: "en",
              });
            }}
            href="#"
          >
            <FormattedMessage id="English" />
          </Dropdown.Item>
          <Dropdown.Item
            data-testid="settings-language-spanish"
            onClick={() => {
              handleLanguageChange({
                id: "Spanish",
                text: "Spanish",
                locale: "es",
              });
            }}
            href="#"
          >
            <FormattedMessage id="Spanish" />
          </Dropdown.Item>
        </DropdownButton>
      </div>
      <div className={style.technicalInfo}>
        <h2>
          <FormattedMessage id="Technical" />
        </h2>
        <p>
          <FormattedMessage id="TechnicalDescription" />
          <a
            href="https://arquisoft.github.io/viade_en1b/docs/"
            target="_blank"
            rel="noopener noreferrer"
          >
            <FormattedMessage id="ThisPage" />
          </a>
        </p>
      </div>
      <div className={style.howToUse}>
        <h2>
          <FormattedMessage id="HowToUse" />
        </h2>
        <p>
          <FormattedMessage id="HowToUseDescription" /> <br></br>
          <a
            href="https://lamasumas.github.io/Solid/"
            target="_blank"
            rel="noopener noreferrer"
          >
            <FormattedMessage id="Here" />
          </a>
        </p>
      </div>
    </div>
  );
}
Example #6
Source File: jitsibroadcaster.js    From RC4Community with Apache License 2.0 4 votes vote down vote up
Jitsibroadcaster = ({ room, disName, rtmpSrc, handleChat }) => {
  const apiRef = useRef();
  const [logItems, updateLog] = useState([]);
  const [knockingParticipants, updateKnockingParticipants] = useState([]);
  const [mute, setMute] = useState(true);
  const [name, setName] = useState(null);
  const dataArr = [
    { speaker: "A", hour: "10" },
    { speaker: "B", hour: "20" },
    { speaker: "C", hour: "30" },
    { speaker: "D", hour: "40" },
    { speaker: "Z", hour: "50" },
  ];

  const handleDisplayName = async (hr) => {
    const tar = dataArr.find((o) => o.hour === hr);
    if (!tar || tar.speaker == name) {
      return;
    }
    setName(tar.speaker);
    await apiRef.current.executeCommand("displayName", tar.speaker);
  };

  useEffect(() => {
    setInterval(() => {
      const tada = new Date();
      handleDisplayName(tada.getHours().toString());
    }, 900000);
  }, []);

  const printEventOutput = (payload) => {
    updateLog((items) => [...items, JSON.stringify(payload)]);
  };

  const handleAudioStatusChange = (payload, feature) => {
    if (payload.muted) {
      updateLog((items) => [...items, `${feature} off`]);
    } else {
      updateLog((items) => [...items, `${feature} on`]);
    }
  };

  const handleChatUpdates = (payload, ref) => {
    if (payload.isOpen || !payload.unreadCount) {
      return;
    }
    ref.current.executeCommand("toggleChat");
    updateLog((items) => [
      ...items,
      `you have ${payload.unreadCount} unread messages`,
    ]);
  };

  const handleKnockingParticipant = (payload) => {
    updateLog((items) => [...items, JSON.stringify(payload)]);
    updateKnockingParticipants((participants) => [
      ...participants,
      payload?.participant,
    ]);
  };

  const resolveKnockingParticipants = (ref, condition) => {
    knockingParticipants.forEach((participant) => {
      ref.current.executeCommand(
        "answerKnockingParticipant",
        participant?.id,
        condition(participant)
      );
      updateKnockingParticipants((participants) =>
        participants.filter((item) => item.id === participant.id)
      );
    });
  };

  const handleJitsiIFrameRef1 = (iframeRef) => {
    iframeRef.style.border = "10px solid cadetblue";
    iframeRef.style.background = "cadetblue";
    iframeRef.style.height = "25em";
    iframeRef.style.width = "75%";
  };

  const showDevices = async (ref) => {
    const videoInputs = [];
    // get all available video input
    const devices = await ref.current.getAvailableDevices();

    for (const [key, value] of Object.entries(devices)) {
      if (key == "videoInput") {
        value.forEach((vid) => {
          videoInputs.push(vid.label);
        });
      }
    }
    // log for debug
    updateLog((items) => [...items, JSON.stringify(videoInputs)]);

    let nextDevice = "";
    let devs = await ref.current.getCurrentDevices();

    for (const [key, value] of Object.entries(devs)) {
      if (key == "videoInput") {
        updateLog((items) => [...items, "found " + JSON.stringify(value)]);
        let devLabel = value.label;
        let idx = 0;
        videoInputs.forEach((vid) => {
          if (devLabel == vid) {
            let cur = idx + 1;
            if (cur >= videoInputs.length) {
              nextDevice = videoInputs[0];
            } else {
              nextDevice = videoInputs[cur];
              updateLog((items) => [...items, "next is " + nextDevice]);
            }
          }
          idx++;
        });
      }
    }
    updateLog((items) => [...items, "switching to " + nextDevice]);

    await ref.current.setVideoInputDevice(nextDevice);
  };

  const showAudioOutDevices = async (ref) => {
    const audioOutputs = [];
    // get all available audio output
    const devices = await ref.current.getAvailableDevices();

    for (const [key, value] of Object.entries(devices)) {
      if (key == "audioOutput") {
        value.forEach((vid) => {
          audioOutputs.push(vid.label);
        });
      }
    }
    // log for debug
    updateLog((items) => [...items, JSON.stringify(audioOutputs)]);

    let nextDevice = "";
    let devs = await ref.current.getCurrentDevices();

    for (const [key, value] of Object.entries(devs)) {
      if (key == "audioOutput") {
        updateLog((items) => [...items, "found " + JSON.stringify(value)]);
        let devLabel = value.label;
        let idx = 0;
        audioOutputs.forEach((vid) => {
          if (devLabel == vid) {
            let cur = idx + 1;
            if (cur >= audioOutputs.length) {
              nextDevice = audioOutputs[0];
            } else {
              nextDevice = audioOutputs[cur];
              updateLog((items) => [...items, "next is " + nextDevice]);
            }
          }
          idx++;
        });
      }
    }
    updateLog((items) => [...items, "switching to " + nextDevice]);

    await ref.current.setAudioOutputDevice(nextDevice);
  };

  const showAudioDevice = async (ref) => {
    const audioInputs = [];
    // get all available audio input
    const devices = await ref.current.getAvailableDevices();

    for (const [key, value] of Object.entries(devices)) {
      if (key == "audioInput") {
        value.forEach((vid) => {
          audioInputs.push(vid.label);
        });
      }
    }
    // log for debug
    updateLog((items) => [...items, JSON.stringify(audioInputs)]);

    let nextDevice = "";
    let devs = await ref.current.getCurrentDevices();

    for (const [key, value] of Object.entries(devs)) {
      if (key == "audioInput") {
        updateLog((items) => [...items, "found " + JSON.stringify(value)]);
        let devLabel = value.label;
        let idx = 0;
        audioInputs.forEach((vid) => {
          if (devLabel == vid) {
            let cur = idx + 1;
            if (cur >= audioInputs.length) {
              nextDevice = audioInputs[0];
            } else {
              nextDevice = audioInputs[cur];
              updateLog((items) => [...items, "next is " + nextDevice]);
            }
          }
          idx++;
        });
      }
    }
    updateLog((items) => [...items, "switching to " + nextDevice]);
    await ref.current.setAudioInputDevice(nextDevice);
  };

  const handleApiReady = async (apiObj, ref) => {
    ref.current = apiObj;
    await ref.current.addEventListeners({
      // Listening to events from the external API
      audioMuteStatusChanged: (payload) =>
        handleAudioStatusChange(payload, "audio"),
      videoMuteStatusChanged: (payload) =>
        handleAudioStatusChange(payload, "video"),
      raiseHandUpdated: printEventOutput,
      tileViewChanged: printEventOutput,
      chatUpdated: (payload) => handleChatUpdates(payload, ref),
      knockingParticipant: handleKnockingParticipant,
    });

    await ref.current.executeCommand("toggleFilmStrip");
  };

  // Multiple instances demo
  const showUsers = async (ref, which) => {
    try {
      const pinfo = await ref.current.getParticipantsInfo();
      updateLog((items) => [
        ...items,
        "participantes " + JSON.stringify(pinfo),
      ]);
      await ref.current.executeCommand("setTileView", false);
      await ref.current.setLargeVideoParticipant(pinfo[which].participantId);
    } catch (e) {
      console.error("Participant not found!");
      return;
    }
  };

  const makeTile = (ref) => {
    ref.current.executeCommand("setTileView", true);
  };

  const renderStream = (key) => (
    <div className={styles.streamButton}>
      <ButtonGroup className="m-auto">
        <Button
          variant="warning"
          title="Click to start streaming"
          onClick={() =>
            apiRef.current.executeCommand("startRecording", {
              mode: "stream",
              rtmpStreamKey: key,
              youtubeStreamKey: "",
            })
          }
        >
          Go live!
        </Button>
      </ButtonGroup>
    </div>
  );

  const toggleDevice = () => (
    <div className={styles.device}>
      <Button disabled variant="light">
        <AiFillSetting size={20} />
      </Button>
      <ButtonGroup vertical className="m-auto">
        <OverlayTrigger
          overlay={<Tooltip id="tooltip-disabled">Microphone Device</Tooltip>}
        >
          <Button
            title="Click to switch audio devices"
            onClick={() => showAudioDevice(apiRef)}
          >
            <RiMic2Line size={20} />
          </Button>
        </OverlayTrigger>
        <OverlayTrigger
          overlay={<Tooltip id="tooltip-disabled">Camera Device</Tooltip>}
        >
          <Button
            title="Click to switch video devices"
            onClick={() => showDevices(apiRef)}
          >
            <MdCameraswitch size={20} />
          </Button>
        </OverlayTrigger>
        <OverlayTrigger
          overlay={<Tooltip id="tooltip-disabled">Audio Device</Tooltip>}
        >
          <Button
            title="Click to switch audio devices"
            onClick={() => showAudioOutDevices(apiRef)}
          >
            <MdHeadset size={20} />
          </Button>
        </OverlayTrigger>
      </ButtonGroup>
    </div>
  );

  const toggleView = () => (
    <div className={styles.view}>
      <Button variant="light" disabled>
        <AiFillEye size={20} />
      </Button>
      <ButtonGroup vertical className="m-auto">
        <OverlayTrigger
          overlay={<Tooltip id="tooltip-disabled">Tile View</Tooltip>}
        >
          <Button
            variant="secondary"
            onClick={() => makeTile(apiRef)}
            title="Click to toggle tile view"
          >
            <HiViewGridAdd size={20} />
          </Button>
        </OverlayTrigger>
        <OverlayTrigger
          overlay={<Tooltip id="tooltip-disabled">First User</Tooltip>}
        >
          <Button onClick={() => showUsers(apiRef, 0)} variant="secondary">
            <BiUserPin size={20} />
          </Button>
        </OverlayTrigger>
        <OverlayTrigger
          overlay={<Tooltip id="tooltip-disabled">Second User</Tooltip>}
        >
          <Button onClick={() => showUsers(apiRef, 1)} variant="secondary">
            <FiUsers size={20} />
          </Button>
        </OverlayTrigger>
      </ButtonGroup>
    </div>
  );

  const toolButton = () => (
    <div className={styles.deviceButton}>
      <ButtonGroup className="m-auto">
        <Button
          variant="success"
          title="Click to toogle audio"
          onClick={() => {
            apiRef.current.executeCommand("toggleAudio");
            setMute(!mute);
          }}
        >
          {mute ? <BiMicrophoneOff /> : <BiMicrophone />}
        </Button>
        <DropdownButton variant="danger" as={ButtonGroup} title="End">
          <Dropdown.Item
            as="button"
            onClick={() => apiRef.current.executeCommand("hangup")}
          >
            Leave Meet
          </Dropdown.Item>
          <Dropdown.Item
            variant="danger"
            as="button"
            onClick={() => apiRef.current.stopRecording("stream")}
          >
            End for everyone!
          </Dropdown.Item>
        </DropdownButton>
        <Button color="#f5455c" onClick={handleChat}>
          <FaRocketchat />
        </Button>
      </ButtonGroup>
    </div>
  );

  const renderLog = () =>
    logItems.map((item, index) => (
      <div
        style={{
          fontFamily: "monospace",
          padding: "5px",
        }}
        key={index}
      >
        {item}
      </div>
    ));

  const renderSpinner = () => (
    <div
      style={{
        fontFamily: "sans-serif",
        textAlign: "center",
      }}
    >
      Loading..
    </div>
  );

  return (
    <>
      {rtmp ? renderStream(rtmp) : rtmpSrc && renderStream(rtmpSrc)}
      <div className={styles.jitsiContainer}>
        {toggleDevice()}

        <JitsiMeeting
          domain="meet.jit.si"
          roomName={room}
          spinner={renderSpinner}
          onApiReady={(externalApi) => handleApiReady(externalApi, apiRef)}
          getIFrameRef={handleJitsiIFrameRef1}
          configOverwrite={{
            startWithAudioMuted: true,
            disableModeratorIndicator: true,
            startScreenSharing: false,
            enableEmailInStats: false,
            toolbarButtons: [],
            enableWelcomePage: false,
            prejoinPageEnabled: false,
            startWithVideoMuted: false,
            liveStreamingEnabled: true,
            disableSelfView: false,
            disableSelfViewSettings: true,
            disableShortcuts: true,
            disable1On1Mode: true,
            p2p: {
              enabled: false,
            },
          }}
          interfaceConfigOverwrite={{
            DISABLE_JOIN_LEAVE_NOTIFICATIONS: true,
            FILM_STRIP_MAX_HEIGHT: 0,
            TILE_VIEW_MAX_COLUMNS: 0,
            VIDEO_QUALITY_LABEL_DISABLED: true,
          }}
          userInfo={{
            displayName: disName,
          }}
        />
        {toggleView()}
      </div>
      {toolButton()}
      <div className={styles.log}>{renderLog()}</div>
    </>
  );
}
Example #7
Source File: index.js    From Algorithm-Visualizer with MIT License 4 votes vote down vote up
Header = ({
  algorithm,
  animationSpeed,
  device,
  fenceToggle,
  ready,
  resizeGrid,
  resetFences,
  resetVisited,
  run: propRun,
  setAlgorithm,
  speed: propsSpeed,
  setNodeSize: propsNodeSize,
}) => {
  const mobile = device === "mobile";

  const [nodeSize, setNodeSize] = useState(defaultNodeSize);

  const [screenWidth, screenHeight] = getDimensions();
  const defaultDimensions = [
    maxFill(window.innerWidth, nodeSize),
    mobile ? maxFill(window.innerHeight, nodeSize) : screenHeight,
  ];
  const [maxDimensions, setMaxDimensions] = useState(defaultDimensions);

  const [maxWidth, maxHeight] = maxDimensions;

  // form value display
  const [width, setWidth] = useState(Math.ceil(screenWidth));
  const [height, setHeight] = useState(Math.ceil(screenHeight));
  const [speed, setSpeed] = useState(propsSpeed);

  // bootstrap
  const [show, setShow] = useState();
  const [expanded, setExpanded] = useState(false);

  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);
  const collapseNav = () => setExpanded(false);

  const run = () => {
    if (algorithm === "") alert("Please select an algorithm");

    if (!ready)
      alert(
        "Please choose a start and finish point before running by clicking on the desired squares"
      );

    if (ready && algorithm) {
      if (mobile) {
        setTimeout(() => propRun(), 200);
        collapseNav();
        scroll.scrollToBottom({
          duration: 1200,
          delay: 100,
          smooth: true,
        });
      } else setTimeout(() => propRun(), 200);
    }
  };

  const nodeSizeHandler = (e) => {
    // for display
    setNodeSize(e.target.value);
    // for visualizer to change node inline style
    propsNodeSize(e.target.value);

    let [width, height] = getDimensions(e.target.value);

    resizeGrid([width, height]);
    setMaxDimensions([
      maxFill(window.innerWidth, nodeSize),
      mobile ? maxFill(window.innerWidth, e.target.value) : height,
    ]);
    setWidth(width);
    setHeight(height);
  };

  const gitHubImage = (
    <Image
      src="/images/github.png"
      className={"github-img"}
      alt={"Github"}
      fluid
    />
  );

  const linkedInImage = (
    <Image
      src="/images/linkedin.png"
      alt={"LinkedIn"}
      className={"linkedin-img"}
      fluid
    />
  );

  const algorithmDropdowns = algorithmInfo.map((alg, i) => {
    return (
      <OverlayTrigger
        key={i}
        trigger={["hover", "focus"]}
        placement={mobile ? "bottom" : "right"}
        overlay={
          <Popover id={`${alg.id}-popover`}>
            <Popover.Title as="h2" children={`${alg.name}`} />
            <Popover.Content>
              <p>
                <strong>{`${alg.header}`}</strong>
              </p>
              <p style={{ whiteSpace: "pre-line" }}>{`${alg.content}`}</p>
              <p>{`${alg.footer}`}</p>
            </Popover.Content>
          </Popover>
        }
      >
        <NavDropdown.Item
          id={`set-${alg.id}`}
          onClick={() => setAlgorithm(`${alg.name}`)}
          children={`${alg.name}`}
          active={algorithm === `${alg.name}`}
        />
      </OverlayTrigger>
    );
  });

  const howToUse = (
    <Modal show={show} onHide={handleClose}>
      <Modal.Header closeButton>
        <Modal.Title>How To Use</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <Container>
          <Row>
            1. Place a start and end point by clicking on the grid! (You can
            remove them by clicking on them again)
          </Row>
          <Row>
            {" "}
            2. Then place fences by checking "Fence Mode" and clicking on the
            grid.{" "}
          </Row>
          <Row>3. Choose an algorithm via the "Algorithms" dropdown. </Row>
          <Row>4. Run it via pressing the green "Run Algorithm" button. </Row>
          <Row>5. Enjoy!</Row>
        </Container>
      </Modal.Body>
      <Modal.Footer>
        <Button variant="primary" onClick={handleClose}>
          Close
        </Button>
      </Modal.Footer>
    </Modal>
  );

  const settings = (
    <DropdownButton title="Settings" size="sm" variant="dark">
      <Container variant="dark">
        <Row>
          <Form variant="dark" inline>
            <Col>
              Node Size
              <FormControl
                size="sm"
                type="text"
                placeholder={`Currently ${nodeSize})`}
                onChange={(e) => {
                  setNodeSize(e.target.value);
                }}
              />
              <Form.Control
                type="range"
                size="sm"
                min="10"
                max="100"
                value={nodeSize}
                onChange={nodeSizeHandler}
                custom
              />
              Grid Size
              <FormControl
                size="sm"
                type="text"
                placeholder={`Width (Currently ${width})`}
                onChange={(e) => {
                  setWidth(e.target.value);
                }}
              />
              <Form.Control
                type="range"
                size="sm"
                min="1"
                max={maxWidth}
                value={width}
                onChange={(e) => {
                  setWidth(e.target.value);
                  resizeGrid([e.target.value, height]);
                }}
                custom
              />
              <NavDropdown.Divider />
              <FormControl
                type="text"
                size="sm"
                placeholder={`Height (Currently ${height})`}
                onChange={(e) => {
                  setHeight(e.target.value);
                }}
                className="Row-Input"
              />
              <Form.Control
                type="range"
                min="1"
                max={maxHeight}
                value={height}
                onChange={(e) => {
                  setHeight(e.target.value);
                  resizeGrid([width, e.target.value]);
                }}
                custom
              />
              <NavDropdown.Divider />
              <Form.Label children={"Draw Square"} />
              <Form.Control
                type="range"
                size="sm"
                min="1"
                max={mobile ? maxWidth : maxHeight}
                value={(height, width)}
                onChange={(e) => {
                  setWidth(e.target.value);
                  setHeight(e.target.value);
                  resizeGrid([e.target.value, e.target.value]);
                }}
                custom
              />
              <NavDropdown.Divider />
              <Form.Label children={"Animation Speed"} />
              <Form.Control
                type="range"
                min="1"
                max="5"
                value={speed}
                onChange={(e) => {
                  setSpeed(e.target.value);
                  animationSpeed(e.target.value);
                }}
                custom
              />
            </Col>
          </Form>
        </Row>
      </Container>
    </DropdownButton>
  );

  const contactInfo = (
    <DropdownButton title=" Contact The Creators" size="sm" id="contact-info">
      <Container>
        <Row>
          <NavDropdown.Item id={"bassel"} children={"Bassel"} />
          <a
            className={"image-link"}
            href="https://github.com/basselalsayed"
            children={gitHubImage}
          />
          <a
            className={"image-link"}
            href="https://www.linkedin.com/in/bsas/"
            children={linkedInImage}
          />
        </Row>
        <Row>
          <NavDropdown.Item id={"tom"} children={"Tom"} />
          <a
            className={"image-link"}
            href="https://github.com/Walker-TW"
            children={gitHubImage}
          />
          <a
            className={"image-link"}
            href="https://www.linkedin.com/in/thomas-w-walker"
            children={linkedInImage}
          />
        </Row>
      </Container>
    </DropdownButton>
  );

  return (
    <Navbar
      expanded={expanded}
      expand="lg"
      bg="dark"
      variant="dark"
      collapseOnSelect
    >
      <Navbar.Brand
        href="https://github.com/Walker-TW/Algorithm-Visualizer"
        children={"Algo-Visualiser"}
      />
      <Navbar.Toggle
        onClick={() => setExpanded(expanded ? false : "lg")}
        aria-controls="responsive-navbar-nav"
      />
      <Navbar.Collapse id="responsive-navbar-nav">
        <Container fluid>
          <Col md={{ span: 2 }}>
            <Nav className="mr-auto">
              <NavDropdown title="Algorithms" id="collapsible-nav-dropdown">
                {algorithmDropdowns}
              </NavDropdown>
            </Nav>
          </Col>
          <Col md={{ span: 4 }}>
            <Nav>
              <Button
                id="info-btn"
                style={{ border: "2px solid cyan", color: "cyan" }}
                variant="dark"
                children={"How To Use"}
                onClick={handleShow}
              />
              {howToUse}
              <Button
                id="run-btn"
                style={{ border: "2px solid chartreuse", color: "chartreuse" }}
                variant="dark"
                onClick={run}
                children={
                  algorithm
                    ? `Let's Run ${algorithm}`
                    : "Please Select Algorithm"
                }
                disabled={!ready || algorithm === ""}
              />
              <Dropdown as={ButtonGroup}>
                <Button
                  id="reset-btn"
                  variant="dark"
                  style={{ border: "2px solid red", color: "red" }}
                  children={"Reset Visited"}
                  onClick={resetVisited}
                />
                <Dropdown.Toggle
                  split
                  variant="dark"
                  style={{ border: "2px solid red", color: "red" }}
                  id="dropdown-custom-2"
                />
                <Dropdown.Menu>
                  <Dropdown.Item
                    id="fence-reset-btn"
                    onClick={resetFences}
                    variant="dark"
                    children={"Reset Fences"}
                  />
                </Dropdown.Menu>
              </Dropdown>
            </Nav>
          </Col>
          <Col md={{ span: 4 }}>
            <Nav navbar="true">
              <Container>
                <Form inline>
                  <Form.Check
                    type="switch"
                    id="fence-check"
                    name="fences"
                    label="Fence mode"
                    style={{ color: "white" }}
                    onChange={fenceToggle}
                  />
                </Form>
              </Container>
              {settings}
              {contactInfo}
            </Nav>
          </Col>
        </Container>
      </Navbar.Collapse>
    </Navbar>
  );
}
Example #8
Source File: tasks.js    From community-forum-frontend with GNU General Public License v3.0 4 votes vote down vote up
render() {
    return (
      <div>
        <Modal show={this.state.showModal} onHide={this.handleClose} centered>
          <div className="modalbody">
            <Modal.Body>
              <Form>
                <div className="formdetails">
                  <div className="forminsides">
                    <Form.Group controlId="Description">
                      <Form.Label>Description</Form.Label>
                      <Form.Control
                        as="textarea"
                        rows="3"
                        placeholder="Description"
                        onChange={(e) => {
                          this.handleChange("description", e);
                        }}
                      />
                    </Form.Group>
                    <Form.Group controlId="TopicList">
                      <Form.Label>Topic</Form.Label>
                      <InputGroup>
                        <FormControl
                          placeholder={this.state.topicName}
                          aria-describedby="basic-addon2"
                          disabled="true"
                        />

                        <DropdownButton
                          as={InputGroup.Append}
                          variant="outline-secondary"
                          title=""
                          id="input-group-dropdown-2"
                        >
                          {this.state.Topics.map((topic) => {
                            return (
                              <Dropdown.Item
                                eventKey={topic.topicName}
                                onSelect={() =>
                                  this.handleSelect(
                                    topic.topicName,
                                    {
                                      topic: topic.topicName,
                                      id: topic._id,
                                    },
                                    "topics"
                                  )
                                }
                              >
                                {topic.topicName}
                              </Dropdown.Item>
                            );
                          })}
                        </DropdownButton>
                      </InputGroup>
                    </Form.Group>
                    <Form.Group controlId="assigned">
                      <Form.Label>Assign To:</Form.Label>
                      <InputGroup>
                        <FormControl
                          placeholder={this.state.username}
                          aria-describedby="basic-addon2"
                          disabled="true"
                        />
                        <DropdownButton
                          as={InputGroup.Append}
                          variant="outline-secondary"
                          title=""
                          id="input-group-dropdown-2"
                        >
                          {this.state.users.map((user) => {
                            return (
                              <Dropdown.Item
                                eventKey={user.username}
                                onSelect={() =>
                                  this.handleSelect(
                                    user.username,
                                    {
                                      username: user.username,
                                      email: user.email,
                                      id: user._id,
                                    },
                                    "users"
                                  )
                                }
                              >
                                {user.username}
                              </Dropdown.Item>
                            );
                          })}
                        </DropdownButton>
                      </InputGroup>
                    </Form.Group>
                    <Form.Group controlId="setDate">
                      <Form.Label>Complete By: </Form.Label>
                      <Form.Control
                        type="date"
                        placeholder="Enter email"
                        onChange={(e) => this.handleChange("date", e)}
                      />
                    </Form.Group>
                  </div>
                </div>
                <div className="cta-register">
                  <Button
                    variant="primary"
                    type="submit"
                    onClick={(e) => this.handleAddTask(e)}
                  >
                    Add Task
                  </Button>
                </div>
              </Form>
            </Modal.Body>
          </div>
        </Modal>
        <div className="ToDosHeading">
          To-Do Tasks
          <Button className="addbutton" onClick={this.handleTasksAdd}>
            Add
          </Button>
        </div>
        <div className="navTabs">
          <Tabs defaultActiveKey="ongoing" id="uncontrolled-tab-example">
            <Tab eventKey="ongoing" title="OnGoing" className="ongoingTab">
              <Form>
                {this.state.tasks.map((task) => {
                  return task.completed ? (
                    ""
                  ) : (
                    <div>
                      <Form.Group
                        controlId="formBasicCheckbox"
                        className="formCheckbox"
                        onChange={(e) =>
                          this.handleChangeTask("completed", e, task._id)
                        }
                        id={task.description}
                      >
                        <Form.Check type="checkbox" />
                        <div className="textTasks">
                          <div className="labelParra">{task.description}</div>
                          <div className="subparra">
                            {task.assignedBy.username}, {task.dueDate}.
                          </div>
                        </div>
                        <div className="icons">
                          <FiMoreVertical
                            size={20}
                            className="FiMoreVertical"
                          />
                          <MdInfoOutline size={20} className="FiMoreVertical" />
                        </div>
                      </Form.Group>
                    </div>
                  );
                })}
              </Form>
            </Tab>

            <Tab
              eventKey="completed"
              title="Completed"
              className="completedTab"
            >
              {this.state.tasks.map((task) => {
                return task.completed ? (
                  <Form.Group
                    controlId="formBasicCheckbox"
                    className="formCheckbox"
                    onChange={(e) =>
                      this.handleChangeTask("notCompleted", e, task._id)
                    }
                  >
                    <Form.Check
                      defaultChecked="true"
                      type="checkbox"
                      label={
                        <div className="textTasks">
                          <div className="labelParra">
                            <s>{task.description}</s>
                          </div>
                          <div className="subparra">
                            {task.assignedBy.username}, {task.dueDate}.
                          </div>
                        </div>
                      }
                    />
                    <div className="icons">
                      <FiMoreVertical size={20} className="FiMoreVertical" />
                      <MdInfoOutline size={20} className="FiMoreVertical" />
                    </div>
                  </Form.Group>
                ) : (
                  ""
                );
              })}
            </Tab>
          </Tabs>
        </div>
      </div>
    );
  }
Example #9
Source File: PlotSelectionToolbar.jsx    From mapstore2-cadastrapp with GNU General Public License v3.0 4 votes vote down vote up
export default function PlotSelectionToolbar({
    foncier,
    authLevel = {},
    currentData = [],
    loadInfo = () => {},
    onSaveAsAnnotation = () => {},
    zoomToSelection = () => {},
    removePlots = () => {},
    showLandedPropertyInformationByParcelle = () => {},
    selectedPlots = []
}) {
    const atLeastOneSelected = selectedPlots.length > 0;
    const onlyOneSelected = selectedPlots.length === 1;
    const isDataPresent = currentData.length > 0;
    const { isCNIL1, isCNIL2 } = authLevel;
    const [showBundleInformation, setShowBundleInformation] = useState(false);
    const [exportPlotModal, setExportPlotModal] = useState(false);
    return (
        <>
            <Toolbar
                btnGroupProps={{className: "pull-right"}}
                btnDefaultProps={{
                    tooltipPosition: 'bottom'
                }}
                buttons={[{
                    disabled: !isDataPresent,
                    glyph: "zoom-in",
                    tooltipId: atLeastOneSelected ? "cadastrapp.result.parcelle.zoom.selection" : "cadastrapp.result.parcelle.zoom.list",
                    onClick: zoomToSelection
                }, ...(foncier
                    ? [{
                        disabled: !onlyOneSelected,
                        glyph: "th-list",
                        tooltipId: "cadastrapp.result.parcelle.uf",
                        onClick: () => { showLandedPropertyInformationByParcelle(find(currentData, {parcelle: selectedPlots[0]})); }
                    }]
                    : []), {
                    disabled: !atLeastOneSelected,
                    glyph: "trash",
                    tooltipId: "cadastrapp.result.parcelle.delete",
                    onClick: () => { removePlots(selectedPlots); }
                }, {
                    disabled: !atLeastOneSelected,
                    glyph: "info-sign",
                    tooltipId: "cadastrapp.result.parcelle.fiche",
                    onClick: () => { loadInfo(selectedPlots);}
                }, {
                    disabled: !isDataPresent,
                    glyph: "comment",
                    tooltipId: "cadastrapp.result.parcelle.saveAsAnnotation",
                    onClick: () => { onSaveAsAnnotation(selectedPlots);}
                }, ((isCNIL1 || isCNIL2) ? {
                    renderButton:
                        (<DropdownButton
                            disabled={!atLeastOneSelected}
                            pullRight title={< Glyphicon glyph="export" />}>
                            <MenuItem onClick={() => exportParcellesAsCSV({ parcelles: selectedPlots }).then(downloadResponse)}>
                                <Message msgId={"cadastrapp.result.csv.button.parcelles"} />
                            </MenuItem>
                            <MenuItem onClick={() => exportProprietaireByParcelles({ parcelles: selectedPlots }).then(downloadResponse)}>
                                <Message msgId={"cadastrapp.result.csv.button.owner"} />
                            </MenuItem>
                            <MenuItem onClick={() => exportCoProprietaireByParcelles({ parcelles: selectedPlots }).then(downloadResponse)}>
                                <Message msgId={"cadastrapp.result.csv.button.coowner"} />
                            </MenuItem>
                            <MenuItem disabled={!onlyOneSelected} onClick={() => {
                                // prevent click event when disabled
                                if (onlyOneSelected) {
                                    setShowBundleInformation(true);
                                }
                            }}><Message msgId={"cadastrapp.result.csv.button.bundle"} /></MenuItem>
                            <MenuItem onClick={() => setExportPlotModal(true)}>
                                <Message msgId={"cadastrapp.result.pdf.export"} /></MenuItem>
                        </DropdownButton>)
                } : {
                    renderButton: (
                        <DropdownButton
                            disabled={!isDataPresent || !atLeastOneSelected}
                            pullRight title={< Glyphicon glyph="export" />}>
                            <MenuItem
                                onClick={() => exportParcellesAsCSV({ parcelles: selectedPlots }).then(downloadResponse)}>
                                <Message msgId={"cadastrapp.result.csv.export"} />
                            </MenuItem>
                            <MenuItem onClick={() => setExportPlotModal(true)}>
                                <Message msgId={"cadastrapp.result.pdf.export"} /></MenuItem>
                        </DropdownButton>
                    )
                })
                ]}
            />
            <BundleInformationModal show={showBundleInformation} onClose={() => setShowBundleInformation(false)} parcelle={selectedPlots[0]} />
            <ExportPlotsAsPDFModal show={exportPlotModal} onClose={()=> setExportPlotModal(false) }
                parcelle={selectedPlots} isCNIL1={isCNIL1} isCNIL2={isCNIL2}/>
        </>);
}
Example #10
Source File: SelectedPool.js    From katanapools with GNU General Public License v2.0 4 votes vote down vote up
render() {
    const {pool: {currentSelectedPool, currentSelectedPoolError}} = this.props;

    const {reservesNeeded, reservesAdded, fundAllReservesActive, fundOneReserveActive, singleTokenFundConversionPaths,
      withdrawAllReservesActive, withdrawOneReserveActive, singleTokenWithdrawReserveSelection, singleTokenFundReserveSelection,
      singleTokenWithdrawConversionPaths, calculatingFunding, calculatingWithdraw, submitFundingEnabled, fundingCalculateInit, withdrawCalculateInit,
      calculatingAllInputFunding, calculatingAllInputWithdraw,
      
      fundReserveSelection, withdrawSelection
    } = this.state;
    
    const self = this;
    
    let isPurchaseBtnDisabled = false;

    
    let isFundingLoading = <span/>;
    let isWithdrawLoading = <span/>;
    if (calculatingFunding && !fundingCalculateInit) {
      isFundingLoading = <FontAwesomeIcon icon={faSpinner} size="lg" rotation={270} pulse/>;
    }
    
    if (calculatingWithdraw && !withdrawCalculateInit) {
      isWithdrawLoading = <FontAwesomeIcon icon={faSpinner} size="lg" rotation={270} pulse/>;
    }

    let isWithdrawBtnDisabled = false;
    
    if (calculatingFunding) {
     // isPurchaseBtnDisabled = true;
    }

    if (calculatingWithdraw) {
      isWithdrawBtnDisabled = true;
    }
    
    let reserveRatio = '';

    reserveRatio = currentSelectedPool.reserves && currentSelectedPool.reserves.length > 0 ?currentSelectedPool.reserves.map(function(item){
      if (item) {
      return parseInt(item.reserveRatio) / 10000;
      } else {
        return null;
      }
    }).filter(Boolean).join("/") : '';


    if (currentSelectedPoolError) {
      return (<div>
      <div>Could not fetch pool details.</div>
      <div>Currently only pool contracts which expose reserveTokenCount() and reserveTokens() methods are supported.</div>
      </div>)
    }
    const { fundAmount, liquidateAmount } = this.state;

    let minTotalSupply = currentSelectedPool.totalSupply ? 
                          parseFloat(fromDecimals(currentSelectedPool.totalSupply, currentSelectedPool.decimals)).toFixed(4) : "";
    let reserveTokenList = currentSelectedPool.reserves && currentSelectedPool.reserves.length > 0 ? currentSelectedPool.reserves.map(function(item, idx){
      return <div key={`token-${idx}`}>
        <div className="holdings-label">{item.name}</div>
        <div className="holdings-data">&nbsp;{parseFloat(fromDecimals(item.reserveBalance, item.decimals)).toFixed(4)}</div>
      </div>
    }) : <span/>;

    let userHoldingsList = currentSelectedPool.reserves && currentSelectedPool.reserves.length > 0 ? currentSelectedPool.reserves.map(function(item, idx){
      let userBalanceItem = parseFloat(item.userBalance);
      let userBalanceDisplay = "-";
      if (!isNaN(userBalanceItem)) {
        userBalanceDisplay = userBalanceItem.toFixed(4);
      }
      return (<div key={`token-${idx}`}>
        <div className="holdings-label">{item.name}</div>
        <div className="holdings-data">&nbsp;{userBalanceDisplay}</div>
      </div>)
    }) : <span/>;

    let poolHoldings = "";
    if (currentSelectedPool.senderBalance ) {
      poolHoldings = parseFloat(fromDecimals(currentSelectedPool.senderBalance, currentSelectedPool.decimals)).toFixed(4) + " " + currentSelectedPool.symbol;
    }
    let liquidateInfo = <span/>;
    if (liquidateAmount && liquidateAmount > 0 && reservesAdded && reservesAdded.length > 0) {
      liquidateInfo = (
        <div>
          <div>You will receive</div>
            {reservesAdded.map(function(item, idx){
              return <div key={`reserve-added-${idx}`}>{item.addedDisplay} {item.symbol}</div>
            })}
        </div>
        )
    }
    let fundInfo = <span/>;

    if (fundAmount && fundAmount > 0 && reservesNeeded && reservesNeeded.length > 0) {
      fundInfo = (
        <div>
            <div>You will needs to stake</div>
            {reservesNeeded.map(function(item, idx){
              return <div key={`reserve-needed-${idx}`}>{item.neededDisplay} {item.symbol}</div>
            })}
        </div>
        )
    }
    let conversionFee = "";
    if (currentSelectedPool && currentSelectedPool.conversionFee) {
       conversionFee = currentSelectedPool.conversionFee + "%";
    }

    let poolLiquidateAction = <span/>;
    let poolFundAction = <span/>;
    let tokenAllowances = <span/>;
    
    let tokenAllowanceRowVisible = "row-hidden";
    if (this.state.approvalDisplay) {
      tokenAllowanceRowVisible = "row-visible"; 
    }
    
    if (currentSelectedPool.reserves && currentSelectedPool.reserves.length > 0){
      
      if (withdrawAllReservesActive === 'reserve-active') {
      poolLiquidateAction = (
        <div>
          <div className="select-reserve-container">
            <Form.Control type="number" placeholder="Enter amount to liquidate" onChange={this.onLiquidateInputChanged}/>
            <Button className="calculate-btn" disabled={isPurchaseBtnDisabled} onClick={this.calculateAllInputWithdraw}>Calculate</Button>            
          </div>
          <div className="action-info-col">
          {liquidateInfo}
          <Button onClick={this.submitSellPoolToken}  className="pool-action-btn">Sell</Button>
          </div>
        </div>
        )
      } else if (withdrawOneReserveActive === 'reserve-active') {
          let reserveOptions = currentSelectedPool.reserves.map(function(item, key){
            return <Dropdown.Item eventKey={item.symbol} key={`${item.symbol}-${key}`}>{item.symbol}</Dropdown.Item>
          });
          let withdrawActiveAmount = <span/>;
          if (singleTokenWithdrawConversionPaths && singleTokenWithdrawConversionPaths.length > 0) {
            let totalReserveAmount  = 0;
            singleTokenWithdrawConversionPaths.forEach(function(item){
              totalReserveAmount += parseFloat(item.quantity);
            });
            totalReserveAmount = totalReserveAmount.toFixed(4);
            withdrawActiveAmount = <div>{isWithdrawLoading} You will receive {totalReserveAmount} {singleTokenWithdrawReserveSelection.symbol}</div>
          }
        poolLiquidateAction = (
            <div>
            <div className="select-reserve-container">
              <div>
              <label>
                Reserve token in which to withdraw
              </label>
              <DropdownButton id="dropdown-basic-button" title={singleTokenWithdrawReserveSelection.symbol} onSelect={this.withdrawSingleBaseChanged}>
                {reserveOptions}
              </DropdownButton>
              </div>
              <div>
                 <label>Amount of pool tokens to withdraw</label>
                 <div>
                  <Form.Control type="number" placeholder="Pool tokens to withdraw" onChange={this.onSingleReserveLiquidateFundChanged}/>
                  <Button className="calculate-btn" onClick={this.calculateSingleInputWithdraw}>Calculate</Button>
                </div>
              </div>
            </div>
                <div className="action-info-col">
                {withdrawActiveAmount}
                <Button onClick={this.submitSellPoolTokenWithSingleReserve} disabled={isWithdrawBtnDisabled} className="pool-action-btn">Withdraw</Button>
                </div>
            </div>
            )
      }

      if (fundAllReservesActive === 'reserve-active' && fundReserveSelection.length > 0) {
          poolFundAction = (
            <div className="select-reserve-container">
                <div>
                  {
                    fundReserveSelection.map(function(item, idx){
                      return <Form.Control type="number" placeholder={`Enter amount of ${item.symbol} to fund`} value={item.value}
                      onChange={self.fundInputAmountChange.bind(self, idx)}/>
                    })
                  }
                  <div> 
                  <Button className="calculate-btn" disabled={isPurchaseBtnDisabled} onClick={this.calculateAllInputFund}>Calculate</Button>
                  </div>
                </div>
                
                <div className="action-info-col">
                {fundInfo}
                <Button onClick={this.submitBuyPoolToken} className="pool-action-btn">Purchase</Button>
                </div>
            </div>
            )
        } else if (fundOneReserveActive === 'reserve-active') {
          let reserveOptions = currentSelectedPool.reserves.map(function(item, key){
            return <Dropdown.Item eventKey={item.symbol} key={`${item.symbol}-${key}`} >{item.symbol}</Dropdown.Item>
          });
          let fundActiveAmount = <span/>;
          if (singleTokenFundConversionPaths) {
            let totalReserveAmount  = 0;
            singleTokenFundConversionPaths.forEach(function(item){
              totalReserveAmount += parseFloat(item.quantity);
            });
            totalReserveAmount = totalReserveAmount.toFixed(4);
            fundActiveAmount = <div>{isFundingLoading} You will need to stake {totalReserveAmount} {singleTokenFundReserveSelection.symbol}</div>
          }

          poolFundAction = (
            <div>
            <div className="select-reserve-container">
            <div>
              <label>
                Reserve token with which to fund.
              </label>
              <DropdownButton id="dropdown-basic-button" title={singleTokenFundReserveSelection.symbol} onSelect={this.fundSingleBaseChanged}>
                {reserveOptions}
              </DropdownButton>
            </div>
            <div>
              <label>Amount of {singleTokenFundReserveSelection.symbol} to fund</label>
              <div>
                <Form.Control type="number" placeholder={`Enter amount of ${singleTokenFundReserveSelection.symbol} to fund`} onChange={this.onSingleReserveFundInputChanged} className="single-reserve-amount-text"/>
                <Button className="calculate-btn" disabled={isPurchaseBtnDisabled} onClick={this.calculateSingleInputFund}>Calculate</Button>
              </div>
            </div>
            </div>
                <div className="action-info-col">
                {fundActiveAmount}
                <Button onClick={this.submitBuyPoolTokenWithSingleReserve} className="pool-action-btn">Purchase</Button>
                </div>
            </div>
            )
        }
        
    let tokenAllowanceReserves = currentSelectedPool.reserves.map(function(item, idx){
      return <div key={`allowance-${idx}`} className="selected-pool-balance">
      {item.symbol} {item.userAllowance ? parseFloat(item.userAllowance).toFixed(5) : '-'}
      </div>
    });
    
    let tokenSwapAllowanceReserves = currentSelectedPool.reserves.map(function(item, idx){
      return <div key={`allowance-${idx}`} className="selected-pool-balance">
      {item.symbol} {item.swapAllowance ? parseFloat(item.swapAllowance).toFixed(5) : '-'}
      </div>
    });
    
    tokenAllowances = 
    <div className={`${tokenAllowanceRowVisible}`}>
    <div className="approval-type-label">
     Approvals for pool converter contract.
    </div>
    <Row className={`token-allowances-display-row`}>
    <Col lg={8}>
      {tokenAllowanceReserves}
      </Col>
      <Col lg={4}>
      <Button onClick={()=>this.showApprovalDialog("pool")}>Approve reserves </Button>
      <Button onClick={()=>this.showRevokeDialog("pool")} className="revoke-approval-btn">Revoke approval </Button>
      </Col>
    </Row>
    <div className="approval-type-label">
     Approvals for Bancor Network contract.
    </div>
    <Row className="single-token-description">
     <Col lg={12}>
       If you using single token funding, it is also recommended that you approve BancorNetwork contract for swaps.
     </Col>
     </Row>
    <Row>
      <Col lg={8}>
      {tokenSwapAllowanceReserves}
      </Col>
      <Col lg={4}>
      <Button onClick={()=>this.showApprovalDialog("swap")}>Approve reserves </Button>
      <Button onClick={()=>this.showRevokeDialog("swap")} className="revoke-approval-btn">Revoke approval </Button>
      </Col>
    </Row>
    </div>
    }
    
    function allowanceToolTip(props) {
       return <Tooltip {...props}>
        <div>Token allowances refer to amount you have approved the converter contract to spend.</div>
        <div>Set allowances for BancorConverter for faster pool funding and liquidation and save on Gas costs</div>
        </Tooltip>;
    }
    
    let currentPoolTransactions = <span/>;

    if (currentSelectedPool.poolVersion === '1') {
      currentPoolTransactions = (
          <div>
          <Col lg={6}>
            <div className="allowance-label">Fund Pool Holdings</div>
            {poolFundAction}
          </Col>
          <Col lg={6}>
            <div className="allowance-label">Liquitate Pool Holdings</div>
            {poolLiquidateAction}
          </Col>
          </div>
        )
    } else {
      currentPoolTransactions = (
        <div>
          <SelectedV2PoolContainer pool={this.props.pool}/>
        </div>
        )
    }

    return (
      <div>
        <Row className="select-pool-row-1">
          <Col lg={1} className="pool-logo-container">
            <img src={currentSelectedPool.imageURI} className="selected-pool-image" alt="pool-token-img"/>
          </Col>
          <Col lg={2}>
            <div className="cell-label">{currentSelectedPool.symbol}</div>
            <div className="cell-data">{currentSelectedPool.name}</div>
          </Col>
          <Col lg={2}>
           <div className="cell-label">Address</div>
           <div className="cell-data"><AddressDisplay address={currentSelectedPool.address}/></div>
          </Col>
          <Col lg={2}>
            <div className="cell-label">Pool Supply</div>
            <div className="cell-data">{minTotalSupply}</div>
          </Col>
          <Col lg={3}>
            <div>
              <div className="cell-label">Reserves</div>
              <div className="cell-data">{reserveTokenList}</div>
            </div>
          </Col>
          <Col lg={2}>
            <div className="cell-label">Reserve Ratio</div>
            <div className="cell-data">{reserveRatio}</div>
          </Col>
        </Row>
        <Row className="selected-pool-meta-row">
          <Col lg={3}>
            <div className="cell-label">Conversion fee generated</div>
            <div className="cell-data">{conversionFee}</div>
          </Col>
          <Col lg={3}>
            <div className="cell-label">Your pool token holdings</div>
            <div className="cell-data">{poolHoldings}</div>
          </Col>
          <Col lg={4}>
            <div className="cell-label">Your reserve token holdings</div>
            <div className="cell-data">{userHoldingsList}</div>
          </Col>
        </Row>
        
       <div className="pool-action-container pool-allowance-container">

        <Row>
         <Col lg={12}>
          <div className="pool-approval-container">
           <div className="allowance-label">
           Your pool allowances 
           <OverlayTrigger
              placement="right"
              delay={{ show: 250, hide: 400 }}
              overlay={allowanceToolTip}>
              <FontAwesomeIcon icon={faQuestionCircle} className="info-tooltip-btn"/>
            </OverlayTrigger>
           </div>
           <FontAwesomeIcon icon={faChevronDown} className="show-approval-toggle" onClick={this.toggleApprovalDisplay}/>
           {tokenAllowances}
           </div>
         </Col>
        </Row>
        
        <Row className="selected-pool-buy-sell-row">
          <Col lg={12}>
          {currentPoolTransactions}
          </Col>
        </Row>
        
        </div>  
      </div>
      )
  }
Example #11
Source File: index.js    From pooled-loan with MIT License 4 votes vote down vote up
export default function CreatePool() {
    const [processing, setProcessing] = useState(false);
    const [addPoolState, setAddPoolState] = useState({
        maximumBidAmount: "",
        minimumBidAmount: "",
        auctionInterval: "",
        auctionDuration: "",
        maxParticipants: "",
        token: "0xFf795577d9AC8bD7D90Ee22b6C1703490b6512FD",
    });

    const [showMetamaskError, setShowMetamaskError] = useState(
        false
    );

    const [errorModal, setErrorModal] = useState({
        msg: "",
        open: false
    });

    const [successModal, setSuccessModal] = useState({
        msg: "",
        open: false
    });

    const [lendingPool] = useState([
        { pool: "Aave", token: "0xFf795577d9AC8bD7D90Ee22b6C1703490b6512FD" },
        { pool: "Mstable", token: "0x70605Bdd16e52c86FC7031446D995Cf5c7E1b0e7" }
    ]);

    const handleCreatePool = () => {
        window.loanPoolFactory.methods
            .addLoanPool(
                addPoolState.maximumBidAmount,
                addPoolState.minimumBidAmount,
                addPoolState.auctionInterval,
                addPoolState.auctionDuration,
                addPoolState.maxParticipants,
                addPoolState.token,
            )
            .send()
            .on('transactionHash', () => {
                setProcessing(true);
            })
            .on('receipt', (_) => {
                setProcessing(false);
                setSuccessModal({
                    open: true,
                    msg: "Congratulations ? !! " +
                        "Pool successfully created !! " +
                        "Within 2 minutes you will be able to " +
                        "see created pool on the dashboard.",
                });
            })
            .catch((error) => {
                setProcessing(false);
                setErrorModal({
                    open: true,
                    msg: error.message,
                });
                console.log(error.message)
            });
    };

    useEffect(() => {
        if (typeof window.ethereum === 'undefined' ||
            !window.ethereum.selectedAddress
        ) {
            setShowMetamaskError(true);
        }
    }, []);

    return (
        <div>
            {showMetamaskError ?
                <AlertModal
                    open={showMetamaskError}
                    toggle={() => {
                        setShowMetamaskError(false);
                        history.push('/');
                    }}
                >
                    <div>
                        {typeof window.ethereum === 'undefined' ?
                            <div>
                                You can't use these features without Metamask.
                                <br />
                                Please install
                                <Image width="50px" src={metamask}></Image>
                                first !!
                            </div>
                            :
                            <div>
                                Please connect to
                                <Image width="50px" src={metamask}></Image>
                                to use this feature !!
                            </div>
                        }
                    </div>
                </AlertModal>
                :
                <CardDeck>
                    <Card className="hidden-card"></Card>

                    <Card className="mx-auto form-card">
                        <Card.Header>
                            <u>Create Loan Pool</u>
                        </Card.Header>

                        <Card.Body>
                            <Row style={{ marginTop: "10px" }}>
                                <Col className="text-header">
                                    Collateral Amount:
                                </Col>
                                <Col style={{ paddingLeft: "0px" }}>
                                    <Form.Control
                                        className="mb-4"
                                        type="number"
                                        placeholder="(Max Bid Amount * Max Participants)"
                                        style={{ width: "80%" }}
                                        value={
                                            (addPoolState.maximumBidAmount *
                                                (addPoolState.maxParticipants > 0 ?
                                                    addPoolState.maxParticipants : 1
                                                ) > 0 ?
                                                addPoolState.maximumBidAmount *
                                                (addPoolState.maxParticipants > 0 ?
                                                    addPoolState.maxParticipants : 1
                                                )
                                                : ""
                                            )
                                        }
                                        disabled={true}
                                    />
                                </Col>
                            </Row>

                            <Row>
                                <Col className="text-header">
                                    Maximum Bid Amount:
                                </Col>
                                <Col style={{ paddingLeft: "0px" }}>
                                    <Form.Control
                                        className="mb-4"
                                        type="number"
                                        step="0"
                                        placeholder="No decimal places"
                                        onChange={(e) => setAddPoolState({
                                            ...addPoolState,
                                            maximumBidAmount: e.target.value
                                        })}
                                        style={{ width: "80%" }}
                                        value={addPoolState.maximumBidAmount}
                                        required
                                    />
                                </Col>
                            </Row>

                            <Row>
                                <Col className="text-header">
                                    Maximum Participants:
                                </Col>
                                <Col style={{ paddingLeft: "0px" }}>
                                    <Form.Control
                                        className="mb-4"
                                        type="number"
                                        step="0"
                                        placeholder="No decimal places"
                                        onChange={(e) => setAddPoolState({
                                            ...addPoolState,
                                            maxParticipants: e.target.value
                                        })}
                                        style={{ width: "80%" }}
                                        value={addPoolState.maxParticipants}
                                        required
                                    />
                                </Col>
                            </Row>

                            <Row>
                                <Col className="text-header">
                                    Minimum Bid Amount:
                                </Col>
                                <Col style={{ paddingLeft: "0px" }}>
                                    <Form.Control
                                        className="mb-4"
                                        type="number"
                                        step="0"
                                        placeholder="No decimal places"
                                        onChange={(e) => setAddPoolState({
                                            ...addPoolState,
                                            minimumBidAmount: e.target.value
                                        })}
                                        style={{ width: "80%" }}
                                        value={addPoolState.minimumBidAmount}
                                        required
                                    />
                                </Col>
                            </Row>

                            <Row>
                                <Col className="text-header">
                                    Every Auction Interval:
                                </Col>
                                <Col style={{ paddingLeft: "0px" }}>
                                    <Form.Control
                                        className="mb-4"
                                        type="number"
                                        step="0"
                                        placeholder="In hours (Eg. 1)"
                                        onChange={(e) => setAddPoolState({
                                            ...addPoolState,
                                            auctionInterval: e.target.value
                                        })}
                                        style={{ width: "80%" }}
                                        value={addPoolState.auctionInterval}
                                        required
                                    />
                                </Col>
                            </Row>

                            <Row>
                                <Col className="text-header">
                                    Aution Duration:
                                </Col>
                                <Col style={{ paddingLeft: "0px" }}>
                                    <Form.Control
                                        className="mb-4"
                                        type="number"
                                        min="0"
                                        max={addPoolState.auctionInterval - 1}
                                        step="0"
                                        placeholder="10 (For 10 hours)"
                                        onChange={(e) => setAddPoolState({
                                            ...addPoolState,
                                            auctionDuration: e.target.value
                                        })}
                                        style={{ width: "80%" }}
                                        value={addPoolState.auctionDuration}
                                        required
                                    />
                                </Col>
                            </Row>

                            <Row style={{ marginBottom: "20px" }}>
                                <Col className="text-header">
                                    Lending Pool:
                            </Col>
                                <Col style={{ paddingLeft: "0px" }}>
                                    <DropdownButton
                                        style={{
                                            position: "absolute",
                                        }}
                                        title={lendingPool.map((element) => (
                                            addPoolState.token === element.token ?
                                                element.pool
                                                : null
                                        ))}
                                        variant="outline-info"
                                        onSelect={(e) => setAddPoolState({
                                            ...addPoolState,
                                            token: e
                                        })}
                                    >
                                        {lendingPool.map((element, key) => (
                                            <Dropdown.Item
                                                key={key}
                                                eventKey={element.token}
                                            >
                                                {element.pool}
                                            </Dropdown.Item>
                                        ))}
                                    </DropdownButton>
                                </Col>
                            </Row>
                        </Card.Body>

                        <Card.Footer className="text-center">
                            <Button
                                onClick={handleCreatePool}
                                variant="success"
                            >
                                {processing ?
                                    <div className="d-flex align-items-center">
                                        Processing
                                <span className="loading ml-2"></span>
                                    </div>
                                    :
                                    <div>Submit</div>
                                }
                            </Button>
                        </Card.Footer>
                    </Card>

                    <Card className="hidden-card"></Card>
                </CardDeck>
            }

            <AlertModal
                open={errorModal.open}
                toggle={() => setErrorModal({
                    ...errorModal, open: false
                })}
            >
                {errorModal.msg}
            </AlertModal>

            <SuccessModal
                open={successModal.open}
                toggle={() => setSuccessModal({
                    ...successModal, open: false
                })}
                onConfirm={() => history.push("/")}
            >
                {successModal.msg}
            </SuccessModal>
        </div>
    );
}
Example #12
Source File: index.js    From pooled-loan with MIT License 4 votes vote down vote up
export default function SwapToken({
    buyToken,
    fixedBuyToken,
    availableBalance,
    balanaceNeeded
}) {
    const [processing, setProcessing] = useState(false);
    const [allTokens, setAllTokens] = useState([]);
    const [state, setState] = useState({
        buyToken: buyToken,
        sellToken: "USDC",
        buyAmount: "1",
    });
    const [errorModal, setErrorModal] = useState({
        msg: "",
        open: false
    });
    const [successModal, setSuccessModal] = useState({
        msg: "",
        open: false
    });

    const handleSwapToken = async () => {
        try {
            const quote = await api0x.fetchTokenQuote({
                buyToken: state.buyToken,
                sellToken: state.sellToken,
                buyAmount: await precision.add(
                    state.buyAmount,
                    18,
                ),
            });

            if (state.sellToken !== "ETH") {
                let tokenAddress;
                allTokens.forEach((element) => {
                    if (state.sellToken === element.symbol)
                        tokenAddress = element.address
                });

                const contract = new ERC20TokenContract(
                    tokenAddress, window.web3.eth.currentProvider
                );
                const maxApproval = new BigNumber(2)
                    .pow(256).minus(1);

                const approvalTxData = await contract
                    .approve(quote.allowanceTarget, maxApproval)
                    .getABIEncodedTransactionData();

                await window.web3.eth.sendTransaction
                    ({
                        to: tokenAddress,
                        data: approvalTxData,
                        from: window.userAddress
                    })
                    .on("transactionHash", () => {
                        setProcessing(true);
                    });
            }

            await window.web3.eth.sendTransaction(quote)
                .on("transactionHash", () => {
                    setProcessing(true);
                })
                .on("receipt", () => {
                    setProcessing(false);
                    setSuccessModal({
                        open: true,
                        msg: "Congratulations ? !!"
                    });
                });
        } catch (error) {
            setProcessing(false);
            setErrorModal({
                open: true,
                msg: error.message,
            });
        }
    };

    const fetchAllTokens = async () => {
        const tokens = await api0x.fetchAllTokens();
        setAllTokens([{ symbol: "ETH" }].concat(tokens.records));
    };

    const handleReload = () => {
        history.go(0);
    }

    useEffect(() => {
        if (allTokens.length === 0) {
            fetchAllTokens();
        }
    });

    return (
        <div>
            <Card
                className="mx-auto form-card text-center"
                style={{ backgroundColor: "rgb(253, 255, 255)" }}
            >
                <Card.Header>
                    Swap Your Asset
                </Card.Header>

                <Card.Body>
                    {fixedBuyToken ?
                        <div>
                            <div style={{ marginBottom: "20px", color: "orange" }}>
                                You don't have enough collateral amount available in your wallet.
                                Please use another wallet or Get Token by swapping another asset
                                directly from 0x protocol using below method:
                            </div>

                            <Row className="text-center" style={{ paddingBottom: "20px" }}>
                                <Col>
                                    <u>Available Balance</u>
                                    <span> : </span>
                                    <span>{availableBalance} {buyToken}</span>
                                </Col>
                            </Row>
                            <Row className="text-center" style={{ paddingBottom: "30px" }}>
                                <Col>
                                    <u>Balance Needed</u>
                                    <span> : </span>
                                    <span>{balanaceNeeded} {buyToken}</span>
                                </Col>
                            </Row>
                        </div>
                        : <div
                            className="auction-message"
                            style={{ fontSize: "medium" }}
                        >
                            * Swap Using 0x Protocol
                        </div>
                    }

                    <Row>
                        <Col className="text-header">
                            Buy Token:
                        </Col>
                        {fixedBuyToken ?
                            <Col style={{ paddingLeft: "0px" }}>
                                <Form.Control
                                    className="mb-4"
                                    type="text"
                                    style={{ width: "60%" }}
                                    value={state.buyToken}
                                    readOnly={!buyToken ? false : true}
                                />
                            </Col>
                            :
                            <Col
                                className="text-left float-left"
                                style={{ marginBottom: "20px", paddingLeft: "0px" }}
                            >
                                <DropdownButton
                                    title={state.buyToken}
                                    variant="outline-info"
                                    onSelect={(event) => setState({
                                        ...state,
                                        buyToken: event
                                    })}
                                >
                                    {allTokens.map((element, key) => (
                                        <Dropdown.Item
                                            key={key}
                                            eventKey={element.symbol}
                                        >
                                            {element.symbol}
                                        </Dropdown.Item>
                                    ))}
                                </DropdownButton>
                            </Col>
                        }
                    </Row>

                    <Row style={{ marginBottom: "30px" }}>
                        <Col className="text-header">
                            Sell Token:
                        </Col>
                        <Col style={{ paddingLeft: "0px" }}>
                            <DropdownButton
                                style={{
                                    position: "absolute",
                                }}
                                title={state.sellToken}
                                variant="outline-info"
                                onSelect={(event) => setState({
                                    ...state,
                                    sellToken: event
                                })}
                            >
                                {allTokens.map((element, key) => (
                                    <Dropdown.Item
                                        key={key}
                                        eventKey={element.symbol}
                                    >
                                        {element.symbol}
                                    </Dropdown.Item>
                                ))}
                            </DropdownButton>
                        </Col>
                    </Row>

                    <Row>
                        <Col className="text-header">
                            Buy Amount:
                        </Col>
                        <Col style={{ paddingLeft: "0px" }}>
                            <Form.Control
                                className="mb-4"
                                type="number"
                                min="0"
                                placeholder="0"
                                onChange={async (e) => setState({
                                    ...state,
                                    buyAmount: e.target.value,
                                })}
                                style={{ width: "60%" }}
                                value={state.buyAmount}
                            />
                        </Col>
                    </Row>

                    <Row className="text-center">
                        <Col>
                            <Button
                                onClick={handleSwapToken}
                                variant="outline-success"
                            >
                                {processing ?
                                    <div className="d-flex align-items-center">
                                        Processing
                                <span className="loading ml-2"></span>
                                    </div>
                                    :
                                    <div>
                                        <Image src={zeroxLogo} width="25px"></Image>
                                        <span> Submit</span>
                                    </div>
                                }
                            </Button>
                        </Col>
                    </Row>
                </Card.Body>
            </Card>

            <AlertModal
                open={errorModal.open}
                toggle={() => setErrorModal({
                    ...errorModal, open: false
                })}
            >
                {errorModal.msg}
            </AlertModal>

            <SuccessModal
                open={successModal.open}
                toggle={() => setSuccessModal({
                    ...successModal, open: false
                })}
                onConfirm={handleReload}
            >
                {successModal.msg}
            </SuccessModal>
        </div>
    );
}
Example #13
Source File: UserPageComponent.js    From project-s0-t1-budget with MIT License 4 votes vote down vote up
render() {
    return (
      <Container>
        {this.state.dataLoaded ? (
          <div>
            {this.state.dataFound ? (
              <div>
                <br />
                <Form.Row>
                  <Form.Group as={Col} md="2" controlId="Month">
                    <Form.Control
                      as="select"
                      name="Month"
                      onChange={this.handleChange}
                      value={this.state.selectMonth}
                    >
                      <option value="1">January</option>
                      <option value="2">February</option>
                      <option value="3">March</option>
                      <option value="4">April</option>
                      <option value="5">May</option>
                      <option value="6">June</option>
                      <option value="7">July</option>
                      <option value="8">August</option>
                      <option value="9">September</option>
                      <option value="10">October</option>
                      <option value="11">November</option>
                      <option value="12">December</option>
                    </Form.Control>
                  </Form.Group>
                  <Form.Group as={Col} md="2" controlId="Year">
                    <Form.Control
                      as="select"
                      name="Year"
                      onChange={this.handleChange2}
                      value={this.state.selectYear}
                    >
                      <option value="2020">2020</option>
                      <option value="2019">2019</option>
                      <option value="2018">2018</option>
                      <option value="2017">2017</option>
                      <option value="2016">2016</option>
                      <option value="2015">2015</option>
                      <option value="2014">2014</option>
                      <option value="2013">2013</option>
                      <option value="2012">2012</option>
                      <option value="2011">2011</option>
                      <option value="2010">2010</option>
                    </Form.Control>
                  </Form.Group>
                </Form.Row>
                {this.state.dataModify ? (
                  <div>
                    <Row>
                      <Col md="6">
                        <Jumbotron>
                          <UserPageUpdateComponent
                            user={this.props.user}
                            month={this.state.selectMonth}
                            year={this.state.selectYear}
                            update={this.update}
                            currData={this.state.data}
                          />
                          <br />
                          <Button onClick={this.cancelModifyBudget}>
                            Cancel
                          </Button>
                        </Jumbotron>
                      </Col>
                      <Col md="6">
                        <TableComponent
                          category={this.state.data.labels}
                          price={this.state.data.data}
                        />
                      </Col>
                    </Row>
                  </div>
                ) : (
                  <div>
                    <ButtonToolbar>
                      <ButtonGroup className="mr-2">
                        <Button variant="danger" onClick={this.deleteBudget}>
                          Delete Month's Finances
                        </Button>
                      </ButtonGroup>
                      <ButtonGroup className="mr-2">
                        <Button onClick={this.modifyBudget}>
                          Modify Month's Finances
                        </Button>
                      </ButtonGroup>
                      <ButtonGroup className="mr-2">
                        <DropdownButton
                          id="dropdown-item-button"
                          title="Graphs"
                        >
                          <Dropdown.Item as="button" onClick={this.handleBar}>
                            Bar Graph
                          </Dropdown.Item>
                          <Dropdown.Item
                            as="button"
                            onClick={this.handlePieIncome}
                          >
                            Income Pie Chart
                          </Dropdown.Item>
                          <Dropdown.Item
                            as="button"
                            onClick={this.handlePieExpense}
                          >
                            Expenses Pie Chart
                          </Dropdown.Item>
                          <Dropdown.Item
                            as="button"
                            onClick={this.handleBarGoals}
                          >
                            Goal Chart
                          </Dropdown.Item>
                          <Dropdown.Item as="button" onClick={this.handleRadar}>
                            Expense Variance Chart
                          </Dropdown.Item>
                        </DropdownButton>
                      </ButtonGroup>
                    </ButtonToolbar>
                    <Form.Switch
                      checked={this.state.colorMode}
                      id="custom-switch"
                      label="Colorblind Mode"
                      onChange={this.handleSwitchChange}
                    />
                    <br />
                    {this.state.showTable ? (
                      <div>
                        <Button onClick={this.toggleTable}>
                          Hide Finances Table
                        </Button>
                        <br />
                        <br />
                        <TableComponent
                          category={this.state.data.labels}
                          price={this.state.data.data}
                        />
                      </div>
                    ) : (
                      <div>
                        <Button onClick={this.toggleTable}>
                          Show Finances Table
                        </Button>
                        <br />
                        <br />
                      </div>
                    )}
                  </div>
                )}

                <CardColumns>
                  <Card
                    border="none"
                    style={
                      this.state.barActive
                        ? { border: "none" }
                        : { display: "none" }
                    }
                  >
                    <ChartCardComponent
                      handleBar={this.handleBar}
                      labels={this.state.data.labels}
                      data={this.state.data.data}
                      Component={"BarChart"}
                    />
                  </Card>

                  <Card
                    border="none"
                    style={
                      this.state.incomePieActive
                        ? { border: "none" }
                        : { display: "none" }
                    }
                  >
                    <ChartCardComponent
                      handlePieIncome={this.handlePieIncome}
                      labels={this.state.data.labels}
                      data={this.state.data.data}
                      color={this.state.colorMode}
                      Component={"IncomePie"}
                    />
                  </Card>

                  <Card
                    border="none"
                    style={
                      this.state.expensePieActive
                        ? { border: "none" }
                        : { display: "none" }
                    }
                  >
                    <ChartCardComponent
                      handlePieExpense={this.handlePieExpense}
                      labels={this.state.data.labels}
                      data={this.state.data.data}
                      color={this.state.colorMode}
                      Component={"ExpensePie"}
                    />
                  </Card>

                  <Card
                    border="none"
                    style={
                      this.state.barGoalsPieActive
                        ? { border: "none" }
                        : { display: "none" }
                    }
                  >
                    <ChartCardComponent
                      handleBarGoals={this.handleBarGoals}
                      data={this.state.data.data}
                      goal={this.state.data.goal}
                      color={this.state.colorMode}
                      Component={"BarGoal"}
                    />
                  </Card>
                  <Card
                    style={
                      this.state.radarActive
                        ? { border: "none" }
                        : { display: "none" }
                    }
                  >
                    <ChartCardComponent
                      handleRadar={this.handleRadar}
                      labels={this.state.data.labels}
                      data={this.state.data.data}
                      Component={"RadarPie"}
                    />
                  </Card>
                </CardColumns>
              </div>
            ) : (
              <div>
                <br />
                <Form.Row>
                  <Form.Group as={Col} md="2" controlId="Month2">
                    <Form.Control
                      as="select"
                      name="Month"
                      onChange={this.handleChange}
                      value={this.state.selectMonth}
                    >
                      <option value="1">January</option>
                      <option value="2">February</option>
                      <option value="3">March</option>
                      <option value="4">April</option>
                      <option value="5">May</option>
                      <option value="6">June</option>
                      <option value="7">July</option>
                      <option value="8">August</option>
                      <option value="9">September</option>
                      <option value="10">October</option>
                      <option value="11">November</option>
                      <option value="12">December</option>
                    </Form.Control>
                  </Form.Group>
                  <Form.Group as={Col} md="2" controlId="Year2">
                    <Form.Control
                      as="select"
                      name="Year"
                      onChange={this.handleChange2}
                      value={this.state.selectYear}
                    >
                      <option value="2020">2020</option>
                      <option value="2019">2019</option>
                      <option value="2018">2018</option>
                      <option value="2017">2017</option>
                      <option value="2016">2016</option>
                      <option value="2015">2015</option>
                      <option value="2014">2014</option>
                      <option value="2013">2013</option>
                      <option value="2012">2012</option>
                      <option value="2011">2011</option>
                      <option value="2010">2010</option>
                    </Form.Control>
                  </Form.Group>
                </Form.Row>

                <h3>No Data for this month :(</h3>
                <br />
                <h4>Would you like to add some?</h4>
                <Jumbotron>
                  <UserPageFormComponent
                    user={this.props.user}
                    month={this.state.selectMonth}
                    year={this.state.selectYear}
                    update={this.update}
                  />
                </Jumbotron>
              </div>
            )}
            <LineGraphComponent
              year={this.state.selectYear}
              user={this.props.user}
            />
          </div>
        ) : (
          <Spinner animation="border" variant="primary">
            <span className="sr-only">Loading...</span>
          </Spinner>
        )}
      </Container>
    );
  }
Example #14
Source File: index.js    From project-s0-t1-budget with MIT License 4 votes vote down vote up
render() {
    return (
      <Layout user={this.props.user}>
        {this.props.user ? (
          <UserPageComponent user={this.props.user} />
        ) : (
          <Container>
            <br />
            <Row>
              <Col md="5">
                <Jumbotron>
                  <ChartFormComponent
                    handleFormUpdate={this.handleFormUpdate.bind(this)}
                  />
                  <br />
                  <ButtonToolbar>
                    <ButtonGroup className="mr-2">
                      <Button
                        variant="secondary"
                        onClick={this.handleResetUpdate}
                      >
                        Reset
                      </Button>
                    </ButtonGroup>

                    <ButtonGroup className="mr-2">
                      <DropdownButton id="dropdown-item-button" title="Graphs">
                        <Dropdown.Item as="button" onClick={this.handleBar}>
                          Bar Graph
                        </Dropdown.Item>
                        <Dropdown.Item
                          as="button"
                          onClick={this.handlePieIncome}
                        >
                          Income Pie Chart
                        </Dropdown.Item>
                        <Dropdown.Item
                          as="button"
                          onClick={this.handlePieExpense}
                        >
                          Expenses Pie Chart
                        </Dropdown.Item>
                        <Dropdown.Item as="button" onClick={this.handleRadar}>
                          Expense Variance Chart
                        </Dropdown.Item>
                      </DropdownButton>
                    </ButtonGroup>
                  </ButtonToolbar>
                  <br />
                  <Form.Switch
                    checked={this.state.colorMode}
                    id="custom-switch"
                    label="Colorblind Mode"
                    onChange={this.handleSwitchChange}
                  />
                </Jumbotron>
              </Col>
              <Col md="7">
                <TableComponent
                  category={this.state.labels}
                  price={this.state.data}
                />
              </Col>
            </Row>

            <CardColumns>
              <Card
                border="none"
                style={
                  this.state.barActive
                    ? { border: "none" }
                    : { display: "none" }
                }
              >
                <ChartCardComponent
                  handleBar={this.handleBar}
                  labels={this.state.labels}
                  data={this.state.data}
                  Component={"BarChart"}
                />
              </Card>
              <Card
                border="none"
                style={
                  this.state.incomePieActive
                    ? { border: "none" }
                    : { display: "none" }
                }
              >
                <ChartCardComponent
                  handlePieIncome={this.handlePieIncome}
                  labels={this.state.labels}
                  data={this.state.data}
                  color={this.state.colorMode}
                  Component={"IncomePie"}
                />
              </Card>
              <Card
                style={
                  this.state.expensePieActive
                    ? { border: "none" }
                    : { display: "none" }
                }
              >
                <ChartCardComponent
                  handlePieExpense={this.handlePieExpense}
                  labels={this.state.labels}
                  data={this.state.data}
                  color={this.state.colorMode}
                  Component={"ExpensePie"}
                />
              </Card>

              <Card
                style={
                  this.state.radarActive
                    ? { border: "none" }
                    : { display: "none" }
                }
              >
                <ChartCardComponent
                  handleRadar={this.handleRadar}
                  labels={this.state.labels}
                  data={this.state.data}
                  Component={"RadarPie"}
                />
              </Card>
            </CardColumns>
          </Container>
        )}
      </Layout>
    );
  }
Example #15
Source File: FuncTestPage2.js    From openos with MIT License 4 votes vote down vote up
function FuncTestPage2() {
  const [serverIp, setServerIp] = useState("");
  const [serverPort, setServerPort] = useState(0);
  const [netLog, setNetLog] = useState("");
  const [localLog, setLocalLog] = useState("");
  const [loginId, setloginId] = useState("kitt1");
  const [loginPwd, setloginPwd] = useState("1234");
  const [searchMode, setSearchMode] = useState('ALL');
  const [searchText, setSearchText] = useState('이봉석');
  const [orgGroupCode, setOrgGroupCode] = useState("ORG001");
  const [msgKey, setMsgKey] = useState("4a264afc26d9801584df97cccf4907ee");
  const netLogArea = useRef(null);
  const localLogArea = useRef(null);
  

  //initialize
  useEffect(() => {
    console.log("FuncTestPage Init");

    electron.ipcRenderer.once('net-log', (event, msg, ...args) => {
      appendNetLog(msg, args);
    });

    async function loadConfig() {
      let config = await getConfig();
      setServerIp(config.server_ip);
      setServerPort(config.server_port);  
    }

    loadConfig();
  }, []);

  //#region WriteLog ...
  const appendNetLog = (msg, ...args) => {
    msg = moment().format("hh:mm:ss.SSS >") + msg + ':' + args
    setNetLog(prev => prev + (prev ? "\r\n" : "") + msg);

    if (netLogArea.current) {
      netLogArea.current.scrollTop = netLogArea.current.scrollHeight;
    }
  }

  const appendLocalLog = (msg, ...args) => {
    msg = moment().format("hh:mm:ss.SSS >") + msg + ':' + args;
    setLocalLog(prev => prev + (prev ? "\r\n" : "") + msg);

    if (localLogArea.current) {
      localLogArea.current.scrollTop = localLogArea.current.scrollHeight;
    }
  }

  const clearLog = () => {
    setNetLog('');
    setLocalLog('');
  }
  //#endregion WriteLog ...

  // Login
  const handleLogin = (e) => {
    appendLocalLog("Login1" , loginId, loginPwd);

    login(loginId, loginPwd).then(function(resData){
      console.log('Promiss login res', resData);
      if (resData.resCode) {
        appendLocalLog('Login Success! ', JSON.stringify(resData))
      } else {
        appendLocalLog('Login fail! ', JSON.stringify(resData))
      }
    }).catch(function(err){
      appendLocalLog('Login fail! ', JSON.stringify(err))
    });;
  }
 
  // SearchUser
  const handleSearchUser = (e) => {
    appendLocalLog("handleSearchUser:", searchMode, searchText);

    searchUsers(searchMode, searchText).then(function(data) {
      appendLocalLog('handleSearchUser Result:' + JSON.stringify(data));
    });
  }

  // SearOrgUser
  const handleSearchOrgUser = (e) => {
    appendLocalLog("handleSearchOrgUser:", orgGroupCode, searchText);

    searchOrgUsers(orgGroupCode, searchText).then(function(data) {
      appendLocalLog('handleSearchOrgUser Result:' + JSON.stringify(data));
    });
  }

  // GetMessage
  const handleGetMessage = (e) => {
    appendLocalLog("handleGetMessage:", e.target.value);
    getMessage(e.target.value, 0, 10).then(function(data) {
      appendLocalLog('handleGetMessage Result:' + JSON.stringify(data));
    });
  }

  // GetMessageDetail
  const handleGetMessageDetail = (e) => {
    appendLocalLog("handleGetMessageDetail:", msgKey);

    getMessageDetail(msgKey).then(function(data) {
      appendLocalLog('handleGetMessageDetail Result:' + JSON.stringify(data));
    });
  }

  // DeleteMessage
  const handleDeleteMessage = (e) => {
    appendLocalLog("handleDeleteMessage:", msgKey);

    deleteMessage('SEND', msgKey.split(',')).then(function(data) {
      appendLocalLog('handleDeleteMessage Result:' + JSON.stringify(data));
    });
  }

  // GetChatRoomList
  const handleGetChatRoomList = (e) => {
    appendLocalLog("handleGetChatRoomList");

    getChatRoomList().then(function(data) {
      appendLocalLog('handleGetChatRoomList Result:' + JSON.stringify(data));
    });
  }
  
  // LogClear
  const handleLogClear = (e) => {
    clearLog();
  }

  return (
    <GridWrapper >
      <Container fluid='false' className='mt-5'>
        <Row  xs={2} md={3} lg={5}>
          <Col>Server IP : {serverIp}</Col>
          <Col>Server PORT : {serverPort}</Col>
        </Row>
        
        {/* 로그인 */}
        <Row className='mt-1'>
          <Col>
            <InputGroup >
              <InputGroup.Prepend>
                <InputGroup.Text id="loginId">Login Id</InputGroup.Text>
              </InputGroup.Prepend>
              <FormControl
                aria-label="Default"
                aria-describedby="inputGroup-sizing-default"
                placeholder={loginId}
                onChange={(e) => setloginId(e.target.value)}
              />
              <InputGroup.Prepend>
                <InputGroup.Text id="loginPwd">Password</InputGroup.Text>
              </InputGroup.Prepend>
              <FormControl
                aria-label="Default"
                aria-describedby="inputGroup-sizing-default"
                placeholder={loginPwd}
                onChange={(e) => setloginPwd(e.target.value)}
              />
              <InputGroup.Append>
                <Button variant="outline-secondary" onClick={handleLogin}>Login</Button>
              </InputGroup.Append>
            </InputGroup>
          </Col>
        </Row>

        <Row>
          {/* 사용자 통합검색 요청 */}
          <Col>
            <InputGroup >
              <DropdownButton
                  as={InputGroup.Prepend}
                  variant="outline-secondary"
                  title={searchMode}
                  id="input-group-dropdown-1"
                  onSelect={setSearchMode}
                >
                <Dropdown.Item eventKey="ALL" active >ALL</Dropdown.Item>
                <Dropdown.Item eventKey="PHONE">PHONE</Dropdown.Item>
                <Dropdown.Item eventKey="IPPHONE">IPPHONE</Dropdown.Item>
                <Dropdown.Item eventKey="MOBILE">MOBILE</Dropdown.Item>
                <Dropdown.Divider />
              </DropdownButton>
              <FormControl
                aria-label="Default"
                aria-describedby="inputGroup-sizing-default"
                placeholder={searchText}
                onChange={(e) => setSearchText(e.target.value)}
              />
              <InputGroup.Append>
                <Button variant="outline-secondary" onClick={handleSearchUser}>통합검색</Button>
              </InputGroup.Append>
            </InputGroup>
          </Col>
          {/* 조직도 검색 요청 */}
          <Col>
            <InputGroup >
            <FormControl
                aria-label="Default"
                aria-describedby="inputGroup-sizing-default"
                placeholder={orgGroupCode}
                onChange={(e) => setOrgGroupCode(e.target.value)}
              />
              <FormControl
                aria-label="Default"
                aria-describedby="inputGroup-sizing-default"
                placeholder={searchText}
                onChange={(e) => setSearchText(e.target.value)}
              />

              <InputGroup.Append>
                <Button variant="outline-secondary" onClick={handleSearchOrgUser}>조직도검색</Button>
              </InputGroup.Append>
            </InputGroup>
          </Col>
        </Row>

        <Row>
          {/*  쪽지 이력 요청 */}
          <Col>
            <InputGroup >
              <InputGroup.Append>
                <Button variant="outline-secondary" onClick={handleGetMessage} value='RECV'>받은쪽지</Button> &nbsp;
                <Button variant="outline-secondary" onClick={handleGetMessage} value='SEND'> 보낸쪽지</Button>
              </InputGroup.Append>
            </InputGroup>
          </Col>
          {/*  쪽지 상세정보 요청 */}
          <Col>
            <InputGroup >
              <FormControl
                aria-label="Default"
                aria-describedby="inputGroup-sizing-default"
                placeholder={msgKey}
                onChange={(e) => setMsgKey(e.target.value)}
              />

              <InputGroup.Append>
                <Button variant="outline-secondary" onClick={handleGetMessageDetail}>쪽지 정보 요청</Button>
                <Button variant="outline-secondary" onClick={handleDeleteMessage}>쪽지 삭제 요청</Button>
              </InputGroup.Append>
            </InputGroup>
          </Col>
        </Row>
        <Row>
          {/*  쪽지 이력 요청 */}
          <Col>
            <InputGroup >
              <InputGroup.Append>
                <Button variant="outline-secondary" onClick={handleGetChatRoomList}>대화방목록</Button>
              </InputGroup.Append>
            </InputGroup>
          </Col>
        </Row>
        <Row>
          <Col>
            <Button onClick={handleLogClear}>
              Clear
            </Button>
          </Col>
        </Row>

        <Row xs={1} className='mt-1' >
          <textarea ref={localLogArea} rows={10} value={localLog} className='mt-1' />
        </Row>
        <Row xs={1} className='mt-1'>
          <textarea ref={netLogArea} rows={10} value={netLog} className='mt-1'/>
        </Row>
      </Container>
    </GridWrapper>
  );
}