webcomponent datetime format helpers

This commit is contained in:
lesion 2022-09-05 12:32:27 +02:00
parent 3c176ff7af
commit e8ed2ec4b0
No known key found for this signature in database
GPG key ID: 352918250B012177
7 changed files with 1685 additions and 3425 deletions

File diff suppressed because it is too large Load diff

View file

@ -48,14 +48,14 @@ domPurify.addHook('beforeSanitizeElements', node => {
module.exports = { module.exports = {
randomString (length = 12) { randomString(length = 12) {
const wishlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' const wishlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
return Array.from(crypto.randomFillSync(new Uint32Array(length))) return Array.from(crypto.randomFillSync(new Uint32Array(length)))
.map(x => wishlist[x % wishlist.length]) .map(x => wishlist[x % wishlist.length])
.join('') .join('')
}, },
sanitizeHTML (html) { sanitizeHTML(html) {
return domPurify.sanitize(html, { return domPurify.sanitize(html, {
ALLOWED_TAGS: ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'br', 'i', 'span', ALLOWED_TAGS: ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'br', 'i', 'span',
'h6', 'b', 'a', 'li', 'ul', 'ol', 'code', 'blockquote', 'u', 's', 'strong'], 'h6', 'b', 'a', 'li', 'ul', 'ol', 'code', 'blockquote', 'u', 's', 'strong'],
@ -63,7 +63,7 @@ module.exports = {
}) })
}, },
async setUserLocale (req, res, next) { async setUserLocale(req, res, next) {
// select locale based on cookie? and accept-language header // select locale based on cookie? and accept-language header
acceptLanguage.languages(Object.keys(locales)) acceptLanguage.languages(Object.keys(locales))
res.locals.acceptedLocale = acceptLanguage.get(req.headers['accept-language']) res.locals.acceptedLocale = acceptLanguage.get(req.headers['accept-language'])
@ -71,7 +71,7 @@ module.exports = {
next() next()
}, },
async initSettings (_req, res, next) { async initSettings(_req, res, next) {
// initialize settings // initialize settings
res.locals.settings = cloneDeep(settingsController.settings) res.locals.settings = cloneDeep(settingsController.settings)
delete res.locals.settings.smtp delete res.locals.settings.smtp
@ -87,12 +87,12 @@ module.exports = {
next() next()
}, },
serveStatic () { serveStatic() {
const router = express.Router() const router = express.Router()
// serve images/thumb // serve images/thumb
router.use('/media/', express.static(config.upload_path, { immutable: true, maxAge: '1y' } ), (_req, res) => res.sendStatus(404)) router.use('/media/', express.static(config.upload_path, { immutable: true, maxAge: '1y' }), (_req, res) => res.sendStatus(404))
router.use('/noimg.svg', express.static('./static/noimg.svg')) router.use('/noimg.svg', express.static('./static/noimg.svg'))
router.use('/logo.png', (req, res, next) => { router.use('/logo.png', (req, res, next) => {
const logoPath = res.locals.settings.logo || './static/gancio' const logoPath = res.locals.settings.logo || './static/gancio'
return express.static(logoPath + '.png')(req, res, next) return express.static(logoPath + '.png')(req, res, next)
@ -106,12 +106,12 @@ module.exports = {
return router return router
}, },
logRequest (req, _res, next) { logRequest(req, _res, next) {
log.debug(`${req.method} ${req.path}`) log.debug(`${req.method} ${req.path}`)
next() next()
}, },
col (field) { col(field) {
if (config.db.dialect === 'postgres') { if (config.db.dialect === 'postgres') {
return '"' + field.split('.').join('"."') + '"' return '"' + field.split('.').join('"."') + '"'
} else if (config.db.dialect === 'mariadb') { } else if (config.db.dialect === 'mariadb') {
@ -121,14 +121,14 @@ module.exports = {
} }
}, },
async getImageFromURL (url) { async getImageFromURL(url) {
log.debug(`getImageFromURL ${url}`) log.debug(`getImageFromURL ${url}`)
const filename = crypto.randomBytes(16).toString('hex') const filename = crypto.randomBytes(16).toString('hex')
const sharpStream = sharp({ failOnError: true }) const sharpStream = sharp({ failOnError: true })
const promises = [ const promises = [
sharpStream.clone().resize(500, null, { withoutEnlargement: true }).jpeg({ effort: 6, mozjpeg: true }).toFile(path.resolve(config.upload_path, 'thumb', filename + '.jpg')), sharpStream.clone().resize(500, null, { withoutEnlargement: true }).jpeg({ effort: 6, mozjpeg: true }).toFile(path.resolve(config.upload_path, 'thumb', filename + '.jpg')),
sharpStream.clone().resize(1200, null, { withoutEnlargement: true } ).jpeg({ quality: 95, effort: 6, mozjpeg: true}).toFile(path.resolve(config.upload_path, filename + '.jpg')), sharpStream.clone().resize(1200, null, { withoutEnlargement: true }).jpeg({ quality: 95, effort: 6, mozjpeg: true }).toFile(path.resolve(config.upload_path, filename + '.jpg')),
] ]
const response = await axios({ method: 'GET', url: encodeURI(url), responseType: 'stream' }) const response = await axios({ method: 'GET', url: encodeURI(url), responseType: 'stream' })
@ -157,7 +157,7 @@ module.exports = {
* Import events from url * Import events from url
* It does supports ICS and H-EVENT * It does supports ICS and H-EVENT
*/ */
async importURL (req, res) { async importURL(req, res) {
const URL = req.query.URL const URL = req.query.URL
try { try {
const response = await axios.get(URL) const response = await axios.get(URL)
@ -210,7 +210,7 @@ module.exports = {
} }
}, },
getWeekdayN (date, n, weekday) { getWeekdayN(date, n, weekday) {
let cursor let cursor
if (n === -1) { if (n === -1) {
cursor = date.endOf('month') cursor = date.endOf('month')
@ -227,8 +227,8 @@ module.exports = {
log.debug(cursor) log.debug(cursor)
return cursor return cursor
}, },
async APRedirect (req, res, next) { async APRedirect(req, res, next) {
const acceptJson = req.accepts('html', 'application/activity+json') === 'application/activity+json' const acceptJson = req.accepts('html', 'application/activity+json') === 'application/activity+json'
if (acceptJson) { if (acceptJson) {
const eventController = require('../server/api/controller/event') const eventController = require('../server/api/controller/event')
@ -240,7 +240,7 @@ module.exports = {
next() next()
}, },
async feedRedirect (req, res, next) { async feedRedirect(req, res, next) {
const accepted = req.accepts('html', 'application/rss+xml', 'text/calendar') const accepted = req.accepts('html', 'application/rss+xml', 'text/calendar')
if (['application/rss+xml', 'text/calendar'].includes(accepted) && /^\/(tag|place|collection)\/.*/.test(req.path)) { if (['application/rss+xml', 'text/calendar'].includes(accepted) && /^\/(tag|place|collection)\/.*/.test(req.path)) {
return res.redirect((accepted === 'application/rss+xml' ? '/feed/rss' : '/feed/ics') + req.path) return res.redirect((accepted === 'application/rss+xml' ? '/feed/rss' : '/feed/ics') + req.path)

File diff suppressed because it is too large Load diff

View file

@ -1,16 +1,19 @@
<svelte:options tag="gancio-event" />
<script> <script>
import { onMount } from 'svelte' import { onMount } from 'svelte'
import { when } from './helpers'
export let baseurl = 'https://demo.gancio.org' export let baseurl = 'https://demo.gancio.org'
export let id export let id
let mounted = false let mounted = false
let event let event
function update (id, baseurl) { function update(id, baseurl) {
if (mounted) { if (mounted) {
fetch(`${baseurl}/api/event/${id}`) fetch(`${baseurl}/api/event/${id}`)
.then(res => res.json()) .then((res) => res.json())
.then(e => event = e) .then((e) => (event = e))
} }
} }
@ -20,85 +23,82 @@
}) })
$: update(id, baseurl) $: update(id, baseurl)
function when (event) {
return new Date(event.start_datetime*1000)
.toLocaleDateString(undefined,
{
weekday: 'long',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})
}
function thumbnail(event) { function thumbnail(event) {
return `${baseurl}/media/thumb/${event.media[0].url}` return `${baseurl}/media/thumb/${event.media[0].url}`
} }
function position(event) { function position(event) {
if (event.media[0].focalpoint) { if (event.media[0].focalpoint) {
const focalpoint = event.media[0].focalpoint const focalpoint = event.media[0].focalpoint
return `${(focalpoint[0] + 1) * 50}% ${(focalpoint[1] + 1) * 50}%` return `${(focalpoint[0] + 1) * 50}% ${(focalpoint[1] + 1) * 50}%`
} }
return 'center center' return 'center center'
}
</script>
{#if event}
<a
href="{baseurl}/event/{event.slug || event.id}"
class="card"
target="_blank"
>
{#if event.media.length}
<img
src={thumbnail(event)}
alt={event.media[0].name}
style="object-position: {position(event)}; aspect-ratio=1.7778;"
/>
{/if}
<div class="container">
<strong>{event.title}</strong>
<div>{when(event)}</div>
<div class="place">@{event.place.name}</div>
</div>
</a>
{/if}
<style>
.card {
display: block;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS',
sans-serif;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
transition: 0.3s;
border-radius: 5px; /* 5px rounded corners */
max-width: 500px;
text-decoration: none;
color: white;
background-color: #1e1e1e;
overflow: hidden;
} }
</script> /* Add rounded corners to the top left and the top right corner of the image */
<svelte:options tag="gancio-event"/> img {
{#if event} border-radius: 5px 5px 0 0;
<a href='{baseurl}/event/{event.slug || event.id}' class='card' target='_blank'> max-height: 250px;
{#if event.media.length} min-height: 160px;
<img src="{thumbnail(event)}" alt="{event.media[0].name}" style="object-position: {position(event)}; aspect-ratio=1.7778;"> width: 100%;
{/if} object-fit: cover;
<div class="container"> object-position: top;
<strong>{event.title}</strong> }
<div>{when(event)}</div>
<div class='place'>@{event.place.name}</div>
</div>
</a>
{/if}
<style>
.card {
display: block;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
transition: 0.3s;
border-radius: 5px; /* 5px rounded corners */
max-width: 500px;
text-decoration: none;
color: white;
background-color: #1e1e1e;
overflow: hidden;
}
/* Add rounded corners to the top left and the top right corner of the image */ .card:hover .container {
img { padding-left: 20px;
border-radius: 5px 5px 0 0; }
max-height: 250px;
min-height: 160px;
width: 100%;
object-fit: cover;
object-position: top;
}
.card:hover .container { /* On mouse-over, add a deeper shadow */
padding-left: 20px; .card:hover {
} box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}
/* On mouse-over, add a deeper shadow */ /* Add some padding inside the card container */
.card:hover { .container {
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2); transition: padding-left 0.2s;
} padding: 16px;
}
/* Add some padding inside the card container */ .place {
.container { font-weight: 600;
transition: padding-left .2s; color: #ff6e40;
padding: 16px; }
}
.place {
font-weight: 600;
color: #ff6e40;
}
</style> </style>

View file

@ -2,6 +2,7 @@
<script> <script>
import { onMount } from 'svelte' import { onMount } from 'svelte'
import { when } from './helpers'
export let baseurl = '' export let baseurl = ''
export let title = '' export let title = ''
export let maxlength = false export let maxlength = false
@ -51,31 +52,6 @@
return 'center center' return 'center center'
} }
function _when(unix_timestamp, type = 'long') {
const options =
type === 'long'
? {
weekday: 'long',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}
: { hour: '2-digit', minute: '2-digit' }
const d = new Date(unix_timestamp * 1000).toLocaleString(undefined, options)
return d
}
function when(event) {
if (event.multidate) {
return _when(event.start_datetime) + ' - ' + _when(event.end_datetime)
}
return (
_when(event.start_datetime) +
(event.end_datetime ? '-' + _when(event.end_datetime, 'short') : '')
)
}
onMount(() => { onMount(() => {
mounted = true mounted = true
update() update()

View file

@ -0,0 +1,24 @@
function formatDatetime(timestamp, type = 'long') {
const options =
type === 'long'
? {
weekday: 'long',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}
: { hour: '2-digit', minute: '2-digit' }
return new Date(timestamp * 1000).toLocaleString(undefined, options)
}
export function when(event) {
if (event.multidate) {
return formatDatetime(event.start_datetime) + ' - ' + formatDatetime(event.end_datetime)
}
return (
formatDatetime(event.start_datetime) +
(event.end_datetime ? '-' + formatDatetime(event.end_datetime, 'short') : '')
)
}

File diff suppressed because it is too large Load diff