Skip to content

Commit

Permalink
Rename ColorBar props (#27)
Browse files Browse the repository at this point in the history
* rename props text->label, text_side->label_side, text_style->label_style, ramp_points->steps

increase default steps 10->50

* try fix invalid cscale key test

* fallback on d3sc.interpolateViridis if passed invalid color scale key

* update deps
  • Loading branch information
janosh authored Apr 20, 2023
1 parent ce366c2 commit 83c8351
Show file tree
Hide file tree
Showing 8 changed files with 83 additions and 67 deletions.
18 changes: 9 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
"update-coverage": "vitest tests/unit --run --coverage && npx istanbul-badges-readme"
},
"dependencies": {
"@iconify/svelte": "^3.1.1",
"@sveltejs/kit": "^1.15.2",
"@iconify/svelte": "^3.1.3",
"@sveltejs/kit": "^1.15.7",
"d3-array": "^3.2.3",
"d3-color": "^3.1.0",
"d3-format": "^3.1.0",
Expand All @@ -36,18 +36,18 @@
"svelte-multiselect": "^8.6.0"
},
"devDependencies": {
"@playwright/test": "^1.32.2",
"@sveltejs/adapter-static": "2.0.1",
"@playwright/test": "^1.32.3",
"@sveltejs/adapter-static": "2.0.2",
"@sveltejs/package": "^2.0.2",
"@types/d3-array": "^3.0.4",
"@types/d3-color": "^3.1.0",
"@types/d3-interpolate-path": "^2.0.0",
"@types/d3-scale": "^4.0.3",
"@types/d3-scale-chromatic": "^3.0.0",
"@types/d3-shape": "^3.1.1",
"@typescript-eslint/eslint-plugin": "^5.57.1",
"@typescript-eslint/parser": "^5.57.1",
"@vitest/coverage-c8": "^0.29.8",
"@typescript-eslint/eslint-plugin": "^5.59.0",
"@typescript-eslint/parser": "^5.59.0",
"@vitest/coverage-c8": "^0.30.1",
"eslint": "^8.38.0",
"eslint-plugin-svelte3": "^4.0.0",
"hastscript": "^7.2.0",
Expand All @@ -67,8 +67,8 @@
"svelte-zoo": "^0.4.3",
"svelte2tsx": "^0.6.11",
"typescript": "5.0.4",
"vite": "^4.2.1",
"vitest": "^0.29.8"
"vite": "^4.3.0",
"vitest": "^0.30.1"
},
"keywords": [
"svelte",
Expand Down
48 changes: 23 additions & 25 deletions src/lib/ColorBar.svelte
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
<script lang="ts">
import * as d3 from 'd3-scale'
import * as d3sc from 'd3-scale-chromatic'
import { pretty_num } from './labels'
export let text: string | null = null
export let color_scale: ((x: number) => string) | string | null = null
export let text_side: 'left' | 'right' | 'top' | 'bottom' = `left`
export let label: string | null = null
export let color_scale: ((x: number) => string) | string | null = `Viridis`
export let label_side: 'left' | 'right' | 'top' | 'bottom' = `left`
export let style: string | null = null
export let text_style: string | null = null
export let label_style: string | null = null
export let wrapper_style: string | null = null
export let tick_labels: (string | number)[] | number = 0
export let range: [number, number] = [0, 1]
Expand All @@ -16,7 +17,7 @@
// snap ticks to pretty, more readable values
export let snap_ticks: boolean = true
// at how many equidistant points to sample the color scale
export let ramp_points: number = 10
export let steps: number = 50
// the new range of the color bar resulting from snapping ticks
// https://github.com/d3/d3-scale/issues/86
export let nice_range: [number, number] = range
Expand All @@ -40,34 +41,31 @@
}
}
$: if (color_scale === null || typeof color_scale == `string`) {
const cscale_key = color_scale ?? text
color_scale = d3sc[`interpolate${cscale_key}`]
if (color_scale === undefined) {
const list_valid = Object.keys(d3sc)
.map((key) => key.split(`interpolate`)[1])
.filter(Boolean)
.join(`, `)
const valid_color_scale_keys = Object.keys(d3sc)
.map((key) => key.split(`interpolate`)[1])
.filter(Boolean)
.join(`, `)
$: if (typeof color_scale == `string`) {
if (`interpolate${color_scale}` in d3sc) {
color_scale = d3sc[`interpolate${color_scale}`]
} else {
console.error(
`Color scale '${cscale_key}' not found, supported color scale names are ${list_valid}`
`Color scale '${color_scale}' not found, supported color scale names are ${valid_color_scale_keys}. Falling back on 'Viridis'.`
)
color_scale = d3sc.interpolateViridis
}
}
$: grad_dir = {
horizontal: `to right`,
vertical: `to bottom`,
}[orientation]
$: grad_dir = { horizontal: `to right`, vertical: `to bottom` }[orientation]
$: ramped = [...Array(ramp_points).keys()].map((idx) =>
color_scale?.(idx / ramp_points)
)
$: ramped = [...Array(steps).keys()].map((_, idx) => color_scale?.(idx / steps))
$: flex_dir = {
left: `row`,
right: `row-reverse`,
top: `column`,
bottom: `column-reverse`,
}[text_side]
}[label_side]
$: tick_pos = {
bottom: `top: 100%`,
top: `bottom: 100%`,
Expand All @@ -76,12 +74,12 @@
</script>

<div style:flex-direction={flex_dir} style={wrapper_style} class="colorbar">
<!-- don't pass unsanitized user input into text! -->
{#if text}<span style={text_style}>{@html text}</span>{/if}
<!-- don't pass unsanitized user input into label! -->
{#if label}<span style={label_style}>{@html label}</span>{/if}
<div style:background="linear-gradient({grad_dir}, {ramped})" {style}>
{#each tick_labels || [] as tick_label, idx}
<span style="left: calc(100% * {idx} / {tick_labels?.length - 1}); {tick_pos}">
{tick_label}
{pretty_num(tick_label)}
</span>
{/each}
</div>
Expand Down
18 changes: 16 additions & 2 deletions src/lib/ColorScaleSelect.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,20 @@
{placeholder}
{...$$props}
>
<ColorBar slot="option" let:option text={option} {...cbar_props} {wrapper_style} />
<ColorBar slot="selected" let:option text={option} {...cbar_props} {wrapper_style} />
<ColorBar
slot="option"
let:option
label={option}
color_scale={option}
{...cbar_props}
{wrapper_style}
/>
<ColorBar
slot="selected"
let:option
label={option}
color_scale={option}
{...cbar_props}
{wrapper_style}
/>
</Select>
46 changes: 26 additions & 20 deletions src/routes/(demos)/color-bar/+page.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,23 @@ Here's a `ColorBar` with tick labels:
]
</script>
{#each bars as [color_scale, tick_side, tick_labels, range]}
<ColorBar
text="{color_scale}<br>&bull; tick side={tick_side}<br>&bull; range={range}"
{color_scale}
{tick_side}
{tick_labels}
{range}
text_style="white-space: nowrap; padding-right: 1em;"
--cbar-width="100%"
--cbar-padding="2em"
/>
{/each}
<div style="border: 0.1px dashed white;">
{#each bars as [color_scale, tick_side, tick_labels, range, width]}
<ColorBar
label="{color_scale}<br>&bull; tick side={tick_side}<br>&bull; range={range}"
{color_scale}
{tick_side}
{tick_labels}
{range}
label_style="white-space: nowrap; padding-right: 1em;"
--cbar-width="100%"
--cbar-padding="2em"
/>
{/each}
</div>
```

`ColorBar` supports `text_side = ['top', 'bottom', 'left', 'right']`
`ColorBar` supports `label_side = ['top', 'bottom', 'left', 'right']`

```svelte example stackblitz
<script>
Expand All @@ -38,15 +40,17 @@ Here's a `ColorBar` with tick labels:
</script>
<section>
{#each [`top`, `bottom`, `left`, `right`] as text_side, idx}
{#each [`top`, `bottom`, `left`, `right`] as label_side, idx}
<ul>
<code>{text_side}</code>
<code>{label_side}</code>
{#each names.slice(idx * 5, 5 * idx + 5) as name}
{@const color_scale = name.replace(`interpolate`, ``)}
<li>
<ColorBar
text={name.replace(`interpolate`, ``)}
{text_side}
text_style="min-width: 5em;"
label={color_scale}
{color_scale}
{label_side}
label_style="min-width: 5em;"
/>
</li>
{/each}
Expand Down Expand Up @@ -82,9 +86,11 @@ You can make fat and skinny bars:
const wrapper_style = 'place-items: center;'
</script>
<ColorBar text="Viridis" {wrapper_style} style="width: 10em; height: 1ex;" />
<ColorBar {wrapper_style} style="width: 10em; height: 1ex;" />
<br />
<ColorBar label="Viridis" {wrapper_style} style="width: 3em; height: 2em;" />
<br />
<ColorBar text="Viridis" {wrapper_style} style="width: 3em; height: 2em;" />
<ColorBar {wrapper_style} --cbar-width="8em" --cbar-height="2em" />
```

`PeriodicTable.svelte` heatmap example with `ColorBar` inside `TableInset`
Expand Down
2 changes: 1 addition & 1 deletion tests/element-detail-pages.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import element_data from '../src/lib/element-data.ts'
test.describe(`Element detail page`, async () => {
test(`has periodicity plot`, async ({ page }) => {
// test any 5 random elements
for (const _ of [...Array(5)]) {
for (const _ of Array(5)) {
const rand_idx = Math.floor(Math.random() * element_data.length)
const random_element = element_data[rand_idx]

Expand Down
2 changes: 1 addition & 1 deletion tests/periodic-table.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ test.describe(`Periodic Table`, () => {
await page.click(`text=${heatmap_label}`)
}

for (const _ of [...Array(5)]) {
for (const _ of Array(5)) {
// check 5 random element tiles display the expected heatmap value

const rand_idx = Math.floor(Math.random() * element_data.length)
Expand Down
14 changes: 6 additions & 8 deletions tests/unit/ColorBar.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import * as d3sc from 'd3-scale-chromatic'
import { describe, expect, test, vi } from 'vitest'
import { doc_query } from '.'

const valid_cscale_names = Object.keys(d3sc)
const valid_color_scale_keys = Object.keys(d3sc)
.map((key) => key.split(`interpolate`)[1])
.filter(Boolean)
.join(`, `)
Expand All @@ -13,13 +13,13 @@ describe(`ColorBar`, () => {
new ColorBar({
target: document.body,
props: {
text: `Test`,
label: `Test`,
color_scale: `Viridis`,
tick_labels: 5,
range: [0, 100],
text_side: `left`,
label_side: `left`,
style: `width: 200px;`,
text_style: `font-weight: bold;`,
label_style: `font-weight: bold;`,
wrapper_style: `margin: 10px;`,
},
})
Expand All @@ -43,13 +43,11 @@ describe(`ColorBar`, () => {

new ColorBar({
target: document.body,
props: {
color_scale: `invalid color scale`,
},
props: { color_scale: `purposely invalid color scale` },
})

expect(spy).toHaveBeenCalledWith(
`Color scale 'invalid color scale' not found, supported color scale names are ${valid_cscale_names}`
`Color scale 'purposely invalid color scale' not found, supported color scale names are ${valid_color_scale_keys}. Falling back on 'Viridis'.`
)
})
})
2 changes: 1 addition & 1 deletion tests/unit/PeriodicTable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ describe(`PeriodicTable`, () => {
}
)

test.each([[[...Array(1000).keys()]], [[...Array(119).keys()]]])(
test.each([[[...Array(200).keys()]], [[...Array(119).keys()]]])(
`raises error when receiving more than 118 heatmap values`,
(heatmap_values) => {
console.error = vi.fn()
Expand Down

0 comments on commit 83c8351

Please sign in to comment.