start a better events selection

This commit is contained in:
les
2020-10-17 00:41:21 +02:00
parent b80eb3f6e3
commit 3f892f7f4a
18 changed files with 199 additions and 266 deletions

View File

@@ -19,6 +19,9 @@ import { take, get } from 'lodash'
export default {
name: 'Calendar',
props: {
events: { type: Array, default: [] }
},
data () {
const month = dayjs().month() + 1
const year = dayjs().year()
@@ -27,7 +30,6 @@ export default {
}
},
computed: {
...mapGetters(['filteredEventsWithPast']),
...mapState(['tags', 'filters', 'in_past', 'settings']),
// TODO: could be better
@@ -48,7 +50,7 @@ export default {
return color
}
attributes = attributes.concat(this.filteredEventsWithPast
attributes = attributes.concat(this.events
.filter(e => !e.multidate)
.map(e => {
return {
@@ -58,7 +60,7 @@ export default {
}
}))
attributes = attributes.concat(this.filteredEventsWithPast
attributes = attributes.concat(this.events
.filter(e => e.multidate)
.map(e => ({
key: e.id,
@@ -72,11 +74,12 @@ export default {
methods: {
...mapActions(['updateEvents', 'showPastEvents']),
updatePage (page) {
this.updateEvents(page)
this.$emit('monthchange', page)
},
click (day) {
const element = document.getElementById(day.day)
if (element) { element.scrollIntoView() } // Even IE6 supports this
this.$emit('dayclick', day)
// const element = document.getElementById(day.day)
// if (element) { element.scrollIntoView() } // Even IE6 supports this
}
}
}

View File

@@ -9,11 +9,11 @@
v-card-text
time.text-h6(:datetime='event.start_datetime|unixFormat("YYYY-MM-DD HH:mm")') <v-icon>mdi-event</v-icon> {{ event|when }}
v-btn.d-block.text-h6(text color='primary' big) <v-icon>mdi-map-marker</v-icon> {{event.place.name}}
v-btn.d-block.text-h6(text color='primary' big @click="$emit('placeclick', event.place.id)") <v-icon>mdi-map-marker</v-icon> {{event.place.name}}
v-card-actions
v-chip.ml-1(v-for='tag in event.tags' link
:key='tag' outlined color='primary' @click='addTag(tag)') {{tag}}
:key='tag' outlined color='primary' @click="$emit('tagclick',tag)") {{tag}}
v-spacer
v-menu(offset-y)
@@ -31,20 +31,9 @@ import { mapState, mapActions } from 'vuex'
export default {
props: {
event: { type: Object, default: () => ({}) },
showTags: {
type: Boolean,
default: true
},
showImage: {
type: Boolean,
default: true
}
},
computed: {
...mapState(['settings', 'filters']),
description () {
return this.event.description.replace(/(<br>)+/g, '<br>')
},
...mapState(['settings']),
show_footer () {
return (this.event.tags.length || this.event.resources.length)
}

View File

@@ -10,18 +10,26 @@
//- this is needed as v-calendar does not support SSR
//- https://github.com/nathanreyes/v-calendar/issues/336
client-only
Calendar
Calendar(@dayclick='dayClick'
@monthchange='monthChange' :events='events')
.col
Search
Search(
:filters='filters'
@update='updateFilters'
)
.text-h3.text-center(v-if='selectedDay') {{selectedDay|day}}
#events
Event(v-for='event in events' :key='event.id' :event='event')
Event(v-for='event in events'
:key='event.id' :event='event'
@tagclick='tagClick' @placeclick='placeClick')
</template>
<script>
import { mapGetters, mapState } from 'vuex'
import { mapState, mapActions } from 'vuex'
import dayjs from 'dayjs'
import Event from '@/components/Event'
import Announcement from '@/components/Announcement'
import Calendar from '@/components/Calendar'
@@ -29,13 +37,66 @@ import Search from '@/components/Search'
export default {
name: 'Home',
data () {
return {
events: [],
start: null,
end: null,
filters: { tags: [], places: []},
selectedDay: null
}
},
components: { Calendar, Event, Search, Announcement },
computed: {
events () {
return this.in_past ? this.filteredEventsWithPast : this.filteredEvents
...mapState(['settings', 'announcements'])
},
...mapGetters(['filteredEvents', 'filteredEventsWithPast']),
...mapState(['settings', 'in_past', 'announcements'])
methods: {
...mapActions(['setFilters']),
async updateEvents () {
this.events = await this.$api.getEvents({
start: this.start, end: this.end,
places: this.filters.places, tags: this.filters.tags
})
this.setFilters(this.filters)
},
placeClick (place_id) {
if (this.filters.places.includes(place_id)) {
this.filters.places = this.filters.places.filter(p_id => p_id !== place_id)
} else {
this.filters.places.push(place_id)
}
this.updateEvents()
},
tagClick (tag) {
if (this.filters.tags.includes(tag)) {
this.filters.tags = this.filters.tags.filter(t => t !== tag)
} else {
this.filters.tags.push(tag)
}
this.updateEvents()
},
updateFilters (filters) {
this.filters = filters
this.updateEvents()
},
monthChange (page) {
this.start = dayjs().year(page.year).month(page.month - 1).startOf('month').startOf('week').unix()
this.end = dayjs().year(page.year).month(page.month - 1).endOf('month').endOf('week').unix()
this.updateEvents ()
},
async dayClick (day) {
const datetime = day.dateTime / 1000
if (this.selectedDay === datetime) {
this.selectedDay = null
this.updateEvents()
return
}
this.selectedDay = datetime
this.events = await this.$api.getEvents({
start: this.selectedDay,
end: this.selectedDay+24*60*60
})
}
},
head () {
return {

View File

@@ -77,8 +77,8 @@ export default {
computed: {
...mapState(['filters', 'settings']),
feedLink () {
const tags = this.filters.tags.join(',')
const places = this.filters.places.join(',')
const tags = this.filters.tags && this.filters.tags.join(',')
const places = this.filters.places && this.filters.places.join(',')
let query = ''
if (tags || places) {
query = '?'

View File

@@ -4,28 +4,27 @@
v-if='recurrentFilter && settings.allow_recurrent_event'
inset color='primary'
:label="$t('event.show_recurrent')"
v-model='showRecurrent')
@change="v => $emit('showrecurrent', v)")
v-switch.mt-0(
v-if='pastFilter' inset color='primary'
:label="$t('event.show_past')"
v-model='showPast')
@change="v => $emit('showpast', v)")
v-autocomplete.mt-0(
:label='$t("common.search")'
:items='keywords'
v-model='filter'
@change='change'
:value='selectedFilters'
clearable
:search-input.sync='search'
item-text='label'
item-value='id'
chips rounded outlined single-line
return-object
chips single-line
multiple)
template(v-slot:selection="data")
v-chip(v-bind="data.attrs"
:input-value="data.selected"
close
@click="data.select"
@click:close="remove(data.item)")
:input-value="data.selected")
v-avatar(left)
v-icon {{data.item.type === 'place' ? 'mdi-map-marker' : 'mdi-tag' }}
span {{ data.item.label }}
@@ -41,8 +40,9 @@ import { mapState, mapActions } from 'vuex'
export default {
name: 'Search',
props: {
pastFilter: Boolean,
recurrentFilter: Boolean
pastFilter: { type: Boolean, default: true },
recurrentFilter: { type: Boolean, default: true },
filters: { type: Object, default: () => {} }
},
data () {
return {
@@ -51,80 +51,29 @@ export default {
}
},
computed: {
filter: {
set (value) {
console.error('set', value)
this.tmpfilter = value
},
get () {
// console.error('dentro get')
// const tags = this.filters.tags.map(t => t.tag)// ({ type: 'tag', label: t.tag, weigth: t.weigth, id: t.tag }))
// const places = this.filters.places.map(p => p.name) //({ type: 'place', label: p.name, weigth: p.weigth, id: p.id }))
// const keywords = tags.concat(places).sort((a, b) => b.weigth - a.weigth)
// const ret = tags.concat(places)
// console.error(ret)
return this.tmpfilter
// const ret = this.filters.tags
// console.error(ret)
// return ret
// return ['ciao']
}
},
...mapState(['tags', 'places', 'filters', 'settings']),
// selectedPlaces () {
// return this.places.filter(p => this.filters.places.includes(p.id))
// },
keywords () {
const tags = this.tags.filter(t => !this.filters.tags.includes(t.tag)).map(t => ({ type: 'tag', label: t.tag, weigth: t.weigth, id: t.tag }))
const places = this.places.filter(p => !this.filters.places.includes(p.id))
...mapState(['tags', 'places', , 'settings']),
selectedFilters () {
const tags = this.tags.filter(t => this.filters.tags.includes(t.tag)).map(t => ({ type: 'tag', label: t.tag, weigth: t.weigth, id: t.tag }))
const places = this.places.filter(p => this.filters.places.includes(p.id))
.map(p => ({ type: 'place', label: p.name, weigth: p.weigth, id: p.id }))
const keywords = tags.concat(places).sort((a, b) => b.weigth - a.weigth)
return keywords
},
showPast: {
set (value) { this.showPastEvents(value) },
get () { return this.filters.show_past_events }
keywords () {
const tags = this.tags.map(t => ({ type: 'tag', label: t.tag, weigth: t.weigth, id: t.tag }))
const places = this.places.map(p => ({ type: 'place', label: p.name, weigth: p.weigth, id: p.id }))
const keywords = tags.concat(places).sort((a, b) => b.weigth - a.weigth)
return keywords
},
showRecurrent: {
set (value) { this.showRecurrentEvents(value) },
get () { return this.filters.show_recurrent_events }
}
// filter () {
// return this.filters.tags.concat(this.filters.places)
// }
},
methods: {
...mapActions(['setSearchPlaces', 'setSearchTags',
'showPastEvents', 'showRecurrentEvents', 'updateEvent']),
remove (item) {
console.error(item)
if (item.type === 'tag') {
this.removeTag(item.id)
} else {
this.removePlace(item.id)
change (filters) {
filters = {
tags: filters.filter(t => t.type === 'tag').map(t => t.id),
places: filters.filter(p => p.type === 'place').map(p => p.id)
}
this.$emit('update', filters)
},
removeTag (tag) {
this.setSearchTags(this.filters.tags.filter(t => t !== tag))
},
removePlace (place) {
this.setSearchPlaces(this.filters.places.filter(p => p !== place))
},
querySearch (queryString, cb) {
const ret = this.keywords
.filter(k => !this.filter.map(f => f.id).includes(k.id))
.filter(k => k.label.toLowerCase().includes(queryString))
.slice(0, 5)
cb(ret)
},
addFilter (item) {
if (item.type === 'tag') {
this.setSearchTags(this.filters.tags.concat(item.id))
} else {
this.setSearchPlaces(this.filters.places.concat(item.id))
}
this.search = ''
}
}
}
</script>

View File

@@ -4,5 +4,7 @@ export default {
es: 'Español',
ca: 'Català',
pl: 'Polski',
eu: 'Euskara'
eu: 'Euskara',
nb_NO: 'Norwegian Bokmål',
fr: 'Francais'
}

View File

@@ -41,6 +41,7 @@ module.exports = {
'@/plugins/vue-clipboard', // vuetify
'@/plugins/axios', // axios baseurl configuration
'@/plugins/validators', // inject validators
'@/plugins/api', // api helpers
{ src: '@/plugins/v-calendar', ssr: false } // calendar, fix ssr
],

View File

@@ -56,9 +56,7 @@ export default {
reader.readAsText(this.file)
reader.onload = () => {
const data = reader.result
console.error(data)
const event = ical.parse(data)
console.error(event)
this.event = {
title: event.name
}
@@ -79,7 +77,6 @@ export default {
this.event = ret
// check if contain an h-event
this.$emit('imported', ret)
console.error(ret)
} catch (e) {
console.error(e)
this.error = true

View File

@@ -281,7 +281,6 @@ export default {
}
if (this.event.image) {
console.error(this.event.image)
formData.append('image', this.event.image)
}
formData.append('title', this.event.title)
@@ -307,7 +306,6 @@ export default {
this.loading = false
this.$root.$message(this.$auth.loggedIn ? 'event.added' : 'event.added_anon', { color: 'success' })
} catch (e) {
console.error(e.response)
switch (e.request.status) {
case 413:
this.$root.$message('event.image_too_big', { color: 'error' })

View File

@@ -17,7 +17,6 @@ export default {
try {
const id = Number(params.id)
const announcement = store.state.announcements.find(a => a.id === id)
console.error(announcement)
return { announcement }
} catch (e) {
error({ statusCode: 404, message: 'Announcement not found' })

View File

@@ -85,8 +85,7 @@ export default {
}
},
computed: {
...mapState(['filters', 'events', 'settings']),
...mapGetters(['filteredEvents']),
...mapState(['filters', 'settings']),
domain () {
const URL = url.parse(this.settings.baseurl)
return URL.hostname

34
plugins/api.js Normal file
View File

@@ -0,0 +1,34 @@
export default ({ $axios, store }, inject) => {
const api = {
/**
* Get events
*
* filter: {
* start_datetime: unix_timestamp (default now)
* end_datetime: unix_timestamp
* tags: [tag, list],
* places: [place_id],
* limit: (default ∞)
* }
*
*/
async getEvents (params) {
try {
const events = await $axios.$get(`/events`, { params: {
start: params.start,
end: params.end,
places: params.places && params.places.join(','),
tags: params.tags && params.tags.join(',')
}} )
return events
} catch (e) {
console.error(e)
return []
}
}
}
inject('api', api)
}

View File

@@ -417,17 +417,30 @@ const eventController = {
}
},
async _select (start = moment().unix(), limit = 100) {
async _select ({ start, end, tags, places}) {
const where = {
// confirmed event only
recurrent: null,
is_visible: true,
start_datetime: { [Op.gt]: start }
start_datetime: { [Op.gt]: start },
}
if (end) {
where['end_datetime'] = { [Op.lt]: end }
}
if (places) {
where.placeId = places.split(',')
}
let where_tags = {}
if (tags) {
where_tags = { where: { tag: tags.split(',') } }
}
const events = await Event.findAll({
where,
limit,
attributes: {
exclude: ['slug', 'likes', 'boost', 'userId', 'is_visible', 'createdAt', 'updatedAt', 'placeId']
// include: [[Sequelize.fn('COUNT', Sequelize.col('activitypub_id')), 'ressources']]
@@ -435,7 +448,7 @@ const eventController = {
order: ['start_datetime', [Tag, 'weigth', 'DESC']],
include: [
{ model: Resource, required: false, attributes: ['id'] },
{ model: Tag, attributes: ['tag'], required: false, through: { attributes: [] } },
{ model: Tag, attributes: ['tag'], required: tags ? true : false, ...where_tags, through: { attributes: [] } },
{ model: Place, required: false, attributes: ['id', 'name', 'address'] }
]
})
@@ -451,9 +464,14 @@ const eventController = {
* Select events based on params
*/
async select (req, res) {
const start = req.query.start || moment().unix()
const limit = req.query.limit || 100
res.json(await eventController._select(start, limit))
const start = req.query.start
const end = req.query.end
const tags = req.query.tags
const places = req.query.places
res.json(await eventController._select({
start, end, places, tags
}))
},
/**

View File

@@ -125,7 +125,6 @@ const settingsController = {
.resize(400)
.png({ quality: 90 })
.toFile(baseImgPath + '.png', async (err, info) => {
console.error(err)
const image = await readFile(baseImgPath + '.png')
const favicon = await toIco([image], { sizes: [64], resize: true })
writeFile(baseImgPath + '.ico', favicon)

View File

@@ -121,7 +121,7 @@ api.get('/export/:type', cors, exportController.export)
// get events in this range
// api.get('/event/:month/:year', cors, eventController.getAll)
api.get('/event', cors, eventController.select)
api.get('/events', cors, eventController.select)
api.get('/instances', isAdmin, instanceController.getAll)
api.get('/instances/:instance_domain', isAdmin, instanceController.get)

View File

@@ -115,7 +115,6 @@ module.exports = {
Microformats.get({ html: response.data, filter: ['h-event'] }, (err, data) => {
if (!data.items.length || !data.items[0].properties) return res.sendStatus(404)
const event = data.items[0].properties
console.error(event)
return res.json({
title: get(event, 'name[0]', ''),
description: get(event, 'content[0]', ''),

View File

@@ -66,8 +66,8 @@ app.use((error, req, res, next) => {
// first nuxt component is ./pages/index.vue (with ./layouts/default.vue)
// prefill current events, tags, places and announcements (used in every path)
app.use(async (req, res, next) => {
const start_datetime = getUnixTime(startOfWeek(startOfMonth(new Date())))
req.events = await eventController._select(start_datetime, 100)
// const start_datetime = getUnixTime(startOfWeek(startOfMonth(new Date())))
// req.events = await eventController._select(start_datetime, 100)
req.meta = await eventController._getMeta()
req.announcements = await announceController._getVisible()
next()

View File

@@ -1,10 +1,10 @@
import moment from 'moment-timezone'
import dayjs from 'dayjs'
import intersection from 'lodash/intersection'
export const state = () => ({
locale: '',
user_locale: {},
events: [],
filters: { tags: [], places: [] },
tags: [],
places: [],
settings: {
@@ -20,113 +20,27 @@ export const state = () => ({
enable_trusted_instances: true,
trusted_instances: []
},
in_past: false,
filters: {
tags: [],
places: [],
show_past_events: false,
show_recurrent_events: false,
show_pinned_event: false
},
announcements: []
})
export const getters = {
// filter matches search tag/place
filteredEvents: state => {
const search_for_tags = !!state.filters.tags.length
const search_for_places = !!state.filters.places.length
return state.events.filter(e => {
// filter past events
if (!state.filters.show_past_events && e.past) { return false }
// filter recurrent events
if (!state.filters.show_recurrent_events && e.parentId) { return false }
if (search_for_places && !state.filters.places.includes(e.place.id)) {
return false
}
if (search_for_tags) {
const common_tags = intersection(e.tags, state.filters.tags)
if (common_tags.length === 0) { return false }
}
if (!search_for_places && !search_for_tags) { return true }
return true
})
},
// filter matches search tag/place including past events
filteredEventsWithPast: state => {
const search_for_tags = !!state.filters.tags.length
const search_for_places = !!state.filters.places.length
return state.events.filter(e => {
// filter recurrent events
if (!state.filters.show_recurrent_events && e.parentId) { return false }
if (search_for_places && !state.filters.places.includes(e.place.id)) {
return false
}
if (search_for_tags) {
const common_tags = intersection(e.tags, state.filters.tags)
if (common_tags.length === 0) { return false }
}
return true
})
}
}
export const mutations = {
setEvents (state, events) {
// set`past` and `newDay` flags to event
let lastDay = null
state.events = events.map(e => {
const currentDay = moment.unix(e.start_datetime).date()
e.newDay = (!lastDay || lastDay !== currentDay) && currentDay
lastDay = currentDay
const end_datetime = e.end_datetime || e.start_datetime + 3600 * 2
const past = ((moment().unix()) - end_datetime) > 0
e.past = !!past
return e
})
},
addEvent (state, event) {
state.events.push(event)
},
updateEvent (state, event) {
state.events = state.events.map((e) => {
if (e.id !== event.id) { return e }
return event
})
},
delEvent (state, eventId) {
state.events = state.events.filter(ev => {
return ev.id !== eventId
})
},
// setEvents (state, events) {
// // set`past` and `newDay` flags to event
// let lastDay = null
// state.events = events.map(e => {
// const currentDay = dayjs.unix(e.start_datetime).date()
// e.newDay = (!lastDay || lastDay !== currentDay) && currentDay
// lastDay = currentDay
// const end_datetime = e.end_datetime || e.start_datetime + 3600 * 2
// const past = ((dayjs().unix()) - end_datetime) > 0
// e.past = !!past
// return e
// })
// },
update (state, { tags, places }) {
state.tags = tags
state.places = places
},
setSearchTags (state, tags) {
state.filters.tags = tags
},
setSearchPlaces (state, places) {
state.filters.places = places
},
showPastEvents (state, show) {
state.filters.show_past_events = show
},
showRecurrentEvents (state, show) {
state.filters.show_recurrent_events = show
},
setSettings (state, settings) {
state.settings = settings
},
@@ -136,8 +50,9 @@ export const mutations = {
setLocale (state, locale) {
state.locale = locale
},
setPast (state, in_past) {
state.in_past = in_past
setFilters (state, filters) {
state.filters.tags = [...filters.tags]
state.filters.places = [...filters.places]
},
setAnnouncements (state, announcements) {
state.announcements = announcements
@@ -149,23 +64,8 @@ export const actions = {
// we use it to get configuration from db, set locale, etc...
nuxtServerInit ({ commit }, { req }) {
commit('setSettings', req.settings)
commit('setEvents', req.events)
commit('setAnnouncements', req.announcements)
commit('update', req.meta)
// apply settings
commit('showRecurrentEvents', req.settings.allow_recurrent_event && req.settings.recurrent_event_visible)
},
async updateEvents ({ commit }, page) {
const [month, year] = [moment().month(), moment().year()]
const in_past = page.year < year || (page.year === year && page.month <= month)
// commit('setPast', in_past)
const start_datetime = moment().year(page.year).month(page.month - 1).startOf('month').startOf('week').unix()
const query = `start=${start_datetime}`
const events = await this.$axios.$get(`/event?${query}`)
commit('setEvents', events)
commit('showPastEvents', in_past)
},
async updateAnnouncements ({ commit }) {
const announcements = await this.$axios.$get('/announcements')
@@ -176,16 +76,13 @@ export const actions = {
commit('update', { tags, places })
},
async addEvent ({ commit }, formData) {
const event = await this.$axios.$post('/event', formData)
if (event.user) {
commit('addEvent', event)
}
await this.$axios.$post('/event', formData)
},
async updateEvent ({ commit }, formData) {
const event = await this.$axios.$put('/event', formData)
if (event.user) {
commit('updateEvent', event)
}
await this.$axios.$put('/event', formData)
},
setFilters({ commit }, filters) {
commit('setFilters', filters)
},
setAnnouncements ({ commit }, announcements) {
commit('setAnnouncements', announcements)
@@ -193,18 +90,6 @@ export const actions = {
delEvent ({ commit }, eventId) {
commit('delEvent', eventId)
},
setSearchTags ({ commit }, tags) {
commit('setSearchTags', tags)
},
setSearchPlaces ({ commit }, places) {
commit('setSearchPlaces', places)
},
showPastEvents ({ commit }, show) {
commit('showPastEvents', show)
},
showRecurrentEvents ({ commit }, show) {
commit('showRecurrentEvents', show)
},
async setSetting ({ commit }, setting) {
await this.$axios.$post('/settings', setting)
commit('setSetting', setting)