<script>
  import { onMount } from 'svelte'
  import { GridStack } from 'gridstack'
  import 'gridstack/dist/gridstack.css'
  import 'gridstack/dist/gridstack-extra.css'
  import './index.css'

  let count = 0
  let info = ''
  let grid = null

  const addWidget = () => {
    const constraint = Math.round(1 + 1 * Math.random())

    const node = {
      minW: constraint,
      minH: constraint,
      autoPosition: true,
    }

    node.id = count.toString()
    node.content = `
      <div class="widget-header">Draggable</div>
      <div class="widget-content"><p>${count}</p></div>
    `
    grid.addWidget(node)

    count = count + 1
  }

  onMount(async () => {
    await import('gridstack/dist/h5/gridstack-dd-native')

    grid = GridStack.init(
      {
        cellHeight: '15em',
        minRow: 1,
        column: 8,
        margin: '0.25em',
        resizable: { handles: 'n,e,s,w' },
        draggable: { handle: '.widget-header' },
      },
      document.getElementById('gridstack')
    )

    grid.on('dragstop', (event, element) => {
      const node = element.gridstackNode
      info = `You just dragged node #${node.id} to ${node.x},${node.y} – good job!`
    })
  })
</script>

<button on:click={addWidget}>Add Widget</button>
<pre>{info}</pre>
<div id="gridstack" class="grid-stack" />