semantic-ui-react#Checkbox JavaScript Examples

The following examples show how to use semantic-ui-react#Checkbox. 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: EmbargoCheckboxField.js    From react-invenio-deposit with MIT License 6 votes vote down vote up
render() {
    const { fieldPath, formik, checked, disabled } = this.props;
    return (
      <Checkbox
        id={fieldPath}
        data-testid="embargo-checkbox-component"
        disabled={disabled}
        checked={checked}
        onChange={(event, data) => {
          if (formik.field.value) {
            // NOTE: We reset values, so if embargo filled and user unchecks,
            //       user needs to fill embargo again. Otherwise, lots of
            //       bookkeeping.
            formik.form.setFieldValue('access.embargo', {
              active: false,
            });
          } else {
            formik.form.setFieldValue(fieldPath, true);
          }
        }}
      />
    );
  }
Example #2
Source File: TotalChart.jsx    From covid-19-nsw with GNU General Public License v3.0 6 votes vote down vote up
TotalChart = ({ pageId, totalData, predictData }) => {
  let [useLog, setUseLog] = useState(false);
  return (
    <>
      <ReactEcharts
        option={getTotalChartOptions(pageId, totalData, predictData, useLog)}
        theme='custom_theme'
      />
      <div style={{ textAlign: 'center' }}>
        <Checkbox
          toggle
          label='use log scale'
          onChange={() => setUseLog(prev => !prev)}
          checked={useLog}
        />
        <a
          className='ui'
          target='_blank'
          rel='noopener noreferrer'
          href='https://blog.datawrapper.de/weeklychart-logscale/'
          title='how to read log scale chart'
        >
          <Icon name='question circle outline'></Icon>
        </a>
      </div>
    </>
  );
}
Example #3
Source File: StatesTotalTrendingChart.jsx    From covid-19-nsw with GNU General Public License v3.0 6 votes vote down vote up
StatesTotalTrendingChart = ({ pageId, data }) => {
  let [useLog, setUseLog] = useState(false);
  return (
    <div>
      <ReactEcharts
        option={getOptions(pageId, data, useLog)}
        style={{ height: 400 }}
        theme='custom_theme'
      />
      <div style={{ textAlign: 'center' }}>
        <Checkbox
          toggle
          label='use log scale'
          onChange={() => setUseLog(prev => !prev)}
          checked={useLog}
        />
        <a
          className='ui'
          target='_blank'
          rel='noopener noreferrer'
          href='https://blog.datawrapper.de/weeklychart-logscale/'
          title='how to read log scale chart'
        >
          <Icon name='question circle outline'></Icon>
        </a>
      </div>
    </div>
  );
}
Example #4
Source File: Sidebar.js    From cord-19 with Apache License 2.0 6 votes vote down vote up
PaddedCheckbox = styled(Checkbox)`
  && {
    display: block;
    padding: 2px;
    font-size: 0.9em;
    label {
      color: #303030;
    }
  }
`
Example #5
Source File: StayItem.js    From app-personium-trails with Apache License 2.0 6 votes vote down vote up
export function StayItem(props) {
  const { __id, name, startTime: _startTime, endTime: _endTime } = props.dat;
  const startTime = parseInt(_startTime.match(/\/Date\((\d+)\)\//)[1]);
  const endTime = parseInt(_endTime.match(/\/Date\((\d+)\)\//)[1]);

  const { isPublic, isLoading, onClick } = props;
  const strPublic = isPublic ? 'public' : 'private';

  return (
    <Item>
      <Item.Content verticalAlign="middle">
        <Item.Header as={Link} to={`/detail/${__id}`}>
          <Icon name="map marker alternate" />
          {name}
        </Item.Header>
        <Item.Meta>#{__id}</Item.Meta>
        <Item.Extra>
          <div>
            {new Date(startTime).toLocaleTimeString()} -{' '}
            {new Date(endTime).toLocaleTimeString()}
          </div>
          <Checkbox
            toggle
            disabled={isLoading}
            readOnly
            onClick={onClick}
            label={strPublic}
            checked={isPublic}
          />
        </Item.Extra>
      </Item.Content>
    </Item>
  );
}
Example #6
Source File: MoveItem.js    From app-personium-trails with Apache License 2.0 6 votes vote down vote up
export function MoveItem(props) {
  const { __id, startTime: _startTime, endTime: _endTime } = props.dat;
  const startTime = parseInt(_startTime.match(/\/Date\((\d+)\)\//)[1]);
  const endTime = parseInt(_endTime.match(/\/Date\((\d+)\)\//)[1]);

  const { isPublic, isLoading, onClick } = props;
  const strPublic = isPublic ? 'public' : 'private';

  return (
    <Item>
      <Item.Content verticalAlign="middle">
        <Item.Header as={Link} to={`/detail/${__id}`}>
          <Icon name="road" />
          MOVE
        </Item.Header>
        <Item.Meta>#{__id}</Item.Meta>
        <Item.Extra>
          <div>
            {new Date(startTime).toLocaleTimeString()} -{' '}
            {new Date(endTime).toLocaleTimeString()}
          </div>
          <Checkbox
            toggle
            disabled={isLoading}
            readOnly
            onClick={onClick}
            label={strPublic}
            checked={isPublic}
          />
        </Item.Extra>
      </Item.Content>
    </Item>
  );
}
Example #7
Source File: CardBucketAggregationValueElement.js    From react-invenio-app-ils with MIT License 6 votes vote down vote up
CardBucketAggregationValueElementOverrides = ({
  bucket,
  isSelected,
  onFilterClicked,
  getChildAggCmps,
  overridableId,
  valueLabel,
}) => {
  const childAggCmps = getChildAggCmps(bucket);
  const key = bucket.key_as_string ? bucket.key_as_string : bucket.key;
  const label = generateLabel(key);

  return (
    <List.Item key={bucket.key}>
      <List.Content floated="right">
        <Label>{bucket.doc_count}</Label>
      </List.Content>
      <List.Content>
        <Checkbox
          label={label}
          value={key}
          onClick={() => onFilterClicked(key)}
          checked={isSelected}
        />
        {childAggCmps}
      </List.Content>
    </List.Item>
  );
}
Example #8
Source File: AvailableLoanBucketAggregationValues.js    From react-invenio-app-ils with MIT License 6 votes vote down vote up
AvailableLoanBucketAggregationValues = ({
  bucket,
  isSelected,
  onFilterClicked,
  getChildAggCmps,
  overridableId,
  valueLabel,
}) => {
  const key = bucket.key_as_string ? bucket.key_as_string : bucket.key;
  return (
    <Checkbox
      label="Available now"
      value={key}
      onClick={() => onFilterClicked(key)}
      checked={isSelected}
      fitted
      toggle
    />
  );
}
Example #9
Source File: RulesTableRow.js    From vch-mri with MIT License 6 votes vote down vote up
render() {
        return (
        <Table.Row disabled={this.props.loading}>
            <Table.Cell collapsing>
                <Checkbox toggle checked={this.state.active} onChange={this.handleToggle}/>
            </Table.Cell>
            <Table.Cell collapsing>{this.props.id}</Table.Cell>
            <Table.Cell collapsing>{this.props.body_part}</Table.Cell>
            <Table.Cell collapsing>{this.props.contrast.toString()}</Table.Cell>
            <Table.Cell collapsing>{this.props.priority}</Table.Cell>
            <Table.Cell>{this.props.info}</Table.Cell>
            <Table.Cell collapsing>
                <ModifyRuleForm
                    id={this.props.id}
                    body_part={this.props.body_part}
                    info={this.props.info}
                    contrast={this.props.contrast}
                    mriPriority={this.props.priority}
                />
            </Table.Cell>
        </Table.Row>
        );
    }
Example #10
Source File: Dprofile.jsx    From HACC-Hui with MIT License 6 votes vote down vote up
renderChallenge() {
    const handleOnChange = (e, data) => {
      if (data.checked === true) {
        const challenge = _.findWhere(this.props.challenges, { title: data.label });
        this.challenges.push(challenge);

      } else {
        // eslint-disable-next-line eqeqeq
        this.challenges = _.filter(this.challenges, function (challenge) {
          return challenge.title !== data.label;
        });
      }
      console.log(this.challenges);
    };
    const ChallengesOptions = this.props.challenges;
    return _.map(ChallengesOptions, function (challenge) {
      //  const name = `${challenge.title}   ( ${challenge.description} )`;
      return <Grid.Row key={challenge._id}><Checkbox label={challenge.title} onChange={handleOnChange} /></Grid.Row>;
    });
  }
Example #11
Source File: UpdateMinorParticipantsWidget.jsx    From HACC-Hui with MIT License 6 votes vote down vote up
renderMinorParticipants() {

    const CheckBoxFun = {};
    const allMPs = this.props.MinorParticipantsID;
    allMPs.forEach((MP) => {
 CheckBoxFun[MP] = (evt, data) => {
    if (data.checked) this.selected.push(MP);
    // eslint-disable-next-line eqeqeq
    else this.selected = this.selected.filter((Minor) => Minor != MP);
    };
});
    const MinorParticipantsList = this.getMinorParticipants();
    return MinorParticipantsList.map((p) => (<Table.Row key={p._id} columns={3}>
      <Table.Cell>{ `${p.firstName} ${p.lastName}`}</Table.Cell>
      <Table.Cell>{p.ParentName}</Table.Cell>
      <Table.Cell><Checkbox value={p._id} onClick={(evt, data) => CheckBoxFun[p._id](evt, data)}/></Table.Cell>
    </Table.Row>));
  }
Example #12
Source File: App.js    From cra-rich-chrome-ext-example with MIT License 5 votes vote down vote up
render() {
    const { matchWhole, matchCase, color, colorBg, bold, underline } = this.props;
    return (
      <div className='App'>
        <h2>Keyword Marker: Settings</h2>
        <Form>
          <Divider />
          <Form.Field>
            <Checkbox toggle name='matchWhole' label='Match whole word' defaultChecked={Boolean(matchWhole)} onChange={this.onCheck} />
          </Form.Field>
          <Divider />
          <Form.Field>
            <Checkbox toggle name='matchCase' label='Match case' defaultChecked={Boolean(matchCase)} onChange={this.onCheck} />
          </Form.Field>
          <Divider />
          <Form.Group inline>
            <Form.Field>
              <label>Mark Color:</label>
            </Form.Field>
            <Form.Group inline>
              <Form.Field>
                <input type='color' name='colorBg' className='color-field' title='Background Color' value={colorBg} onChange={this.onColor} />
              </Form.Field>
              <Form.Field>
                <input type='color' name='color' className='color-field' title='Text Color' value={color} onChange={this.onColor} />
              </Form.Field>
            </Form.Group>
          </Form.Group>
          <Divider />
          <Form.Group inline>
            <Form.Field>
              <label>Mark Style:</label>
            </Form.Field>
            <Form.Field>
              <Button.Group>
                <Button icon='bold' name='bold' title='Bold' active={Boolean(bold)} onToggle={this.onToggle} />
                <Button icon='underline' name='underline' title='Underline' active={Boolean(underline)} onToggle={this.onToggle} />
              </Button.Group>
            </Form.Field>
          </Form.Group>
        </Form>
      </div>
    );
  }
Example #13
Source File: Authed.js    From cra-rich-chrome-ext-example with MIT License 5 votes vote down vote up
render () {
    const { name, keywords, enabled, stats } = this.props;
    return (
      <div>

        <Container textAlign='center'>
          <Button floated='left' circular icon='cog' onClick={this.onSettings} />
          <Button floated='right' circular icon='sign out' onClick={this.onLogout} />
          <Checkbox toggle disabled={!keywords} defaultChecked={Boolean(enabled)} onChange={this.onCheck} />
        </Container>

        <Segment textAlign='center'>

          {!name && !keywords &&
          <Placeholder fluid>
            <Placeholder.Line />
            <Placeholder.Line />
            <Placeholder.Line />
            <Placeholder.Line />
          </Placeholder>
          }

          {name &&
          <Header as='h4'>
            <Icon name='user' />{name}
          </Header>
          }

          {keywords && keywords.map((v, i) =>
            <Label color='red' tag>
              {v}
              {stats &&
                <Label.Detail>{stats[i]}</Label.Detail>
              }
            </Label>
          )}
        
        </Segment>

      </div>
    );
  }
Example #14
Source File: functional-ref-focus.js    From nextfeathers with Apache License 2.0 5 votes vote down vote up
UseRef = () => {
  const firstNameRef = useRef();
  const lastNameRef = useRef();

  useEffect(() => {
    firstNameRef.current.focus();
    // document.getElementById("dnx-input").focus();
  }, []);

  const handleKeyDown = (e) => {
    if (e.key === "Enter") {
      lastNameRef.current.focus();
    }
  };

  return (
    <Layout>
      <Header as="h3">Ref Demo - Focus</Header>
      <Message info>
        <Message.Header>How this works</Message.Header>
        <p>
          When the page loads, we use <code>firstNameRef.current.focus()</code>{" "}
          to set focus on the First Name input.
          <br />
          When we press {`'Enter'`} in the First Name input, we use{" "}
          <code>lastNameRef.current.focus();</code> to set focus on the Last
          Name input.
        </p>
      </Message>

      <Form>
        <Form.Field>
          <label>First Name</label>
          <input
            placeholder="First Name"
            ref={firstNameRef}
            onKeyDown={handleKeyDown}
          />
        </Form.Field>
        <Form.Field>
          <label>Last Name</label>
          <input placeholder="Last Name" ref={lastNameRef} />
        </Form.Field>
        <Form.Field>
          <Checkbox label="I agree to the Terms and Conditions" />
        </Form.Field>
        <Button type="submit">Submit</Button>
      </Form>
      <Header as="h3">Codepen Demo</Header>
      <a href="" target="_blank">
        https://codepen.io/deniapps/pen/wvGaaPV
      </a>
    </Layout>
  );
}
Example #15
Source File: class-ref-focus.js    From nextfeathers with Apache License 2.0 5 votes vote down vote up
render() {
    return (
      <Layout>
        <Header as="h3">Ref Demo - Focus</Header>

        <Message info>
          <Message.Header>How this works</Message.Header>
          <p>
            When the page loads, we use{" "}
            <code>this.firstNameRef.current.focus()</code> to set focus on the
            First Name input.
            <br />
            When we press {`'Enter'`} in the First Name input, we use{" "}
            <code>this.lastNameRef.current.focus();</code> to set focus on the
            Last Name input.
          </p>
        </Message>

        <Form>
          <Form.Field>
            <label>First Name</label>
            <input
              placeholder="First Name"
              ref={this.firstNameRef}
              onKeyDown={this.handleKeyDown}
            />
          </Form.Field>
          <Form.Field>
            <label>Last Name</label>
            <input placeholder="Last Name" ref={this.lastNameRef} />
          </Form.Field>
          <Form.Field>
            <Checkbox label="I agree to the Terms and Conditions" />
          </Form.Field>
          <Button type="submit">Submit</Button>
        </Form>

        <Header as="h3">Codepen Demo</Header>
        <a href="" target="_blank">
          https://codepen.io/deniapps/pen/xxVGxNv
        </a>
      </Layout>
    );
  }
Example #16
Source File: FileUploaderToolbar.js    From react-invenio-deposit with MIT License 5 votes vote down vote up
FileUploaderToolbar = ({
  config,
  filesList,
  filesSize,
  filesEnabled,
  quota,
  decimalSizeDisplay,
}) => {
  const { setFieldValue } = useFormikContext();

  const handleOnChangeMetadataOnly = () => {
    setFieldValue('files.enabled', !filesEnabled)
    setFieldValue('access.files', 'public')
  }

  return (
    <>
      <Grid.Column verticalAlign="middle" floated="left" mobile={16} tablet={6} computer={6}>
        {config.canHaveMetadataOnlyRecords && (
          <List horizontal>
            <List.Item>
              <Checkbox
                label={i18next.t('Metadata-only record')}
                onChange={handleOnChangeMetadataOnly}
                disabled={filesList.length > 0}
                checked={!filesEnabled}
              />
            </List.Item>
            <List.Item>
              <Popup
                trigger={<Icon name="question circle outline" className="neutral" />}
                content={i18next.t('Disable files for this record')}
                position="top center"
              />
            </List.Item>
          </List>
        )}
      </Grid.Column>
      {filesEnabled && (
        <Grid.Column mobile={16} tablet={10} computer={10} className="storage-col">
          <Header size="tiny" className="mr-10">{i18next.t('Storage available')}</Header>
          <List horizontal floated="right">
            <List.Item>
              <Label
                {...(filesList.length === quota.maxFiles
                  ? { color: 'blue' }
                  : {})}
              >
                {i18next.t(`{{length}} out of {{maxfiles}} files`, {
                  length: filesList.length,
                  maxfiles: quota.maxFiles,
                })}
              </Label>
            </List.Item>
            <List.Item>
              <Label
                {...(humanReadableBytes(filesSize, decimalSizeDisplay) ===
                humanReadableBytes(quota.maxStorage, decimalSizeDisplay)
                  ? { color: 'blue' }
                  : {})}
              >
                {humanReadableBytes(filesSize, decimalSizeDisplay)}{' '}
                {i18next.t('out of')}{' '}
                {humanReadableBytes(quota.maxStorage, decimalSizeDisplay)}
              </Label>
            </List.Item>
          </List>
        </Grid.Column>
      )}
    </>
  );
}
Example #17
Source File: filter-modal.jsx    From gsoc-organizations with GNU General Public License v3.0 5 votes vote down vote up
render() {
    const filteredCheckboxes = this.getFilteredOptionsIndexes().map(index => {
      return (
        <Grid.Column>
          <Checkbox
            checked={this.isIndexSelected(index)}
            label={this.getCheckboxLabel(index)}
            value={this.isIndexSelected(index)}
            onChange={this.toggleChecked(index)}
          />
        </Grid.Column>
      )
    })

    return (
      <div className="filter-modal">
        <Modal
          onClose={this.toggleModal(false)}
          onOpen={this.toggleModal(true)}
          open={this.state.open}
          trigger={this.props.trigger}
        >
          <Modal.Header>Filter by {this.getDisplayableName()}</Modal.Header>
          <Modal.Content className="filter-modal-content" scrolling>
            <Input
              size="small"
              icon="search"
              className="filter-modal-content-search"
              value={this.state.searchQuery}
              onChange={this.handleSearchQuery.bind(this)}
              placeholder={`Search ${this.props.name}`}
            />
            <div className="filter-modal-content-filters">
              <Grid stackable columns={3}>
                {filteredCheckboxes}
              </Grid>
            </div>
          </Modal.Content>
          <Modal.Actions>
            <Button
              content="Done"
              labelPosition="right"
              icon="checkmark"
              onClick={this.toggleModal(false)}
              color="orange"
            />
          </Modal.Actions>
        </Modal>
      </div>
    )
  }
Example #18
Source File: filter.jsx    From gsoc-organizations with GNU General Public License v3.0 5 votes vote down vote up
render() {
    let filteredCheckboxes = this.getFilteredOptionsIndexes().map(index => {
      return (
        <tr>
          <td>
            <Checkbox
              checked={this.isIndexSelected(index)}
              label={this.getCheckboxLabel(index)}
              value={this.isIndexSelected(index)}
              onChange={this.toggleChecked(index)}
            />
          </td>
        </tr>
      )
    })

    const max_options_displayed = Math.max(
      this.getOptionIndexes(true).length,
      this.DEFAULT_OPTIONS_DISPLAYED
    )
    const num_options_displayed = Math.min(
      max_options_displayed,
      filteredCheckboxes.length
    )
    filteredCheckboxes = filteredCheckboxes.slice(0, num_options_displayed)
    const displayModalOption =
      this.getAllOptions().length > num_options_displayed

    return (
      <div className="filter-filter">
        <div className="filter-topic">
          <u>{this.getDisplayableName()}</u>
        </div>
        <div className="filter-search">
          <Input
            size="mini"
            icon="search"
            value={this.state.searchQuery}
            placeholder={`Search ${this.props.name}`}
            onChange={this.handleSearchQuery.bind(this)}
          />
        </div>
        <div className="filter-boxes">
          <center>
            <div className="filter-boxes-container">
              <table>
                <tbody>{filteredCheckboxes}</tbody>
              </table>
            </div>
          </center>
        </div>
        <div style={displayModalOption ? {} : { display: "none" }}>
          <FilterModal
            name={this.props.name}
            choices={this.props.choices}
            sortBy={this.props.sortBy}
            order={this.props.order}
            trigger={<div className="filter-view-more">View all</div>}
          />
        </div>
        <div style={this.props.showDivider ? {} : { display: "none" }}>
          <center>
            <Divider className="filter-divider" />
          </center>
        </div>
      </div>
    )
  }
Example #19
Source File: CCPDataTables.js    From aws-amplify-connect with MIT No Attribution 5 votes vote down vote up
render() {
    //console.log("this.items");
    //console.log(this.state.items);

    var tableitems = this.state.items.sort( compare );
    var tablerows = tableitems.map(function (item, i) {
      let toggleEnabled;
      if (item.enabled === "0"){
        toggleEnabled = <Checkbox toggle checked={false} onChange={(event) => this.onEnabledClickHandler(item, i, event, "1")} /> // click enables "1"
      };
      if (item.enabled === "1") { 
        toggleEnabled = <Checkbox toggle checked={true} onChange={(event) => this.onEnabledClickHandler(item, i, event, "0")} />  // click disabled "0"
      }; 
      return <Table.Row key={i} >
        <Table.Cell collapsing>{item.telephoneNumber}</Table.Cell>
        <Table.Cell>{item.firstName} {item.lastName}</Table.Cell>
        <Table.Cell>{toggleEnabled}</Table.Cell>
        <Table.Cell><Button negative circular icon='delete' onClick={(event) => this.onDeleteClickHandler(item, i, event)}/></Table.Cell>
      </Table.Row>
    }.bind(this));

    var leftDisabled = false
    var rightDisabled = false
    if(this.state.scanIndexForward === false && this.state.lastEvaluatedKey === ""){leftDisabled = true} else {leftDisabled = false};
    if(this.state.scanIndexForward === true  && this.state.lastEvaluatedKey === ""){rightDisabled = true} else {rightDisabled = false};
    if(this.state.pageturns < 2){leftDisabled = true} // handle just started use case


    const table =
    <div>
      <Table celled striped>
        <Table.Header>
          <Table.Row>
            <Table.HeaderCell>Telephone</Table.HeaderCell>
            <Table.HeaderCell>Name</Table.HeaderCell>
            <Table.HeaderCell><Checkbox toggle checked={this.state.filterEnabled} onClick={(event) => this.onFilterEnabledClickHandler()}/> Enabled</Table.HeaderCell>
            <Table.HeaderCell>Delete</Table.HeaderCell>
          </Table.Row>
        </Table.Header>
        <Table.Body>
          {tablerows}
        </Table.Body>
      </Table>
      
      <Button icon labelPosition='left' onClick={(event) => this.componentDidMount(true)} disabled={leftDisabled}><Icon name='left arrow' />Back</Button>
      <Button icon labelPosition='right' onClick={(event) => this.componentDidMount(false)} disabled={rightDisabled}>Next<Icon name='right arrow' /></Button>
    </div>
    return table;
  }
Example #20
Source File: ListParticipantsWidgetAdmin.jsx    From HACC-Hui with MIT License 4 votes vote down vote up
render() {
    // console.log(this.props);
    // console.log(this.state.result);
    if (this.props.participants.length === 0) {
      return (
        <div align={'center'}>
          <Header as='h2' icon>
            <Icon name='users' />
            There are no participants at the moment.
            <Header.Subheader>
              Please check back later.
            </Header.Subheader>
          </Header>
        </div>
      );
    }

    const sticky = {
      position1: '-webkit-sticky',
      position: 'sticky',
      top: '6.5rem',
    };

    const filters = new ListParticipantsFilterAdmin();

    const setFilters = () => {
      const searchResults = filters.filterBySearch(this.props.participants, this.state.search);
      const skillResults = filters.filterBySkills(this.state.skills,
        this.props.skills, this.props.participantSkills, searchResults);
      const toolResults = filters.filterByTools(this.state.tools,
        this.props.tools, this.props.participantTools, skillResults);
      const challengeResults = filters.filterByChallenge(this.state.challenges,
        this.props.challenges, this.props.participantChallenges, toolResults);
      const teamResults = filters.filterByTeam(this.state.teams, this.props.teams,
        this.props.teamParticipants, challengeResults);
      // const noTeamResults = filters.filterNoTeam(this.props.teamParticipants, teamResults);
      const sorted = _.uniqBy(filters.sortBy(teamResults, 'participants'), 'username');
      // console.log(sorted);
      this.setState({
        result: sorted,
      }, () => {
      });
    };

    const handleSearchChange = (event) => {
      this.setState({
        search: event.target.value,
      }, () => {
        setFilters();
      });
    };

    const getSkills = (event, { value }) => {
      this.setState({
        skills: value,
      }, () => {
        setFilters();
      });
    };

    const getTools = (event, { value }) => {
      this.setState({
        tools: value,
      }, () => {
        setFilters();
      });
    };

    const getChallenge = (event, { value }) => {
      this.setState({
        challenges: value,
      }, () => {
        setFilters();
      });
    };

    const getTeam = (event, { value }) => {
      this.setState({
        teams: value,
      }, () => {
        setFilters();
      });
    };

    const universalSkills = this.props.skills;

    function getParticipantSkills(participantID, participantSkills) {
      const data = [];
      const skills = _.filter(participantSkills, { participantID: participantID });
      for (let i = 0; i < skills.length; i++) {
        for (let j = 0; j < universalSkills.length; j++) {
          if (skills[i].skillID === universalSkills[j]._id) {
            data.push({ name: universalSkills[j].name });
          }
        }
      }
      // console.log(data);
      return data;
    }

    const universalTools = this.props.tools;

    function getParticipantTools(participantID, participantTools) {
      const data = [];
      const tools = _.filter(participantTools, { participantID: participantID });
      for (let i = 0; i < tools.length; i++) {
        for (let j = 0; j < universalTools.length; j++) {
          if (tools[i].toolID === universalTools[j]._id) {
            data.push({ name: universalTools[j].name });
          }
        }
      }
      return data;
    }

    const universalChallenges = this.props.challenges;

    function getParticipantChallenges(participantID, participantChallenges) {
      const data = [];
      const challenges = _.filter(participantChallenges, { participantID: participantID });
      for (let i = 0; i < challenges.length; i++) {
        for (let j = 0; j < universalChallenges.length; j++) {
          if (challenges[i].challengeID === universalChallenges[j]._id) {
            data.push(universalChallenges[j].title);
          }
        }
      }
      return data;
    }

    const universalTeams = this.props.teams;
    function getParticipantTeams(participantID, teamParticipants) {
      const data = [];
      const teams = _.filter(teamParticipants, { participantID: participantID });
      for (let i = 0; i < teams.length; i++) {
        for (let j = 0; j < universalTeams.length; j++) {
          if (teams[i].teamID === universalTeams[j]._id) {
            data.push(universalTeams[j].name);
          }
        }
      }
      return data;
    }

    const handleDownload = () => {
      const zip = new ZipZap();
      const dir = 'hacchui-participants';
      const fileName = `${dir}/${moment().format(databaseFileDateFormat)}-participants.txt`;
      const participants = this.state.result;
      const emails = participants.map(p => p.username);
      zip.file(fileName, emails.join('\n'));
      zip.saveAs(`${dir}.zip`);
    };

    const handleMultipleTeams = () => {
      if (!this.state.multipleTeamsCheckbox) {
        const participants = this.state.result;
        const results = filters.filterMultipleTeams(this.props.teamParticipants, participants);
        const sorted = _.uniqBy(filters.sortBy(results, 'participants'), 'username');
        this.setState({
          result: sorted,
        }, () => {
        });
      } else {
        this.setState({
          result: this.props.participants,
        }, () => {
        });

      }
      const checked = this.state.multipleTeamsCheckbox;
      this.setState({ multipleTeamsCheckbox: !checked });
    };

    const handleNoTeam = () => {
      if (!this.state.noTeamCheckbox) {
        const participants = this.state.result;
        const results = filters.filterNoTeam(this.props.teamParticipants, participants);
        const sorted = _.uniqBy(filters.sortBy(results, 'participants'), 'username');
        this.setState({
          result: sorted,
        }, () => {
        });
      } else {
        this.setState({
          result: this.props.participants,
        }, () => {
        });
      }
      const checked = this.state.noTeamCheckbox;
      this.setState({ noTeamCheckbox: !checked });
    };

    const handleNotCompliant = () => {
      if (!this.state.compliantCheckbox) {
        const participants = this.state.result;
        const results = participants.filter(p => !p.isCompliant);
        const sorted = _.uniqBy(filters.sortBy(results, 'participants'), 'username');
        this.setState({
          result: sorted,
        }, () => {
        });
      } else {
        this.setState({
          result: this.props.participants,
        }, () => {
        });
      }
      const checked = this.state.compliantCheckbox;
      this.setState({ compliantCheckbox: !checked });
    };

    const filterStyle = {
      paddingTop: 4,
    };
    // console.log(this.state.result);
    return (
      <div style={{ paddingBottom: '50px' }}>
        <Grid container doubling relaxed stackable centered>
          <Grid.Row centered>
            <Grid.Column width={16}>
              <div style={{
                backgroundColor: '#E5F0FE', padding: '1rem 0rem', margin: '2rem 0rem',
                borderRadius: '2rem',
              }}>
                <Header as={'h2'} textAlign="center">
                  All Participants
                </Header>
              </div>
            </Grid.Column>
          </Grid.Row>
          <Grid.Row centered>
            <Grid.Column>
              <Button onClick={handleDownload}>Download emails</Button>
            </Grid.Column>
          </Grid.Row>
          <Grid.Column width={4}>
            <Segment style={sticky}>
              <div style={filterStyle}>
                <Header>
                  <Header.Content>
                    Filter Participants
                    <Header.Subheader>Total Participants: {this.state.result.length}</Header.Subheader>
                  </Header.Content>
                </Header>
                <Checkbox onChange={handleNoTeam} label="No Team"/>
                <Checkbox onChange={handleMultipleTeams} label="Multiple Teams"/>
                <Checkbox onChange={handleNotCompliant} label="Not Compliant"/>
              </div>
              <div style={filterStyle}>
                <Input icon='search'
                       iconPosition='left'
                       placeholder='Search by participants name...'
                       onChange={handleSearchChange}
                       fluid
                />

                <div style={filterStyle}>
                  <Header>Teams</Header>
                  <Dropdown
                    placeholder='Teams'
                    fluid
                    multiple
                    search
                    selection
                    options={filters.dropdownValues(this.props.teams, 'name')}
                    onChange={getTeam}
                  />
                </div>

                <div style={filterStyle}>
                  <Header>Challenges</Header>
                  <Dropdown
                    placeholder='Challenges'
                    fluid
                    multiple
                    search
                    selection
                    options={filters.dropdownValues(this.props.challenges, 'title')}
                    onChange={getChallenge}
                  />
                </div>
              </div>
              <div style={filterStyle}>
                <Header>Skills</Header>
                <Dropdown placeholder='Skills'
                          fluid
                          multiple
                          search
                          selection
                          options={filters.dropdownValues(this.props.skills, 'name')}
                          onChange={getSkills}
                />
              </div>
              <div style={filterStyle}>
                <Header>Tools</Header>
                <Dropdown
                  placeholder='Tools'
                  fluid
                  multiple
                  search
                  selection
                  options={filters.dropdownValues(this.props.tools, 'name')}
                  onChange={getTools}
                />
              </div>
            </Segment>
          </Grid.Column>
          <Grid.Column width={12}>
            <Item.Group divided>
              {this.state.result.map((participants) => <ListParticipantCardAdmin
                key={participants._id}
                participantID={participants._id}
                participants={participants}
                skills={getParticipantSkills(participants._id, this.props.participantSkills)}
                tools={getParticipantTools(participants._id, this.props.participantTools)}
                challenges={getParticipantChallenges(participants._id, this.props.participantChallenges)}
                teams={getParticipantTeams(participants._id, this.props.teamParticipants)}
              />)}
            </Item.Group>
          </Grid.Column>
        </Grid>
      </div>
    );
  }
Example #21
Source File: FileUploaderArea.js    From react-invenio-deposit with MIT License 4 votes vote down vote up
FileTableRow = ({
  isDraftRecord,
  file,
  deleteFile,
  defaultPreview,
  setDefaultPreview,
  decimalSizeDisplay,
}) => {
  const [isCancelling, setIsCancelling] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const isDefaultPreview = defaultPreview === file.name;

  const handleDelete = async (file) => {
    setIsDeleting(true);
    try {
      await deleteFile(file);
      if (isDefaultPreview) {
        setDefaultPreview('');
      }
    } catch (error) {}
  };

  const handleCancelUpload = (file) => {
    setIsCancelling(true);
    file.cancelUploadFn();
  };

  return (
    <Table.Row key={file.name}>
      <Table.Cell data-label={i18next.t('Default preview')} width={2}>
        {/* TODO: Investigate if react-deposit-forms optimized Checkbox field
                  would be more performant */}
        <Checkbox
          checked={isDefaultPreview}
          onChange={() => setDefaultPreview(isDefaultPreview ? '' : file.name)}
        />
      </Table.Cell>
      <Table.Cell data-label={i18next.t('Filename')} width={10}>
        <div>
        {file.uploadState.isPending ? (
            file.name
          ) : (
            <a
              href={_get(file, 'links.content', '')}
              target="_blank"
              rel="noopener noreferrer"
              className="mr-5"
            >
              {file.name}
            </a>
          )}
          <br />
          {file.checksum && (
            <div className="ui text-muted">
              <span style={{ fontSize: '10px' }}>{file.checksum}</span>{' '}
              <Popup
                content={i18next.t(
                  'This is the file fingerprint (MD5 checksum), which can be used to verify the file integrity.'
                )}
                trigger={<Icon fitted name="help circle" size="small" />}
                position="top center"
              />
            </div>
          )}
        </div>
      </Table.Cell>
      <Table.Cell data-label={i18next.t('Size')} width={2}>
        {file.size ? humanReadableBytes(file.size, decimalSizeDisplay) : ''}
      </Table.Cell>
      {isDraftRecord && (
        <Table.Cell className="file-upload-pending" data-label={i18next.t('Progress')} width={2}>
          {!file.uploadState?.isPending && (
            <Progress
              className="file-upload-progress primary"
              percent={file.progressPercentage}
              error={file.uploadState.isFailed}
              size="medium"
              progress
              autoSuccess
              active
            />
          )}
          {file.uploadState?.isPending && <span>{i18next.t('Pending')}</span>}
        </Table.Cell>
      )}
      {isDraftRecord && (
        <Table.Cell textAlign="right" width={2}>
          {(file.uploadState?.isFinished || file.uploadState?.isFailed) &&
            (isDeleting ? (
              <Icon loading name="spinner" />
            ) : (
              <Icon
                link
                className="action primary"
                name="trash alternate outline"
                disabled={isDeleting}
                onClick={() => handleDelete(file)}
                aria-label={i18next.t("Delete file")}
                title={i18next.t("Delete file")}
              />
            ))}
          {file.uploadState?.isUploading && (
            <Button
              compact
              type="button"
              negative
              size="tiny"
              disabled={isCancelling}
              onClick={() => handleCancelUpload(file)}
            >
              {isCancelling ? (
                <Icon loading name="spinner" />
              ) : (
                i18next.t('Cancel')
              )}
            </Button>
          )}
        </Table.Cell>
      )}
    </Table.Row>
  );
}
Example #22
Source File: SubmitReviewModal.js    From react-invenio-deposit with MIT License 4 votes vote down vote up
render() {
    const {
      initialReviewComment,
      isConfirmModalOpen,
      community,
      onClose,
      onSubmit,
    } = this.props;
    const communityTitle = community.metadata.title;
    return (
      <Formik
        initialValues={{
          acceptAccessToRecord: '',
          acceptAfterPublishRecord: '',
          reviewComment: initialReviewComment || '',
        }}
        onSubmit={onSubmit}
        validationSchema={this.ConfirmSubmitReviewSchema}
        validateOnChange={false}
        validateOnBlur={false}
      >
        {({ values, resetForm, handleSubmit }) => {
          return (
            <Modal
              open={isConfirmModalOpen}
              onClose={onClose}
              size="small"
              closeIcon={true}
              closeOnDimmerClick={false}
            >
              <Modal.Header>
                <Trans>Submit for review</Trans>
              </Modal.Header>
              <Modal.Content>
                <Message visible warning>
                  <p>
                    <Icon name="warning sign" />
                    {i18next.t(
                      'Before requesting review please read and check the following:'
                    )}
                  </p>
                </Message>
                <Form>
                  <Form.Field>
                    <RadioField
                      control={Checkbox}
                      fieldPath="acceptAccessToRecord"
                      label={
                        <Trans
                          defaults="The '{{communityTitle}}' curators will have access to
                 <bold>view</bold> and <bold>edit</bold> your
                 upload's metadata and files."
                          values={{
                            communityTitle,
                          }}
                          components={{ bold: <b /> }}
                          shouldUnescape={true}
                        />
                      }
                      checked={
                        _get(values, 'acceptAccessToRecord') === 'checked'
                      }
                      onChange={({ event, data, formikProps }) => {
                        formikProps.form.setFieldValue(
                          'acceptAccessToRecord',
                          data.checked ? 'checked' : ''
                        );
                      }}
                      optimized
                    />
                    <ErrorLabel
                      fieldPath="acceptAccessToRecord"
                      className="mt-0 mb-5"
                    />
                  </Form.Field>
                  <Form.Field>
                    <RadioField
                      control={Checkbox}
                      fieldPath="acceptAfterPublishRecord"
                      label={
                        <Trans
                          defaults="If your upload is accepted by the community curators, it will be <bold>immediately published</bold>. Before that, you will still be able to modify metadata and files of this upload."
                          values={{
                            communityTitle: communityTitle,
                          }}
                          components={{ bold: <b /> }}
                        />
                      }
                      checked={
                        _get(values, 'acceptAfterPublishRecord') === 'checked'
                      }
                      onChange={({ event, data, formikProps }) => {
                        formikProps.form.setFieldValue(
                          'acceptAfterPublishRecord',
                          data.checked ? 'checked' : ''
                        );
                      }}
                      optimized
                    />
                    <ErrorLabel
                      fieldPath="acceptAfterPublishRecord"
                      className="mt-0 mb-5"
                    />
                  </Form.Field>
                  <TextAreaField
                    fieldPath="reviewComment"
                    label="Message to curators (optional)"
                  />
                </Form>
              </Modal.Content>
              <Modal.Actions>
                <Button onClick={onClose} floated="left">
                  {i18next.t('Cancel')}
                </Button>
                <Button
                  name="submitReview"
                  onClick={(event) => {
                    handleSubmit(event);
                  }}
                  positive
                  content={i18next.t('Submit review')}
                />
              </Modal.Actions>
            </Modal>
          );
        }}
      </Formik>
    );
  }
Example #23
Source File: 07-controlled.js    From react-fluid-table with MIT License 4 votes vote down vote up
Example7 = () => {
  // hooks
  const [toggles, setToggles] = useState({
    data: false,
    height: false,
    columns: false
  });

  // variables
  const keys = Object.keys(toggles);
  const props = {
    data: toggles.data ? testData2 : testData,
    height: toggles.height ? 200 : 400,
    columns: toggles.columns
      ? [...columns, { key: "address", header: "Address", sortable: true }]
      : columns
  };

  // functions
  const onToggle = key => {
    setToggles({
      ...toggles,
      [key]: !toggles[key]
    });
  };

  return (
    <>
      <Grid stackable columns={2}>
        <Grid.Row>
          <Grid.Column width={8}>
            <Form>
              <h4>Select properties to control</h4>
              <Form.Field>
                <Checkbox
                  toggle
                  label="data - changes data source"
                  value={toggles.data.toString()}
                  checked={toggles.data}
                  onChange={() => onToggle("data")}
                />
              </Form.Field>
              <Form.Field>
                <Checkbox
                  toggle
                  label="height - changes tableHeight"
                  value={toggles.height.toString()}
                  checked={toggles.height}
                  onChange={() => onToggle("height")}
                />
              </Form.Field>
              <Form.Field>
                <Checkbox
                  toggle
                  label="columns - adds an address column"
                  checked={toggles.columns}
                  onChange={() => onToggle("columns")}
                />
              </Form.Field>
            </Form>
          </Grid.Column>
          <Grid.Column width={8}>
            <h4>Controlled Props:</h4>
            <Background>
              <pre>
                {"{\n"}
                {keys.map((key, index) => {
                  const ending = index !== keys.length - 1 ? ",\n" : "\n";
                  const val = viewableTypes.has(typeof props[key]);
                  let color = "rgb(166, 226, 46)";
                  if (typeof props[key] === "number") {
                    color = "rgb(174, 129, 255)";
                  } else if (typeof props[key] === "boolean") {
                    color = "rgb(102, 217, 239)";
                  }
                  return (
                    <React.Fragment key={key}>
                      {`  ${key}: `}
                      <span style={{ color }}>
                        {val ? props[key] : toggles[key] ? '"altered"' : '"original"'}
                      </span>
                      {ending}
                    </React.Fragment>
                  );
                })}
                {"}"}
              </pre>
            </Background>
          </Grid.Column>
        </Grid.Row>
      </Grid>
      <Controlled {...props} />
    </>
  );
}
Example #24
Source File: ViewTeams.jsx    From HACC-Hui with MIT License 4 votes vote down vote up
ViewTeams = ({ participants, teams, teamChallenges, teamParticipants }) => {
  const [filteredTeams, setFilteredTeams] = useState(teams);
  const [filterValue, setFilterValue] = useState('None');
  // console.log(filteredTeams);
  const stickyStyle = {
    position1: '-webkit-sticky',
    position: 'sticky',
    top: '6.5rem',
  };

  const teamIsCompliant = (teamID) => {
    const tps = teamParticipants.filter(tp => tp.teamID === teamID);
    let compliant = true;
    tps.forEach(tp => {
      const participant = participants.filter(p => p._id === tp.participantID);
      // console.log(participant);
      compliant = compliant && participant[0].isCompliant;
    });
    return compliant;
  };

  const handleChange = (e, { value }) => {
    setFilterValue(value);
    const remainingTeams = [];
    const localTeams = filteredTeams;
    switch (value) {
      case 'Challenge':
        localTeams.forEach(team => {
          const challengeIDs = teamChallenges.filter(tc => tc.teamID === team._id);
          if (challengeIDs.length === 0) {
            remainingTeams.push(team);
          }
        });
        setFilteredTeams(remainingTeams);
        break;
      case 'NonCompliant':
        localTeams.forEach(team => {
          if (!teamIsCompliant(team._id)) {
            remainingTeams.push(team);
          }
        });
        setFilteredTeams(remainingTeams);
        break;
      case 'NoDevPost':
        localTeams.forEach(team => {
          if (!team.devPostPage) {
            remainingTeams.push(team);
          }
        });
        setFilteredTeams(remainingTeams);
        break;
      case 'NoGitHub':
        localTeams.forEach(team => {
          if (!team.gitHubRepo) {
            remainingTeams.push(team);
          }
        });
        setFilteredTeams(remainingTeams);
        break;
      default:
        setFilteredTeams(teams);
    }
  };

  const handleDownload = () => {
    const zip = new ZipZap();
    const dir = 'hacchui-team-captains';
    const fileName = `${dir}/${moment().format(databaseFileDateFormat)}-team-captains.txt`;
    const localTeams = filteredTeams;
    const ownerIDs = localTeams.map(t => t.owner);
    const emails = [];
    ownerIDs.forEach(id => {
      const pArr = participants.filter(p => p._id === id);
      emails.push(pArr[0].username);
    });
    zip.file(fileName, emails.join('\n'));
    zip.saveAs(`${dir}.zip`);
  };

  return (
      <Grid container centered>
        <Grid.Row>
          <Grid.Column width={16}>
            <div style={{
              backgroundColor: '#E5F0FE', padding: '1rem 0rem', margin: '2rem 0rem',
              borderRadius: '2rem',
            }}>
              <Header as="h2" textAlign="center">View Teams ({filteredTeams.length})</Header>
            </div>
          </Grid.Column>
        </Grid.Row>
        <Grid.Row>
          <Button onClick={handleDownload}>Download Team Captain emails</Button>
        </Grid.Row>
        <Grid.Row>
          <Grid.Column width={4}>
            <Segment style={stickyStyle}>
              <Form>
                <Form.Field>Select a filter</Form.Field>
                {/* <Form.Field> */}
                {/*  <Checkbox checked={filterValue === 'Challenge'} label="No challenge" onChange={handleChange} */}
                {/*            radio name='checkboxRadioGroup' value='Challenge' */}
                {/*  /> */}
                {/* </Form.Field> */}
                <Form.Field>
                  <Checkbox checked={filterValue === 'NonCompliant'} label="Non Compliant" onChange={handleChange}
                            radio name='checkboxRadioGroup' value='NonCompliant'
                  />
                </Form.Field>
                <Form.Field>
                  <Checkbox checked={filterValue === 'NoDevPost'} label="No devpost" onChange={handleChange}
                            radio name='checkboxRadioGroup' value='NoDevPost'
                  />
                </Form.Field>
                <Form.Field>
                  <Checkbox checked={filterValue === 'NoGitHub'} label="No GitHub" onChange={handleChange}
                            radio name='checkboxRadioGroup' value='NoGitHub'
                  />
                </Form.Field>
                <Form.Field>
                  <Checkbox checked={filterValue === 'None'} label="None" onChange={handleChange}
                            radio name='checkboxRadioGroup' value='None' />
                </Form.Field>
              </Form>
            </Segment>
          </Grid.Column>
          <Grid.Column width={12}>
            <Item.Group divided>
              {filteredTeams.map((team) => (
                  <ViewTeamExample key={team._id}
                                   team={team}
                                   teamMembers={getTeamMembers(team)}
                                   isCompliant={teamIsCompliant(team._id)}
                  />
              ))}
            </Item.Group>
          </Grid.Column></Grid.Row>
      </Grid>
  );
}