luxon#DateTime JavaScript Examples
The following examples show how to use
luxon#DateTime.
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: utils.js From jdtry with GNU General Public License v3.0 | 7 votes |
export function readableTime(dateTime, withSeconds = false) {
if (typeof dateTime === 'number') {
dateTime = DateTime.fromMillis(dateTime)
}
const mode = withSeconds ? DateTime.TIME_24_WITH_SECONDS : DateTime.TIME_SIMPLE
if (DateTime.local().hasSame(dateTime, 'day')) {
return '今天 ' + dateTime.setLocale('zh-cn').toLocaleString(mode)
}
if (DateTime.local().hasSame(dateTime.plus({ days: 1 }), 'day')) {
return '昨天 ' + dateTime.setLocale('zh-cn').toLocaleString(mode)
}
if (DateTime.local().hasSame(dateTime.plus({ days: -1 }), 'day')) {
return '明天 ' + dateTime.setLocale('zh-cn').toLocaleString(mode)
}
return dateTime.setLocale('zh-cn').toFormat('f')
}
Example #2
Source File: docker-hub-utils.esm.js From action-debian-package with MIT License | 7 votes |
extractRepositoryDetails = function extractRepositoryDetails(repos, lastUpdatedSince) {
if (!repos || R.isEmpty(repos)) {
return [];
}
var parsedRepos = camelcaseKeys(repos);
if (R.isNil(lastUpdatedSince)) {
return parsedRepos;
}
return parsedRepos.filter(function (repo) {
return DateTime.fromISO(repo.lastUpdated) < lastUpdatedSince;
});
}
Example #3
Source File: main.esm.js From Go-Gin-Api with MIT License | 6 votes |
function toDateTime(date, calendar) {
if (!(calendar instanceof Calendar)) {
throw new Error('must supply a Calendar instance');
}
return DateTime.fromJSDate(date, {
zone: calendar.dateEnv.timeZone,
locale: calendar.dateEnv.locale.codes[0]
});
}
Example #4
Source File: format.js From website with Apache License 2.0 | 6 votes |
function formatDateToString(date, format = 'ccc LLL d yyyy h:mm a') {
if (typeof date === 'undefined') {
return null
}
return lowercaseMeridiem(
DateTime.fromISO(date)
.setZone('America/New_York')
.toFormat(format),
)
}
Example #5
Source File: background.js From jdtry with GNU General Public License v3.0 | 6 votes |
function getTaskActionsByHref(data) {
const now = DateTime.local().valueOf()
const href = data.href
for (let task of defaultTasks) {
if (task.id !== runtime.taskId) continue
for (let ptn of task.href_patterns) {
if (href.search(ptn) >= 0) { //&& now >= task.last_run_at + task.auto.frequency){
return task.actions
}
}
}
for (let task of commonTasks) {
for (let ptn of task.href_patterns) {
if (href.search(ptn) >= 0) {
return task.actions
}
}
}
return undefined
}
Example #6
Source File: EventListing.js From agility-website-gatsby with MIT License | 6 votes |
Event = ({ moduleItem, event, index }) => {
let item = event.customFields;
const url = `/resources/events/${item.uRL}`
return (
<div className="event">
<div className="event-image">
{item.mainImage &&
<Link to={url}>
<AgilityImage image={item.mainImage} layout="constrained" width="600" />
</Link>}
</div>
<div className="event-content">
<Link to={url}><h2>{item.title}</h2></Link>
<div className="event-date">
<span className="date">
<img style={{width: '18px'}} src="https://static.agilitycms.com/layout/img/ico/calendar-check-gray.svg" />
{DateTime.fromISO(item.date).toFormat("MMM d, yyyy")}
</span>
<span className="time">
<img style={{width: '18px'}} src="https://static.agilitycms.com/layout/img/ico/clock-gray.svg" />
{DateTime.fromISO(item.date).toFormat("h:mma")}
</span>
</div>
<p>
{item.description}
</p>
<div className="read-more-btn">
<Link to={url} className="btn">{moduleItem.customFields.viewDetailsLabel}</Link>
</div>
</div>
</div>
)
}
Example #7
Source File: Calendar.js From anutimetable with Creative Commons Attribution Share Alike 4.0 International | 6 votes |
getLocaleStartFinishTime = (events, timeZone) => {
// 9 - 5 Workday
let startTime = DateTime.fromFormat('09:00', 'HH:mm', { zone: 'Australia/Sydney' })
// Exclusive times mean end of 7pm equals 8pm
let finishTime = DateTime.fromFormat('18:00', 'HH:mm', { zone: 'Australia/Sydney' })
// Find any events that push these default boundaries
events.forEach(eventList => {
eventList.events.forEach(e => {
if (e.display === 'auto') {
let start = DateTime.fromFormat(e.start, 'HH:mm', { zone: 'Australia/Sydney' })
let finish = DateTime.fromFormat(e.finish, 'HH:mm', { zone: 'Australia/Sydney' })
if (start < startTime) startTime = start
if (finish > finishTime) finishTime = finish
}
})
})
// Change the local to the users timezone
startTime = startTime.setZone(timeZone)
finishTime = finishTime.setZone(timeZone)
// Unfortunatly when an event wrappes around past midnight local time, we must show all of the calendar rows
if (startTime.hour >= finishTime.hour) {
startTime = DateTime.fromFormat('00:00', 'HH:mm')
finishTime = DateTime.fromFormat('23:59', 'HH:mm')
}
return [startTime.toLocaleString(DateTime.TIME_24_SIMPLE), finishTime.toLocaleString(DateTime.TIME_24_SIMPLE)]
}
Example #8
Source File: calendar.js From jc-calendar with MIT License | 6 votes |
/**
* Returns a localized formatted month and year string.
* @param {string} monthString The month to get the key from.
*/
export function getDisplayMonthAndYear(monthString) {
return DateTime.fromFormat(monthString, MONTH_FORMAT).toLocaleString({
locale: APP_LOCALE,
year: 'numeric',
month: 'long',
});
}
Example #9
Source File: date.js From react-invenio-app-ils with MIT License | 6 votes |
/**
* Serializes date for display in tables
*/
export function dateFormatter({ col, row }, defaultValue = null) {
const dateField = _get(row, col.field);
return dateField
? DateTime.fromISO(dateField).toLocaleString()
: defaultValue;
}
Example #10
Source File: Map.js From Tweet-Locator with MIT License | 6 votes |
function Map(props) {
const { tweets } = props;
console.log(tweets);
return (
<MapContainer center={[25, 0]} zoom={2.3} scrollWheelZoom={false}>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{tweets.map((tweet) => (
<Marker
position={[
tweet.geometry.coordinates[1],
tweet.geometry.coordinates[0],
]}
>
<Popup className="popup-toast">
<Toast>
<Toast.Header closeButton={false}>
<strong className="me-auto">{tweet.properties.username}</strong>
<small>
{DateTime.fromISO(tweet.properties.created_at).toRelative()}
</small>
</Toast.Header>
<Toast.Body>{tweet.properties.text}</Toast.Body>
</Toast>
</Popup>
</Marker>
))}
</MapContainer>
);
}
Example #11
Source File: helper.js From linked with GNU General Public License v3.0 | 6 votes |
getCurrentWeekDates = (date) => {
let week = []
const startOfWeek = DateTime.fromISO(date).startOf('week')
for (let i = 0; i <= 6; i++) {
let day = startOfWeek
.plus({ days: i })
.setLocale(localStorage.lang ?? 'en-US')
week.push({
isoDate: day.toISODate(),
day: day.toFormat('d'),
weekDay: day.toFormat('EEE')
})
}
return week
}
Example #12
Source File: date.js From file-picker with Apache License 2.0 | 6 votes |
// TODO: Investiage if we can set language manually
// Getting the browser set language is not a good UX
// Passing as a prop doesn't seem like a nice solution
export function formDateFromNow(date) {
const locale = Vue.config.language.replace('cs_CZ', 'cs')
return DateTime.fromJSDate(new Date(date)).setLocale(locale).toRelative()
}
Example #13
Source File: guildMemberAdd.js From manny with MIT License | 6 votes |
exec (member) {
const channel = this.client.channels.cache.get(config.channels.logs.memberLog)
const now = DateTime.local()
const accountCreated = DateTime.fromJSDate(member.user.createdAt)
const accountAge = now.diff(accountCreated, 'minutes').toObject()
// Flag bots
if (member.user.bot) {
return channel.send(`:robot: <@${member.user.id}> was added to the server \`BOT\``)
}
// Flag new accounts
if (accountAge.minutes <= config.automod.newAccountAge) {
return channel.send(`:inbox_tray: <@${member.user.id}> joined the server \`NEW\``)
}
return channel.send(`:inbox_tray: <@${member.user.id}> joined the server`)
}
Example #14
Source File: sparklines.js From website with Apache License 2.0 | 5 votes |
StatisticSparkline = ({ data, field, color }) => {
const height = 40
const width = 120
const marginTop = 5
const marginRight = 20
const dates = []
const values = []
const averages = []
data.forEach((item, key) => {
if (key < 14) {
return
}
let sum = 0
for (let i = key; i > key - 7; i -= 1) {
sum += data[i][field]
}
averages.push({
value: sum / 7,
date: DateTime.fromISO(item.date).toJSDate(),
})
})
averages.forEach(item => {
dates.push(item.date)
values.push(item.value)
})
const dateDomain = extent(dates)
const xScaleTime = scaleTime()
.domain(dateDomain)
.range([0, width])
const yMaxEffective = max(values)
const yScale = scaleLinear()
.domain([0, yMaxEffective])
.nice()
.range([height, 0])
const lineFn = line()
.defined(d => !Number.isNaN(d.value) && d.value !== null)
.curve(curveNatural)
.x(d => xScaleTime(d.date))
.y(d => yScale(d.value))
return (
<svg
className={sparklineStyles.sparkline}
viewBox={`0 0 ${width + marginRight} ${height - marginTop}`}
aria-hidden
>
<g transform={`translate(0 ${marginTop})`}>
<defs>
<marker
id={`triangle-${field}`}
refX="10"
refY="6"
markerWidth="30"
markerHeight="30"
markerUnits="userSpaceOnUse"
orient="auto"
>
<path d="M 0 0 12 6 0 12 3 6" style={{ fill: color }} />
</marker>
</defs>
<path
d={lineFn(averages)}
stroke={color}
strokeWidth={3}
fill="none"
markerEnd={`url(#triangle-${field})`}
/>
</g>
</svg>
)
}
Example #15
Source File: background.js From jdtry with GNU General Public License v3.0 | 5 votes |
window.joinTaskInQueue = function(task, run=false, data={}){
console.log(`joinTaskInQueue`)
console.log(task)
let id = task
if(typeof (task) === 'object'){
task.last_run_at = DateTime.local().valueOf()
updateTaskInfo(task)
id = task.id
}
switch (id) {
case TASK_ID.FOLLOW_VENDER_NUM_RETRIEVAL:
runtime.taskQueue.push(checkLoginStatusValid)
runtime.taskQueue.push(followVenderNumberRetrieval)
break
case TASK_ID.EMPTY_FOLLOW_VENDER_LIST:
runtime.taskQueue.push(checkLoginStatusValid)
runtime.taskQueue.push(emptyFollowVenderList)
break
case TASK_ID.ACTIVITY_RETRIEVAL:
runtime.taskQueue.push(activityRetrieval)
break
case TASK_ID.SUCCESS_ACTIVITY_RETRIEVAL:
runtime.taskQueue.push(checkLoginStatusValid)
runtime.taskQueue.push(successActivityRetrieval)
break
case TASK_ID.ACTIVITY_APPLY:
if(data.activity){
runtime.taskQueue.push(async ()=>{await activityApply(data.activity)})
}
else{
runtime.taskQueue.push(checkLoginStatusValid)
runtime.taskQueue.push(activityApply)
runtime.taskQueue.push(followVenderNumberRetrieval)
}
break
case TASK_ID.CHECK_OR_DO_LOGIN_OPT:
runtime.taskQueue.push(checkLoginStatusValid)
default:
break
}
if(run){
runTask()
}
}
Example #16
Source File: Calendar.js From anutimetable with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
weekNumberCalculation = date => {
const startDate = getStartOfSession()
const start = startDate ? DateTime.fromJSDate(startDate).weekNumber : 0
const end = DateTime.fromJSDate(date).plus({ days: 1 }).weekNumber // Add 1 to convert FullCalendar (Sun-Sat) to Luxon/ISO (Mon-Sun)
return end - start + 1 // 0 weeks after start is week 1
}
Example #17
Source File: App.js From jc-calendar with MIT License | 5 votes |
componentDidMount() {
window.addEventListener('resize', setNavigationBarHeightCSSVariable);
if (this.props.month === null) {
this.props.dispatch(setMonth(DateTime.local().toFormat('yyyy-MM')));
}
}
Example #18
Source File: filters.js From Quest with MIT License | 5 votes |
function computeDate(days) {
return () => DateTime.local().minus({ days }).toISODate();
}
Example #19
Source File: date.js From react-invenio-app-ils with MIT License | 5 votes |
toShortDateTime = (date) => {
return date instanceof DateTime ? date.toFormat('yyyy-MM-dd HH:mm') : date;
}
Example #20
Source File: EmbargoAccess.js From react-invenio-deposit with MIT License | 5 votes |
EmbargoAccess = ({access, accessCommunity, metadataOnly}) => {
const recordPublic = access.record === 'public';
const filesPublic = access.files === 'public';
const communityPublic = accessCommunity === 'public';
const filesRestricted = !metadataOnly && !filesPublic;
const embargoActive = access.embargo?.active || false;
const embargoUntil = access.embargo?.until;
const embargoReason = access.embargo?.reason;
const embargoWasLifted = !embargoActive && !_isEmpty(embargoUntil);
const embargoEnabled = communityPublic && (!recordPublic || filesRestricted);
const fmtDate = embargoUntil ?
DateTime.fromISO(embargoUntil).toLocaleString(DateTime.DATE_FULL) : '???';
return (
<List>
<List.Item
disabled={!embargoEnabled}
data-testid="option-list-embargo"
>
<List.Icon>
<EmbargoCheckboxField
fieldPath="access.embargo.active"
checked={embargoActive}
disabled={!embargoEnabled}
/>
</List.Icon>
<List.Content>
<List.Header>
<label
htmlFor='access.embargo.active'
>
{i18next.t('Apply an embargo')} <Icon name="clock outline" />
</label>
</List.Header>
<List.Description>
<Trans>
Record or files protection must be <b>restricted</b> to apply an
embargo.
</Trans>
</List.Description>
{embargoActive && (
<>
<Divider hidden />
<EmbargoDateField fieldPath="access.embargo.until" required />
<TextAreaField
label={i18next.t('Embargo reason')}
fieldPath={'access.embargo.reason'}
placeholder={i18next.t(
'Optionally, describe the reason for the embargo.'
)}
optimized="true"
/>
</>
)}
{embargoWasLifted && (
<>
<Divider hidden />
<p>
{i18next.t(`Embargo was lifted on {{fmtDate}}.`, {
fmtDate: fmtDate,
})}
</p>
{embargoReason && (
<p>
<b>{i18next.t('Reason')}</b>:{' '}
{embargoReason}.
</p>
)}
</>
)}
</List.Content>
</List.Item>
</List>
);
}
Example #21
Source File: Tweet.js From Tweet-Locator with MIT License | 5 votes |
/**
* @param {object} props
* @param {object[]} props.tweets
* @param {string} props.tweets[].type
* @param {object} props.tweets[].properties
* @param {string} props.tweets[].properties.username
* @param {string} props.tweets[].properties.text
* @param {string} props.tweets[].properties.created_at
* @param {object} props.tweets[].geometry
* @param {string} props.tweets[].geometry.type
* @param {[number, number]} props.tweets[].geometry.coordinates
*/
function Tweet(props) {
const { tweets } = props;
return (
<div className="tweet">
<div className="tweet-group">
{tweets.map((tweet) => (
<Card>
<Card.Header as="h5">
{tweet.properties.username}
{" - "}
<small>
{DateTime.fromISO(tweet.properties.created_at).toRelative()}
</small>
</Card.Header>
<Card.Body>
<Card.Text>{tweet.properties.text}</Card.Text>
<Button
variant="primary"
href={tweet.properties.url}
target="__blank"
>
View Tweet
</Button>
</Card.Body>
</Card>
))}
</div>
</div>
);
}
Example #22
Source File: helper.js From linked with GNU General Public License v3.0 | 5 votes |
getToday = () => {
return DateTime.now().toISODate()
}
Example #23
Source File: ProposalsList.jsx From pooltogether-governance-ui with MIT License | 5 votes |
ProposalStatus = (props) => {
const { proposal } = props
const { t } = useTranslation()
const { status } = proposal
let statusValue
switch (status) {
case PROPOSAL_STATUS.executed:
case PROPOSAL_STATUS.succeeded:
case PROPOSAL_STATUS.active:
case PROPOSAL_STATUS.queued: {
statusValue = 1
break
}
case PROPOSAL_STATUS.expired:
case PROPOSAL_STATUS.defeated:
case PROPOSAL_STATUS.cancelled: {
statusValue = -1
break
}
default:
case PROPOSAL_STATUS.pending: {
statusValue = 0
break
}
}
let icon
if (statusValue < 0) {
icon = 'x-circle'
} else if (statusValue > 0) {
icon = 'check-circle'
}
const showIcon = status !== PROPOSAL_STATUS.active && status !== PROPOSAL_STATUS.pending
if (status === PROPOSAL_STATUS.active) {
return <ProposalCountDown proposal={proposal} />
}
return (
<div
className={classnames(
'sm:ml-auto text-white sm:ml-0 mb-2 sm:mb-0 flex items-center rounded-lg px-2 py-1 w-fit-content h-fit-content bg-tertiary whitespace-no-wrap',
{
'text-orange': statusValue < 0,
'text-highlight-9': statusValue > 0,
'text-inverse': statusValue === 0
}
)}
>
{proposal.endDate && (
<div className='sm:pl-4 mr-2 sm:mr-4 sm:text-right' style={{ minWidth: 104 }}>
{proposal.endDate.toLocaleString(DateTime.DATE_MED)}
</div>
)}
{icon && showIcon && (
<FeatherIcon icon={icon} className='mr-2 stroke-current w-3 h-3 sm:w-4 sm:h-4' />
)}
<div className='sm:pr-4 font-bold capitalized'>{t(status)}</div>
</div>
)
}
Example #24
Source File: [collectionId].js From pure.finance with MIT License | 5 votes |
DPAuctionsRow = function ({ auction }) {
const { lang, t } = useTranslation('common')
const calcEndTime = () =>
Date.now() +
(auction.endBlock - auction.currentBlock) * ETH_BLOCK_TIME * 1000
const endTime = useUpdatingState(calcEndTime, 10000, [auction.currentBlock]) // 10s
return (
<Link href={`/dp-auctions/auctions/${auction.id}`} passHref>
<tr className="cursor-pointer">
<td className="border-2">{auction.id}</td>
<td className="border-2">
{auction.tokens.map(token => (
<div key={token.address}>
<TokenAmount {...token} />
</div>
))}
</td>
<td className="border-2">
{auction.status === 'won' || auction.status === 'stopped' ? (
'-'
) : (
<TokenAmount
amount={auction.currentPrice}
{...auction.paymentToken}
/>
)}
</td>
<td className="border-2">
{t(auction.status)}
{auction.status === 'running' &&
` (${t('ends')} ${DateTime.fromMillis(endTime).toRelative({
locale: lang
})})`}
</td>
</tr>
</Link>
)
}
Example #25
Source File: stream.js From manny with MIT License | 5 votes |
async exec (message) {
try {
const member = this.client.guilds.cache.first().member(message.author)
const now = DateTime.local()
const joinedServer = DateTime.fromJSDate(member.joinedAt)
const timeSinceJoin = now.diff(joinedServer, 'days').toObject()
const timeUntilEligible = joinedServer.plus({ days: 7 })
const strikes = await Case.findAll({
where: {
action: 'strike',
userID: member.id,
active: true
},
order: [['timestamp', 'DESC']]
})
const strikeCount = strikes.length
if (timeSinceJoin.days < 7) {
return message.channel.send(`${_.prefix('warning')} You are not eligible for streaming until **${_.prettyDate(timeUntilEligible.toJSDate())}**.`)
}
if (strikeCount === 0) {
if (member.roles.cache.some(role => role.id === config.roles.stream)) {
return message.channel.send(`${_.prefix('warning')} You are already able to stream in the **${member.voice.channel.name}** voice channel.`)
}
if (member.voice.channel !== null) {
await member.roles.add(config.roles.stream)
this.client.log.info(`Streaming role added >> ${member.user.tag}`)
return message.channel.send(`${_.prefix('success')} You may now stream in the **${member.voice.channel.name}** voice channel.`)
} else {
return message.channel.send(`${_.prefix('warning')} Please join the voice channel you want to stream in, then try again.`)
}
}
return message.channel.send(`${_.prefix('warning')} You are not eligible for streaming until **${_.prettyStrikeExpiration(strikes[0].timestamp)}**.`)
} catch (e) {
await message.channel.send(`${_.prefix('error')} Something went wrong. Please notify a moderator.`)
return this.client.log.error(e)
}
}
Example #26
Source File: legend.js From website with Apache License 2.0 | 4 votes |
Legend = ({ mapLayer, date }) => (
<Container>
<Row className={legendStyles.wrapper}>
<Col width={[4, 6, 6]} paddingRight={[0, 0, 0]}>
<LayerToggle
layers={[
{
id: 'patients',
name: 'All inpatients',
},
{
id: 'icu',
name: 'ICU inpatients',
},
]}
/>
<p className={legendStyles.dates}>
{date ? (
<>
Data for{' '}
<FormatDate date={date} format="LLLL d, yyyy" timezone={false} />{' '}
to{' '}
<FormatDate
date={DateTime.fromISO(date)
.plus({ days: 6 })
.toISO()}
format="LLLL d, yyyy"
timezone={false}
/>
</>
) : (
<> </>
)}
</p>
</Col>
<Col width={[4, 6, 6]} paddingLeft={[0, 0, 16]}>
<div className={legendStyles.legend} aria-hidden>
<div>
<div className={legendStyles.label}>
% of {mapLayer === 'patients' ? <>hospital</> : <>ICU</>} beds
with COVID patients
</div>
<div className={legendStyles.scale}>
<div>
<div />
N/A
</div>
<div>
<div />
0%
</div>
<div>
<div />
{'<'}15%
</div>
<div>
<div />
15-30%
</div>
<div>
<div />
30-45%
</div>
<div>
<div />
{'>'}45%
</div>
<div>
<div />
Anomaly
</div>
</div>
<div className={legendStyles.label}>
Circle size indicates total COVID{' '}
{mapLayer === 'patients' ? <>inpatients</> : <>ICU patients</>}
</div>
</div>
</div>
</Col>
</Row>
</Container>
)
Example #27
Source File: EventDetails.js From agility-website-gatsby with MIT License | 4 votes |
EventDetails = ({ item, dynamicPageItem, page }) => {
const [loaded, setLoaded] = useState(false)
const event = dynamicPageItem.customFields
const eventDate = DateTime.fromISO(event.date)
const isPastEvent = eventDate.diffNow("seconds").seconds < 0
let externalLink = null
let exernalTarget = null
if (event.externalLink) {
externalLink = event.externalLink.href
exernalTarget = event.externalLink.target
}
useEffect(() => {
//load the eventbrites cript - but only if we have to
if (typeof window === "undefined") return
//only load the event brite stuff if we are NOT on a past event...
if (loaded || isPastEvent) return
setTimeout(function() {
if (event.demioID) {
//add the demo embed...
let script = document.createElement("script")
script.src =
"https://cdn.demio.com/production/dashboard/embed.bundle.js"
script.async = true
document.body.appendChild(script)
} else if (event.eventbriteID) {
//add the script embed...
let script = document.createElement("script")
script.src = "https://www.eventbrite.com/static/widgets/eb_widgets.js"
script.async = true
document.body.appendChild(script)
loadEventBriteForm()
}
setLoaded(true)
}, 100)
scrollToform()
})
const scrollToform = () => {
document
.getElementsByClassName("scroll-to-form")[0]
.addEventListener("click", e => {
e.preventDefault()
let id = document.querySelectorAll(e.target.getAttribute("href"))
// console.log(id)
if (id.length) {
let header = document.querySelectorAll("#header")[0].offsetHeight
HelperFunc.animateScrollTop(id[0].offsetTop - header - 100, 350)
}
})
}
const loadEventBriteForm = () => {
if (!window.EBWidgets) {
setTimeout(loadEventBriteForm, 100)
return
}
window.EBWidgets.createWidget({
widgetType: "checkout",
eventId: event.eventbriteID,
modal: true,
modalTriggerElementId: `eventbrite-widget-button-${event.eventbriteID}`,
})
setTimeout(function() {
window.EBWidgets.createWidget({
// Required
widgetType: "checkout",
eventId: event.eventbriteID,
iframeContainerId: `eventbrite-widget-container-${event.eventbriteID}`,
// Optional
iframeContainerHeight: 425, // Widget height in pixels. Defaults to a minimum of 425px if not provided
//onOrderComplete: exampleCallback // Method called when an order has successfully completed
})
}, 1000)
}
return (
<section className="event-details">
<div className="container p-w-small rich-text">
<h1 className="title-component">{event.title}</h1>
<div className="event-date">
<span className="event-type">
{event.eventType.customFields.title}
</span>
<span className="date">{eventDate.toFormat("MMM d, yyyy")}</span>
<span className="time">{eventDate.toFormat("h:mma")}</span>
</div>
<div className="event-image">
{event.mainImage && (
<a href={externalLink} target={exernalTarget}>
<AgilityImage image={event.mainImage} layout="fullWidth" />
</a>
)}
</div>
<div className="event">
<div className="form-container">
{event.demioID && !isPastEvent && (
<section className="demio-register" id="register-now">
<h2>Register Now</h2>
<div>
<span
className="demio-embed-registration"
data-hash={event.demioID}
data-api="api/v1"
data-base-uri="https://my.demio.com/"
data-form-width="100%"
data-color="#4600a8"
data-text="REGISTER"
></span>
</div>
</section>
)}
{event.eventbriteID && !isPastEvent && (
<div
id={`eventbrite-widget-container-${event.eventbriteID}`}
></div>
)}
</div>
<div
className="event-content"
dangerouslySetInnerHTML={renderHTML(event.textblob)}
></div>
<div>
{event.externalLink && (
<div className="event-link">
<a href={externalLink} target={exernalTarget} className="btn">
{event.externalLink.text}
</a>
</div>
)}
{event.demioID && !isPastEvent && (
<div className="event-link">
<a href="#register-now" className="btn scroll-to-form">
Register Now
</a>
</div>
)}
{event.eventbriteID && !isPastEvent && (
<div className="event-link">
<a
className="btn"
id={`eventbrite-widget-button-${event.eventbriteID}`}
type="button"
>
Register Now
</a>
</div>
)}
</div>
</div>
<Link to="/resources/events" className="back d-flex ai-center">
<img
src="https://static.agilitycms.com/layout/img/ico/gray.svg"
alt=""
/>
<span>Back to Event Listing</span>
</Link>
</div>
</section>
)
}
Example #28
Source File: reminder.test.js From jc-calendar with MIT License | 4 votes |
describe('sagas::ui::reminder', () => {
test('openReminder', () => {
const iterator = openReminder({
city: 'Lorem Ipsum',
color: 'indigo-600',
dateTime: 1608247620000,
description: 'TEST EDITED',
id: 'hqsd5mj1g7o13jkyhdeg',
});
expect(iterator.next().value).toEqual(
put(
reminderUIActions.openReminder({
city: 'Lorem Ipsum',
color: 'indigo-600',
dateTime: 1608247620000,
description: 'TEST EDITED',
id: 'hqsd5mj1g7o13jkyhdeg',
})
)
);
});
test('newReminder', () => {
let iterator = newReminder(reminderUIActions.newReminder());
expect(iterator.next().value).toEqual(apply(DateTime, 'local'));
const now = DateTime.fromMillis(1608247620000);
expect(iterator.next(now).value).toEqual(
call(openReminder, {
id: null,
description: '',
color: DEFAULT_COLOR,
dateTime: 1608247620000,
city: '',
})
);
iterator = newReminder(
// '2020-12-17' is the date part from 1608247620000
reminderUIActions.newReminder('2020-12-17')
);
expect(iterator.next().value).toEqual(apply(DateTime, 'local'));
expect(iterator.next(now).value).toEqual(
call(openReminder, {
id: null,
description: '',
color: DEFAULT_COLOR,
dateTime: 1608247620000,
city: '',
})
);
});
test('editReminder', () => {
const iterator = editReminder(
reminderUIActions.editReminder({
city: 'Lorem Ipsum',
color: 'indigo-600',
dateTime: 1608247620000,
description: 'TEST EDITED',
id: 'hqsd5mj1g7o13jkyhdeg',
})
);
expect(iterator.next().value).toEqual(
call(openReminder, {
city: 'Lorem Ipsum',
color: 'indigo-600',
dateTime: 1608247620000,
description: 'TEST EDITED',
id: 'hqsd5mj1g7o13jkyhdeg',
})
);
});
test('submitReminder - new', () => {
const iterator = submitReminder(
reminderUIActions.submitReminder({
city: 'Lorem Ipsum',
color: 'indigo-600',
date: '2020-12-11',
time: '10:55',
description: 'TEST',
id: null,
})
);
expect(iterator.next().value).toEqual(call(generateUUID));
expect(iterator.next('some-id').value).toEqual(
put(
setReminder({
id: 'some-id',
description: 'TEST',
color: 'indigo-600',
dateTime: dateTimeStringsToMillis('2020-12-11', '10:55'),
city: 'Lorem Ipsum',
})
)
);
expect(iterator.next().value).toEqual(
put(
setDateReminder({
date: '2020-12-11',
reminderId: 'some-id',
})
)
);
expect(iterator.next().value).toEqual(
put(reminderUIActions.closeReminder())
);
});
test('submitReminder - existing', () => {
const iterator = submitReminder(
reminderUIActions.submitReminder({
city: 'Lorem Ipsum',
color: 'indigo-600',
date: '2020-12-11',
time: '10:55',
description: 'TEST',
id: 'some-existing-id',
})
);
expect(iterator.next().value).toEqual(
put(
setReminder({
id: 'some-existing-id',
description: 'TEST',
color: 'indigo-600',
dateTime: dateTimeStringsToMillis('2020-12-11', '10:55'),
city: 'Lorem Ipsum',
})
)
);
expect(iterator.next().value).toEqual(
put(
setDateReminder({
date: '2020-12-11',
reminderId: 'some-existing-id',
})
)
);
expect(iterator.next().value).toEqual(
put(reminderUIActions.closeReminder())
);
});
});
Example #29
Source File: BorrowingRequestLoanExtension.js From react-invenio-app-ils with MIT License | 4 votes |
render() {
const {
isLoading,
patron,
patronLoan,
patronLoan: { extension },
} = this.props;
const { modalOpen } = this.state;
const max = new DateTime(
DateTime.local().plus({
days: invenioConfig.ILL_BORROWING_REQUESTS.loanMaxDuration,
})
);
return (
<Container>
<Divider horizontal>Loan extension</Divider>
<Table definition>
<Table.Body>
<Table.Row>
<Table.Cell>Extensions</Table.Cell>
<Table.Cell>{patronLoan.loan.extension_count || 0}</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
{!_isEmpty(extension) && extension.status && (
<>
The patron requested an extension for this loan on{' '}
<Label basic>
{DateTime.fromISO(extension.request_date).toLocaleString()}
</Label>
<Divider hidden />
{invenioConfig.ILL_BORROWING_REQUESTS.extensionPendingStatuses.includes(
extension.status
) && (
<Grid>
<Grid.Row>
<Grid.Column width={8} textAlign="left">
<Modal
open={modalOpen}
trigger={
<Button
positive
onClick={this.handleOpenModal}
loading={isLoading}
disabled={isLoading}
>
Accept extension
</Button>
}
>
<Modal.Header>Accept extension</Modal.Header>
<Modal.Content>
Current loan end date:{' '}
<Label basic size="large">
{DateTime.fromISO(
patronLoan.loan.end_date
).toLocaleString()}
</Label>
<Divider hidden />
<Form>
<Form.Group>
<Form.Field inline required>
<label>Extension end date</label>
<LocationDatePicker
locationPid={patron.location_pid}
defaultValue={this.endDate}
minDate={toShortDate(DateTime.local())}
maxDate={toShortDate(max)}
placeholder="End date"
handleDateChange={(value) =>
this.handleEndDateChange(value)
}
/>
</Form.Field>
</Form.Group>
</Form>
<Divider hidden />
<i>
The extension end date should not be before the
borrowing request start date and not before current
loan end date.
</i>
</Modal.Content>
<Modal.Actions>
<Button onClick={this.handleCloseModal}>Cancel</Button>
<Button positive onClick={this.acceptHandler}>
Accept extension
</Button>
</Modal.Actions>
</Modal>
</Grid.Column>
<Grid.Column width={8} textAlign="right">
<Button
negative
onClick={this.declineHandler}
loading={isLoading}
disabled={isLoading}
>
Decline extension
</Button>
</Grid.Column>
</Grid.Row>
</Grid>
)}
{invenioConfig.ILL_BORROWING_REQUESTS.extensionDeclinedStatuses.includes(
extension.status
) && (
<InfoMessage
title="Extension declined"
message="The extension is already declined."
/>
)}
</>
)}
</Container>
);
}