page.js 12.5 KB
Newer Older
1
import { defineStore } from 'pinia'
2
import gql from 'graphql-tag'
3
import { cloneDeep, dropRight, initial, last, pick, transform } from 'lodash-es'
4
import { DateTime } from 'luxon'
5 6

import { useSiteStore } from './site'
7 8
import { useEditorStore } from './editor'

9 10
const pagePropsFragment = gql`
  fragment PageRead on Page {
11
    alias
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    allowComments
    allowContributions
    allowRatings
    contentType
    createdAt
    description
    editor
    icon
    id
    isBrowsable
    locale
    password
    path
    publishEndDate
    publishStartDate
    publishState
    relations {
      id
      position
      label
      caption
      icon
      target
    }
    render
    scriptJsLoad
    scriptJsUnload
    scriptCss
    showSidebar
    showTags
    showToc
    tags {
      tag
      title
    }
    title
    toc
    tocDepth {
      min
      max
    }
    updatedAt
  }
`
56 57 58 59 60 61 62 63
const gqlQueries = {
  pageById: gql`
    query loadPage (
      $id: UUID!
    ) {
      pageById(
        id: $id
      ) {
64
        ...PageRead
65 66
      }
    }
67
    ${pagePropsFragment}
68 69 70 71 72 73 74 75 76 77
  `,
  pageByPath: gql`
    query loadPage (
      $siteId: UUID!
      $path: String!
    ) {
      pageByPath(
        siteId: $siteId
        path: $path
      ) {
78
        ...PageRead
79 80
      }
    }
81
    ${pagePropsFragment}
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
  `,
  pageByIdWithContent: gql`
    query loadPageWithContent (
      $id: UUID!
    ) {
      pageById(
        id: $id
      ) {
        ...PageRead,
        content
      }
    }
    ${pagePropsFragment}
  `,
  pageByPathWithContent: gql`
    query loadPageWithContent (
      $siteId: UUID!
      $path: String!
    ) {
      pageByPath(
        siteId: $siteId
        path: $path
      ) {
        ...PageRead,
        content
      }
    }
    ${pagePropsFragment}
110 111
  `
}
112

113 114 115
const gqlMutations = {
  createPage: gql`
    mutation createPage (
116
      $alias: String
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
      $allowComments: Boolean
      $allowContributions: Boolean
      $allowRatings: Boolean
      $content: String!
      $description: String!
      $editor: String!
      $icon: String
      $isBrowsable: Boolean
      $locale: String!
      $path: String!
      $publishState: PagePublishState!
      $publishEndDate: Date
      $publishStartDate: Date
      $relations: [PageRelationInput!]
      $scriptCss: String
      $scriptJsLoad: String
      $scriptJsUnload: String
      $showSidebar: Boolean
      $showTags: Boolean
      $showToc: Boolean
      $siteId: UUID!
      $tags: [String!]
      $title: String!
      $tocDepth: PageTocDepthInput
    ) {
      createPage (
143
        alias: $alias
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
        allowComments: $allowComments
        allowContributions: $allowContributions
        allowRatings: $allowRatings
        content: $content
        description: $description
        editor: $editor
        icon: $icon
        isBrowsable: $isBrowsable
        locale: $locale
        path: $path
        publishState: $publishState
        publishEndDate: $publishEndDate
        publishStartDate: $publishStartDate
        relations: $relations
        scriptCss: $scriptCss
        scriptJsLoad: $scriptJsLoad
        scriptJsUnload: $scriptJsUnload
        showSidebar: $showSidebar
        showTags: $showTags
        showToc: $showToc
        siteId: $siteId
        tags: $tags
        title: $title
        tocDepth: $tocDepth
      ) {
        operation {
          succeeded
          message
        }
        page {
          ...PageRead
        }
      }
    }
    ${pagePropsFragment}
  `
}

182 183
export const usePageStore = defineStore('page', {
  state: () => ({
184
    alias: '',
185 186 187
    allowComments: false,
    allowContributions: true,
    allowRatings: true,
188
    authorId: 0,
189
    authorName: '',
190 191
    commentsCount: 0,
    content: '',
192
    createdAt: '',
193
    description: '',
194
    editor: '',
195 196 197
    icon: 'las la-file-alt',
    id: '',
    isBrowsable: true,
198
    locale: 'en',
199
    password: '',
200 201 202
    path: '',
    publishEndDate: '',
    publishStartDate: '',
203
    publishState: '',
204
    relations: [],
205
    render: '',
206 207
    scriptJsLoad: '',
    scriptJsUnload: '',
208
    scriptCss: '',
209 210
    showSidebar: true,
    showTags: true,
211 212 213 214
    showToc: true,
    tags: [],
    title: '',
    toc: [],
215 216 217 218
    tocDepth: {
      min: 1,
      max: 2
    },
219
    updatedAt: ''
220
  }),
221 222 223 224 225 226 227 228 229 230 231 232 233
  getters: {
    breadcrumbs: (state) => {
      const siteStore = useSiteStore()
      const pathPrefix = siteStore.useLocales ? `/${state.locale}` : ''
      return transform(state.path.split('/'), (result, value, key) => {
        result.push({
          id: key,
          title: value,
          icon: 'las la-file-alt',
          locale: 'en',
          path: (last(result)?.path || pathPrefix) + `/${value}`
        })
      }, [])
234 235 236
    },
    folderPath: (state) => {
      return initial(state.path.split('/')).join('/')
237 238
    }
  },
239
  actions: {
240 241 242
    /**
     * PAGE - LOAD
     */
243
    async pageLoad ({ path, id, withContent = false }) {
244
      const editorStore = useEditorStore()
245 246
      const siteStore = useSiteStore()
      try {
247 248 249 250 251 252
        let query
        if (withContent) {
          query = id ? gqlQueries.pageByIdWithContent : gqlQueries.pageByPathWithContent
        } else {
          query = id ? gqlQueries.pageById : gqlQueries.pageByPath
        }
253
        const resp = await APOLLO_CLIENT.query({
254
          query,
255
          variables: id ? { id } : { siteId: siteStore.id, path },
256 257
          fetchPolicy: 'network-only'
        })
258
        const pageData = cloneDeep((id ? resp?.data?.pageById : resp?.data?.pageByPath) ?? {})
259 260 261
        if (!pageData?.id) {
          throw new Error('ERR_PAGE_NOT_FOUND')
        }
262
        // Update page store
263 264 265 266 267
        this.$patch({
          ...pageData,
          relations: pageData.relations.map(r => pick(r, ['id', 'position', 'label', 'caption', 'icon', 'target'])),
          tocDepth: pick(pageData.tocDepth, ['min', 'max'])
        })
268 269 270 271 272
        // Update editor state timestamps
        const curDate = DateTime.utc()
        editorStore.$patch({
          lastChangeTimestamp: curDate,
          lastSaveTimestamp: curDate
273 274 275 276 277 278
        })
      } catch (err) {
        console.warn(err)
        throw err
      }
    },
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    /**
     * PAGE - GET PATH FROM ALIAS
     */
    async pageAlias (alias) {
      const siteStore = useSiteStore()
      try {
        const resp = await APOLLO_CLIENT.query({
          query: gql`
            query fetchPathFromAlias (
              $siteId: UUID!
              $alias: String!
            ) {
              pathFromAlias (
                siteId: $siteId
                alias: $alias
              ) {
                id
                path
              }
            }
          `,
          variables: { siteId: siteStore.id, alias },
          fetchPolicy: 'cache-first'
        })
        const pagePath = cloneDeep(resp?.data?.pathFromAlias)
        if (!pagePath?.id) {
          throw new Error('ERR_PAGE_NOT_FOUND')
        }
        return pagePath.path
      } catch (err) {
        console.warn(err)
        throw err
      }
    },
313 314 315
    /**
     * PAGE - CREATE
     */
316
    async pageCreate ({ editor, locale, path, title = '', description = '', content = '' }) {
317
      const editorStore = useEditorStore()
318

319 320 321 322
      if (!editorStore.configIsLoaded) {
        await editorStore.fetchConfigs()
      }

323 324
      const noDefaultPath = Boolean(!path && path !== '')

325 326 327 328 329 330 331
      // -> Init editor
      editorStore.$patch({
        originPageId: editorStore.isActive ? editorStore.originPageId : this.id, // Don't replace if already in edit mode
        isActive: true,
        mode: 'create',
        editor
      })
332

333 334 335
      // -> Default Page Path
      let newPath = path
      if (!path && path !== '') {
336 337
        const parentPath = dropRight(this.path.split('/'), 1).join('/')
        newPath = parentPath ? `${parentPath}/new-page` : 'new-page'
338 339
      }

340 341 342 343 344 345 346 347
      // -> Set Default Page Data
      this.$patch({
        id: 0,
        locale: locale || this.locale,
        path: newPath,
        title: title ?? '',
        description: description ?? '',
        icon: 'las la-file-alt',
348
        alias: '',
349 350 351 352 353 354
        publishState: 'published',
        relations: [],
        tags: [],
        content: content ?? '',
        render: '',
        mode: 'edit'
355
      })
356

357 358 359
      if (noDefaultPath) {
        this.router.push(`/_create/${editor}`)
      }
360
    },
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    /**
     * PAGE - EDIT
     */
    async pageEdit () {
      const editorStore = useEditorStore()

      await this.pageLoad({ id: this.id, withContent: true })

      if (!editorStore.configIsLoaded) {
        await editorStore.fetchConfigs()
      }

      editorStore.$patch({
        isActive: true,
        mode: 'edit',
        editor: this.editor
      })
    },
379 380 381 382 383
    /**
     * PAGE SAVE
     */
    async pageSave () {
      const editorStore = useEditorStore()
384
      const siteStore = useSiteStore()
385
      try {
386 387
        if (editorStore.mode === 'create') {
          const resp = await APOLLO_CLIENT.mutate({
388
            mutation: gqlMutations.createPage,
389 390
            variables: {
              ...pick(this, [
391
                'alias',
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
                'allowComments',
                'allowContributions',
                'allowRatings',
                'content',
                'description',
                'icon',
                'isBrowsable',
                'locale',
                'password',
                'path',
                'publishEndDate',
                'publishStartDate',
                'publishState',
                'relations',
                'scriptJsLoad',
                'scriptJsUnload',
                'scriptCss',
                'showSidebar',
                'showTags',
                'showToc',
                'tags',
                'title',
                'tocDepth'
              ]),
              editor: editorStore.editor,
              siteId: siteStore.id
418
            }
419 420 421 422 423
          })
          const result = resp?.data?.createPage?.operation ?? {}
          if (!result.succeeded) {
            throw new Error(result.message)
          }
424 425 426 427 428 429 430 431 432 433 434
          const pageData = cloneDeep(resp.data.createPage.page ?? {})
          if (!pageData?.id) {
            throw new Error('ERR_CREATED_PAGE_NOT_FOUND')
          }
          // Update page store
          this.$patch({
            ...pageData,
            relations: pageData.relations.map(r => pick(r, ['id', 'position', 'label', 'caption', 'icon', 'target'])),
            tocDepth: pick(pageData.tocDepth, ['min', 'max'])
          })

435 436 437 438
          editorStore.$patch({
            mode: 'edit'
          })

439
          this.router.replace(`/${this.path}`)
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
        } else {
          const resp = await APOLLO_CLIENT.mutate({
            mutation: gql`
              mutation savePage (
                $id: UUID!
                $patch: PageUpdateInput!
              ) {
                updatePage (
                  id: $id
                  patch: $patch
                ) {
                  operation {
                    succeeded
                    message
                  }
                }
              }
              `,
            variables: {
              id: this.id,
460 461
              patch: {
                ...pick(this, [
462
                  'alias',
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
                  'allowComments',
                  'allowContributions',
                  'allowRatings',
                  'content',
                  'description',
                  'icon',
                  'isBrowsable',
                  'locale',
                  'password',
                  'path',
                  'publishEndDate',
                  'publishStartDate',
                  'publishState',
                  'relations',
                  'scriptJsLoad',
                  'scriptJsUnload',
                  'scriptCss',
                  'showSidebar',
                  'showTags',
                  'showToc',
                  'tags',
                  'title',
                  'tocDepth'
                ]),
                reasonForChange: editorStore.reasonForChange
              }
489 490 491 492 493
            }
          })
          const result = resp?.data?.updatePage?.operation ?? {}
          if (!result.succeeded) {
            throw new Error(result.message)
494 495 496 497 498 499
          }
        }
        // Update editor state timestamps
        const curDate = DateTime.utc()
        editorStore.$patch({
          lastChangeTimestamp: curDate,
500 501
          lastSaveTimestamp: curDate,
          reasonForChange: ''
502 503 504 505 506 507
        })
      } catch (err) {
        console.warn(err)
        throw err
      }
    },
508 509 510 511 512
    async cancelPageEdit () {
      const editorStore = useEditorStore()
      await this.pageLoad({ id: editorStore.originPageId ? editorStore.originPageId : this.id })
      this.router.replace(`/${this.path}`)
    },
513 514 515 516 517
    generateToc () {

    }
  }
})