Add/Remove Items

Use the Grid Controller to find available positions when adding items. The getFirstAvailablePosition(w, h) method returns the first position that can fit an item of the given size.

3 items in grid

Code

svelte
<script lang="ts">
  import Grid, { GridItem, type GridController } from '@appulsauce/svelte-grid';

  let items = $state([...]);
  let gridController: GridController | undefined = $state();

  function addItem() {
    const w = 2, h = 2;
    const position = gridController?.getFirstAvailablePosition(w, h);
    if (position) {
      items = [...items, { id: crypto.randomUUID(), ...position, w, h }];
    }
  }

  function removeItem(id: string) {
    items = items.filter(item => item.id !== id);
  }
</script>

<button onclick={addItem}>Add</button>

<Grid cols={8} collision="push" bind:controller={gridController}>
  {#each items as item (item.id)}
    <GridItem id={item.id} bind:x={item.x} bind:y={item.y} bind:w={item.w} bind:h={item.h}>
      {#snippet children()}
        <button onclick={() => removeItem(item.id)}>X</button>
      {/snippet}
    </GridItem>
  {/each}
</Grid>