comments.vue 15.4 KB
Newer Older
NGPixel's avatar
NGPixel committed
1
<template lang="pug">
2
  div(v-intersect.once='onIntersect')
NGPixel's avatar
NGPixel committed
3
    v-textarea#discussion-new(
4
      outlined
NGPixel's avatar
NGPixel committed
5
      flat
6
      :placeholder='$t(`common:comments.newPlaceholder`)'
NGPixel's avatar
NGPixel committed
7 8 9 10
      auto-grow
      dense
      rows='3'
      hide-details
11 12 13
      v-model='newcomment'
      color='blue-grey darken-2'
      :background-color='$vuetify.theme.dark ? `grey darken-5` : `white`'
14
      v-if='permissions.write'
NGPixel's avatar
NGPixel committed
15
    )
16 17 18 19 20 21
    v-row.mt-2(dense, v-if='!isAuthenticated && permissions.write')
      v-col(cols='12', lg='6')
        v-text-field(
          outlined
          color='blue-grey darken-2'
          :background-color='$vuetify.theme.dark ? `grey darken-5` : `white`'
22
          :placeholder='$t(`common:comments.fieldName`)'
23 24 25 26 27 28 29 30 31 32
          hide-details
          dense
          autocomplete='name'
          v-model='guestName'
        )
      v-col(cols='12', lg='6')
        v-text-field(
          outlined
          color='blue-grey darken-2'
          :background-color='$vuetify.theme.dark ? `grey darken-5` : `white`'
33
          :placeholder='$t(`common:comments.fieldEmail`)'
34 35 36 37 38 39 40
          hide-details
          type='email'
          dense
          autocomplete='email'
          v-model='guestEmail'
        )
    .d-flex.align-center.pt-3(v-if='permissions.write')
NGPixel's avatar
NGPixel committed
41
      v-icon.mr-1(color='blue-grey') mdi-language-markdown-outline
42
      .caption.blue-grey--text {{$t('common:comments.markdownFormat')}}
NGPixel's avatar
NGPixel committed
43
      v-spacer
44 45
      .caption.mr-3(v-if='isAuthenticated')
        i18next(tag='span', path='common:comments.postingAs')
46
          strong(place='name') {{userDisplayName}}
NGPixel's avatar
NGPixel committed
47 48
      v-btn(
        dark
49 50 51
        color='blue-grey darken-2'
        @click='postComment'
        depressed
NGPixel's avatar
NGPixel committed
52 53
        )
        v-icon(left) mdi-comment
54
        span.text-none {{$t('common:comments.postComment')}}
55
    v-divider.mt-3(v-if='permissions.write')
56
    .pa-5.d-flex.align-center.justify-center(v-if='isLoading && !hasLoadedOnce')
57 58 59 60 61 62
      v-progress-circular(
        indeterminate
        size='20'
        width='1'
        color='blue-grey'
      )
63
      .caption.blue-grey--text.pl-3: em {{$t('common:comments.loading')}}
NGPixel's avatar
NGPixel committed
64 65
    v-timeline(
      dense
66
      v-else-if='comments && comments.length > 0'
NGPixel's avatar
NGPixel committed
67
      )
68
      v-timeline-item.comments-post(
NGPixel's avatar
NGPixel committed
69 70
        color='pink darken-4'
        large
71 72
        v-for='cm of comments'
        :key='`comment-` + cm.id'
73
        :id='`comment-post-id-` + cm.id'
NGPixel's avatar
NGPixel committed
74 75
        )
        template(v-slot:icon)
76 77 78
          v-avatar(color='blue-grey')
            //- v-img(src='http://i.pravatar.cc/64')
            span.white--text.title {{cm.initials}}
NGPixel's avatar
NGPixel committed
79 80
        v-card.elevation-1
          v-card-text
NGPixel's avatar
NGPixel committed
81
            .comments-post-actions(v-if='permissions.manage && !isBusy && commentEditId === 0')
82 83 84
              v-icon.mr-3(small, @click='editComment(cm)') mdi-pencil
              v-icon(small, @click='deleteCommentConfirm(cm)') mdi-delete
            .comments-post-name.caption: strong {{cm.authorName}}
85
            .comments-post-date.overline.grey--text {{cm.createdAt | moment('from') }} #[em(v-if='cm.createdAt !== cm.updatedAt') - {{$t('common:comments.modified', { reldate: $options.filters.moment(cm.updatedAt, 'from') })}}]
NGPixel's avatar
NGPixel committed
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
            .comments-post-content.mt-3(v-if='commentEditId !== cm.id', v-html='cm.render')
            .comments-post-editcontent.mt-3(v-else)
              v-textarea(
                outlined
                flat
                auto-grow
                dense
                rows='3'
                hide-details
                v-model='commentEditContent'
                color='blue-grey darken-2'
                :background-color='$vuetify.theme.dark ? `grey darken-5` : `white`'
              )
              .d-flex.align-center.pt-3
                v-spacer
                v-btn.mr-3(
                  dark
                  color='blue-grey darken-2'
                  @click='editCommentCancel'
                  outlined
                  )
                  v-icon(left) mdi-close
108
                  span.text-none {{$t('common:action.cancel')}}
NGPixel's avatar
NGPixel committed
109 110 111 112 113 114 115
                v-btn(
                  dark
                  color='blue-grey darken-2'
                  @click='updateComment'
                  depressed
                  )
                  v-icon(left) mdi-comment
116 117 118
                  span.text-none {{$t('common:comments.updateComment')}}
    .pt-5.text-center.body-2.blue-grey--text(v-else-if='permissions.write') {{$t('common:comments.beFirst')}}
    .text-center.body-2.blue-grey--text(v-else) {{$t('common:comments.none')}}
119 120 121

    v-dialog(v-model='deleteCommentDialogShown', max-width='500')
      v-card
122
        .dialog-header.is-red {{$t('common:comments.deleteConfirmTitle')}}
123
        v-card-text.pt-5
124 125
          span {{$t('common:comments.deleteWarn')}}
          .caption: strong {{$t('common:comments.deletePermanentWarn')}}
126 127 128 129
        v-card-chin
          v-spacer
          v-btn(text, @click='deleteCommentDialogShown = false') {{$t('common:actions.cancel')}}
          v-btn(color='red', dark, @click='deleteComment') {{$t('common:actions.delete')}}
NGPixel's avatar
NGPixel committed
130 131 132
</template>

<script>
133 134
import gql from 'graphql-tag'
import { get } from 'vuex-pathify'
135 136
import validate from 'validate.js'
import _ from 'lodash'
137

NGPixel's avatar
NGPixel committed
138
export default {
139 140 141 142
  data () {
    return {
      newcomment: '',
      isLoading: true,
143
      hasLoadedOnce: false,
144 145
      comments: [],
      guestName: '',
146 147
      guestEmail: '',
      commentToDelete: {},
NGPixel's avatar
NGPixel committed
148 149
      commentEditId: 0,
      commentEditContent: null,
150 151 152 153 154 155 156
      deleteCommentDialogShown: false,
      isBusy: false,
      scrollOpts: {
        duration: 1500,
        offset: 0,
        easing: 'easeInOutCubic'
      }
157 158 159
    }
  },
  computed: {
160
    pageId: get('page/id'),
161
    permissions: get('page/effectivePermissions@comments'),
162 163
    isAuthenticated: get('user/authenticated'),
    userDisplayName: get('user/name')
164 165
  },
  methods: {
166 167
    onIntersect (entries, observer, isIntersecting) {
      if (isIntersecting) {
168
        this.fetch(true)
169
      }
170
    },
171
    async fetch (silent = false) {
172
      this.isLoading = true
173 174 175 176 177 178 179 180 181 182 183 184
      try {
        const results = await this.$apollo.query({
          query: gql`
            query ($locale: String!, $path: String!) {
              comments {
                list(locale: $locale, path: $path) {
                  id
                  render
                  authorName
                  createdAt
                  updatedAt
                }
185 186
              }
            }
187 188 189 190 191 192 193 194 195 196 197 198
          `,
          variables: {
            locale: this.$store.get('page/locale'),
            path: this.$store.get('page/path')
          },
          fetchPolicy: 'network-only'
        })
        this.comments = _.get(results, 'data.comments.list', []).map(c => {
          const nameParts = c.authorName.toUpperCase().split(' ')
          let initials = _.head(nameParts).charAt(0)
          if (nameParts.length > 1) {
            initials += _.last(nameParts).charAt(0)
199
          }
200 201 202 203 204 205 206 207 208 209 210
          c.initials = initials
          return c
        })
      } catch (err) {
        console.warn(err)
        if (!silent) {
          this.$store.commit('showNotification', {
            style: 'red',
            message: err.message,
            icon: 'alert'
          })
211
        }
212
      }
213 214 215 216 217 218
      this.isLoading = false
      this.hasLoadedOnce = true
    },
    /**
     * Post New Comment
     */
219
    async postComment () {
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
      let rules = {
        comment: {
          presence: {
            allowEmpty: false
          },
          length: {
            minimum: 2
          }
        }
      }
      if (!this.isAuthenticated && this.permissions.write) {
        rules.name = {
          presence: {
            allowEmpty: false
          },
          length: {
            minimum: 2,
            maximum: 255
          }
        }
        rules.email = {
          presence: {
            allowEmpty: false
          },
          email: true
        }
      }
      const validationResults = validate({
        comment: this.newcomment,
        name: this.guestName,
        email: this.guestEmail
      }, rules, { format: 'flat' })

      if (validationResults) {
        this.$store.commit('showNotification', {
          style: 'red',
          message: validationResults[0],
          icon: 'alert'
        })
        return
      }
NGPixel's avatar
NGPixel committed
261

262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
      try {
        const resp = await this.$apollo.mutate({
          mutation: gql`
            mutation (
              $pageId: Int!
              $replyTo: Int
              $content: String!
              $guestName: String
              $guestEmail: String
            ) {
              comments {
                create (
                  pageId: $pageId
                  replyTo: $replyTo
                  content: $content
                  guestName: $guestName
                  guestEmail: $guestEmail
                ) {
                  responseResult {
                    succeeded
                    errorCode
                    slug
                    message
                  }
                  id
287 288 289
                }
              }
            }
290 291 292 293 294 295 296
          `,
          variables: {
            pageId: this.pageId,
            replyTo: 0,
            content: this.newcomment,
            guestName: this.guestName,
            guestEmail: this.guestEmail
297 298 299
          }
        })

300 301 302
        if (_.get(resp, 'data.comments.create.responseResult.succeeded', false)) {
          this.$store.commit('showNotification', {
            style: 'success',
303
            message: this.$t('common:comments.postSuccess'),
304 305 306 307 308 309 310 311 312 313 314 315
            icon: 'check'
          })

          this.newcomment = ''
          await this.fetch()
          this.$nextTick(() => {
            this.$vuetify.goTo(`#comment-post-id-${_.get(resp, 'data.comments.create.id', 0)}`, this.scrollOpts)
          })
        } else {
          throw new Error(_.get(resp, 'data.comments.create.responseResult.message', 'An unexpected error occured.'))
        }
      } catch (err) {
316 317
        this.$store.commit('showNotification', {
          style: 'red',
318
          message: err.message,
319 320 321
          icon: 'alert'
        })
      }
322
    },
NGPixel's avatar
NGPixel committed
323 324 325
    /**
     * Show Comment Editing Form
     */
326
    async editComment (cm) {
NGPixel's avatar
NGPixel committed
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
      this.$store.commit(`loadingStart`, 'comments-edit')
      this.isBusy = true
      try {
        const results = await this.$apollo.query({
          query: gql`
            query ($id: Int!) {
              comments {
                single(id: $id) {
                  content
                }
              }
            }
          `,
          variables: {
            id: cm.id
          },
          fetchPolicy: 'network-only'
        })
        this.commentEditContent = _.get(results, 'data.comments.single.content', null)
        if (this.commentEditContent === null) {
          throw new Error('Failed to load comment content.')
        }
      } catch (err) {
        console.warn(err)
        this.$store.commit('showNotification', {
          style: 'red',
          message: err.message,
          icon: 'alert'
        })
      }
      this.commentEditId = cm.id
      this.isBusy = false
      this.$store.commit(`loadingStop`, 'comments-edit')
    },
    /**
     * Cancel Comment Edit
     */
    editCommentCancel () {
      this.commentEditId = 0
      this.commentEditContent = null
    },
    /**
     * Update Comment with new content
     */
    async updateComment () {
      this.$store.commit(`loadingStart`, 'comments-edit')
      this.isBusy = true
      try {
        if (this.commentEditContent.length < 2) {
376
          throw new Error(this.$t('common:comments.contentMissingError'))
NGPixel's avatar
NGPixel committed
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
        }
        const resp = await this.$apollo.mutate({
          mutation: gql`
            mutation (
              $id: Int!
              $content: String!
            ) {
              comments {
                update (
                  id: $id,
                  content: $content
                ) {
                  responseResult {
                    succeeded
                    errorCode
                    slug
                    message
                  }
                  render
                }
              }
            }
          `,
          variables: {
            id: this.commentEditId,
            content: this.commentEditContent
          }
        })
405

NGPixel's avatar
NGPixel committed
406 407 408
        if (_.get(resp, 'data.comments.update.responseResult.succeeded', false)) {
          this.$store.commit('showNotification', {
            style: 'success',
409
            message: this.$t('common:comments.updateSuccess'),
NGPixel's avatar
NGPixel committed
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
            icon: 'check'
          })

          const cm = _.find(this.comments, ['id', this.commentEditId])
          cm.render = _.get(resp, 'data.comments.update.render', '-- Failed to load updated comment --')
          cm.updatedAt = (new Date()).toISOString()

          this.editCommentCancel()
        } else {
          throw new Error(_.get(resp, 'data.comments.delete.responseResult.message', 'An unexpected error occured.'))
        }
      } catch (err) {
        console.warn(err)
        this.$store.commit('showNotification', {
          style: 'red',
          message: err.message,
          icon: 'alert'
        })
      }
      this.isBusy = false
      this.$store.commit(`loadingStop`, 'comments-edit')
431
    },
NGPixel's avatar
NGPixel committed
432 433 434
    /**
     * Show Delete Comment Confirmation Dialog
     */
435 436 437 438 439 440 441 442 443 444 445 446
    deleteCommentConfirm (cm) {
      this.commentToDelete = cm
      this.deleteCommentDialogShown = true
    },
    /**
     * Delete Comment
     */
    async deleteComment () {
      this.$store.commit(`loadingStart`, 'comments-delete')
      this.isBusy = true
      this.deleteCommentDialogShown = false

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
      try {
        const resp = await this.$apollo.mutate({
          mutation: gql`
            mutation (
              $id: Int!
            ) {
              comments {
                delete (
                  id: $id
                ) {
                  responseResult {
                    succeeded
                    errorCode
                    slug
                    message
                  }
463 464
                }
              }
465
            }
466 467 468
          `,
          variables: {
            id: this.commentToDelete.id
469
          }
470 471
        })

472 473 474
        if (_.get(resp, 'data.comments.delete.responseResult.succeeded', false)) {
          this.$store.commit('showNotification', {
            style: 'success',
475
            message: this.$t('common:comments.deleteSuccess'),
476 477 478 479 480 481 482 483
            icon: 'check'
          })

          this.comments = _.reject(this.comments, ['id', this.commentToDelete.id])
        } else {
          throw new Error(_.get(resp, 'data.comments.delete.responseResult.message', 'An unexpected error occured.'))
        }
      } catch (err) {
484 485
        this.$store.commit('showNotification', {
          style: 'red',
486
          message: err.message,
487 488
          icon: 'alert'
        })
489
      }
490 491
      this.isBusy = false
      this.$store.commit(`loadingStop`, 'comments-delete')
492 493
    }
  }
NGPixel's avatar
NGPixel committed
494 495 496 497
}
</script>

<style lang="scss">
498 499
.comments-post {
  position: relative;
NGPixel's avatar
NGPixel committed
500

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
  &:hover {
    .comments-post-actions {
      opacity: 1;
    }
  }

  &-actions {
    position: absolute;
    top: 16px;
    right: 16px;
    opacity: 0;
    transition: opacity .4s ease;
  }

  &-content {
    > p:first-child {
      padding-top: 0;
    }

    p {
      padding-top: 1rem;
      margin-bottom: 0;
    }

    img {
      max-width: 100%;
527
      border-radius: 5px;
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
    }

    code {
      background-color: rgba(mc('pink', '500'), .1);
      box-shadow: none;
    }

    pre > code {
      margin-top: 1rem;
      padding: 12px;
      background-color: #111;
      box-shadow: none;
      border-radius: 5px;
      width: 100%;
      color: #FFF;
      font-weight: 400;
      font-size: .85rem;
      font-family: Roboto Mono, monospace;
    }
  }
}
NGPixel's avatar
NGPixel committed
549
</style>