react-bootstrap#Alert JavaScript Examples
The following examples show how to use
react-bootstrap#Alert.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 | 6 votes |
Browse = (props) => {
const { match, browse, browseResults } = props;
// Init
useEffect(() => {
window.scrollTo(0, 0);
const url = new URL(window.location.href);
const email = url.searchParams.get('user_email');
const domainName = url.searchParams.get('api_domain_url');
const courseId = url.searchParams.get('course_id');
const courseName = url.searchParams.get('course_name');
browse({
lms_url: match.params.lmsUrl,
lti_client_id: match.params.ltiClientId,
user_email: email,
mode: 'browse',
course_id: courseId,
api_domain_url: domainName,
course_name: courseName,
});
}, [match]);
return (
<div className="row">
<div className="col">
{browseResults === null && (
<div className="row">
<div className="col text-center">
<img style={{ width: '50px' }} src={gifloader} alt="" />
</div>
</div>
)}
{browseResults !== null && browseResults.length === 0 && <Alert variant="warning">No projects found.</Alert>}
{browseResults !== null && browseResults.length > 0 && browseResults.map((project) => <Project project={project} key={project.id} />)}
</div>
</div>
);
}
Example #2
Source File: AlertPanel.jsx From ashteki with GNU Affero General Public License v3.0 | 6 votes |
AlertPanel = ({ type = AlertType.Info, title, message, noIcon = false, children }) => {
let icon;
/**
* @type {AlertType}
*/
let alertType;
switch (type) {
case AlertType.Warning:
icon = faExclamationTriangle;
alertType = 'warning';
break;
case AlertType.Danger:
icon = faExclamationCircle;
alertType = 'danger';
break;
case AlertType.Info:
icon = faInfoCircle;
alertType = 'info';
break;
case AlertType.Success:
icon = faCheckCircle;
alertType = 'success';
break;
}
return (
<Alert variant={alertType}>
{title && <Alert.Heading>{title}</Alert.Heading>}
{!noIcon && <FontAwesomeIcon icon={icon} />}
{message && <span id='alert-message'> {getMessageWithLinks(message)}</span>}
{children && <span> {children}</span>}
</Alert>
);
}
Example #3
Source File: connectMeta.js From RC4Community with Apache License 2.0 | 6 votes |
export function ErrorModal({ show, handleClose, err }) {
return (
<>
<Modal
show={show}
onHide={handleClose}
backdrop="static"
keyboard={false}
>
<Modal.Body>
<Alert variant="danger" onClose={handleClose}>
<Alert.Heading>Oh snap! You got an error!</Alert.Heading>
<p>
{err}
</p>
</Alert>
</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={handleClose}>
Understood
</Button>
</Modal.Footer>
</Modal>
</>
);
}
Example #4
Source File: Error.js From weatherman-react with GNU General Public License v3.0 | 6 votes |
Error = ({ errorMessage }) => {
const [show, setShow] = useState(true);
return show ? (
<Alert
className="text-center"
variant="danger"
onClose={() => setShow(false)}
dismissible
>
<p>{errorMessage || "Unfortunately, some error has occurred."}</p>
</Alert>
) : null;
}
Example #5
Source File: alert-box.js From what-front with MIT License | 6 votes |
AlertBox = () => {
const { messages } = useSelector(alertSelector, shallowEqual);
const dispatchRemoveAlert = useActions(removeAlert);
return (
messages.length ? (
<div className={styles['alert-container']}>
{
messages.map(({ variant, message, id }) => (
<Alert
variant={variant}
key={id}
dismissible
onClose={() => dispatchRemoveAlert(id)}
>
{message}
</Alert>
))
}
</div>
) : null
);
}
Example #6
Source File: ExploreTokens.js From katanapools with GNU General Public License v2.0 | 6 votes |
render() {
let statusIndicator = <span/>;
const {swap: {swapTokenStatus}} = this.props;
if (swapTokenStatus.type === 'error') {
statusIndicator = (
<Alert variant={"danger"}>
{swapTokenStatus.message}
</Alert>
)
}
return (
<div>
<ExploreTokensToolbar renderExploreView={this.renderExploreView}/>
{statusIndicator}
<Container className="explore-tokens-container">
<Switch>
<Route path="/explore/advanced">
<ExploreTokensAdvanced {...this.props}/>
</Route>
<Route path="/explore/basic">
<ExploreTokensBasic {...this.props}/>
</Route>
<Route exact path="/explore">
<ExploreTokensAdvanced {...this.props}/>
</Route>
<Route exact path="/">
<ExploreTokensAdvanced {...this.props}/>
</Route>
</Switch>
</Container>
</div>
)
}
Example #7
Source File: xpubImporter.js From xpub-tool with MIT License | 6 votes |
static renderMessage(message, i) {
// The `message` object will always have a `text` property
// but may have additional properties useful for display.
return (
<Alert variant="info" key={i}>
{message.text}
</Alert>
)
}
Example #8
Source File: dismissableAlert.js From turqV2 with GNU General Public License v3.0 | 6 votes |
function DismissableAlert({heading, children, variant}) {
const [show, setShow] = useState(true);
if (show) {
return (
<Alert variant={variant} onClose={() => setShow(false)} dismissible>
<Alert.Heading>{heading}</Alert.Heading>
{children ? children : null}
</Alert>
);
} else {
return (<></>)
}
}
Example #9
Source File: UserPageFormComponent.js From project-s0-t1-budget with MIT License | 6 votes |
handleSubmit(event) {
event.preventDefault();
const diff = parseInt(this.state.income) - parseInt(this.state.input);
const data = {
email: this.props.user.email,
month: parseInt(this.props.month),
year: parseInt(this.props.year),
labels: ["Income", "Net Income", this.state.category],
data: [this.state.income, diff.toString(), this.state.input],
goal: this.state.goal,
};
fetch("/api/userbudgets", {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
},
}).then((response) => {
if (response.status >= 200 && response.status < 300) {
this.props.update(this.props.month, this.props.year);
} else {
Alert("Something Went Wrong Try Again");
}
});
}
Example #10
Source File: Message.js From mern_library_nginx with MIT License | 5 votes |
Message = ({ variant, children }) => {
return <Alert variant={variant}>{children}</Alert>;
}
Example #11
Source File: index.js From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 | 5 votes |
function CompleteProfileAlert() {
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
// a and b are javascript Date objects
function dateDiffInDays(dateStored) {
const previousDate = new Date(dateStored);
const todaysDate = new Date();
const diffTime = Math.abs(todaysDate - previousDate);
const diffDays = Math.ceil(diffTime / (_MS_PER_DAY));
return diffDays;
}
const time = localStorage.getItem('alertclosetime');
let flag;
if (!time) {
flag = true;
} else if (dateDiffInDays(time) > 7) {
flag = true;
localStorage.removeItem('alertclosetime');
} else {
flag = false;
}
const [display, setDisplay] = useState(flag);
const hideAlert = () => {
setDisplay(false);
const date = new Date();
// const day = date.getDate();
// const month = date.getMonth();
// const year = date.getFullYear();
// localStorage.setItem('alertclosetime', `${day}/${month + 1}/${year}`);
localStorage.setItem('alertclosetime', date);
};
return (
<div>
<Alert className="alert" variant="warning" style={{ display: display ? 'block' : 'none' }}>
<FontAwesomeIcon className="close" icon="window-close" onClick={hideAlert} />
Your organization name is missing in the profile, Kindly go to My Account to update your
<Link className="goto-button" to="/account">profile info.</Link>
</Alert>
</div>
);
}
Example #12
Source File: AlertPanel.jsx From ashteki with GNU Affero General Public License v3.0 | 5 votes |
/**
* @typedef {Object} AlertPanelProps
* @property {import('react').ReactNode | import('react').ReactNodeArray} [children]
* @property {string} [className]
* @property {string} [title]
* @property {string} [message]
* @property {boolean} [noIcon]
* @property {string} [titleClass]
* @property {string} [type]
*/
/**
* @param {string} message
*/
function getMessageWithLinks(message) {
let links = message.match(/(https?:\/\/)?([^.\s]+)?[^.\s]+\.[^\s]+/gi);
let retMessage = [];
if (!links || links.length === 0) {
return message;
}
let lastIndex = 0;
let linkCount = 0;
for (let link of links) {
let index = message.indexOf(link);
retMessage.push(message.substring(lastIndex, index));
retMessage.push(
<Alert.Link key={linkCount++} href={link}>
{link}
</Alert.Link>
);
lastIndex += index + link.length;
}
retMessage.push(message.substr(lastIndex, message.length - lastIndex));
return retMessage;
}
Example #13
Source File: PopUpBox.jsx From SWEethearts-2.0 with MIT License | 5 votes |
PopUpBox = ({ currentName, creatorName, creatorEmail, currentEmail, projectName }) => {
const [message, setMessage] = useState({
subjectText: '',
messageText: '',
});
const [show, setShow] = useState(false);
const sendData = () => {
setShow(true);
const body = {
email: currentEmail,
subject: message.subjectText,
message: message.messageText,
};
fetch('/api/sendEmail', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
};
const form = currentName ? (
currentEmail ? (
<Fragment>
<Jumbotron className="jumbo">
<h1>Let's get started on {projectName}</h1>
<hr></hr>
<h3>Contact {creatorName}!</h3>
<br></br>
<Form>
<Form.Group controlId="Subject">
<Form.Label>Subject</Form.Label>
<Form.Control
type="username"
placeholder="Re:"
onChange={(e) => setMessage({ ...message, subjectText: e.target.value })}
/>
{/* onChange={setInput} /> */}
</Form.Group>
<Form.Group controlId="Message">
<Form.Label>Message</Form.Label>
<Form.Control
as="textarea"
rows="3"
placeholder="Show off your skills here..."
onChange={(e) => setMessage({ ...message, messageText: e.target.value })}
/>
</Form.Group>
<Button onClick={() => sendData()}>Submit</Button>
</Form>
{show && (
<>
<br></br>
<Alert variant="success">Message sent!</Alert>
</>
)}
</Jumbotron>
</Fragment>
) : (
<Fragment>
<h1>Let's get started on {projectName}</h1>
<br></br>
<h3>Contact {creatorName}!</h3>
<h3> You are {currentName}</h3>
<br></br>
<h1>Please register an email with your account to access messaging features!</h1>
<Nav.Link href="/profile">Add Email Here</Nav.Link>
</Fragment>
)
) : (
<Fragment>
<h1> Please login first! </h1>
</Fragment>
);
return form;
}
Example #14
Source File: addCategoryModal.js From community-forum-frontend with GNU General Public License v3.0 | 5 votes |
render() {
return (
<Modal
show={this.props.showModal}
onHide={this.props.handleClose}
centered
>
<Modal.Header closeButton>
<Modal.Title>
<Container>
<Row>
<Col xs={12}>
<h1 className="modal-heading">
New Category
</h1>
</Col>
</Row>
</Container>
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Container>
<Row>
<Col xs={12}>
<div className="modal-form">
{this.state.formSubmissionError && (
<Alert variant="danger">
{this.state.formSubmissionError}
</Alert>
)}
<Form onSubmit={this.onFormSubmit}>
<Form.Group controlId="addCategoryFormBasicText">
<Form.Label>Name</Form.Label>
<Form.Control
onChange={this.onFieldChange}
type="text"
name={fieldNames.NAME}
value={this.state.name}
/>
{this.state.nameError && (
<h6 className="form-field-error">
{this.state.nameError}
</h6>
)}
</Form.Group>
<Form.Group controlId="addCategoryFormBasicTextArea">
<Form.Label>Description</Form.Label>
<Form.Control
onChange={this.onFieldChange}
as="textarea"
rows={3}
name={fieldNames.DESCRIPTION}
value={this.state.description}
/>
{this.state.descriptionError && (
<h6 className="form-field-error">
{this.state.descriptionError}
</h6>
)}
</Form.Group>
<Row className="center-row">
<Button
variant=""
className="primary-button organization-page-create-button"
type="submit"
disabled={this.state.isFormInvalid}
>
Create
</Button>
</Row>
</Form>
</div>
</Col>
</Row>
</Container>
</Modal.Body>
</Modal>
);
}
Example #15
Source File: TestsPage.js From caricovidsite with MIT License | 5 votes |
render() {
return (
<div className={"graph-style"}>
<Form>
<Form.Group controlId="caribbeanForm.SelectCustom">
<Form.Label>Choose a country to view test data</Form.Label>
<Form.Control
ref={(select) => {
this.select = select;
}}
as="select"
custom
onChange={this.handleChange}
defaultValue={svg}
>
<option value={bb}>{bb}</option>
<option value={svg}>{svg}</option>
</Form.Control>
</Form.Group>
</Form>
<ResponsiveContainer width="99%" height={500}>
<LineChart
data={this.state.data[this.state.selectedCountry]}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 5,
}}
>
<CartesianGrid strokeDasharray="3 3" stroke={graphGridColour} />
<XAxis dataKey="date" />
<YAxis domain={[0, 30000]} />
<Tooltip content={<TestsCustomTooltip />} />
<Legend />
<Line
type="monotone"
dataKey={this.t('tests')}
stroke={testPageLineColour}
dot={false}
/>
</LineChart>
</ResponsiveContainer>
<Alert dismissable={"true"} key={1} variant={'secondary'} style={{color: 'gray', fontSize: '0.75rem',backgroundColor: '#273852', borderColor: '#273852', padding:'0.45rem', marginTop:'1rem'}}>
{this.t('tests_disclaimer')} {this.state.selectedCountry === bb? this.t('credit_kevz') : svgCredit}
</Alert>
<Alert dismissable={"true"} key={1} variant={'secondary'} style={{color: 'gray', fontSize: '0.75rem',backgroundColor: '#273852', borderColor: '#273852', padding:'0.45rem', marginTop:'1rem'}}>
Interested in volunteering for data entry? contact me on <Alert.Link href="https://www.twitter.com/janiquekajohn" target="_blank">Twitter</Alert.Link>
</Alert>
</div>
);
}
Example #16
Source File: ViewPools.js From katanapools with GNU General Public License v2.0 | 5 votes |
render() {
const { pool: {currentSelectedPool, poolTransactionStatus, currentViewPoolType}, poolData} = this.props;
let poolSelectionView = poolData;
if (currentViewPoolType === 'all') {
poolSelectionView = poolData;
} else if (currentViewPoolType === 'v1') {
poolSelectionView = poolData.filter((pool) => (pool.poolVersion === '1'));
} else {
poolSelectionView = poolData.filter((pool) => (pool.poolVersion === '2'));
}
const {selectedPoolIndex, isError, errorMessage} = this.state;
const self = this;
let poolDataList = <span/>;
if (poolSelectionView.length === 0) {
poolDataList = <span/>;
} else {
poolDataList =
<span>
<ListGroupItem>
Symbol
</ListGroupItem>
{
poolSelectionView.map(function(poolRow, idx){
let cellActive = '';
if (idx === selectedPoolIndex) {
cellActive = 'cell-active';
}
return <ListGroupItem onClick={self.setSelectedPool.bind(self, poolRow, idx)} key={'pool-select-'+idx} className={`select-pool-toolbar ${cellActive}`}>
{poolRow.symbol}
</ListGroupItem>
})
}</span>
}
let selectedPool = (<div className="loading-spinner">
<FontAwesomeIcon icon={faSpinner} size="lg" rotation={270} pulse/>
</div>
)
if (isNonEmptyObject(currentSelectedPool)) {
selectedPool = <SelectedPool {...this.props} currentSelectedPool={currentSelectedPool} setErrorMessage={this.setErrorMessage} resetErrorMessage={this.resetErrorMessage}/>
}
let transactionStatusMessage = <span/>;
if (isError) {
transactionStatusMessage = <Alert variant={"danger"}>
{errorMessage}
</Alert>
}
if (poolTransactionStatus.type === 'pending') {
transactionStatusMessage = <Alert variant={"info"}>
<FontAwesomeIcon icon={faSpinner} size="lg" rotation={270} pulse/> {poolTransactionStatus.message}
</Alert>
}
if (poolTransactionStatus.type === 'error') {
transactionStatusMessage = <Alert variant={"danger"}>
<FontAwesomeIcon icon={faTimes}/> {poolTransactionStatus.message}
</Alert>
}
return (
<div>
{transactionStatusMessage}
<div className="app-toolbar-container">
<Row style={{'marginBottom': '40px'}}>
<Col lg={2}>
<ListGroup className="select-pool-group">
{poolDataList}
</ListGroup>
</Col>
<Col lg={10}>
{selectedPool}
</Col>
</Row>
</div>
</div>
)
}
Example #17
Source File: select_entry.js From twmwallet with MIT License | 5 votes |
render() {
return (
<div className="width100 height100 d-flex flex-column text-center">
<Container fluid className="height100 flex-column d-flex justify-content-center start-background-image">
<Image onClick={this.back} className="entry-off-button pointer" src={require("./../../img/off_black.svg")}/>
<Row className="rowjustify-content-md-center justify-content-center p-3">
<Image className="w-25" src={require("./../../img/safex-home-multi.png")}/>
</Row>
<Col className="my-5">
<Col className="my-2 p-3">
<button onClick={this.open_existing} className="custom-button-entry">Open Existing Wallet</button>
</Col>
<Col className="my-2 p-3">
<button onClick={this.create_new} className="custom-button-entry">Create New Wallet</button>
</Col>
<Col className="my-2 p-3">
<button onClick={this.restore_keys} className="custom-button-entry">Recover Wallet From Keys</button>
</Col>
<Col className="my-2 p-3">
<button onClick={this.seed_phrase} className="custom-button-entry">Recover Wallet From Seed Phrase</button>
</Col>
{this.state.legacy_detected ?
(
<Col className="my-5 p-3">
<button className="custom-button-entry orange-border" onClick={() => this.setState({showLegacyAlert: !this.state.showLegacyAlert})}>Open Legacy Wallet</button>
<Collapse in={this.state.showLegacyAlert}>
<Alert
variant="info"
transition={false}
className="mt-3 w-50 mx-auto entry-back-text"
>
<Alert.Heading>We are working on this feature. Thank you for your patience!</Alert.Heading>
</Alert>
</Collapse>
</Col>
)
:
(<div></div>)
}
</Col>
</Container>
</div>);
}
Example #18
Source File: wallet.js From stacker.news with MIT License | 5 votes |
export function FundForm () {
const me = useMe()
const [showAlert, setShowAlert] = useState(true)
const router = useRouter()
const [createInvoice, { called, error }] = useMutation(gql`
mutation createInvoice($amount: Int!) {
createInvoice(amount: $amount) {
id
}
}`)
useEffect(() => {
setShowAlert(!localStorage.getItem('hideLnAddrAlert'))
}, [])
if (called && !error) {
return <LnQRSkeleton status='generating' />
}
return (
<>
<YouHaveSats />
{me && showAlert &&
<Alert
variant='success' dismissible onClose={() => {
localStorage.setItem('hideLnAddrAlert', 'yep')
setShowAlert(false)
}}
>
You can also fund your account via lightning address with <strong>{`${me.name}@stacker.news`}</strong>
</Alert>}
<Form
initial={{
amount: 1000
}}
initialError={error?.toString()}
schema={FundSchema}
onSubmit={async ({ amount }) => {
const { data } = await createInvoice({ variables: { amount: Number(amount) } })
router.push(`/invoices/${data.createInvoice.id}`)
}}
>
<Input
label='amount'
name='amount'
required
autoFocus
append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
/>
<SubmitButton variant='success' className='mt-2'>generate invoice</SubmitButton>
</Form>
<WalletHistory />
</>
)
}
Example #19
Source File: xpubImporter.js From xpub-tool with MIT License | 5 votes |
render() {
const { keystoreState, extPubKey, error } = this.state
const { bip32Path } = this.props
return (
<div>
<h3>
{humanReadableDerivationPath({ bip32Path })} <code>{bip32Path}</code>
</h3>
{extPubKey ? (
<div>
<Alert key={bip32Path} variant="success" dismissible>
Imported {humanReadableDerivationPath({ bip32Path })}
</Alert>
<p>
<code>{maskKey(extPubKey)}</code>
<Button
variant="light"
title="Copy to clipboard"
onClick={() => {
navigator.clipboard.writeText(extPubKey)
}}
>
<span role="img" aria-label="Copy to clipboard">
?
</span>
</Button>
</p>
</div>
) : (
<div>
{this.renderMessages()}
{error && <Alert type="danger">{error}</Alert>}
<Button
variant="outline-primary"
disabled={keystoreState !== PENDING}
onClick={this.importExtPubKey}
title={humanReadableDerivationPath({ bip32Path })}
>
Import {bip32Path}
</Button>
</div>
)}
<hr />
</div>
)
}
Example #20
Source File: index.js From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 | 4 votes |
function ExistingActivitySearch(props) {
const { fromTeam, addActivity, libraries } = props;
const [toggleStates, setToggleStates] = useState({
searchLibrary: true,
subject: true,
education: false,
type: false,
});
const allState = useSelector((state) => state.search);
const activityTypesState = useSelector((state) => state.resource.types);
const { currentOrganization, permission } = useSelector((state) => state.organization);
const dispatch = useDispatch();
const [activityTypes, setActivityTypes] = useState([]);
const [search, setSearch] = useState([]);
const [searchQueries, SetSearchQuery] = useState('');
const [searchInput, setSearchInput] = useState('');
const [meta, setMeta] = useState({});
const [activePage, setActivePage] = useState(1);
const [totalCount, setTotalCount] = useState(0);
const [activeModel, setActiveModel] = useState('activities');
const [activeType, setActiveType] = useState([]);
const [activeSubject, setActiveSubject] = useState([]);
const [activeEducation, setActiveEducation] = useState([]);
const [searchType, setSearchType] = useState(null);
const [authorName, SetAuthor] = useState('');
const [activetab, setActiveTab] = useState('activities');
const [todate, Settodate] = useState(undefined);
const [fromdate, Setfromdate] = useState(undefined);
useEffect(() => {
if (localStorage.getItem('refreshPage') === 'true' && currentOrganization && searchType) {
let dataSend;
if (searchType === 'orgSearch') {
dataSend = {
phrase: searchInput.trim(),
subjectArray: activeSubject,
gradeArray: activeEducation,
standardArray: activeType,
author: authorName || undefined,
type: searchType,
from: 0,
size: 20,
model: 'activities',
standardArray: libraries,
};
} else {
dataSend = {
phrase: searchInput.trim(),
subjectArray: activeSubject,
gradeArray: activeEducation,
standardArray: activeType,
author: authorName || undefined,
type: searchType,
from: 0,
size: 20,
model: 'activities',
standardArray: libraries,
};
}
let result;
(async () => {
result = await dispatch(simpleSearchAction(dataSend));
})();
setTotalCount(result?.meta?.total);
const tempEducation = [];
const tempSubject = [];
if (activeEducation) {
activeEducation.forEach((edu) => {
if (String(edu).includes('&')) {
const temp = String(edu).replace('&', 'and');
tempEducation.push(temp);
} else {
tempEducation.push(edu);
}
});
setActiveEducation(tempEducation);
}
if (activeSubject) {
activeSubject.forEach((sub) => {
if (String(sub).includes('&')) {
const temp = String(sub).replace('&', 'and');
tempSubject.push(temp);
} else {
tempSubject.push(sub);
}
});
setActiveSubject(tempSubject);
}
}
}, [currentOrganization]);
useEffect(() => {
if (allState.searchResult) {
if (allState.searchResult.length > 0) {
setSearch(allState.searchResult);
SetSearchQuery(allState.searchQuery);
setSearchInput(allState.searchQuery);
setMeta(allState.searchMeta);
localStorage.setItem('loading', 'false');
Swal.close();
} else if (allState.searchMeta.total === 0) {
setSearch([]);
SetSearchQuery(allState.searchQuery);
setSearchInput(allState.searchQuery);
setMeta({});
localStorage.setItem('loading', 'false');
Swal.close();
}
}
}, [allState.searchMeta, allState.searchQuery, allState.searchResult]);
useEffect(() => {
if (allState.searchResult) {
if (allState.searchResult.length > 0 && paginationStarter) {
paginationStarter = false;
setTotalCount(allState.searchMeta.total);
}
}
}, [allState.searchMeta, allState.searchResult, totalCount]);
useEffect(() => {
if (localStorage.getItem('loading') === 'true') {
Swal.fire({
html: 'Searching...', // add html attribute if you want or remove
allowOutsideClick: false,
onBeforeOpen: () => {
Swal.showLoading();
},
});
}
});
useEffect(() => {
if (activityTypesState.length === 0) {
dispatch(loadResourceTypesAction());
}
}, []);
const compare = (a, b) => {
// Use toUpperCase() to ignore character casing
const bandA = a.title.toUpperCase();
const bandB = b.title.toUpperCase();
let comparison = 0;
if (bandA > bandB) {
comparison = 1;
} else if (bandA < bandB) {
comparison = -1;
}
return comparison;
};
useEffect(() => {
const allItems = [];
activityTypesState?.data?.map((data) => data.activityItems.map((itm) => allItems.push(itm)));
setActivityTypes(allItems.sort(compare));
}, [activityTypesState]);
return (
<>
<div>
<div className={!fromTeam && 'search-wrapper'}>
<div className="content-search">
{true ? (
<div className="search-result-main">
{!fromTeam && <div className="current-org-search">{currentOrganization?.name}</div>}
{!fromTeam && <div className="exp-lib-cnt">Explore library content</div>}
<div
className="total-count"
style={{
display: totalCount > 1000 || !!searchQueries ? 'block' : 'none',
}}
>
{totalCount > 10000 ? (
<div>
Your search returned more than <span>10,000</span> results. Please refine your search criteria.
</div>
) : null}
{!!searchQueries && (
<div>
Showing {search ? meta.total : '0'} results For <span>{searchQueries}</span>
</div>
)}
</div>
<div className="main-content-search">
<div className="left-search">
<div className="search-library">
<Accordion defaultActiveKey="0">
<Card>
<Accordion.Toggle
as={Card.Header}
eventKey="0"
onClick={() =>
setToggleStates({
...toggleStates,
searchLibrary: !toggleStates.searchLibrary,
})
}
>
Search Library
<FontAwesomeIcon className="ml-2" icon={toggleStates.searchLibrary ? 'chevron-up' : 'chevron-down'} />
</Accordion.Toggle>
<Accordion.Collapse eventKey="0">
<Card.Body>
<div className="body-search">
<input
// style={{ display: searchType === 'orgSearch' ? 'none' : 'block' }}
value={searchInput}
onChange={(e) => {
setSearchInput(e.target.value);
}}
onKeyPress={async (e) => {
if (e.key === 'Enter') {
if (!searchInput.trim() && searchType !== 'orgSearch') {
Swal.fire('Search field is required.');
} else if (searchInput.length > 255) {
Swal.fire('Character limit should be less than 255.');
} else {
Swal.fire({
title: 'Searching...', // add html attribute if you want or remove
html: 'We are fetching results for you!',
allowOutsideClick: false,
onBeforeOpen: () => {
Swal.showLoading();
},
});
let dataSend;
if (searchType === 'orgSearch') {
dataSend = {
phrase: searchInput.trim(),
subjectArray: activeSubject,
gradeArray: activeEducation,
authors: authorName || undefined,
standardArray: activeType,
type: searchType,
from: 0,
size: 20,
model: 'activities',
standardArray: libraries,
};
} else {
dataSend = {
phrase: searchInput.trim(),
subjectArray: activeSubject,
gradeArray: activeEducation,
authors: authorName || undefined,
standardArray: activeType,
type: searchType,
from: 0,
size: 20,
model: 'activities',
standardArray: libraries,
};
}
const result = await dispatch(simpleSearchAction(dataSend));
setTotalCount(result.meta?.total);
const tempEducation = [];
const tempSubject = [];
if (activeEducation) {
activeEducation.forEach((edu) => {
if (String(edu).includes('&')) {
const temp = String(edu).replace('&', 'and');
tempEducation.push(temp);
} else {
tempEducation.push(edu);
}
});
setActiveEducation(tempEducation);
}
if (activeSubject) {
activeSubject.forEach((sub) => {
if (String(sub).includes('&')) {
const temp = String(sub).replace('&', 'and');
tempSubject.push(temp);
} else {
tempSubject.push(sub);
}
});
setActiveSubject(tempSubject);
}
}
}
}}
type="search"
placeholder="Search"
/>
<div className="form-group">
<div className="radio-btns">
{true && (
<label>
<input
name="type"
onChange={(e) => {
setSearchType(e.target.value);
}}
value="private"
checked={searchType === 'private'}
type="radio"
/>
<span>My Projects</span>
</label>
)}
{true && (
<label>
<input
name="type"
onChange={(e) => {
setSearchType(e.target.value);
}}
value="public"
checked={searchType === 'public'}
type="radio"
/>
<span>All Shared Projects</span>
</label>
)}
{true && (
<label>
<input
name="type"
onChange={(e) => {
setSearchType(e.target.value);
}}
value="orgSearch"
checked={searchType === 'orgSearch'}
type="radio"
/>
<span>All Shared Projects In My Org</span>
</label>
)}
</div>
</div>
{permission?.Organization?.includes('organization:view-user') && searchType !== 'private' && <div className="author-label">Author</div>}
<div
className="form-group"
style={{
display: permission?.Organization?.includes('organization:view-user') && searchType !== 'private' ? 'block' : 'none',
}}
>
<input
placeholder="Enter author name"
className="authorName"
value={authorName}
onChange={({ target }) => {
if (target.value) {
SetAuthor(target.value);
} else {
SetAuthor('');
}
}}
/>
</div>
<div
className="src-btn"
onClick={async () => {
Setfromdate(undefined);
Settodate(undefined);
setActiveTab('activities');
if (!searchInput.trim() && searchType !== 'orgSearch') {
Swal.fire('Search field is required.');
} else if (searchInput.length > 255) {
Swal.fire('Character limit should be less than 255.');
} else if (!searchType) {
Swal.fire('Search type is required. Click one of the radio buttons.');
} else {
Swal.fire({
title: 'Searching...', // add html attribute if you want or remove
html: 'We are fetching results for you!',
allowOutsideClick: false,
onBeforeOpen: () => {
Swal.showLoading();
},
});
let dataSend;
if (searchType === 'orgSearch') {
dataSend = {
phrase: searchInput.trim(),
subjectArray: activeSubject,
gradeArray: activeEducation,
standardArray: activeType,
author: authorName || undefined,
fromDate: fromdate || undefined,
toDate: todate || undefined,
type: searchType,
from: 0,
size: 20,
model: 'activities',
standardArray: libraries,
};
} else {
dataSend = {
phrase: searchInput.trim(),
subjectArray: activeSubject,
author: authorName || undefined,
fromDate: fromdate || undefined,
toDate: todate || undefined,
gradeArray: activeEducation,
standardArray: activeType,
type: searchType,
from: 0,
size: 20,
model: 'activities',
standardArray: libraries,
};
}
const result = await dispatch(simpleSearchAction(dataSend));
setTotalCount(result.meta?.total);
const tempEducation = [];
const tempSubject = [];
if (activeEducation) {
activeEducation.forEach((edu) => {
if (String(edu).includes('&')) {
const temp = String(edu).replace('&', 'and');
tempEducation.push(temp);
} else {
tempEducation.push(edu);
}
});
setActiveEducation(tempEducation);
}
if (activeSubject) {
activeSubject.forEach((sub) => {
if (String(sub).includes('&')) {
const temp = String(sub).replace('&', 'and');
tempSubject.push(temp);
} else {
tempSubject.push(sub);
}
});
setActiveSubject(tempSubject);
}
}
}}
>
<FontAwesomeIcon icon="search" />
Search
</div>
</div>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
</div>
<div className="refine-search">
<div className="headline">Refine your search</div>
<Accordion defaultActiveKey="0">
<Card>
<Accordion.Toggle
as={Card.Header}
eventKey="0"
onClick={() =>
setToggleStates({
...toggleStates,
type: false,
education: false,
subject: !toggleStates.subject,
})
}
>
Subject
<FontAwesomeIcon className="ml-2" icon={toggleStates.subject ? 'chevron-up' : 'chevron-down'} />
</Accordion.Toggle>
<Accordion.Collapse eventKey="0">
<Card.Body>
{subjects.map((data) => (
<div
className="list-item-keys"
key={data.value}
value={data.subject}
onClick={() => {
if (activeSubject.includes(data.subject)) {
if (data.subject === 'Career & Technical Education') {
setActiveSubject(
activeSubject.filter((index) => {
if (index === 'Career & Technical Education' || index === 'Career and Technical Education') {
return false;
}
return true;
})
);
} else {
setActiveSubject(activeSubject.filter((index) => index !== data.subject));
}
} else {
setActiveSubject([...activeSubject, data.subject]);
}
}}
>
{data.subject === 'Career & Technical Education' ? (
activeSubject.includes('Career & Technical Education') || activeSubject.includes('Career and Technical Education') ? (
<FontAwesomeIcon icon="check-square" />
) : (
<FontAwesomeIcon icon="square" />
)
) : activeSubject.includes(data.subject) ? (
<FontAwesomeIcon icon="check-square" />
) : (
<FontAwesomeIcon icon="square" />
)}
<span>{data.subject}</span>
</div>
))}
</Card.Body>
</Accordion.Collapse>
</Card>
<Card>
<Accordion.Toggle
as={Card.Header}
eventKey="1"
onClick={() =>
setToggleStates({
...toggleStates,
type: false,
subject: false,
education: !toggleStates.education,
})
}
>
Education Level
<FontAwesomeIcon className="ml-2" icon={toggleStates.education ? 'chevron-up' : 'chevron-down'} />
</Accordion.Toggle>
<Accordion.Collapse eventKey="1">
<Card.Body>
{educationLevels.map((data) => (
<div
className="list-item-keys"
key={data.value}
value={data.name}
onClick={() => {
if (activeEducation.includes(data.name)) {
if (data.name === 'College & Beyond') {
setActiveEducation(
activeEducation.filter((index) => {
if (index === 'College & Beyond' || index === 'College and Beyond') {
return false;
}
return true;
})
);
} else {
setActiveEducation(activeEducation.filter((index) => index !== data.name));
}
} else {
setActiveEducation([...activeEducation, data.name]);
}
}}
>
{data.name === 'College & Beyond' ? (
activeEducation.includes('College & Beyond') || activeEducation.includes('College and Beyond') ? (
<FontAwesomeIcon icon="check-square" />
) : (
<FontAwesomeIcon icon="square" />
)
) : activeEducation.includes(data.name) ? (
<FontAwesomeIcon icon="check-square" />
) : (
<FontAwesomeIcon icon="square" />
)}
<span>{data.name}</span>
</div>
))}
</Card.Body>
</Accordion.Collapse>
</Card>
<Card>
<Accordion.Toggle
as={Card.Header}
eventKey="3"
onClick={() =>
setToggleStates({
...toggleStates,
subject: false,
education: false,
type: !toggleStates.type,
})
}
>
Type of Activity
<FontAwesomeIcon className="ml-2" icon={toggleStates.type ? 'chevron-up' : 'chevron-down'} />
</Accordion.Toggle>
<Accordion.Collapse eventKey="3">
<Card.Body
style={{
'max-height': '300px',
'overflow-y': 'auto',
}}
>
{activityTypes.map((data) => (
<div
className="list-item-keys"
key={data.id}
value={data.h5pLib}
onClick={() => {
if (activeType.includes(data.h5pLib)) {
// eslint-disable-next-line eqeqeq
setActiveType(activeType.filter((index) => index != data.h5pLib));
} else {
setActiveType([...activeType, data.h5pLib]);
}
}}
>
{activeType.includes(data.h5pLib) ? <FontAwesomeIcon icon="check-square" /> : <FontAwesomeIcon icon="square" />}
<span>{data.title}</span>
</div>
))}
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
</div>
</div>
<div className="right-search" id="right-search-branding-style">
<Tabs
activeKey={activetab}
id="uncontrolled-tab-example"
onSelect={async (e) => {
if (!searchInput && searchType !== 'orgSearch') {
Swal.fire('Search field is required.');
} else {
setActiveTab(e);
if (e === 'total') {
let searchData;
if (searchType === 'orgSearch') {
searchData = {
phrase: searchQueries.trim() || searchInput,
from: 0,
size: 20,
type: searchType,
author: authorName || undefined,
fromDate: fromdate || undefined,
toDate: todate || undefined,
subjectArray: activeSubject,
gradeArray: activeEducation,
standardArray: activeType,
};
} else {
searchData = {
phrase: searchQueries.trim() || searchInput,
from: 0,
size: 20,
author: authorName || undefined,
fromDate: fromdate || undefined,
toDate: todate || undefined,
type: searchType,
subjectArray: activeSubject,
gradeArray: activeEducation,
standardArray: activeType,
};
}
Swal.fire({
title: 'Loading...', // add html attribute if you want or remove
allowOutsideClick: false,
onBeforeOpen: () => {
Swal.showLoading();
},
});
const resultModel = await dispatch(simpleSearchAction(searchData));
Swal.close();
setTotalCount(resultModel.meta[e]);
setActiveModel(e);
setActivePage(1);
} else {
let searchData;
if (searchType === 'orgSearch') {
searchData = {
phrase: searchQueries.trim() || searchInput,
from: 0,
size: 20,
author: authorName || undefined,
fromDate: fromdate || undefined,
toDate: todate || undefined,
model: e,
type: searchType,
subjectArray: activeSubject,
gradeArray: activeEducation,
standardArray: activeType,
standardArray: libraries,
};
} else {
searchData = {
phrase: searchQueries.trim() || searchInput,
from: 0,
size: 20,
model: e,
author: authorName || undefined,
fromDate: fromdate || undefined,
toDate: todate || undefined,
type: searchType,
subjectArray: activeSubject,
gradeArray: activeEducation,
standardArray: activeType,
standardArray: libraries,
};
}
Swal.fire({
title: 'Loading...', // add html attribute if you want or remove
allowOutsideClick: false,
onBeforeOpen: () => {
Swal.showLoading();
},
});
const resultModel = await dispatch(simpleSearchAction(searchData));
Swal.close();
setTotalCount(resultModel.meta[e]);
setActiveModel(e);
setActivePage(1);
}
}
}}
>
{!fromTeam && (
<Tab eventKey="activities" title={!!search && !!meta.activities ? `activity (${meta.activities})` : 'activity (0)'}>
<div className="content">
<div className="results_search">
{!!search && search.length > 0 ? (
search.map((res) => (
<>
{res.model === 'Activity' && (
<div className="box">
<div className="imgbox">
{res.thumb_url ? (
<div
style={{
backgroundImage: res.thumb_url.includes('pexels.com')
? `url(${res.thumb_url})`
: `url(${global.config.resourceUrl}${res.thumb_url})`,
}}
/>
) : (
<div
style={{
// eslint-disable-next-line max-len
backgroundImage:
'https://images.pexels.com/photos/593158/pexels-photo-593158.jpeg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=200&w=280',
}}
/>
)}
</div>
<div className="contentbox">
<div className="search-content">
<a
href={
res.model === 'Activity'
? `/activity/${res.id}/preview`
: res.model === 'Playlist'
? `/playlist/${res.id}/preview/lti`
: `/project/${res.id}/preview`
}
target="_blank"
rel="noreferrer"
>
<h2>{res.title || res.name}</h2>
</a>
<ul>
{res.user && (
<li>
by <span>{res.user.first_name}</span>
</li>
)}
<li>
Type <span className="type">{res.model}</span>
</li>
</ul>
<p>{res.description}</p>
</div>
<Buttons text="Add" secondary={true} width="153px" height="36px" onClick={() => addActivity(res)} hover={true} />
</div>
</div>
)}
</>
))
) : (
<div className="box">No result found !</div>
)}
</div>
</div>
</Tab>
)}
</Tabs>
{totalCount > 20 && (
<Pagination
activePage={activePage}
itemsCountPerPage={20}
totalItemsCount={totalCount > 10000 ? 10000 : totalCount}
pageRangeDisplayed={8}
onChange={async (e) => {
setActivePage(e);
if (activeModel === 'total') {
const searchData = {
phrase: searchQueries.trim(),
from: e * 20 - 20,
size: 20,
type: searchType,
subjectArray: activeSubject || undefined,
gradeArray: activeEducation || undefined,
standardArray: activeType || undefined,
author: authorName || undefined,
};
Swal.fire({
title: 'Loading...',
allowOutsideClick: false,
onBeforeOpen: () => {
Swal.showLoading();
},
});
await dispatch(simpleSearchAction(searchData));
Swal.close();
} else {
const searchData = {
phrase: searchQueries.trim(),
from: e * 20 - 20,
size: 20,
type: searchType,
model: activeModel,
subjectArray: activeSubject || undefined,
gradeArray: activeEducation || undefined,
standardArray: activeType || undefined,
author: authorName || undefined,
standardArray: libraries,
};
Swal.fire({
title: 'Loading...',
allowOutsideClick: false,
onBeforeOpen: () => {
Swal.showLoading();
},
});
await dispatch(simpleSearchAction(searchData));
Swal.close();
}
}}
itemClass="page-item"
linkClass="page-link"
/>
)}
</div>
</div>
</div>
) : (
<Alert variant="danger">You are not authorized to view this page!</Alert>
)}
</div>
</div>
</div>
</>
);
}
Example #21
Source File: Profile.jsx From ashteki with GNU Affero General Public License v3.0 | 4 votes |
Profile = ({ onSubmit, isLoading }) => {
const { t } = useTranslation();
const user = useSelector((state) => state.account.user);
const [localBackground, setBackground] = useState(user?.settings.background);
const [localCardSize, setCardSize] = useState(user?.settings.cardSize);
const [customBg, setCustomBg] = useState(null);
const topRowRef = useRef(null);
const [bluffTimer, setBluffTimer] = useState(user?.settings.optionSettings.bluffTimer || 0);
const backgrounds = [{ name: 'none', label: t('none'), imageUrl: BlankBg }];
const cardSizes = [
{ name: 'small', label: t('small') },
{ name: 'normal', label: t('normal') },
{ name: 'large', label: t('large') },
{ name: 'x-large', label: t('extra-large') }
];
backgrounds.push({
name: 'ashesreborn',
label: t('Ashes Reborn'),
imageUrl: AshesRebornBg
});
if (!user) {
return <Alert variant='danger'>You need to be logged in to view your profile.</Alert>;
}
initialValues.email = user.email;
initialValues.username = user.username;
if (user?.settings?.optionSettings) {
initialValues.gameOptions = user.settings.optionSettings;
}
const schema = yup.object({
avatar: yup
.mixed()
.test(
'fileSize',
t('Image must be less than 100KB in size'),
(value) => !value || value.size <= 100 * 1024
)
.test(
'fileType',
t('Unsupported image format'),
(value) =>
!value ||
['image/jpg', 'image/jpeg', 'image/gif', 'image/png'].includes(value.type)
),
username: yup
.string()
.required(t('You must specify a username'))
.min(3, t('Your username must be at least 3 characters long'))
.max(15, t('Your username cannot be more than 15 charcters'))
.matches(
/^[A-Za-z0-9_-]+$/,
t('Usernames must only use the characters a-z, 0-9, _ and -')
),
email: yup
.string()
.email(t('Please enter a valid email address'))
.required(t('You must specify an email address')),
password: yup.string().min(6, t('Password must be at least 6 characters')),
passwordAgain: yup
.string()
.oneOf([yup.ref('password'), null], t('The passwords you have entered do not match'))
});
return (
<Formik
validationSchema={schema}
onSubmit={async (values) => {
/**
* @type {ProfileDetails}
*/
const submitValues = {
avatar: values.avatar ? await toBase64(values.avatar) : null,
email: values.email,
username: values.username,
password: values.password,
settings: { optionSettings: values.gameOptions }
};
if (localBackground) {
submitValues.settings.background = localBackground;
}
if (localCardSize) {
submitValues.settings.cardSize = localCardSize;
}
if (customBg) {
submitValues.customBackground = customBg;
}
if (bluffTimer) {
submitValues.settings.optionSettings.bluffTimer = bluffTimer;
}
onSubmit(submitValues);
topRowRef?.current?.scrollIntoView(false);
}}
initialValues={initialValues}
>
{(formProps) => (
<Form
className='profile-form'
onSubmit={(event) => {
event.preventDefault();
formProps.handleSubmit(event);
}}
>
<Row ref={topRowRef}>
<Col sm='12'>
<ProfileMain formProps={formProps} user={user} />
</Col>
</Row>
<Row>
<Col sm='12'>
<ProfileBackground
backgrounds={backgrounds}
selectedBackground={localBackground || user.settings.background}
customBackground={user.settings.customBackground}
onBackgroundSelected={async (name, file) => {
if (name === 'custom') {
let base64File = await toBase64(file);
setCustomBg(base64File);
}
setBackground(name);
}}
/>
</Col>
</Row>
<Row>
<Col sm='6'>
<ProfileCardSize
cardSizes={cardSizes}
selectedCardSize={localCardSize || user.settings.cardSize}
onCardSizeSelected={(name) => setCardSize(name)}
/>
</Col>
<Col sm='6'>
<InGameSettings formProps={formProps} user={user} />
<Panel title='Bluff timer'>
<RangeSlider
min='0'
max='10'
tooltip='on'
value={bluffTimer}
onChange={(event) => setBluffTimer(event.target.value)}
/>
<br />
</Panel>
</Col>
</Row>
<div className='text-center profile-submit'>
<Button variant='primary' type='submit' disabled={isLoading}>
{isLoading ? (
<Spinner
animation='border'
size='sm'
as={'span'}
role='status'
aria-hidden='true'
/>
) : null}
{t('Save')}
</Button>
</div>
</Form>
)}
</Formik>
);
}
Example #22
Source File: Import.js From SaraAlert with Apache License 2.0 | 4 votes |
render() {
if (this.state.patients.length === this.state.accepted.length + this.state.rejected.length) {
location.href = '/';
}
return (
<React.Fragment>
<div className="m-4">
<h5>Please review the monitorees that are about to be imported below. You can individually accept each monitoree, or accept all at once.</h5>
<Button
variant="primary"
className="btn-lg my-2"
onClick={() =>
this.handleConfirm(
'Are you sure you want to import all monitorees? Note: This will not import already rejected or re-import already accepted monitorees listed below, but will import any potential duplicates.'
)
}>
Accept All
</Button>
{this.state.patients.map((patient, index) => {
return (
<Card
body
key={`p-${index}`}
className="card-square mt-3"
bg="light"
border={this.state.accepted.includes(index) ? 'success' : this.state.rejected.includes(index) ? 'danger' : ''}>
<React.Fragment>
{patient.appears_to_be_duplicate && <Alert variant="danger">Warning: This monitoree already appears to exist in the system!</Alert>}
<Row>
<Col>
<b>State/Local ID:</b> {patient.user_defined_id_statelocal}
<br />
<b>CDC ID:</b> {patient.user_defined_id_cdc}
<br />
<b>First Name:</b> {patient.first_name}
<br />
<b>Last Name:</b> {patient.last_name}
<br />
<b>DOB:</b> {patient.date_of_birth}
<br />
<b>Language:</b> {patient.primary_language}
<br />
<b>Flight or Vessel Number:</b> {patient.flight_or_vessel_number}
</Col>
<Col>
<b>Home Address Line 1:</b> {patient.address_line_1}
<br />
<b>Home Town/City:</b> {patient.address_city}
<br />
<b>Home State:</b> {patient.address_state}
<br />
<b>Home Zip:</b> {patient.address_zip}
<br />
<b>Monitored Address Line 1:</b> {patient.monitored_address_line_1}
<br />
<b>Monitored Town/City:</b> {patient.monitored_address_city}
<br />
<b>Monitored State:</b> {patient.monitored_address_state}
<br />
<b>Monitored Zip:</b> {patient.monitored_address_zip}
</Col>
<Col>
<b>Phone Number 1:</b> {patient.primary_telephone}
<br />
<b>Phone Number 2:</b> {patient.secondary_telephone}
<br />
<b>Email:</b> {patient.email}
<br />
<b>Exposure Location:</b> {patient.potential_exposure_location}
<br />
<b>Date of Departure:</b> {patient.date_of_departure}
<br />
<b>Close Contact w/ Known Case:</b> {patient.contact_of_known_case}
<br />
<b>Was in HC Fac. w/ Known Cases:</b> {patient.was_in_health_care_facility_with_known_cases}
</Col>
</Row>
</React.Fragment>
{!(this.state.accepted.includes(index) || this.state.rejected.includes(index)) && (
<React.Fragment>
<Button
variant="danger"
className="my-2 ml-3 float-right"
onClick={() => {
this.rejectSub(index);
}}>
Reject
</Button>
<Button
variant="primary"
className="my-2 float-right"
onClick={() => {
this.importSub(index, true);
}}>
Accept
</Button>
</React.Fragment>
)}
</Card>
);
})}
</div>
</React.Fragment>
);
}
Example #23
Source File: FirebaseLoginForm.js From RC4Community with Apache License 2.0 | 4 votes |
export default function FirebaseLoginForm({onSignupClick}){
const [upsertUserFunc, { data, loading, error }] = useMutation(UPSERT_USER);
const [email,setEmail] = useState("");
const [password,setPassword] = useState("");
const [errorMessage,setError] = useState("");
const [diffCredError,setDiffCredError] = useState(null);
const [progress,setProgress] = useState(false);
if(error) console.log("Error Provider = ", error)
if(data) console.log("Data = ", data)
if(loading) console.log("Loading = ", loading)
const doEmailPasswordLogin = async (e) => {
e.preventDefault();
if(progress){
return true;
}
setProgress(true);
try {
const fbApp = getApp(FB_APP_NAME);
const userCred = await signInWithEmailAndPassword(getAuth(fbApp),email,password);
Cookies.set('user', userCred.user.uid);
if(diffCredError?.oldProvider?.providerId === EmailAuthProvider.PROVIDER_ID){
// The signin was requested to link new credentials with the account
await linkWithCredential(userCred.user,OAuthProvider.credentialFromError(diffCredError.error));
}
} catch(error){
switch(error.code){
case 'auth/user-not-found':
setError("User not found");
break;
case 'auth/wrong-password':
setError("Incorrect Password");
break;
default:
setError("Unknown error occurred");
}
} finally {
setProgress(false);
}
}
const handleProviderSignIn = async provider => {
if(progress){
return;
}
const fbApp = getApp(FB_APP_NAME);
const auth = getAuth(fbApp);
try {
const userCred = await signInWithPopup(auth,provider);
Cookies.set('user', userCred.user.uid);
await upsertUserFunc({
variables: {
uid: userCred.user.uid,
email: userCred.user.email,
displayName: userCred.user.displayName,
phoneNumber: userCred.user.phoneNumber,
photoURL: userCred.user.photoURL
},
})
if(diffCredError){
// The signin was requested to link new credentials with the account
await linkWithCredential(userCred.user,OAuthProvider.credentialFromError(diffCredError.error));
}
} catch (e){
switch(e.code){
case 'auth/popup-closed-by-user':
case 'auth/cancelled-popup-request':
break;
case 'auth/popup-blocked':
setError("Popup blocked by your browser.")
break;
case 'auth/account-exists-with-different-credential':
const methods = await fetchSignInMethodsForEmail(auth,e.customData.email);;
setDiffCredError({error: e, newProviderId: provider.providerId ,oldProviderId: methods[0]});
break;
default:
setError("Unknown error occurred");
}
setProgress(false);
}
}
const onGoogleBtnClick = () => {
if(progress){
return;
}
setProgress(true);
const provider = new GoogleAuthProvider();
handleProviderSignIn(provider);
}
const onFacebookBtnClick = () => {
if(progress){
return;
}
setProgress(true);
const provider = new FacebookAuthProvider();
handleProviderSignIn(provider);
}
return (
<div className="container-fluid p-1">
<form className="container-fluid" onSubmit={doEmailPasswordLogin}>
<FormControl
type="text"
placeholder="email"
className="mb-1"
disabled={progress}
onChange={e=> setEmail(e.target.value)}/>
<FormControl
type="password"
placeholder="password"
className="mb-1"
disabled={progress}
onChange={e => setPassword(e.target.value)}/>
{
errorMessage &&
<Alert variant="danger" className="mb-1">{errorMessage}</Alert>
}
<div className="d-flex justify-content-between">
<Button
type="submit"
className="mb-1"
disabled={progress}>
Login
</Button>
<Button
className="mb-1"
variant="light"
disabled={progress}
onClick={onSignupClick}>
Sign up
</Button>
</div>
</form>
<div className="container-fluid d-flex flex-column">
<Button
variant="danger"
className="mb-1"
onClick={onGoogleBtnClick}
disabled={progress}>
Sign in with Google
</Button>
<Button
className="mb-1"
onClick={onFacebookBtnClick}
disabled={progress}>
Sign in with Facebook
</Button>
</div>
{
diffCredError &&
<div className="p-1 mb-1">
<Alert variant="danger" className="mb-1">
User's email already exists. Sign in with {diffCredError.oldProviderId} to link your {diffCredError.newProviderId} account.
</Alert>
</div>
}
</div>
)
}
Example #24
Source File: updateCategoryModal.js From community-forum-frontend with GNU General Public License v3.0 | 4 votes |
render() {
return (
<React.Fragment>
<Modal
show={this.props.showModal}
onHide={this.props.handleClose}
centered
>
<Modal.Header closeButton>
<Modal.Title>
<Container>
<Row>
<Col xs={12}>
<h1 className="modal-heading">Edit Details</h1>
</Col>
</Row>
</Container>
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Container>
<Row>
<Col xs={12}>
<div className="modal-form">
{this.state.formSubmissionError && (
<Alert variant="danger">
{this.state.formSubmissionError}
</Alert>
)}
<Form onSubmit={this.onFormSubmit}>
<Form.Group controlId="updateCategoryFormBasicText">
<Form.Label>Name</Form.Label>
<Form.Control
onChange={this.onFieldChange}
type="text"
name={fieldNames.NAME}
value={this.state.name}
/>
{this.state.nameError && (
<h6 className="form-field-error">
{this.state.nameError}
</h6>
)}
</Form.Group>
<Form.Group controlId="updateCategoryFormBasicTextArea">
<Form.Label>Description</Form.Label>
<Form.Control
onChange={this.onFieldChange}
as="textarea"
rows={3}
name={fieldNames.DESCRIPTION}
value={this.state.description}
/>
{this.state.descriptionError && (
<h6 className="form-field-error">
{this.state.descriptionError}
</h6>
)}
</Form.Group>
<Button
variant=""
className="primary-button"
type="submit"
disabled={this.state.isFormInvalid}
>
Update
</Button>
<div className="anchor-container">
{this.props.category.isArchived ? (
<Link
className="pl-2 pr-1 anchor-danger-text anchor-update-text"
onClick={() => {
this.onArchiveSubmit("unarchive");
}}
>
Unarchive
</Link>
) : (
<Link
className="pl-2 pr-1 anchor-danger-text anchor-update-text"
onClick={() => {
this.onArchiveSubmit("archive");
}}
>
Archive
</Link>
)}
<Link
className="pl-2 pr-1 anchor-danger-text"
onClick={() => {
this.props.handleClose();
this.setState(handleModal("delete", "open"));
}}
>
Delete
</Link>
</div>
</Form>
</div>
</Col>
</Row>
</Container>
</Modal.Body>
</Modal>
<DeleteModal
showModal={this.state.showDeleteModal}
modalHeading="Category"
objectName={`${this.props.category.name} Category`}
handleClose={() => {
this.setState(handleModal("delete", "close"));
}}
deleteFunction={this.onDeleteSubmit}
/>
</React.Fragment>
);
}
Example #25
Source File: WorkLockDashboard.js From stake-nucypher with GNU Affero General Public License v3.0 | 4 votes |
function WorkLockDashboard(props) {
const store = useStore();
const [loading, setLoading] = useState();
const [busyCancel, setBusyCancel] = useState(false);
const [busyClaim, setBusyClaim] = useState(false);
const [warningShow, setWarningShow] = useState(false);
const [bidValue, setBidBalue] = useState('0');
const onBid = (event) => {
setWarningShow(true);
const ethValue = Web3.utils.toWei(event.bidValue.toString());
setBidBalue(ethValue);
};
const onAgree = () => {
store.workLockStore.bid(bidValue);
setWarningShow(false);
};
const onClaim = async () => {
setBusyClaim(true);
if (store.workLockStore.availableCompensation !== '0') {
await store.workLockStore.withdrawCompensation();
}
await store.workLockStore.claim();
setBusyClaim(false);
};
const onBidCancel = async () => {
setBusyCancel(true);
await store.workLockStore.cancelBid();
setBusyCancel(false);
};
const refundWorkLock = () => {
return store.workLockStore.refund();
};
useEffect(() => {
if (store.web3Initilized && store.workLockStore && !store.workLockStore.inited) {
(async () => {
setLoading(true);
await store.workLockStore.init();
setLoading(false);
})();
}
});
const startDate = new Date();
startDate.setTime(store.workLockStore.startBidDate * 1000);
const endDate = new Date();
endDate.setTime(store.workLockStore.endBidDate * 1000);
const minBidAmount = store.workLockStore.minAllowedBid ? Web3.utils.fromWei(store.workLockStore.minAllowedBid.toString()) : null;
const unlockedEth = store.workLockStore.unlockedEth ? toClosesMeaningfulUnit(store.workLockStore.unlockedEth) : { value: '0', unit: 'wei' };
return store.web3Initilized && !loading ? (<div className="worklock-contrainer">
<Row>
<Col md={4}>
<p className="text-center h6">Total ETH supplied</p>
{ store.workLockStore.tokenSupply ? <p className="text-center h4">{ toUiNumberOfTokens(store.workLockStore.ethSupply) } <br /> ETH</p> : null }
</Col>
<Col md={4}>
<p className="text-center h6">Worklock Participants</p>
{ store.workLockStore.biddersNumber ? <p className="text-center h4">{ store.workLockStore.biddersNumber }</p> : null }
</Col>
<Col md={{ span: 4 }}>
<p className="text-center h6">Total NU to distribute</p>
{ store.workLockStore.tokenSupply ? <p className="text-center h4">{ toUiNumberOfTokens(store.workLockStore.tokenSupply) } <br /> NU</p> : null }
</Col>
</Row>
{
store.workLockStore.workLockStatus() === 'in_progress' ? <>
<Row className="panel">
<Container>
<Row className="mt-2 justify-content-center">
{ store.workLockStore.workInfo ? <>
<Timeline
timelinePoints={[
{
date: store.workLockStore.startBidDate,
label: 'Escrow phase'
},
{
date: store.workLockStore.endBidDate,
label: 'Escrow cancelation window'
},
{
date: +store.workLockStore.endBidDate + (60 * 60 * 24),
label: 'Claiming tokens window'
},
{
textPoint: 'Stake creation',
label: 'Running node'
},
{
textPoint: 'Ether claimed'
}
]}
completedIndex={ store.workLockStore.workInfo.claimed ? (store.workLockStore.workInfo.depositedETH === '0' ? 4 : 3) : null }
></Timeline>
</> : null }
</Row>
<Row className="mt-2 justify-content-center">
<span className="h5">WorkLock event ends on { dateFormat(endDate) }</span>
</Row>
<Row className="mt-3">
{ store.workLockStore.workInfo ? <>
<Col>
<p className="h6 text-center">Your total</p>
<p className="h4 text-center">{toUiNumberOfTokens(store.workLockStore.workInfo.depositedETH)} <br /> ETH</p>
<div className="action d-flex justify-content-center">
{ store.workLockStore.workInfo.depositedETH !== '0' && store.workLockStore.cancelationBidStatus() !== 'finished' ?
<>{ !busyCancel ? <Button onClick={onBidCancel}>Cancel bid</Button> : <Loading size={20}></Loading> }</>
: null }
</div>
</Col>
{
store.workLockStore.workInfo.depositedETH !== '0' && store.workLockStore.cancelationBidStatus() === 'finished' ? <>
<Col>
<p className="h6 text-center">Your claim</p>
<p className="h4 text-center">{toUiNumberOfTokens(store.workLockStore.claimAmount)} <br /> NU</p>
<p className="small text-center text-muted">Warning! Available claim value may fluctuate until Worklock closes and claims are finalized</p>
</Col>
</> : null
}
</> : null }
</Row>
<Row className="mt-4">
<Col md={12} className="m-2 d-flex justify-content-center">
<WorkLock onBid={onBid} minBid={minBidAmount}></WorkLock>
</Col>
</Row>
</Container>
</Row>
</> : null
}
{
store.workLockStore.workLockStatus() === 'finished' ? <>
<Row className="panel">
<Container>
<Row className="mt-2 justify-content-center">
{ store.workLockStore.workInfo ? <>
<Timeline
timelinePoints={[
{
date: store.workLockStore.startBidDate,
label: 'Escrow phase'
},
{
date: store.workLockStore.endBidDate,
label: 'Escrow cancelation window'
},
{
date: +store.workLockStore.endBidDate + (60 * 60 * 24),
label: 'Claiming tokens window'
},
{
textPoint: 'Stake creation',
label: 'Running node'
},
{
textPoint: 'Ether claimed'
}
]}
completedIndex={ store.workLockStore.workInfo.claimed ? (store.workLockStore.workInfo.depositedETH === '0' ? 4 : 3) : null }
></Timeline>
</> : null }
</Row>
<Row className="mt-3 justify-content-center">
{ store.workLockStore.workInfo ? <>
<Col>
<p className="h6 text-center">Deposited amount</p>
<p className="h4 text-center">{toUiNumberOfTokens(store.workLockStore.workInfo.depositedETH)} <br /> ETH</p>
<div className="action d-flex justify-content-center">
{ store.workLockStore.workInfo.depositedETH !== '0' && store.workLockStore.cancelationBidStatus() !== 'finished' ?
<>{ !busyCancel ? <Button onClick={onBidCancel}>Cancel bid</Button> : <Loading size={20}></Loading> }</>
: <p className="small text-center text-muted">Warning! Escrow period ended</p> }
</div>
</Col>
{
!store.workLockStore.workInfo.claimed ? <>
{
store.workLockStore.workInfo.depositedETH !== '0' && store.workLockStore.cancelationBidStatus() === 'finished' ? <>
<Col className="mt-2">
<p className="h6 text-center">Available for claim</p>
<p className="h4 text-center">{toUiNumberOfTokens(store.workLockStore.claimAmount)} <br /> NU</p>
<p className="small text-center text-muted">Warning! Claiming WorkLock NU tokens will initialize a new stake</p>
<div className="action d-flex justify-content-center">
<>{ !busyClaim ? <Button
onClick={onClaim}
disabled={!(store.workLockStore.workInfo.depositedETH !== '0' && store.workLockStore.claimingAvailable && !store.workLockStore.workInfo.claimed)}
>Claim</Button> : <Loading size={20}></Loading> }</>
</div>
</Col>
</> : null }
</> : <>
{
store.workLockStore.workInfo.depositedETH !== '0' && store.workLockStore.cancelationBidStatus() === 'finished' ? <>
<Col className="mt-2">
<p className="h6 text-center">You claimed</p>
<p className="h4 text-center">{toUiNumberOfTokens(store.workLockStore.claimAmount)} <br /> NU</p>
</Col>
</> : null }
</>
}
</> : null }
{
unlockedEth ? <>
<Col>
<p className="h6 text-center">Unlocked from WorkLock</p>
<p className="h4 text-center">{ unlockedEth.value } <br /> { unlockedEth.unit }</p>
<div className="text-center d-flex justify-content-center">{
<Button variant="secondary" className="button-action mt-2" disabled={ store.workLockStore.unlockedEth === '0'} onClick={refundWorkLock}>Refund</Button>
}</div>
</Col>
</> : null
}
</Row>
</Container>
</Row>
</> : null
}
{
store.workLockStore.workLockStatus() === 'not_started' ? <>
<Row className="panel">
<Container>
<Row className="mt-2 justify-content-center">
<span className="h5">WorkLock event starts on { dateFormat(startDate) }</span>
</Row>
</Container>
</Row>
</> : null
}
<Modal
show={warningShow}
onHide={() => setWarningShow(false)}
dialogClassName="modal-90w"
aria-labelledby="example-custom-modal-styling-title"
>
<Modal.Header closeButton>
<Modal.Title id="example-custom-modal-styling-title">
Warning!
</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>
<Alert variant="danger">All ETH contributed during the WorkLock will be automatically returned to the participant by the Worklock smart contract after the WorkLock participant has provided Proxy Re-Encryption services for the required period of approximately six months from network launch. If a participant does not provide the required services, their ETH will remain escrowed in the WorkLock smart contract. Please carefully consider this before choosing to participate in the Worklock program. The WorkLock smart contract has been audited by both NuCypher core developers and Trail of Bits. However, there are no guarantees and a certain degree of smart contract risk remains.</Alert>
</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={onAgree}>Agree</Button>
</Modal.Footer>
</Modal>
</div>) : <div className="d-flex justify-content-center"><Loading size={80}></Loading></div>;
}
Example #26
Source File: GraphPage.js From caricovidsite with MIT License | 4 votes |
render() {
return (
<div className={"graph-style"}>
<Form>
<Form.Group controlId="caribbeanForm.SelectCustom">
<Form.Label>{this.t("choose_country")}</Form.Label>
<Form.Control
ref={(select) => {
this.select = select;
}}
as="select"
custom
onChange={this.handleChange}
defaultValue="Antigua and Barbuda"
>
<option value="All countries">{this.t("all_countries")}</option>
{countryList.map((country) => (
<option value={country}>{country}</option>
))}
</Form.Control>
</Form.Group>
</Form>
<br/>
{this.state.selectedCountry === "All countries" ? (
<div>{this.t("all_countries_placeholder")}</div> //ReactComponent
) : (
// <AllCountriesGraph countryData={[this.state.allCountriesData]}/>
<ResponsiveContainer width="99%" height={500}>
<LineChart
data={this.state.data[this.state.selectedCountry]}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 5,
}}
>
<CartesianGrid strokeDasharray="3 3" stroke={graphGridColour} />
<XAxis dataKey="name" />
<YAxis />
<Tooltip content={<CustomTooltip />} />
<Legend />
<Line
type="monotone"
dataKey={"Confirmed cases"}
stroke={confirmedCasesLineColour}
dot={false}
/>
{/* <Line
type="monotone"
dataKey={"Active cases"}
stroke={activeCasesLineColour}
dot={false}
/> */}
<Line
type="monotone"
dataKey={"Deaths"}
stroke={deathsLineColour}
dot={false}
/>
</LineChart>
</ResponsiveContainer>
)}
<Alert
dismissable={"true"}
key={1}
variant={"secondary"}
style={{
color: "gray",
fontSize: "0.75rem",
backgroundColor: "#273852",
borderColor: "#273852",
padding: "0.45rem",
marginTop: "1rem",
}}
>
{this.t("disclaimer")}
</Alert>
</div>
);
}
Example #27
Source File: AllFresherJob.js From easy-job-intern with MIT License | 4 votes |
AllFreshersJobs = () => {
const { state, dispatch } = useContext(UserContext);
const [freshersJobs, setFreshersJobs] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
axios({
method: "get",
url: "http://localhost:5000/user/all-freshersjobs",
headers: {
Authorization: "Bearer " + localStorage.getItem("jwt"),
},
})
.then((res) => {
// console.log(res);
setLoading(false);
if (res.data.error) {
// console.log(res.data.error);
// alert(res.data.error);
const notify = () => toast(res.data.error);
notify();
} else {
// console.log(res.data.freshersjobs);
setFreshersJobs(res.data.freshersjobs);
// console.log(freshersJobs);
}
})
.catch((err) => {
setLoading(false);
console.log("Error: ", err);
});
}, [freshersJobs]);
if (freshersJobs && freshersJobs[4]) {
console.log(freshersJobs[4]);
const t = new Date(freshersJobs[4].startDate).toString("YYYY-MM-DD");
console.log(t);
}
return (
<div className="internshipsOuterContainer">
<Toaster />
<Row className="justify-content-xl-start justify-content-lg-around justify-content-sm-center">
{loading ? (
<div className="h-100 w-100 d-flex justify-content-center align-items-center">
<Spinner
animation="border"
variant="light"
style={{
borderColor: "#515b66",
borderRightColor: "transparent",
}}
/>
</div>
) : freshersJobs && !freshersJobs.length > 0 ? (
<Alert
variant="danger"
className="w-100"
style={{
backgroundColor: "#343A40",
border: "none",
color: "#ffc107",
}}
>
No Fresher Jobs available right now
</Alert>
) : (
freshersJobs &&
freshersJobs.map((fresher) => {
return (
<Col
key={fresher._id}
className="col-xl-4 col-lg-5 col-md-6 col-sm-11 col-12 colPost"
>
<FresherJobCard
fresherjob={fresher}
userId={state.user._id}
/>
</Col>
);
})
)}
</Row>
</div>
);
}