|
| 1 | +<script> |
| 2 | + import { createEventDispatcher } from 'svelte' |
| 3 | +
|
| 4 | + import { swatch } from '../lib/utils' |
| 5 | + import { clamp } from 'yootils' |
| 6 | + import Symbol from './Symbol.svelte' |
| 7 | + import PatternDefs from './PatternDefs.svelte' |
| 8 | +
|
| 9 | + const dispatch = createEventDispatcher() |
| 10 | +
|
| 11 | + export let label |
| 12 | + export let size = 30 |
| 13 | + export let items = [] |
| 14 | + export let type = 'square' |
| 15 | + export let pad = 10 |
| 16 | + export let columns |
| 17 | + export let rows |
| 18 | + export let limit |
| 19 | + export let start = 0 |
| 20 | + export let autoscale = false |
| 21 | + export let interactive = false |
| 22 | + export let activeIndex = -1 |
| 23 | +
|
| 24 | + function fill(item) { |
| 25 | + return item.fillUrl || item.fill || item |
| 26 | + } |
| 27 | +
|
| 28 | + function stroke(item) { |
| 29 | + return item.stroke || item |
| 30 | + } |
| 31 | +
|
| 32 | + function swapType(inputType) { |
| 33 | + return inputType === 'square' |
| 34 | + ? 'circle' |
| 35 | + : inputType === 'circle' |
| 36 | + ? 'square' |
| 37 | + : type |
| 38 | + } |
| 39 | +
|
| 40 | + function click(index) { |
| 41 | + if (interactive) { |
| 42 | + activeIndex = start + index |
| 43 | + dispatch('click', { index: activeIndex, item: items[activeIndex] }) |
| 44 | + } |
| 45 | + } |
| 46 | +
|
| 47 | + function forwardEvent(event, index) { |
| 48 | + if (interactive) |
| 49 | + dispatch(event, { |
| 50 | + index: start + index, |
| 51 | + item: items[start + index] |
| 52 | + }) |
| 53 | + } |
| 54 | +
|
| 55 | + $: grid = swatch(limit || items.length, size, pad, columns, rows) |
| 56 | + $: data = grid.data.map((item, i) => ({ |
| 57 | + ...item, |
| 58 | + type: i == activeIndex ? swapType(type) : type |
| 59 | + })) |
| 60 | + $: start = clamp(start, 0, items.length - (limit || 0)) |
| 61 | +</script> |
| 62 | + |
| 63 | +<div class="flex flex-col leading-loose"> |
| 64 | + {#if label} |
| 65 | + <span class="py-2">{label}</span> |
| 66 | + {/if} |
| 67 | + <svg |
| 68 | + viewBox="0 0 {grid.width} {grid.height}" |
| 69 | + width="100%" |
| 70 | + class="cursor-pointer" |
| 71 | + > |
| 72 | + {#if label} |
| 73 | + <title>A swatch with label {label}</title> |
| 74 | + {/if} |
| 75 | + |
| 76 | + {#each data as { cx, cy, r, type }, i} |
| 77 | + <Symbol |
| 78 | + x={cx} |
| 79 | + y={cy} |
| 80 | + {size} |
| 81 | + fill={fill(items[i + start])} |
| 82 | + stroke={stroke(items[i + start])} |
| 83 | + shape={items[i + start].shape || type} |
| 84 | + thickness={i + start == activeIndex ? 2 : 0.5} |
| 85 | + on:click={click(i + start)} |
| 86 | + on:mouseover={forwardEvent('mouseover', i + start)} |
| 87 | + on:mouseleave={forwardEvent('mouseleave', i + start)} |
| 88 | + on:focus={forwardEvent('focus', i + start)} |
| 89 | + /> |
| 90 | + {/each} |
| 91 | + <PatternDefs patterns={items} /> |
| 92 | + </svg> |
| 93 | +</div> |
0 commit comments