GridEditor.vue 21.2 KB
Newer Older
Anton's avatar
Intial  
Anton committed
1
2
3
4
5
6
7
8
9
10
11
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
<template lang="pug">

  div.cell-grid-container

    div.cell-grid(
      @dragenter="handleGridDragOver",
      @dragover="handleGridDragOver",
      @dragleave="handleGridDragEnd",
      @drop="handleGridDrop",
      @contextmenu="handleGridContextMenu",
      :style="gridStyle")

      q-context-menu(ref="gridmenu")
        q-list(link, separator, no-border, style="min-width: 150px; max-height: 300px;")
          q-item(
            v-for="action in gridContextMenuActions",
            :key="action.label",
            v-close-overlay,
            @click.native="event => {action.handler(event)}")
              q-item-main(:label="action.label")

      template(v-if="!resizingGrid")

        template(v-for="(cell, index) in cells")
          .cell-item(
            v-if="cellUIStates[cell.uuid] && !cellUIStates[cell.uuid].beingDragged",
            draggable="true",
            @dragstart="event => {handleCellDragStart(event, cell)}",
            @dragend="event => {handleCellDragEnd(event, cell)}",
            @contextmenu="handleCellContextMenu",
            :style="getCellStyle(cell)",
            :title="cell.title",
            @click.prevent="event => {handleCellClick(event, cell)}",
            :class="{selected: cellUIStates[cell.uuid] ? cellUIStates[cell.uuid].selected : false}",
            :key="`cell-${index}`")
              cell(:cell="cell", preview)
              div.cell-item-resize-handle(
                draggable="true",
                @dragstart="event => {handleCellResizerDragStart(event, cell)}",
                @dragend="event => {handleCellResizerDragEnd(event, cell)}",
                @dragexit="event => {handleCellResizerDragEnd(event, cell)}")
                  q-icon(name="network cell")

              q-context-menu
                q-list(link, separator, no-border, style="min-width: 150px; max-height: 300px;")
                  q-item(
                    v-for="action in cellContextMenuActions",
                    :key="action.label",
                    v-close-overlay,
                    @click.native="event => {action.handler(event, cell)}")
                      q-item-main(:label="action.label")

        template(v-for="(tmpCell, index) in tmpCells")
          .cell-item.cell-item-tmp(:style="getCellStyle(tmpCell)", :key="`cell-tmp-${index}`")
            cell(:cell="tmpCell")

      template(v-else)
        .cell-item(:style="getCellStyle({x:0,y:0,width:1,height:1})", key="cell-grid-resizer")
          div.cell-item-resize-handle(
            draggable="true",
            @dragstart="event => {handleGridResizerDragStart(event)}",
            @dragend="event => {handleGridResizerDragEnd(event)}",
            @dragexit="event => {handleGridResizerDragEnd(event)}")
              q-icon(name="network cell")

      div.fixed-top-right(style="right:18px; top:68px", v-if="!$store.state.mosysGridEditorStore.showSources")
        q-btn(round, color="primary", small, @click="handleGridButtonClickEdit", style="margin-right: 0.5em")
          q-icon(name="add")
        q-btn(round, color="primary", small, @click="$router.push(`/mosys/grids/${$route.params.id}`)")
          q-icon(name="remove red eye")

</template>

<script>
  import { ObjectUtil } from 'mbjs-utils'
  import Cell from './Cell'

  const nullImage = new Image()
  nullImage.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='

  export default {
    components: {
      Cell
    },
    props: ['gridUuid'],
    data () {
      return {
        cellContextMenuActions: {
          // edit: {
          //   label: 'Edit',
          //   handler: this.handleCellContextMenuEdit
          // },
          delete: {
            label: 'Delete',
            handler: this.handleCellContextMenuDelete
          },
          insert_column_left: {
            label: 'Insert Column Left',
            handler: this.handleGridContextMenuInsertColumnLeft
          },
          insert_row_above: {
            label: 'Insert Row Above',
            handler: this.handleGridContextMenuInsertRowAbove
          }
        },
        gridContextMenuActions: {
          // add_cell: {
          //   label: 'Add Cell',
          //   handler: this.handleGridContextMenuAddCell
          // },
          insert_column_left: {
            label: 'Insert Column Left',
            handler: this.handleGridContextMenuInsertColumnLeft
          },
          delete_column: {
            label: 'Delete Column',
            handler: this.handleGridContextMenuDeleteColumn
          },
          insert_row_above: {
            label: 'Insert Row Above',
            handler: this.handleGridContextMenuInsertRowAbove
          },
          delete_row: {
            label: 'Delete Row',
            handler: this.handleGridContextMenuDeleteRow
          },
          edit_grid_dimensions: {
            label: 'Change Grid',
            handler: () => { this.resizingGrid = !this.resizingGrid }
          }
        },
        grid: undefined,
        gridMetadata: {},
        cells: [],
        tmpCells: [],
        cellUIStates: {},
Anton's avatar
Anton committed
137
        gridDimensions: { gridWidth: 0, gridHeight: 0, cellWidth: 0, cellHeight: 0 },
Anton's avatar
Intial  
Anton committed
138
139
140
141
142
143
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
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
        gridStyle: {},
        contextMenuClickPosition: {},
        resizingGrid: false
      }
    },
    async mounted () {
      window.addEventListener('resize', this.updateGridDimensions)
      await this.fetchData()
    },
    beforeDestroy () {
      window.removeEventListener('resize', this.updateGridDimensions)
    },
    watch: {
      cells () {
        this.updateCellUIStates()
      },
      gridMetadata () {
        this.updateGridDimensions()
      },
      async gridUuid () {
        await this.fetchData()
      }
    },
    methods: {
      async fetchData () {
        if (this.gridUuid) {
          this.grid = await this.$store.dispatch('maps/get', this.gridUuid)
          await this.fetchMetadataAnnotations()
          this.updateGridDimensions()
          await this.fetchCellAnnotations()
        }
      },
      handleGridResizerDragStart (event) {
        event.dataTransfer.setDragImage(nullImage, 0, 0)
      },
      async handleGridResizerDragEnd () {
        await this.updateGridMetadataStore()
      },
      handleCellResizerDragStart (event, cell) {
        event.dataTransfer.setDragImage(nullImage, 0, 0)
        this.cellUIStates[cell.uuid].beingResized = true
        let tmpCell = this.getTmpCell(cell)
        this.tmpCells.push(tmpCell)
      },
      handleCellResizerDragEnd (event, cell) {
        let position = this.getGridPositionForEvent(event)
        cell.width = Math.max(1, 1 + position.x - cell.x)
        cell.height = Math.max(1, 1 + position.y - cell.y)
        this.cellUIStates[cell.uuid].beingResized = false
        this.tmpCells = []
        this.updateCellStore(cell)
      },
      handleCellClick (event, cell) {
        this.cellUIStates[cell.uuid].selected = !this.cellUIStates[cell.uuid].selected
        this.updateSelectedCells()
      },
      handleCellDragStart (event, cell) {
        if (this.cellUIStates[cell.uuid].beingResized) {
        }
        else {
          event.dataTransfer.setData('text/plain', JSON.stringify(cell))
          event.dataTransfer.setDragImage(nullImage, 0, 0)
          let elContainerBoundingBox = this.$el.getBoundingClientRect()
          let elBoundingBox = event.srcElement.getBoundingClientRect()
          let offset = {
            x: (event.clientX - elContainerBoundingBox.x) - (elBoundingBox.x - elContainerBoundingBox.x),
            y: (event.clientY - elContainerBoundingBox.y) - (elBoundingBox.y - elContainerBoundingBox.y)
          }
          this.cellUIStates[cell.uuid].draggingOffset = offset
          this.cellUIStates[cell.uuid].beginDragged = true
        }
        let tmpCell = this.getTmpCell(cell)
        this.tmpCells.push(tmpCell)
      },
      handleCellDragEnd (event, cell) {
        this.cellUIStates[cell.uuid].beingDragged = false
      },
      // handleCellContextMenuClick () {
      // },
      // handleCellContextMenuEdit (/* event, cell */) {
      //   // this.$store.commit('mosysGridEditorStore/showSources')
      //   // this.$store.commit('mosysGridEditorStore/setSourcesTab', 'tab-default-cells')
      // },
      async handleCellContextMenuDelete (event, cell) {
        this.cellUIStates[cell.uuid].selected = false
        this.updateSelectedCells()
        this.cells = this.cells.filter(c => c !== cell)
        await this.$store.dispatch('annotations/delete', cell.uuid)
        this.fetchCellAnnotations()
      },
      handleCellContextMenu (event) {
        this.contextMenuClickPosition = this.getGridPositionForEvent(event)
      },
      handleGridDragOver (event) {
        let _this = this
        if (this.resizingGrid) {
          const position = this.getGridPositionForEvent(event)
          this.gridMetadata.ratio = position.ox / (position.oy * 1.0)
          this.updateGridDimensions()
        }
        else {
          let cell = Object.keys(this.cellUIStates).filter(uuid => {
            return _this.cellUIStates[uuid].beginDragged || _this.cellUIStates[uuid].beingResized
          }).map(uuid => {
            return _this.cellUIStates[uuid].cell
          }).shift()
          let offset, position
          if (!cell) {
Anton's avatar
Anton committed
246
            cell = { uuid: null, x: 1, y: 1, width: 1, height: 1 }
Anton's avatar
Intial  
Anton committed
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
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
313
314
315
316
317
318
319
320
            position = this.getGridPositionForEvent(event)
          }
          else {
            offset = this.cellUIStates[cell.uuid].draggingOffset
            position = this.getGridPositionForEvent(event, offset)
          }
          let tmpCell = this.tmpCells[0]
          if (!tmpCell && this.tmpCells.length === 0) {
            tmpCell = this.getTmpCell(cell)
            this.tmpCells.push(tmpCell)
          }
          if (event.dataTransfer.types.includes('text/plain')) {
            tmpCell.x = position.x
            tmpCell.y = position.y
            event.preventDefault()
          }
          else {
            tmpCell.width = Math.max(1, 1 + position.x - tmpCell.x)
            tmpCell.height = Math.max(1, 1 + position.y - tmpCell.y)
          }
        }
      },
      handleGridDragEnd () {
        this.tmpCells = []
      },
      handleGridDrop (event) {
        let cellDropped = event.dataTransfer.getData('text/plain')
        if (cellDropped) {
          cellDropped = JSON.parse(cellDropped)
          let cell = this.cells.find(c => c.uuid === cellDropped.uuid)
          let offset, position
          if (cell) {
            offset = this.cellUIStates[cell.uuid].draggingOffset
            position = this.getGridPositionForEvent(event, offset)
          }
          else {
            cell = cellDropped
            position = this.getGridPositionForEvent(event)
          }
          cell.x = position.x
          cell.y = position.y
          this.tmpCells = []
          this.updateCellStore(cell)
          event.preventDefault()
        }
      },
      handleGridContextMenu (event) {
        this.contextMenuClickPosition = this.getGridPositionForEvent(event)
      },
      async handleGridContextMenuAddCell () {
        let position = this.contextMenuClickPosition
        let newCell = {
          x: position.x,
          y: position.y,
          width: 1,
          height: 1,
          type: 'text',
          content: 'A new cell is born'
        }
        let annotation = this.getGridCellAnnotation(newCell)
        await this.$store.dispatch('annotations/post', annotation)
        await this.fetchCellAnnotations()
      },
      async handleGridContextMenuInsertColumnLeft () {
        let position = this.contextMenuClickPosition
        for (let cell of this.cells) {
          if (cell.x >= position.x) {
            cell.x += 1
            let annotation = this.getGridCellAnnotation(cell)
            await this.$store.dispatch('annotations/patch', [cell.uuid, annotation])
            await this.fetchCellAnnotations()
          }
        }

Anton's avatar
Anton committed
321
        this.gridMetadata = ObjectUtil.merge({}, this.gridMetadata, { columns: this.gridMetadata.columns + 1 })
Anton's avatar
Intial  
Anton committed
322
323
324
325
326
327
328
329
330
331
332
333
334
        await this.updateGridMetadataStore()
      },
      async handleGridContextMenuDeleteColumn () {
        let position = this.contextMenuClickPosition
        for (let cell of this.cells) {
          if (cell.x > position.x) {
            cell.x -= 1
            let annotation = this.getGridCellAnnotation(cell)
            await this.$store.dispatch('annotations/patch', [cell.uuid, annotation])
            await this.fetchCellAnnotations()
          }
        }

Anton's avatar
Anton committed
335
        this.gridMetadata = ObjectUtil.merge({}, this.gridMetadata, { columns: this.gridMetadata.columns - 1 })
Anton's avatar
Intial  
Anton committed
336
337
338
339
340
341
342
343
344
345
346
347
        await this.updateGridMetadataStore()
      },
      async handleGridContextMenuInsertRowAbove () {
        let position = this.contextMenuClickPosition
        for (let cell of this.cells) {
          if (cell.y >= position.y) {
            cell.y += 1
            let annotation = this.getGridCellAnnotation(cell)
            await this.$store.dispatch('annotations/patch', [cell.uuid, annotation])
            await this.fetchCellAnnotations()
          }
        }
Anton's avatar
Anton committed
348
        this.gridMetadata = ObjectUtil.merge({}, this.gridMetadata, { rows: this.gridMetadata.rows + 1 })
Anton's avatar
Intial  
Anton committed
349
350
351
352
353
354
355
356
357
358
359
360
361

        await this.updateGridMetadataStore()
      },
      async handleGridContextMenuDeleteRow () {
        let position = this.contextMenuClickPosition
        for (let cell of this.cells) {
          if (cell.y > position.y) {
            cell.y -= 1
            let annotation = this.getGridCellAnnotation(cell)
            await this.$store.dispatch('annotations/patch', [cell.uuid, annotation])
            await this.fetchCellAnnotations()
          }
        }
Anton's avatar
Anton committed
362
        this.gridMetadata = ObjectUtil.merge({}, this.gridMetadata, { rows: this.gridMetadata.rows - 1 })
Anton's avatar
Intial  
Anton committed
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399

        await this.updateGridMetadataStore()
      },
      handleGridButtonClickEdit () {
        this.$store.commit('mosysGridEditorStore/toggleSources')
      },
      updateSelectedCells () {
        const _this = this
        let selectedCells = Object.keys(this.cellUIStates).filter(k => {
          return _this.cellUIStates[k].selected
        }).map(k => {
          return _this.cells.find(c => c.uuid === k)
        })
        this.$store.commit('mosysGridEditorStore/setSelectedCells', selectedCells)
      },
      updateCellUIStates () {
        let newCellUIStates = {}
        this.cells.map(c => {
          newCellUIStates[c.uuid] = {
            selected: false,
            beingResized: false,
            cell: c
          }
        })
        this.cellUIStates = newCellUIStates
        this.updateSelectedCells()
      },
      getTmpCell (cell, type = 'UIFeedback') {
        return {
          srcUuid: cell.uuid,
          type: type,
          x: cell.x,
          y: cell.y,
          width: cell.width,
          height: cell.height
        }
      },
Anton's avatar
Anton committed
400
401
      getGridPositionForEvent (event, offset = { x: 0, y: 0 }) {
        offset = { x: 0, y: 0 } // TODO: remove quick fix
Anton's avatar
Intial  
Anton committed
402
403
404
405
406
        const elContainerBoundingBox = this.$el.getBoundingClientRect()
        const ox = event.clientX + this.$el.scrollLeft - elContainerBoundingBox.x - offset.x
        const oy = event.clientY + this.$el.scrollTop - elContainerBoundingBox.y - offset.y
        const x = Math.ceil(ox / this.gridDimensions.full.cell.width)
        const y = Math.ceil(oy / this.gridDimensions.full.cell.height)
Anton's avatar
Anton committed
407
        return { x: x, y: y, ox: ox, oy: oy }
Anton's avatar
Intial  
Anton committed
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
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
489
490
491
492
493
494
495
496
497
498
499
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
      },
      updateGridDimensions () {
        let elWidth = this.$el.offsetWidth
        let elHeight = this.$el.offsetHeight
        let cellSizeRatio = this.gridMetadata.ratio
        let gridHeight = elHeight
        let cellHeight = gridHeight / this.gridMetadata.rows
        let cellWidth = elWidth / Math.round(elWidth / (cellHeight * cellSizeRatio))
        let gridWidth = cellWidth * this.gridMetadata.columns
        let cellsPerWidth = elWidth / cellWidth
        let cellWidthMini = elWidth / this.gridMetadata.columns
        let gridHeightMini = cellWidthMini / cellSizeRatio
        this.gridDimensions = {
          full: {
            width: gridWidth,
            height: gridHeight,
            cell: {
              width: cellWidth,
              height: cellHeight
            },
            cells_per_width: cellsPerWidth
          },
          mini: {
            width: elWidth,
            height: gridHeightMini * this.gridMetadata.rows,
            cell: {
              width: cellWidthMini,
              height: gridHeightMini
            }
          }
        }
        // TODO: fix mobile grid editor view
        // if (elWidth > 800) {
        this.gridStyle = {
          width: this.gridDimensions.full.width + 'px',
          height: '100%',
          'grid-auto-columns': this.gridDimensions.full.cell.width + 'px',
          'grid-auto-rows': this.gridDimensions.full.cell.height + 'px',
          'background-image': this.getGridBackgroundSVG(this.gridDimensions.full.cell)
        }
        /* }
        else {
          this.gridStyle = {
            width: '100%',
            height: this.gridDimensions.mini.height + 'px',
            'grid-auto-columns': this.gridDimensions.mini.cell.width + 'px',
            'grid-auto-rows': this.gridDimensions.mini.cell.height + 'px',
            'background-image': this.getGridBackgroundSVG(this.gridDimensions.mini.cell)
          }
        } */
      },
      getGridBackgroundSVG (cell) {
        return `url("data:image/svg+xml;utf8,` +
          `<svg xmlns='http://www.w3.org/2000/svg' width='100%' height='100%'><defs>` +
          `<pattern id='smallGrid' width='${cell.width}' height='${cell.height}' patternUnits='userSpaceOnUse'>` +
          `<path d='M ${cell.width} 0 L 0 0 0 ${cell.height}' fill='none' stroke='gray' stroke-width='0.5'/>` +
          `</pattern></defs><rect width='100%' height='100%' fill='url(%23smallGrid)' /></svg>")`
      },
      async fetchCellAnnotations () {
        const query = {
          type: 'Annotation',
          'body.type': '2DCell',
          'target.id': this.grid.id
        }
        const result = await this.$store.dispatch('annotations/find', query)
        this.cells = result.items.map(annotation => {
          let cell = JSON.parse(annotation.body.value)
          if (cell) {
            cell.uuid = annotation.uuid
            return cell
          }
          return null
        }).filter(cell => cell)
        this.updateCellUIStates()
      },
      async fetchMetadataAnnotations () {
        const query = {
          'body.type': '2DGridMetadata',
          'target.id': this.grid.id
        }
        const result = await this.$store.dispatch('annotations/find', query)
        let annotation = result.items.shift()
        if (annotation) {
          let metadata = JSON.parse(annotation.body.value)
          metadata.uuid = annotation.uuid
          if (metadata) {
            this.gridMetadata = metadata
          }
        }
        else {
          this.gridMetadata = {
            columns: 10,
            rows: 6,
            ratio: 16 / 9.0
          }
          await this.updateGridMetadataStore()
        }
      },
      getGridCellAnnotation (cell) {
        return {
          body: {
            type: '2DCell',
            purpose: 'linking',
            value: JSON.stringify(cell)
          },
          target: {
            id: this.grid.id,
            type: 'Map',
            selector: {
              type: '2DLocation',
              value: `x=${cell.x}&y=${cell.y}&width=${cell.width}&height=${cell.height}`
            }
          }
        }
      },
      getGridMetadataAnnotation (id, metadata) {
        return {
          body: {
            type: '2DGridMetadata',
            purpose: 'linking',
            value: JSON.stringify(metadata)
          },
          target: {
            id,
            type: 'Map'
          }
        }
      },
      async updateCellStore (cell) {
        let annotation = this.getGridCellAnnotation(cell)
        if (cell.uuid) {
          await this.$store.dispatch('annotations/patch', [cell.uuid, annotation])
        }
        else {
          await this.$store.dispatch('annotations/post', annotation)
        }
        await this.fetchCellAnnotations()
      },
      async updateGridMetadataStore () {
        let mapAnnotation = this.getGridMetadataAnnotation(this.grid.id, this.gridMetadata)

        if (this.gridMetadata.uuid) {
          await this.$store.dispatch('annotations/patch', [this.gridMetadata.uuid, mapAnnotation])
        }
        await this.$store.dispatch('annotations/post', mapAnnotation)
        this.updateGridDimensions()
      },
      getCellStyle (cell) {
        return {
          'grid-column-start': cell.x,
          'grid-column-end': `span ${cell.width}`,
          'grid-row-start': cell.y,
          'grid-row-end': `span ${cell.height}`
        }
      }
      // setCellSet: function (cellSet) {
      //   this.grid = cellSet
      // }
    }
  }
</script>

<style scoped lang="stylus">

  .cell-grid
    display grid
    background-color #eee

  .cell-item

    &
      background-color rgba(0,0,0,0.2)
      border 1px solid #777
      margin 1px
      box-sizing border-box
      position relative
      overflow: hidden
      grid-column-start: 1
      grid-column-end: span 1
      grid-row-start: 1
      grid-row-end: span 1

    &:hover
      background-color lightblue

    &.selected
      background-color lightpink

    .cell-item-inner
      width 100%
      height 100%

    .cell-item-resize-handle
      color rgba(0,0,0,0.2)
      position absolute
      right 0
      bottom 0
      width 18px
      height 20px

      &:hover
        color black

</style>