old client structure

This commit is contained in:
Matteo Pagliazzi
2019-10-01 11:44:38 +02:00
parent 5b61f65711
commit b44fbdcb14
906 changed files with 44 additions and 44 deletions
@@ -0,0 +1,401 @@
<template lang="pug">
.row
challenge-modal(@updatedChallenge='updatedChallenge')
leave-challenge-modal(:challengeId='challenge._id')
close-challenge-modal(:members='members', :challengeId='challenge._id', :prize='challenge.prize')
challenge-member-progress-modal(:challengeId='challenge._id')
.col-12.col-md-8.standard-page
.row
.col-12.col-md-6
h1(v-markdown='challenge.name')
div
span.mr-1.ml-0.d-block
strong(v-once) {{ $t('createdBy') }}:
user-link.mx-1(:user="challenge.leader")
span.mr-1.ml-0.d-block(v-if="challenge.group && challenge.group.name !== 'Tavern'")
strong(v-once) {{ $t(challenge.group.type) }}:
group-link.mx-1(:group="challenge.group")
// @TODO: make challenge.author a variable inside the createdBy string (helps with RTL languages)
// @TODO: Implement in V2 strong.margin-left(v-once)
.svg-icon.calendar-icon(v-html="icons.calendarIcon")
| {{$t('endDate')}}
// "endDate": "End Date: <% endDate %>",
// span {{challenge.endDate}}
.tags
span.tag(v-for='tag in challenge.tags') {{tag}}
.col-12.col-md-6.text-right
.box(@click="showMemberModal()")
.svg-icon.member-icon(v-html="icons.memberIcon")
| {{challenge.memberCount}}
.details(v-once) {{$t('participantsTitle')}}
.box
.svg-icon.gem-icon(v-html="icons.gemIcon")
| {{challenge.prize}}
.details(v-once) {{$t('prize')}}
.row.challenge-actions
.col-12.col-md-6
strong.view-progress {{ $t('viewProgressOf') }}
member-search-dropdown(:text="$t('selectParticipant')", :members='members', :challengeId='challengeId', @member-selected='openMemberProgressModal')
.col-12.col-md-6.text-right
span(v-if='isLeader || isAdmin')
b-dropdown.create-dropdown(:text="$t('addTaskToChallenge')", :variant="'success'")
b-dropdown-item(v-for="type in columns", :key="type", @click="createTask(type)")
| {{$t(type)}}
task-modal(
:task="workingTask",
:purpose="taskFormPurpose",
@cancel="cancelTaskModal()",
ref="taskModal",
:challengeId="challengeId",
@taskCreated='taskCreated',
@taskEdited='taskEdited',
@taskDestroyed='taskDestroyed'
)
.row
task-column.col-12.col-sm-6(
v-for="column in columns",
:type="column",
:key="column",
:taskListOverride='tasksByType[column]',
:showOptions="showOptions",
@editTask="editTask",
@taskDestroyed="taskDestroyed",
v-if='tasksByType[column].length > 0')
.col-12.col-md-4.sidebar.standard-page
.button-container(v-if='canJoin')
button.btn.btn-success(v-once, @click='joinChallenge()') {{$t('joinChallenge')}}
.button-container(v-if='isLeader || isAdmin')
button.btn.btn-primary(v-once, @click='edit()') {{$t('editChallenge')}}
.button-container(v-if='isLeader || isAdmin')
button.btn.btn-primary(v-once, @click='cloneChallenge()') {{$t('clone')}}
.button-container(v-if='isLeader || isAdmin')
button.btn.btn-primary(v-once, @click='exportChallengeCsv()') {{$t('exportChallengeCsv')}}
.button-container(v-if='isLeader || isAdmin')
button.btn.btn-danger(v-once, @click='closeChallenge()') {{$t('endChallenge')}}
div
sidebar-section(:title="$t('challengeSummary')")
p(v-markdown='challenge.summary')
sidebar-section(:title="$t('challengeDescription')")
p(v-markdown='challenge.description')
.text-center(v-if='isMember')
button.btn.btn-danger(v-once, @click='leaveChallenge()') {{$t('leaveChallenge')}}
</template>
<style lang='scss' scoped>
@import '~client/assets/scss/colors.scss';
h1 {
color: $purple-200;
margin-bottom: 8px;
}
.margin-left {
margin-left: 1em;
}
span {
margin-left: .5em;
}
.button-container {
margin-bottom: 1em;
button {
width: 100%;
}
}
.calendar-icon {
width: 12px;
display: inline-block;
margin-right: .2em;
}
.tags {
margin-top: 1em;
}
.tag {
border-radius: 30px;
background-color: $gray-600;
padding: .5em;
}
.sidebar {
background-color: $gray-600;
}
.box {
display: inline-block;
padding: 1em;
border-radius: 2px;
background-color: $white;
box-shadow: 0 2px 2px 0 rgba(26, 24, 29, 0.16), 0 1px 4px 0 rgba(26, 24, 29, 0.12);
margin-left: 1em;
width: 120px;
height: 76px;
text-align: center;
font-size: 20px;
vertical-align: bottom;
.svg-icon {
width: 30px;
display: inline-block;
margin-right: .2em;
vertical-align: bottom;
}
.details {
font-size: 12px;
margin-top: 0.4em;
color: $gray-200;
}
}
.description-section {
margin-top: 2em;
}
.challenge-actions {
margin-top: 1em;
margin-bottom: 2em;
.view-progress {
margin-right: .5em;
}
}
</style>
<script>
const TASK_KEYS_TO_REMOVE = ['_id', 'completed', 'date', 'dateCompleted', 'history', 'id', 'streak', 'createdAt', 'challenge'];
import Vue from 'vue';
import findIndex from 'lodash/findIndex';
import cloneDeep from 'lodash/cloneDeep';
import omit from 'lodash/omit';
import uuid from 'uuid';
import { mapState } from 'client/libs/store';
import memberSearchDropdown from 'client/components/members/memberSearchDropdown';
import closeChallengeModal from './closeChallengeModal';
import Column from '../tasks/column';
import TaskModal from '../tasks/taskModal';
import markdownDirective from 'client/directives/markdown';
import challengeModal from './challengeModal';
import challengeMemberProgressModal from './challengeMemberProgressModal';
import challengeMemberSearchMixin from 'client/mixins/challengeMemberSearch';
import leaveChallengeModal from './leaveChallengeModal';
import sidebarSection from '../sidebarSection';
import userLink from '../userLink';
import groupLink from '../groupLink';
import taskDefaults from 'common/script/libs/taskDefaults';
import gemIcon from 'assets/svg/gem.svg';
import memberIcon from 'assets/svg/member-icon.svg';
import calendarIcon from 'assets/svg/calendar.svg';
export default {
props: ['challengeId'],
mixins: [challengeMemberSearchMixin],
directives: {
markdown: markdownDirective,
},
components: {
closeChallengeModal,
leaveChallengeModal,
challengeModal,
challengeMemberProgressModal,
memberSearchDropdown,
sidebarSection,
TaskColumn: Column,
TaskModal,
userLink,
groupLink,
},
data () {
return {
searchId: '',
columns: ['habit', 'daily', 'todo', 'reward'],
icons: Object.freeze({
gemIcon,
memberIcon,
calendarIcon,
}),
challenge: {},
members: [],
tasksByType: {
habit: [],
daily: [],
todo: [],
reward: [],
},
editingTask: {},
creatingTask: {},
workingTask: {},
taskFormPurpose: 'create',
searchTerm: '',
memberResults: [],
};
},
computed: {
...mapState({user: 'user.data'}),
isMember () {
return this.user.challenges.indexOf(this.challenge._id) !== -1;
},
isLeader () {
if (!this.challenge.leader) return false;
return this.user._id === this.challenge.leader._id;
},
isAdmin () {
return Boolean(this.user.contributor.admin);
},
canJoin () {
return !this.isMember;
},
showOptions () {
return this.isLeader;
},
},
mounted () {
if (!this.searchId) this.searchId = this.challengeId;
if (!this.challenge._id) this.loadChallenge();
},
async beforeRouteUpdate (to, from, next) {
this.searchId = to.params.challengeId;
await this.loadChallenge();
next();
},
methods: {
cleanUpTask (task) {
let cleansedTask = omit(task, TASK_KEYS_TO_REMOVE);
// Copy checklists but reset to uncomplete and assign new id
if (!cleansedTask.checklist) cleansedTask.checklist = [];
cleansedTask.checklist.forEach((item) => {
item.completed = false;
item.id = uuid();
});
if (cleansedTask.type !== 'reward') {
delete cleansedTask.value;
}
return cleansedTask;
},
async loadChallenge () {
this.challenge = await this.$store.dispatch('challenges:getChallenge', {challengeId: this.searchId});
this.members = await this.loadMembers({ challengeId: this.searchId, includeAllPublicFields: true });
let tasks = await this.$store.dispatch('tasks:getChallengeTasks', {challengeId: this.searchId});
this.tasksByType = {
habit: [],
daily: [],
todo: [],
reward: [],
};
tasks.forEach((task) => {
this.tasksByType[task.type].push(task);
});
},
/**
* Method for loading members of a group, with optional parameters for
* modifying requests.
*
* @param {Object} payload Used for modifying requests for members
*/
loadMembers (payload = null) {
// Remove unnecessary data
if (payload && payload.groupId) {
delete payload.groupId;
}
return this.$store.dispatch('members:getChallengeMembers', payload);
},
editTask (task) {
this.taskFormPurpose = 'edit';
this.editingTask = cloneDeep(task);
this.workingTask = this.editingTask;
// Necessary otherwise the first time the modal is not rendered
Vue.nextTick(() => {
this.$root.$emit('bv::show::modal', 'task-modal');
});
},
createTask (type) {
this.taskFormPurpose = 'create';
this.creatingTask = taskDefaults({type, text: ''}, this.user);
this.workingTask = this.creatingTask;
// Necessary otherwise the first time the modal is not rendered
Vue.nextTick(() => {
this.$root.$emit('bv::show::modal', 'task-modal');
});
},
cancelTaskModal () {
this.editingTask = null;
this.creatingTask = null;
},
taskCreated (task) {
this.tasksByType[task.type].push(task);
},
taskEdited (task) {
let index = findIndex(this.tasksByType[task.type], (taskItem) => {
return taskItem._id === task._id;
});
this.tasksByType[task.type].splice(index, 1, task);
},
taskDestroyed (task) {
let index = findIndex(this.tasksByType[task.type], (taskItem) => {
return taskItem._id === task._id;
});
this.tasksByType[task.type].splice(index, 1);
},
showMemberModal () {
this.$root.$emit('habitica:show-member-modal', {
challengeId: this.challenge._id,
groupId: 'challenge', // @TODO: change these terrible settings
group: this.challenge.group,
memberCount: this.challenge.memberCount,
viewingMembers: this.members,
fetchMoreMembers: this.loadMembers,
});
},
async joinChallenge () {
this.user.challenges.push(this.searchId);
await this.$store.dispatch('challenges:joinChallenge', {challengeId: this.searchId});
await this.$store.dispatch('tasks:fetchUserTasks', {forceLoad: true});
},
async leaveChallenge () {
this.$root.$emit('bv::show::modal', 'leave-challenge-modal');
},
closeChallenge () {
this.$root.$emit('bv::show::modal', 'close-challenge-modal');
},
edit () {
this.$root.$emit('habitica:update-challenge', {
challenge: this.challenge,
});
},
// @TODO: view members
updatedChallenge (eventData) {
Object.assign(this.challenge, eventData.challenge);
},
openMemberProgressModal (member) {
this.$root.$emit('habitica:challenge:member-progress', {
progressMemberId: member._id,
isLeader: this.isLeader,
isAdmin: this.isAdmin,
});
},
async exportChallengeCsv () {
// let response = await this.$store.dispatch('challenges:exportChallengeCsv', {
// challengeId: this.searchId,
// });
window.location = `/api/v4/challenges/${this.searchId}/export/csv`;
},
cloneChallenge () {
this.$root.$emit('habitica:clone-challenge', {
challenge: this.challenge,
});
},
},
};
</script>
@@ -0,0 +1,391 @@
<template lang="pug">
.challenge
.challenge-prize
.number
span.svg-icon(v-html="icons.gemIcon")
span.value {{challenge.prize}}
.label {{ $t('prize') }}
.challenge-header
router-link(
:to="{ name: 'challenge', params: { challengeId: challenge._id } }"
)
h3.challenge-title(v-markdown='challenge.name')
.meta-info
.member-count
.svg-icon.user-icon(v-html="icons.memberIcon")
span.count-label {{challenge.memberCount}}
.divider
.official(v-if="isOfficial")
.svg-icon.user-icon(v-html="icons.officialIcon")
.owner(v-if="fullLayout")
.owner-item
strong {{ $t('createdBy') }}:
user-link.mx-1(:user="challenge.leader")
.owner-item(v-if="challenge.group && !isTavern(challenge.group)")
strong {{ $t(challenge.group.type) }}:
group-link.mx-1(:group="challenge.group")
category-tags.challenge-categories(
:categories="challenge.categories",
:owner="isOwner",
:member="isMember",
)
.challenge-description(v-markdown='challenge.summary')
.well-wrapper(v-if="fullLayout")
.well
div(v-for="task in tasksData", :class="{'muted': task.value === 0}")
.number
.svg-icon(v-html="task.icon", :class="task.label + '-icon'")
span.value {{ task.value }}
.label {{$t(task.label)}}
</template>
<style lang="scss">
@import '~client/assets/scss/colors.scss';
// Have to use this, because v-markdown creates p element in h3. Scoping doesn't work with it.
.challenge-title > p {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
max-height: 3em;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-word;
font-size: 20px;
font-weight: bold;
font-style: normal;
font-stretch: condensed;
line-height: 1.4;
letter-spacing: normal;
color: $gray-10;
}
</style>
<style lang="scss" scoped>
@import '~client/assets/scss/colors.scss';
.challenge {
background-color: $white;
box-shadow: 0 2px 2px 0 rgba($black, 0.15), 0 1px 4px 0 rgba($black, 0.1);
margin-bottom: 1em;
border-radius: 4px;
padding-bottom: .5em;
.number {
display: flex;
align-items: center;
justify-content: center;
.svg-icon {
margin-top: -.2em;
}
.value {
margin-left: .5em;
font-size: 24px;
}
}
.label {
font-size: .9em;
}
.official {
margin-right: 8px;
}
.challenge-prize {
text-align: center;
color: $gems-color;
display: inline-block;
float: right;
padding: 18px 24px;
margin-left: 1em;
background: #24cc8f19;
border-bottom-left-radius: 4px;
width: 107px;
height: 80px;
.svg-icon {
width: 24px;
height: 24px;
object-fit: contain;
}
.value {
margin-left: 8px;
font-size: 20px;
font-weight: bold;
font-style: normal;
font-stretch: normal;
line-height: 1.4;
letter-spacing: normal;
color: #1ca372;
}
.label {
margin-top: 4px;
font-size: 12px;
font-weight: bold;
font-style: normal;
font-stretch: normal;
line-height: 1.33;
letter-spacing: normal;
text-align: center;
color: #1ca372;
}
}
.divider {
width: 1px;
height: 16px;
background-color: $gray-600;
margin-right: 12px;
margin-left: 12px;
}
.challenge-header {
padding: 16px 20px;
}
.well-wrapper {
padding: 16px 20px 20px;
}
.challenge-header {
padding-bottom: 0;
}
.meta-info {
height: 24px;
margin-bottom: 8px;
}
.count-label {
font-size: 14px;
font-weight: normal;
font-style: normal;
font-stretch: normal;
line-height: 1.71;
letter-spacing: normal;
color: $gray-50;
margin-left: 4px;
}
.meta-info, .owner, .member-count {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
}
.meta-item, .owner-item {
display: inline-flex;
color: $gray-200;
align-items: center;
margin-right: 1em;
white-space: nowrap;
.svg-icon {
color: $gray-300;
width: 14px;
}
}
.challenge-categories {
clear: right;
display: flex;
padding: 0 20px 16px;
flex-wrap: wrap;
}
.user-icon {
width: 20px !important;
}
.habit-icon {
width: 30px;
}
.todo-icon {
width: 20px;
}
.daily-icon {
width: 24px;
}
.reward-icon {
width: 26px;
}
.challenge-description {
margin: 0 20px 0;
word-break: break-word;
font-size: 14px;
font-weight: normal;
font-style: normal;
font-stretch: normal;
line-height: 1.71;
letter-spacing: normal;
color: $gray-50;
}
.well {
display: flex;
align-items: center;
justify-content: space-evenly;
background-color: $gray-700;
text-align: center;
padding: 16px;
border-radius: .25em;
> div {
.value {
font-size: 20px;
font-weight: bold;
font-style: normal;
font-stretch: normal;
line-height: 1.4;
letter-spacing: normal;
color: $gray-50;
}
.label {
font-size: 12px;
font-weight: bold;
font-style: normal;
font-stretch: normal;
line-height: 1.33;
letter-spacing: normal;
text-align: center;
color: $gray-100;
}
.svg-icon {
object-fit: contain;
color: $gray-100;
}
}
> div.muted {
.value {
opacity: 0.5;
font-size: 20px;
font-weight: bold;
font-style: normal;
font-stretch: normal;
line-height: 1.4;
letter-spacing: normal;
color: $gray-50;
}
.label {
opacity: 0.5;
font-size: 12px;
font-weight: bold;
font-style: normal;
font-stretch: normal;
line-height: 1.33;
letter-spacing: normal;
text-align: center;
color: $gray-100;
}
.svg-icon {
object-fit: contain;
opacity: 0.5;
color: $gray-100;
}
}
}
}
</style>
<script>
import { TAVERN_ID } from '../../../common/script/constants';
import userLink from '../userLink';
import groupLink from '../groupLink';
import categoryTags from '../categories/categoryTags';
import markdownDirective from 'client/directives/markdown';
import {mapState} from 'client/libs/store';
import gemIcon from 'assets/svg/gem.svg';
import memberIcon from 'assets/svg/member-icon.svg';
import calendarIcon from 'assets/svg/calendar.svg';
import habitIcon from 'assets/svg/habit.svg';
import todoIcon from 'assets/svg/todo.svg';
import dailyIcon from 'assets/svg/daily.svg';
import rewardIcon from 'assets/svg/reward.svg';
import officialIcon from 'assets/svg/official.svg';
export default {
props: {
challenge: {
required: true,
},
fullLayout: {
default: true,
},
},
components: {
userLink,
groupLink,
categoryTags,
},
directives: {
markdown: markdownDirective,
},
data () {
return {
icons: Object.freeze({
gemIcon,
memberIcon,
calendarIcon,
officialIcon,
}),
};
},
computed: {
...mapState({user: 'user.data'}),
isOwner () {
return this.challenge.leader && this.challenge.leader._id === this.user._id;
},
isMember () {
return this.user.challenges.indexOf(this.challenge._id) !== -1;
},
isOfficial () {
return this.challenge.official || this.challenge.categories.map(category => category.slug).includes('habitica_official');
},
tasksData () {
return [
{
icon: habitIcon,
label: 'habit',
value: this.challenge.tasksOrder.habits.length,
},
{
icon: dailyIcon,
label: 'daily',
value: this.challenge.tasksOrder.dailys.length,
},
{
icon: todoIcon,
label: 'todo',
value: this.challenge.tasksOrder.todos.length,
},
{
icon: rewardIcon,
label: 'reward',
value: this.challenge.tasksOrder.rewards.length,
},
];
},
},
methods: {
isTavern (group) {
return group._id === TAVERN_ID;
},
},
};
</script>
@@ -0,0 +1,83 @@
<template lang="pug">
b-modal#challenge-member-modal(title="User Progress", size='lg')
.row.award-row(v-if='isLeader || isAdmin')
.col-12.text-center
button.btn.btn-primary(v-once, @click='closeChallenge()') {{ $t('awardWinners') }}
.row
task-column.col-6(
v-for="column in columns",
:type="column",
:key="column",
:taskListOverride='tasksByType[column]')
</template>
<style scoped>
.award-row {
padding-top: 1rem;
padding-bottom: 1rem;
}
</style>
<script>
import axios from 'axios';
import Column from '../tasks/column';
export default {
props: ['challengeId'],
components: {
TaskColumn: Column,
},
data () {
return {
columns: ['habit', 'daily', 'todo', 'reward'],
tasksByType: {
habit: [],
daily: [],
todo: [],
reward: [],
},
memberId: '',
isLeader: false,
isAdmin: false,
};
},
mounted () {
this.$root.$on('habitica:challenge:member-progress', (data) => {
if (!data.progressMemberId) return;
this.memberId = data.progressMemberId;
this.isLeader = data.isLeader;
this.isAdmin = data.isAdmin;
this.$root.$emit('bv::show::modal', 'challenge-member-modal');
});
},
beforeDestroy () {
this.$root.$off('habitica:challenge:member-progress');
},
watch: {
async memberId (id) {
if (!id) return;
this.tasksByType = {
habit: [],
daily: [],
todo: [],
reward: [],
};
let response = await axios.get(`/api/v4/challenges/${this.challengeId}/members/${this.memberId}`);
let tasks = response.data.data.tasks;
tasks.forEach((task) => {
this.tasksByType[task.type].push(task);
});
},
},
methods: {
async closeChallenge () {
this.challenge = await this.$store.dispatch('challenges:selectChallengeWinner', {
challengeId: this.challengeId,
winnerId: this.memberId,
});
this.$router.push('/challenges/myChallenges');
},
},
};
</script>
@@ -0,0 +1,478 @@
<template lang="pug">
b-modal#challenge-modal(:title="title", size='lg', @shown="shown")
.form
.form-group
label
strong(v-once) {{$t('name')}} *
b-form-input(type="text", :placeholder="$t('challengeNamePlaceholder')", v-model="workingChallenge.name")
.form-group
label
strong(v-once) {{$t('shortName')}} *
b-form-input(type="text", :placeholder="$t('shortNamePlaceholder')", v-model="workingChallenge.shortName")
.form-group
label
strong(v-once) {{$t('challengeSummary')}} *
div.summary-count {{ $t('charactersRemaining', {characters: charactersRemaining}) }}
textarea.summary-textarea.form-control(:placeholder="$t('challengeSummaryPlaceholder')", v-model="workingChallenge.summary")
.form-group
label
strong(v-once) {{$t('challengeDescription')}} *
a.float-right(v-markdown='$t("markdownFormattingHelp")')
textarea.description-textarea.form-control(:placeholder="$t('challengeDescriptionPlaceholder')", v-model="workingChallenge.description")
.form-group(v-if='creating')
label
strong(v-once) {{$t('challengeGuild')}} *
select.form-control(v-model='workingChallenge.group')
option(v-for='group in groups', :value='group._id') {{group.name}}
.form-group(v-if='workingChallenge.categories')
label
strong(v-once) {{$t('categories')}} *
div.category-wrap(@click.prevent="toggleCategorySelect")
span.category-select(v-if='workingChallenge.categories.length === 0') {{$t('none')}}
.category-label(v-for='category in workingChallenge.categories') {{$t(categoriesHashByKey[category])}}
.category-box(v-if="showCategorySelect && creating")
.form-check(
v-for="group in categoryOptions",
:key="group.key",
v-if='group.key !== "habitica_official" || user.contributor.admin'
)
.custom-control.custom-checkbox
input.custom-control-input(type="checkbox",
:value="group.key",
:id="`challenge-modal-cat-${group.key}`",
v-model="workingChallenge.categories")
label.custom-control-label(v-once, :for="`challenge-modal-cat-${group.key}`") {{ $t(group.label) }}
button.btn.btn-primary(@click.prevent="toggleCategorySelect") {{$t('close')}}
// @TODO: Implement in V2 .form-group
label
strong(v-once) {{$t('endDate')}}
b-form-input.end-date-input
.form-group(v-if='creating')
label
strong(v-once) {{$t('prize')}}
input(type='number', :min='minPrize', :max='maxPrize', v-model="workingChallenge.prize")
.row.footer-wrap
.col-12.text-center.submit-button-wrapper
.alert.alert-warning(v-if='insufficientGemsForTavernChallenge') You do not have enough gems to create a Tavern challenge
// @TODO if buy gems button is added, add analytics tracking to it
// see https://github.com/HabitRPG/habitica/blob/develop/website/views/options/social/challenges.jade#L134
button.btn.btn-primary(v-if='creating && !cloning', @click='createChallenge()', :disabled='loading') {{$t('createChallengeAddTasks')}}
button.btn.btn-primary(v-once, v-if='cloning', @click='createChallenge()', :disabled='loading') {{$t('createChallengeCloneTasks')}}
button.btn.btn-primary(v-once, v-if='!creating && !cloning', @click='updateChallenge()') {{$t('updateChallenge')}}
.col-12.text-center
p(v-once) {{$t('challengeMinimum')}}
</template>
<style lang='scss'>
@import '~client/assets/scss/colors.scss';
#challenge-modal {
h5 {
color: $purple-200;
margin-bottom: 1.5em;
}
.modal-header {
border: none;
}
.modal-footer {
display: none;
}
.summary-count {
font-size: 12px;
line-height: 1.33;
margin-top: 1em;
color: $gray-200;
text-align: right;
}
.summary-textarea {
height: 90px;
}
.description-textarea {
height: 220px;
}
label {
margin-right: .5em;
}
.end-date-input {
width: 150px;
display: inline-block;
}
.form-group {
margin-bottom: 2em;
}
.submit-button-wrapper {
margin-bottom: .5em;
}
.footer-wrap {
margin-top: 2em;
margin-bottom: 2em;
}
.category-wrap {
position: relative;
}
.category-box {
top: 20em !important;
z-index: 10;
}
}
</style>
<script>
import clone from 'lodash/clone';
import markdownDirective from 'client/directives/markdown';
import { TAVERN_ID, MIN_SHORTNAME_SIZE_FOR_CHALLENGES, MAX_SUMMARY_SIZE_FOR_CHALLENGES } from '../../../common/script/constants';
import { mapState } from 'client/libs/store';
export default {
props: ['groupId'],
directives: {
markdown: markdownDirective,
},
data () {
let categoryOptions = [
{
label: 'habitica_official',
key: 'habitica_official',
},
{
label: 'academics',
key: 'academics',
},
{
label: 'advocacy_causes',
key: 'advocacy_causes',
},
{
label: 'creativity',
key: 'creativity',
},
{
label: 'entertainment',
key: 'entertainment',
},
{
label: 'finance',
key: 'finance',
},
{
label: 'health_fitness',
key: 'health_fitness',
},
{
label: 'hobbies_occupations',
key: 'hobbies_occupations',
},
{
label: 'location_based',
key: 'location_based',
},
{
label: 'mental_health',
key: 'mental_health',
},
{
label: 'getting_organized',
key: 'getting_organized',
},
{
label: 'self_improvement',
key: 'self_improvement',
},
{
label: 'spirituality',
key: 'spirituality',
},
{
label: 'time_management',
key: 'time_management',
},
];
let hashedCategories = {};
categoryOptions.forEach((category) => {
hashedCategories[category.key] = category.label;
});
let categoriesHashByKey = hashedCategories;
return {
workingChallenge: {
name: '',
summary: '',
description: '',
categories: [],
group: '',
dailys: [],
habits: [],
leader: '',
members: [],
official: false,
prize: 1,
rewards: [],
shortName: '',
todos: [],
},
cloning: false,
cloningChallengeId: '',
showCategorySelect: false,
categoryOptions,
categoriesHashByKey,
loading: false,
groups: [],
};
},
mounted () {
this.$root.$on('habitica:clone-challenge', (data) => {
if (!data.challenge) return;
this.cloning = true;
this.cloningChallengeId = data.challenge._id;
this.$store.state.challengeOptions.workingChallenge = Object.assign({}, this.$store.state.challengeOptions.workingChallenge, data.challenge);
this.$root.$emit('bv::show::modal', 'challenge-modal');
});
this.$root.$on('habitica:update-challenge', (data) => {
if (!data.challenge) return;
this.cloning = false;
this.$store.state.challengeOptions.workingChallenge = Object.assign({}, this.$store.state.challengeOptions.workingChallenge, data.challenge);
this.$root.$emit('bv::show::modal', 'challenge-modal');
});
},
beforeDestroy () {
this.$root.$off('habitica:clone-challenge');
},
watch: {
user () {
if (!this.challenge) this.workingChallenge.leader = this.user._id;
},
challenge () {
this.setUpWorkingChallenge();
},
cloning () {
this.setUpWorkingChallenge();
},
},
computed: {
...mapState({user: 'user.data'}),
creating () {
return !this.workingChallenge.id;
},
title () {
if (this.creating) {
return this.$t('createChallenge');
}
return this.$t('editingChallenge');
},
charactersRemaining () {
let currentLength = this.workingChallenge.summary ? this.workingChallenge.summary.length : 0;
return MAX_SUMMARY_SIZE_FOR_CHALLENGES - currentLength;
},
maxPrize () {
let userBalance = this.user.balance || 0;
userBalance = userBalance * 4;
let groupBalance = 0;
let group;
this.groups.forEach(item => {
if (item._id === this.workingChallenge.group) {
group = item;
return;
}
});
if (group && group.balance && group.leader === this.user._id) {
groupBalance = group.balance * 4;
}
return userBalance + groupBalance;
},
minPrize () {
if (this.workingChallenge.group === TAVERN_ID) return 1;
return 0;
},
insufficientGemsForTavernChallenge () {
let balance = this.user.balance || 0;
let isForTavern = this.workingChallenge.group === TAVERN_ID;
if (isForTavern) {
return balance <= 0;
} else {
return false;
}
},
challenge () {
return this.$store.state.challengeOptions.workingChallenge;
},
},
methods: {
async shown () {
this.groups = await this.$store.dispatch('guilds:getMyGuilds');
if (this.user.party && this.user.party._id) {
await this.$store.dispatch('party:getParty');
const party = this.$store.state.party.data;
if (party._id) {
this.groups.push({
name: party.name,
_id: party._id,
privacy: 'private',
});
}
}
this.groups.push({
name: this.$t('publicChallengesTitle'),
_id: TAVERN_ID,
});
this.setUpWorkingChallenge();
},
setUpWorkingChallenge () {
this.resetWorkingChallenge();
if (!this.challenge) return;
this.workingChallenge = Object.assign({}, this.workingChallenge, this.challenge);
// @TODO: Should we use a separate field? I think the API expects `group` but it is confusing
this.workingChallenge.group = this.workingChallenge.group._id;
this.workingChallenge.categories = [];
if (this.challenge.categories) {
this.challenge.categories.forEach(category => {
this.workingChallenge.categories.push(category.slug);
});
}
if (this.cloning) {
this.$delete(this.workingChallenge, '_id');
this.$delete(this.workingChallenge, 'id');
}
},
resetWorkingChallenge () {
this.workingChallenge = {
name: '',
summary: '',
description: '',
categories: [],
group: '',
dailys: [],
habits: [],
leader: '',
members: [],
official: false,
prize: 1,
rewards: [],
shortName: '',
todos: [],
};
this.$store.state.workingChallenge = {};
},
async createChallenge () {
this.loading = true;
// @TODO: improve error handling, add it to updateChallenge, make errors translatable. Suggestion: `<% fieldName %> is required` where possible, where `fieldName` is inserted as the translatable string that's used for the field header.
let errors = [];
if (!this.workingChallenge.name) errors.push(this.$t('nameRequired'));
if (this.workingChallenge.shortName.length < MIN_SHORTNAME_SIZE_FOR_CHALLENGES) errors.push(this.$t('tagTooShort'));
if (!this.workingChallenge.summary) errors.push(this.$t('summaryRequired'));
if (this.workingChallenge.summary.length > MAX_SUMMARY_SIZE_FOR_CHALLENGES) errors.push(this.$t('summaryTooLong'));
if (!this.workingChallenge.description) errors.push(this.$t('descriptionRequired'));
if (!this.workingChallenge.group) errors.push(this.$t('locationRequired'));
if (!this.workingChallenge.categories || this.workingChallenge.categories.length === 0) errors.push(this.$t('categoiresRequired'));
if (errors.length > 0) {
alert(errors.join('\n'));
this.loading = false;
return;
}
this.workingChallenge.timestamp = new Date().getTime();
let categoryKeys = this.workingChallenge.categories;
let serverCategories = [];
categoryKeys.forEach(key => {
let catName = this.categoriesHashByKey[key];
serverCategories.push({
slug: key,
name: catName,
});
});
let challengeDetails = clone(this.workingChallenge);
challengeDetails.categories = serverCategories;
let challenge;
if (this.cloning) {
challenge = await this.$store.dispatch('challenges:cloneChallenge', {
challenge: challengeDetails,
cloningChallengeId: this.cloningChallengeId,
});
this.cloningChallengeId = '';
} else {
challenge = await this.$store.dispatch('challenges:createChallenge', {challenge: challengeDetails});
}
// Update Group Prize
let challengeGroup = this.groups.find(group => {
return group._id === this.workingChallenge.group;
});
// @TODO: Share with server
const prizeCost = this.workingChallenge.prize / 4;
const challengeGroupLeader = challengeGroup.leader && challengeGroup.leader._id ? challengeGroup.leader._id : challengeGroup.leader;
const userIsLeader = challengeGroupLeader === this.user._id;
if (challengeGroup && userIsLeader && challengeGroup.balance > 0 && challengeGroup.balance >= prizeCost) {
// Group pays for all of prize
} else if (challengeGroup && userIsLeader && challengeGroup.balance > 0) {
// User pays remainder of prize cost after group
let remainder = prizeCost - challengeGroup.balance;
this.user.balance -= remainder;
} else {
// User pays for all of prize
this.user.balance -= prizeCost;
}
this.$emit('createChallenge', challenge);
this.resetWorkingChallenge();
this.$root.$emit('bv::hide::modal', 'challenge-modal');
this.$router.push(`/challenges/${challenge._id}`);
},
updateChallenge () {
let categoryKeys = this.workingChallenge.categories;
let serverCategories = [];
categoryKeys.forEach(key => {
let newKey = key.trim();
let catName = this.categoriesHashByKey[newKey];
serverCategories.push({
slug: newKey,
name: catName,
});
});
let challengeDetails = clone(this.workingChallenge);
challengeDetails.categories = serverCategories;
this.$emit('updatedChallenge', {
challenge: challengeDetails,
});
this.$store.dispatch('challenges:updateChallenge', {challenge: challengeDetails});
this.resetWorkingChallenge();
this.$root.$emit('bv::hide::modal', 'challenge-modal');
},
toggleCategorySelect () {
this.showCategorySelect = !this.showCategorySelect;
},
},
};
</script>
@@ -0,0 +1,113 @@
<template lang="pug">
div
b-modal#close-challenge-modal(:title="$t('createGuild')", size='md')
.header-wrap(slot="modal-header")
h2.text-center(v-once) {{$t('endChallenge')}}
.row.text-center
.col-12
.support-habitica
// @TODO: Add challenge achievement badge here
.col-12
strong(v-once) {{$t('selectChallengeWinnersDescription')}}
.col-12
member-search-dropdown(:text='winnerText', :members='members', :challengeId='challengeId', @member-selected='selectMember')
.col-12
button.btn.btn-primary(v-once, @click='closeChallenge') {{$t('awardWinners')}}
.col-12
hr
.or {{$t('or')}}
.col-12
strong(v-once) {{$t('doYouWantedToDeleteChallenge')}}
.col-12
button.btn.btn-danger(v-once, @click='deleteChallenge()') {{$t('deleteChallenge')}}
.footer-wrap(slot="modal-footer")
</template>
<style lang='scss'>
@import '~client/assets/scss/colors.scss';
#close-challenge-modal {
h2 {
color: $purple-200
}
#close-challenge-modal_modal_body {
padding-bottom: 2em;
}
.header-wrap {
width: 100%;
padding-top: 2em;
}
.support-habitica {
background-image: url('~client/assets/svg/for-css/support-habitica-gems.svg');
width: 325px;
height: 89px;
margin: 0 auto;
}
.modal-footer, .modal-header {
border: none !important;
}
.footer-wrap {
display: none;
}
.col-12 {
margin-top: 2em;
}
.or {
margin-top: -2em;
background: $white;
width: 40px;
margin-right: auto;
margin-left: auto;
font-weight: bold;
}
}
</style>
<script>
import memberSearchDropdown from 'client/components/members/memberSearchDropdown';
export default {
props: ['challengeId', 'members', 'prize'],
components: {
memberSearchDropdown,
},
data () {
return {
winner: {},
};
},
computed: {
winnerText () {
if (!this.winner.profile) return this.$t('selectMember');
return this.winner.profile.name;
},
},
methods: {
selectMember (member) {
this.winner = member;
},
async closeChallenge () {
this.challenge = await this.$store.dispatch('challenges:selectChallengeWinner', {
challengeId: this.challengeId,
winnerId: this.winner._id,
});
this.$router.push('/challenges/myChallenges');
},
async deleteChallenge () {
if (!confirm('Are you sure you want to delete this challenge?')) return;
this.challenge = await this.$store.dispatch('challenges:deleteChallenge', {
challengeId: this.challengeId,
prize: this.prize,
});
this.$router.push('/challenges/myChallenges');
},
},
};
</script>
@@ -0,0 +1,199 @@
<template lang="pug">
.row
challenge-modal(v-on:createChallenge='challengeCreated')
sidebar(v-on:search="updateSearch", v-on:filter="updateFilters")
.col-12.col-md-10.standard-page
.row.header-row
.col-md-8.text-left
h1(v-once) {{$t('findChallenges')}}
.col-md-4
// @TODO: implement sorting span.dropdown-label {{ $t('sortBy') }}
b-dropdown(:text="$t('sort')", right=true)
b-dropdown-item(v-for='sortOption in sortOptions', :key="sortOption.value", @click='sort(sortOption.value)') {{sortOption.text}}
button.btn.btn-secondary.create-challenge-button.float-right(@click='createChallenge()')
.svg-icon.positive-icon(v-html="icons.positiveIcon")
span(v-once) {{$t('createChallenge')}}
.row
.no-challenges.text-center.col-md-6.offset-3(v-if='!loading && filteredChallenges.length === 0')
h2(v-once) {{$t('noChallengeMatchFilters')}}
.row
.col-12.col-md-6(v-for='challenge in filteredChallenges')
challenge-item(:challenge='challenge')
mugen-scroll(
:handler="infiniteScrollTrigger",
:should-handle="!loading && canLoadMore",
:threshold="1",
v-show="loading",
)
h2.col-12.loading(v-once) {{ $t('loading') }}
</template>
<style lang='scss' scoped>
@import '~client/assets/scss/colors.scss';
.header-row {
h1 {
color: $purple-200;
}
.create-challenge-button {
margin-left: 1em;
}
.positive-icon {
color: $green-10;
width: 10px;
display: inline-block;
margin-right: .5em;
}
}
.no-challenges {
color: $gray-200;
margin-top: 10em;
h2 {
color: $gray-200;
}
}
.loading {
text-align: center;
color: $purple-300;
}
</style>
<script>
import { mapState } from 'client/libs/store';
import Sidebar from './sidebar';
import ChallengeItem from './challengeItem';
import challengeModal from './challengeModal';
import challengeUtilities from 'client/mixins/challengeUtilities';
import positiveIcon from 'assets/svg/positive.svg';
import MugenScroll from 'vue-mugen-scroll';
import debounce from 'lodash/debounce';
export default {
mixins: [challengeUtilities],
components: {
Sidebar,
ChallengeItem,
challengeModal,
MugenScroll,
},
data () {
return {
loading: true,
canLoadMore: true,
icons: Object.freeze({
positiveIcon,
}),
challenges: [],
sort: 'none',
sortOptions: [
{
text: this.$t('none'),
value: 'none',
},
{
text: this.$t('participants'),
value: 'participants',
},
{
text: this.$t('name'),
value: 'name',
},
{
text: this.$t('end_date'),
value: 'end_date',
},
{
text: this.$t('start_date'),
value: 'start_date',
},
],
search: '',
filters: {},
page: 0,
};
},
mounted () {
this.loadChallenges();
},
computed: {
...mapState({user: 'user.data'}),
filteredChallenges () {
return this.challenges;
},
},
methods: {
updateSearch (eventData) {
this.search = eventData.searchTerm;
this.page = 0;
this.loadChallenges();
},
updateFilters (eventData) {
this.filters = eventData;
this.page = 0;
this.loadChallenges();
},
createChallenge () {
this.$root.$emit('bv::show::modal', 'challenge-modal');
},
async loadChallenges () {
this.loading = true;
let categories = '';
if (this.filters.categories) {
categories = this.filters.categories.join(',');
}
let owned = '';
// @TODO: we skip ownership === 2 because it is the same as === 0 right now
if (this.filters.ownership && this.filters.ownership.length === 1) {
owned = this.filters.ownership[0];
}
const challenges = await this.$store.dispatch('challenges:getUserChallenges', {
page: this.page,
search: this.search,
categories,
owned,
});
if (this.page === 0) {
this.challenges = challenges;
} else {
this.challenges = this.challenges.concat(challenges);
}
// only show the load more Button if the max count was returned
this.canLoadMore = challenges.length === 10;
this.loading = false;
},
challengeCreated (challenge) {
this.challenges.push(challenge);
},
infiniteScrollTrigger () {
// show loading and wait until the loadMore debounced
// or else it would trigger on every scrolling-pixel (while not loading)
if (this.canLoadMore) {
this.loading = true;
}
this.loadMore();
},
loadMore: debounce(function loadMoreDebounce () {
this.page += 1;
this.loadChallenges();
}, 1000),
},
};
</script>
@@ -0,0 +1,92 @@
<template lang="pug">
div
challenge-modal(:groupId='groupId', v-on:createChallenge='challengeCreated')
.row.no-quest-section(v-if='challenges.length === 0')
.col-12.text-center
.svg-icon.challenge-icon(v-html="icons.challengeIcon")
h4(v-once) {{ $t('haveNoChallenges') }}
p(v-once) {{ $t('challengeDetails') }}
button.btn.btn-secondary(@click='createChallenge()') {{ $t('createChallenge') }}
template(v-else)
challenge-item(v-for='challenge in challenges',:challenge='challenge',:key='challenge._id',:fullLayout='false')
.col-12.text-center
button.btn.btn-secondary(@click='createChallenge()') {{ $t('createChallenge') }}
</template>
<style lang="scss" scoped>
@import '~client/assets/scss/colors.scss';
.no-quest-section {
padding: 2em;
color: $gray-300;
h4 {
color: $gray-300;
}
p {
margin-bottom: 2em;
}
.svg-icon {
height: 30px;
width: 30px;
margin: 0 auto;
margin-bottom: 2em;
}
}
</style>
<script>
import challengeModal from './challengeModal';
import {mapState} from 'client/libs/store';
import markdownDirective from 'client/directives/markdown';
import challengeItem from './challengeItem';
import challengeIcon from 'assets/svg/challenge.svg';
export default {
props: ['groupId'],
components: {
challengeModal,
challengeItem,
},
computed: {
...mapState({user: 'user.data'}),
},
data () {
return {
challenges: [],
icons: Object.freeze({
challengeIcon,
}),
groupIdForChallenges: '',
};
},
directives: {
markdown: markdownDirective,
},
mounted () {
this.loadChallenges();
},
watch: {
async groupId () {
this.loadChallenges();
},
},
methods: {
async loadChallenges () {
this.groupIdForChallenges = this.groupId;
if (this.groupId === 'party' && this.user.party._id) this.groupIdForChallenges = this.user.party._id;
this.challenges = await this.$store.dispatch('challenges:getGroupChallenges', {groupId: this.groupIdForChallenges});
},
createChallenge () {
this.$root.$emit('bv::show::modal', 'challenge-modal');
},
challengeCreated (challenge) {
if (challenge.group._id !== this.groupIdForChallenges) return;
this.challenges.push(challenge);
},
},
};
</script>
@@ -0,0 +1,19 @@
<template lang="pug">
.row
secondary-menu.col-12
router-link.nav-link(:to="{name: 'myChallenges'}", :class="{'active': $route.name === 'myChallenges'}") {{ $t('myChallenges') }}
router-link.nav-link(:to="{name: 'findChallenges'}", :class="{'active': $route.name === 'findChallenges'}") {{ $t('findChallenges') }}
.col-12
router-view
</template>
<script>
import SecondaryMenu from 'client/components/secondaryMenu';
export default {
components: {
SecondaryMenu,
},
};
</script>
@@ -0,0 +1,45 @@
<template lang="pug">
b-modal#leave-challenge-modal(:title="$t('leaveChallenge')", size='sm', :hide-footer="true")
.modal-body
h2 {{ $t('confirmKeepChallengeTasks') }}
div
button.btn.btn-primary(@click='leaveChallenge("keep")') {{ $t('keepThem') }}
button.btn.btn-danger(@click='leaveChallenge("remove-all")') {{ $t('removeThem') }}
</template>
<style scoped>
.modal-body {
padding-bottom: 2em;
}
</style>
<script>
import findIndex from 'lodash/findIndex';
import { mapState } from 'client/libs/store';
import notifications from 'client/mixins/notifications';
export default {
props: ['challengeId'],
mixins: [notifications],
computed: {
...mapState({user: 'user.data'}),
},
methods: {
async leaveChallenge (keep) {
let index = findIndex(this.user.challenges, (id) => {
return id === this.challengeId;
});
this.user.challenges.splice(index, 1);
await this.$store.dispatch('challenges:leaveChallenge', {
challengeId: this.challengeId,
keep,
});
await this.$store.dispatch('tasks:fetchUserTasks', {forceLoad: true});
this.close();
},
close () {
this.$root.$emit('bv::hide::modal', 'leave-challenge-modal');
},
},
};
</script>
@@ -0,0 +1,231 @@
<template lang="pug">
.row
challenge-modal(v-on:createChallenge='challengeCreated')
sidebar(v-on:search="updateSearch", v-on:filter="updateFilters")
.col-10.standard-page
.row.header-row
.col-md-8.text-left
h1(v-once) {{$t('myChallenges')}}
.col-md-4
// @TODO: implement sorting span.dropdown-label {{ $t('sortBy') }}
b-dropdown(:text="$t('sort')", right=true)
b-dropdown-item(v-for='sortOption in sortOptions', :key="sortOption.value", @click='sort(sortOption.value)') {{sortOption.text}}
button.btn.btn-secondary.create-challenge-button.float-right(@click='createChallenge()')
.svg-icon.positive-icon(v-html="icons.positiveIcon")
span(v-once) {{$t('createChallenge')}}
.row
.no-challenges.text-center.col-md-6.offset-3(v-if='!loading && challenges.length === 0')
.svg-icon(v-html="icons.challengeIcon")
h2(v-once) {{$t('noChallengeTitle')}}
p(v-once) {{$t('challengeDescription1')}}
p(v-once) {{$t('challengeDescription2')}}
.row
.no-challenges.text-center.col-md-6.offset-3(v-if='!loading && challenges.length > 0 && filteredChallenges.length === 0')
h2(v-once) {{$t('noChallengeMatchFilters')}}
.row
.col-12.col-md-6(v-for='challenge in filteredChallenges')
challenge-item(:challenge='challenge')
mugen-scroll(
:handler="infiniteScrollTrigger",
:should-handle="!loading && canLoadMore",
:threshold="1",
v-show="loading",
)
h2.col-12.loading(v-once) {{ $t('loading') }}
</template>
<style lang='scss' scoped>
@import '~client/assets/scss/colors.scss';
.header-row {
h1 {
color: $purple-200;
}
.create-challenge-button {
margin-left: 1em;
}
.positive-icon {
color: $green-10;
width: 10px;
display: inline-block;
margin-right: .5em;
}
}
.no-challenges {
color: $gray-200;
margin-top: 10em;
h2 {
color: $gray-200;
}
.svg-icon {
color: #C3C0C7;
width: 88.7px;
margin: 1em auto;
}
}
.loading {
text-align: center;
color: $purple-300;
}
</style>
<script>
import { mapState } from 'client/libs/store';
import Sidebar from './sidebar';
import ChallengeItem from './challengeItem';
import challengeModal from './challengeModal';
import challengeUtilities from 'client/mixins/challengeUtilities';
import challengeIcon from 'assets/svg/challenge.svg';
import positiveIcon from 'assets/svg/positive.svg';
import MugenScroll from 'vue-mugen-scroll';
import debounce from 'lodash/debounce';
export default {
mixins: [challengeUtilities],
components: {
Sidebar,
ChallengeItem,
challengeModal,
MugenScroll,
},
data () {
return {
icons: Object.freeze({
challengeIcon,
positiveIcon,
}),
loading: false,
canLoadMore: true,
challenges: [],
sort: 'none',
sortOptions: [
{
text: this.$t('none'),
value: 'none',
},
{
text: this.$t('participants'),
value: 'participants',
},
{
text: this.$t('name'),
value: 'name',
},
{
text: this.$t('end_date'),
value: 'end_date',
},
{
text: this.$t('start_date'),
value: 'start_date',
},
],
search: '',
filters: {},
page: 0,
};
},
mounted () {
this.loadChallenges();
},
computed: {
...mapState({user: 'user.data'}),
filteredChallenges () {
const filters = this.filters;
const user = this.user;
return this.challenges.filter(challenge => {
let isMember = true;
let filteringRole = filters.roles && filters.roles.length > 0;
if (filteringRole && filters.roles.indexOf('participating') !== -1) {
isMember = this.isMemberOfChallenge(user, challenge);
}
if (filteringRole && filters.roles.indexOf('not_participating') !== -1) {
isMember = !this.isMemberOfChallenge(user, challenge);
}
return isMember;
});
},
},
methods: {
updateSearch (eventData) {
this.search = eventData.searchTerm;
this.page = 0;
this.loadChallenges();
},
updateFilters (eventData) {
this.filters = eventData;
this.page = 0;
this.loadChallenges();
},
createChallenge () {
this.$store.state.challengeOptions.workingChallenge = {};
this.$root.$emit('bv::show::modal', 'challenge-modal');
},
async loadChallenges () {
this.loading = true;
let categories = '';
if (this.filters.categories) {
categories = this.filters.categories.join(',');
}
let owned = '';
// @TODO: we skip ownership === 2 because it is the same as === 0 right now
if (this.filters.ownership && this.filters.ownership.length === 1) {
owned = this.filters.ownership[0];
}
const challenges = await this.$store.dispatch('challenges:getUserChallenges', {
page: this.page,
search: this.search,
categories,
owned,
member: true,
});
if (this.page === 0) {
this.challenges = challenges;
} else {
this.challenges = this.challenges.concat(challenges);
}
// only show the load more Button if the max count was returned
this.canLoadMore = challenges.length === 10;
this.loading = false;
},
challengeCreated (challenge) {
this.challenges.push(challenge);
},
infiniteScrollTrigger () {
// show loading and wait until the loadMore debounced
// or else it would trigger on every scrolling-pixel (while not loading)
if (this.canLoadMore) {
this.loading = true;
}
this.loadMore();
},
loadMore: debounce(function loadMoreDebounce () {
this.page += 1;
this.loadChallenges();
}, 1000),
},
};
</script>
@@ -0,0 +1,160 @@
<template lang="pug">
.standard-sidebar.d-none.d-sm-block
.form-group
input.form-control.search(type="text", :placeholder="$t('search')", v-model='searchTerm')
form
h2(v-once) {{ $t('filter') }}
.form-group
h3 {{ $t('category') }}
.form-check(
v-for="group in categoryOptions",
:key="group.key",
)
.custom-control.custom-checkbox
input.custom-control-input(type="checkbox", :value='group.key' v-model="categoryFilters", :id="group.key")
label.custom-control-label(v-once, :for="group.key") {{ $t(group.label) }}
.form-group(v-if='$route.name !== "findChallenges"')
h3 {{ $t('membership') }}
.form-check(
v-for="group in roleOptions",
:key="group.key",
)
.custom-control.custom-checkbox
input.custom-control-input(type="checkbox", :value='group.key' v-model="roleFilters", :id="group.key")
label.custom-control-label(v-once, :for="group.key") {{ $t(group.label) }}
.form-group
h3 {{ $t('ownership') }}
.form-check(
v-for="group in ownershipOptions",
:key="group.key",
)
.custom-control.custom-checkbox
input.custom-control-input(type="checkbox", :value='group.key' v-model="ownershipFilters", :id="group.key")
label.custom-control-label(v-once, :for="group.key") {{ $t(group.label) }}
</template>
<script>
import throttle from 'lodash/throttle';
export default {
data () {
return {
categoryFilters: [],
categoryOptions: [
{
label: 'habitica_official',
key: 'habitica_official',
},
{
label: 'academics',
key: 'academics',
},
{
label: 'advocacy_causes',
key: 'advocacy_causes',
},
{
label: 'creativity',
key: 'creativity',
},
{
label: 'entertainment',
key: 'entertainment',
},
{
label: 'finance',
key: 'finance',
},
{
label: 'health_fitness',
key: 'health_fitness',
},
{
label: 'hobbies_occupations',
key: 'hobbies_occupations',
},
{
label: 'location_based',
key: 'location_based',
},
{
label: 'mental_health',
key: 'mental_health',
},
{
label: 'getting_organized',
key: 'getting_organized',
},
{
label: 'self_improvement',
key: 'self_improvement',
},
{
label: 'spirituality',
key: 'spirituality',
},
{
label: 'time_management',
key: 'time_management',
},
],
roleFilters: [],
roleOptions: [
{
label: 'participating',
key: 'participating',
},
{
label: 'not_participating',
key: 'not_participating',
},
// {
// label: 'either',
// key: 'either',
// },
],
ownershipFilters: [],
ownershipOptions: [
{
label: 'owned',
key: 'owned',
},
{
label: 'not_owned',
key: 'not_owned',
},
// {
// label: 'either',
// key: 'either',
// },
],
searchTerm: '',
};
},
watch: {
categoryFilters: function categoryFilters () {
this.emitFilters();
},
roleFilters: function roleFilters () {
this.emitFilters();
},
ownershipFilters: function ownershipFilters () {
this.emitFilters();
},
searchTerm: throttle(function searchTerm (newSearch) {
this.$emit('search', {
searchTerm: newSearch,
});
}, 500),
},
methods: {
emitFilters () {
this.$emit('filter', {
categories: this.categoryFilters,
roles: this.roleFilters,
ownership: this.ownershipFilters,
});
},
},
};
</script>