comments.vue 15.6 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(
NGPixel's avatar
NGPixel committed
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
NGPixel's avatar
NGPixel committed
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'
15
      :aria-label='$t(`common:comments.fieldContent`)'
NGPixel's avatar
NGPixel committed
16
    )
17 18 19 20 21 22
    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`'
23
          :placeholder='$t(`common:comments.fieldName`)'
24 25 26 27
          hide-details
          dense
          autocomplete='name'
          v-model='guestName'
28
          :aria-label='$t(`common:comments.fieldName`)'
29 30 31 32 33 34
        )
      v-col(cols='12', lg='6')
        v-text-field(
          outlined
          color='blue-grey darken-2'
          :background-color='$vuetify.theme.dark ? `grey darken-5` : `white`'
35
          :placeholder='$t(`common:comments.fieldEmail`)'
36 37 38 39 40
          hide-details
          type='email'
          dense
          autocomplete='email'
          v-model='guestEmail'
41
          :aria-label='$t(`common:comments.fieldEmail`)'
42 43
        )
    .d-flex.align-center.pt-3(v-if='permissions.write')
NGPixel's avatar
NGPixel committed
44
      v-icon.mr-1(color='blue-grey') mdi-language-markdown-outline
45
      .caption.blue-grey--text {{$t('common:comments.markdownFormat')}}
NGPixel's avatar
NGPixel committed
46
      v-spacer
47 48
      .caption.mr-3(v-if='isAuthenticated')
        i18next(tag='span', path='common:comments.postingAs')
49
          strong(place='name') {{userDisplayName}}
NGPixel's avatar
NGPixel committed
50 51
      v-btn(
        dark
NGPixel's avatar
NGPixel committed
52 53 54
        color='blue-grey darken-2'
        @click='postComment'
        depressed
55
        :aria-label='$t(`common:comments.postComment`)'
NGPixel's avatar
NGPixel committed
56 57
        )
        v-icon(left) mdi-comment
58
        span.text-none {{$t('common:comments.postComment')}}
59
    v-divider.mt-3(v-if='permissions.write')
60
    .pa-5.d-flex.align-center.justify-center(v-if='isLoading && !hasLoadedOnce')
NGPixel's avatar
NGPixel committed
61 62 63 64 65 66
      v-progress-circular(
        indeterminate
        size='20'
        width='1'
        color='blue-grey'
      )
67
      .caption.blue-grey--text.pl-3: em {{$t('common:comments.loading')}}
NGPixel's avatar
NGPixel committed
68 69
    v-timeline(
      dense
NGPixel's avatar
NGPixel committed
70
      v-else-if='comments && comments.length > 0'
NGPixel's avatar
NGPixel committed
71
      )
72
      v-timeline-item.comments-post(
NGPixel's avatar
NGPixel committed
73 74
        color='pink darken-4'
        large
NGPixel's avatar
NGPixel committed
75 76
        v-for='cm of comments'
        :key='`comment-` + cm.id'
77
        :id='`comment-post-id-` + cm.id'
NGPixel's avatar
NGPixel committed
78 79
        )
        template(v-slot:icon)
80 81 82
          v-avatar(color='blue-grey')
            //- v-img(src='http://i.pravatar.cc/64')
            span.white--text.title {{cm.initials}}
NGPixel's avatar
NGPixel committed
83 84
        v-card.elevation-1
          v-card-text
NGPixel's avatar
NGPixel committed
85
            .comments-post-actions(v-if='permissions.manage && !isBusy && commentEditId === 0')
86 87 88
              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}}
89
            .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
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
            .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
112
                  span.text-none {{$t('common:actions.cancel')}}
NGPixel's avatar
NGPixel committed
113 114 115 116 117 118 119
                v-btn(
                  dark
                  color='blue-grey darken-2'
                  @click='updateComment'
                  depressed
                  )
                  v-icon(left) mdi-comment
120 121 122
                  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')}}
123 124 125

    v-dialog(v-model='deleteCommentDialogShown', max-width='500')
      v-card
126
        .dialog-header.is-red {{$t('common:comments.deleteConfirmTitle')}}
127
        v-card-text.pt-5
128 129
          span {{$t('common:comments.deleteWarn')}}
          .caption: strong {{$t('common:comments.deletePermanentWarn')}}
130 131 132 133
        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
134 135 136
</template>

<script>
NGPixel's avatar
NGPixel committed
137 138
import gql from 'graphql-tag'
import { get } from 'vuex-pathify'
139 140
import validate from 'validate.js'
import _ from 'lodash'
NGPixel's avatar
NGPixel committed
141

NGPixel's avatar
NGPixel committed
142
export default {
NGPixel's avatar
NGPixel committed
143 144 145 146
  data () {
    return {
      newcomment: '',
      isLoading: true,
147
      hasLoadedOnce: false,
148 149
      comments: [],
      guestName: '',
150 151
      guestEmail: '',
      commentToDelete: {},
NGPixel's avatar
NGPixel committed
152 153
      commentEditId: 0,
      commentEditContent: null,
154 155 156 157 158 159 160
      deleteCommentDialogShown: false,
      isBusy: false,
      scrollOpts: {
        duration: 1500,
        offset: 0,
        easing: 'easeInOutCubic'
      }
NGPixel's avatar
NGPixel committed
161 162 163
    }
  },
  computed: {
164
    pageId: get('page/id'),
165
    permissions: get('page/effectivePermissions@comments'),
166 167
    isAuthenticated: get('user/authenticated'),
    userDisplayName: get('user/name')
NGPixel's avatar
NGPixel committed
168 169
  },
  methods: {
170 171
    onIntersect (entries, observer, isIntersecting) {
      if (isIntersecting) {
NGPixel's avatar
NGPixel committed
172
        this.fetch(true)
173
      }
NGPixel's avatar
NGPixel committed
174
    },
NGPixel's avatar
NGPixel committed
175
    async fetch (silent = false) {
176
      this.isLoading = true
NGPixel's avatar
NGPixel committed
177 178 179 180 181 182 183 184 185 186 187 188
      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
                }
189 190
              }
            }
NGPixel's avatar
NGPixel committed
191 192 193 194 195 196 197 198 199 200 201 202
          `,
          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)
203
          }
NGPixel's avatar
NGPixel committed
204 205 206 207 208 209 210 211 212 213 214
          c.initials = initials
          return c
        })
      } catch (err) {
        console.warn(err)
        if (!silent) {
          this.$store.commit('showNotification', {
            style: 'red',
            message: err.message,
            icon: 'alert'
          })
215
        }
NGPixel's avatar
NGPixel committed
216
      }
217 218 219 220 221 222
      this.isLoading = false
      this.hasLoadedOnce = true
    },
    /**
     * Post New Comment
     */
NGPixel's avatar
NGPixel committed
223
    async postComment () {
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 261 262 263 264
      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
265

NGPixel's avatar
NGPixel committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
      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
291 292 293
                }
              }
            }
NGPixel's avatar
NGPixel committed
294 295 296 297 298 299 300
          `,
          variables: {
            pageId: this.pageId,
            replyTo: 0,
            content: this.newcomment,
            guestName: this.guestName,
            guestEmail: this.guestEmail
301 302 303
          }
        })

NGPixel's avatar
NGPixel committed
304 305 306
        if (_.get(resp, 'data.comments.create.responseResult.succeeded', false)) {
          this.$store.commit('showNotification', {
            style: 'success',
307
            message: this.$t('common:comments.postSuccess'),
NGPixel's avatar
NGPixel committed
308 309 310 311 312 313 314 315 316
            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 {
317
          throw new Error(_.get(resp, 'data.comments.create.responseResult.message', 'An unexpected error occurred.'))
NGPixel's avatar
NGPixel committed
318 319
        }
      } catch (err) {
320 321
        this.$store.commit('showNotification', {
          style: 'red',
NGPixel's avatar
NGPixel committed
322
          message: err.message,
323 324 325
          icon: 'alert'
        })
      }
326
    },
NGPixel's avatar
NGPixel committed
327 328 329
    /**
     * Show Comment Editing Form
     */
330
    async editComment (cm) {
NGPixel's avatar
NGPixel committed
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 376 377 378 379
      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) {
380
          throw new Error(this.$t('common:comments.contentMissingError'))
NGPixel's avatar
NGPixel committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
        }
        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
          }
        })
409

NGPixel's avatar
NGPixel committed
410 411 412
        if (_.get(resp, 'data.comments.update.responseResult.succeeded', false)) {
          this.$store.commit('showNotification', {
            style: 'success',
413
            message: this.$t('common:comments.updateSuccess'),
NGPixel's avatar
NGPixel committed
414 415 416 417 418 419 420 421 422
            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 {
423
          throw new Error(_.get(resp, 'data.comments.delete.responseResult.message', 'An unexpected error occurred.'))
NGPixel's avatar
NGPixel committed
424 425 426 427 428 429 430 431 432 433 434
        }
      } 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')
435
    },
NGPixel's avatar
NGPixel committed
436 437 438
    /**
     * Show Delete Comment Confirmation Dialog
     */
439 440 441 442 443 444 445 446 447 448 449 450
    deleteCommentConfirm (cm) {
      this.commentToDelete = cm
      this.deleteCommentDialogShown = true
    },
    /**
     * Delete Comment
     */
    async deleteComment () {
      this.$store.commit(`loadingStart`, 'comments-delete')
      this.isBusy = true
      this.deleteCommentDialogShown = false

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

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

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

<style lang="scss">
502 503
.comments-post {
  position: relative;
NGPixel's avatar
NGPixel committed
504

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
  &: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%;
NGPixel's avatar
NGPixel committed
531
      border-radius: 5px;
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    }

    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
553
</style>