import { linkFeet } from '@jbrowse/render-core/linkFeet' import { RAMP_NOT_A_NUMBER_COLOR, RAMP_NO_VALUE_BITS, RAMP_NO_VALUE_COLOR, } from '@jbrowse/render-core/marks' import { GLYPH_DIAMOND, GLYPH_DISC, GLYPH_SQUARE, GLYPH_TRIANGLE, } from '@jbrowse/render-core/shaders/pointMarkConsts' import { categoricalPalette, categoricalValueColor } from '../ui/colors.ts' import { MISCONFIGURED_COLOR, NO_CATEGORY_COLOR } from './color/index.ts' import { cssColorToABGR } from './colorBits.ts' import { ColumnTable } from './featureTable.ts' import Flatbush from './flatbush/index.ts' import createJexlInstance from './jexl.ts' import { DEFAULT_MARK_COLOR, colorAt, colorEvaluator, continuousColorScale, encodeFeatures, encodedChannelTransferables, featureIndexAt, rampOverExtent, } from './markEncoding.ts' import SimpleFeature from './simpleFeature.ts' import { thresholdField, thresholdPalette } from './thresholdScale.ts' import type { Column, NumberLane } from './featureTable.ts' import type { ContinuousRef, ShapeName, LaneName } from './markEncoding.ts' const jexl = createJexlInstance() const ALL: LaneName[] = ['y', 'color', 'glyph', 'row', 'index'] function colorLane(color: Uint32Array | number | undefined) { if (!(color instanceof Uint32Array)) { throw new Error(`expected a color lane, got ${color}`) } return color } function feature( i: number, data: Record = {}, start = i * 100, end = i * 100 + 50, ) { return new SimpleFeature({ uniqueId: `f${i}`, refName: 'chr1', start, end, ...data, }) } const features = [ feature(0, { score: 10, strand: 1, type: 'gene' }), feature(1, { score: 40, strand: -1, type: 'exon' }), feature(2, { score: 25, strand: 1, type: 'gene' }), feature(3, { strand: -1, type: 'cds' }), feature(4, { score: 'n/a', strand: 1, type: 'gene' }), ] test('x and x2 default to start and end, read natively', () => { const r = encodeFeatures(features, {}, ALL, { jexl }) expect(r.count).toBe(5) expect([...r.x]).toEqual([0, 100, 200, 300, 400]) expect([...r.x2]).toEqual([50, 150, 250, 350, 450]) expect(r.featureIndex).toBeUndefined() expect([...r.y]).toEqual([0, 0, 0, 0, 0]) expect(r.yMin).toBe(Infinity) expect(r.yMax).toBe(-Infinity) expect(r.scale).toBeUndefined() }) test('a declared y skips the features whose value is not finite, and counts them', () => { const r = encodeFeatures(features, { y: 'score' }, ALL, { jexl }) expect(r.count).toBe(3) expect(r.skipped).toBe(2) expect([...r.y]).toEqual([10, 40, 25]) expect([...r.featureIndex!]).toEqual([0, 1, 2]) expect(r.yMin).toBe(10) expect(r.yMax).toBe(40) const fb = Flatbush.from(r.flatbushData!) expect(fb.search(90, 39, 160, 41)).toEqual([1]) }) // `Number()` answers 0 for every one of these, which plotted a VCF's `DP=.` // as a measured zero. test('a value that holds no number is skipped, never plotted at zero', () => { const values = [30, null, '', [], [null], true, '.', [0.4, 0.1]] const r = encodeFeatures( values.map((qual, i) => feature(i, { qual })), { y: 'qual' }, ['y'], ) expect([...r.y]).toEqual([30]) expect(r.skipped).toBe(values.length - 1) }) test('a one-element list and a numeric string are the numbers they hold', () => { const r = encodeFeatures( [[0.25], '12', ' 7 '].map((qual, i) => feature(i, { qual })), { y: 'qual' }, ['y'], ) expect([...r.y]).toEqual([0.25, 12, 7]) }) // As every other scale reads the two: no value is the no-value grey, text that // is no number the misconfiguration grey, and an infinity the end on its side. test('under a ramp no value, text and an infinity each paint as every scale paints them', () => { const r = encodeFeatures( [-1, null, 'n/a', 1, Infinity, -Infinity].map((score, i) => feature(i, { score }), ), { color: { field: 'score', scale: 'linear', domainMin: -1, domainMax: 1, range: ['blue', 'white', 'red'], }, }, ['color'], ) expect(colorLane(r.color)[1]).toBe(cssColorToABGR(NO_CATEGORY_COLOR)) expect(colorLane(r.color)[2]).toBe(cssColorToABGR(MISCONFIGURED_COLOR)) expect(colorLane(r.color)[4]).toBe(colorLane(r.color)[3]) expect(colorLane(r.color)[5]).toBe(colorLane(r.color)[0]) expect(r.scale).toMatchObject({ missing: true, notNumber: true }) }) // The ramp lane carries a value-less feature as a NaN of its own payload, and // its bits reach the GPU and the Canvas2D bake as written. test('a ramp lane marks a value-less feature apart from text that is no number', () => { const r = encodeFeatures( [null, 'n/a', 3].map((score, i) => feature(i, { score })), { color: { field: 'score', scale: 'linear' } }, ['colorValue'], ) const bits = new Uint32Array( r.colorValue.buffer, r.colorValue.byteOffset, r.colorValue.length, ) expect(bits[0]).toBe(RAMP_NO_VALUE_BITS) expect(Number.isNaN(r.colorValue[1])).toBe(true) expect(bits[1]).not.toBe(RAMP_NO_VALUE_BITS) expect(r.colorValue[2]).toBe(3) expect(r.scale).toMatchObject({ extent: [3, 3], missing: true, notNumber: true, }) }) // Walking cuts written high to low stopped at the first one a value was // under, so the middle interval was never painted and its key row was empty. test('threshold cuts written high to low paint the intervals they name', () => { const r = encodeFeatures( [0.05, 0.3, 0.7].map((pip, i) => feature(i, { pip })), { color: { field: 'pip', scale: 'threshold', domain: [0.5, 0.1], range: ['#111111', '#222222', '#333333'], }, }, ['color'], ) expect([...colorLane(r.color)]).toEqual( ['#111111', '#222222', '#333333'].map(c => cssColorToABGR(c)), ) expect(r.scale).toMatchObject({ kind: 'threshold', domain: [0.1, 0.5] }) }) function blackToWhite(color: Partial) { return encodeFeatures( [0, 25, 50].map((score, i) => feature(i, { score })), { color: { field: 'score', scale: 'linear', range: ['black', 'white'], ...color, }, }, ['color'], ) } test('reverse turns the ramp round over the same domain', () => { const forward = blackToWhite({ domainMin: 0, domainMax: 50 }) const reversed = blackToWhite({ domainMin: 0, domainMax: 50, reverse: true }) expect([colorLane(forward.color)[0], colorLane(forward.color)[2]]).toEqual( ['black', 'white'].map(c => cssColorToABGR(c)), ) expect([colorLane(reversed.color)[0], colorLane(reversed.color)[2]]).toEqual( ['white', 'black'].map(c => cssColorToABGR(c)), ) // the middle of a 256-entry table rounds either way by one level const grey = (packed: number) => packed & 0xff expect( Math.abs( grey(colorLane(reversed.color)[1]!) - grey(colorLane(forward.color)[1]!), ), ).toBeLessThanOrEqual(1) expect(reversed.scale).toMatchObject({ domain: [0, 50], pinned: [true, true], }) }) // A domain is a span and `reverse` its one direction, so ends written the // wrong way round span the same interval rather than a second way to reverse. test('ends written high to low span the same interval, unreversed', () => { const written = blackToWhite({ domainMin: 50, domainMax: 0 }) const forward = blackToWhite({ domainMin: 0, domainMax: 50 }) expect([...colorLane(written.color)]).toEqual([...colorLane(forward.color)]) expect(written.scale).toMatchObject({ domain: [0, 50] }) }) test('a pinned floor keeps its value and the open ceiling follows the region', () => { const r = blackToWhite({ domainMin: -50 }) expect(r.scale).toMatchObject({ domain: [-50, 50], pinned: [true, false], extent: [0, 50], }) expect(colorLane(r.color)[0]).toBe(cssColorToABGR('rgb(128,128,128)')) expect(colorLane(r.color)[2]).toBe(cssColorToABGR('white')) }) test('a pinned ceiling keeps its value and the open floor follows the region', () => { const r = blackToWhite({ domainMax: 100 }) expect(r.scale).toMatchObject({ domain: [0, 100], pinned: [false, true] }) expect(colorLane(r.color)[0]).toBe(cssColorToABGR('black')) expect(colorLane(r.color)[2]).toBe(cssColorToABGR('rgb(128,128,128)')) }) test('under a domain quantile each open end stops short of its tail', () => { const spiky = encodeFeatures( [...Array.from({ length: 99 }, (_, i) => i + 1), 10000].map((score, i) => feature(i, { score }), ), { color: { field: 'score', scale: 'linear', range: ['black', 'white'], domainQuantile: 0.9, }, }, ['color'], ) expect(spiky.scale).toMatchObject({ domain: [11, 90], extent: [11, 90], extremes: [1, 10000], }) expect(colorLane(spiky.color)[0]).toBe(cssColorToABGR('black')) expect(colorLane(spiky.color)[89]).toBe(cssColorToABGR('white')) expect(colorLane(spiky.color)[99]).toBe(cssColorToABGR('white')) }) test('a log ramp under a domain quantile spreads values below 1 across it', () => { const small = encodeFeatures( [0.001, 0.01, 0.1, 0.5].map((score, i) => feature(i, { score })), { color: { field: 'score', scale: 'log', range: ['black', 'white'], domainQuantile: 0.99, }, }, ['color'], ) expect(small.scale).toMatchObject({ domain: [expect.closeTo(0.001), 0.5] }) expect(new Set(colorLane(small.color)).size).toBe(4) }) test('an open end never crosses a pinned one', () => { const r = blackToWhite({ domainMin: 80 }) expect(r.scale).toMatchObject({ domain: [80, 80] }) expect(new Set(colorLane(r.color))).toEqual( new Set([cssColorToABGR('black')]), ) }) test('scheme names the ramp, and range, where it lists colors, wins over it', () => { const viridis = blackToWhite({ range: undefined, scheme: 'viridis' }) const unset = blackToWhite({ range: undefined }) expect([...colorLane(viridis.color)]).toEqual([...colorLane(unset.color)]) expect(colorLane(viridis.color)[0]).toBe(cssColorToABGR('#440154')) const both = blackToWhite({ scheme: 'viridis' }) expect(colorLane(both.color)[0]).toBe(cssColorToABGR('black')) }) test('a region holding no number spans [0, 1] and contributes no extent', () => { const r = encodeFeatures( [feature(0, { score: 'none' })], { color: { field: 'score', scale: 'linear', range: ['black', 'white'] } }, ['color'], ) expect(r.scale).toMatchObject({ domain: [0, 1], extent: [Infinity, -Infinity], }) if (r.scale?.kind === 'ramp') { expect(rampOverExtent(r.scale, r.scale.extent).domain).toEqual([0, 1]) } }) test('rampOverExtent widens only the open ends of a half-pinned table', () => { const r = blackToWhite({ domainMin: -50 }) const table = r.scale expect(table?.kind).toBe('ramp') if (table?.kind === 'ramp') { expect(rampOverExtent(table, [-20, 200]).domain).toEqual([-50, 200]) expect(rampOverExtent(table, [-100, -60]).domain).toEqual([-50, -50]) const open = blackToWhite({}).scale if (open?.kind === 'ramp') { expect(rampOverExtent(open, [-20, 200]).domain).toEqual([-20, 200]) } } }) test('a jexl: field ref is the escape for a derived channel', () => { const r = encodeFeatures( features, { x: "jexl:get(feature,'start')+5", y: 'jexl:feature.score*2' }, ALL, { jexl }, ) expect([...r.x]).toEqual([5, 105, 205]) expect([...r.y]).toEqual([20, 80, 50]) }) test('a constant color ships as one number, a jexl color as a lane', () => { const constant = encodeFeatures(features, { color: 'red' }, ALL, { jexl }) expect(constant.color).toBe(cssColorToABGR('red')) expect(colorAt(constant, 2)).toBe(cssColorToABGR('red')) const unset = encodeFeatures(features, {}, ['color'], { jexl }) expect(unset.color).toBe(cssColorToABGR(DEFAULT_MARK_COLOR)) expect(encodedChannelTransferables(unset)).toEqual([ unset.x.buffer, unset.x2.buffer, ]) const perFeature = encodeFeatures( features, { color: "jexl:get(feature,'strand')==1?'red':'blue'" }, ALL, { jexl }, ) expect([...colorLane(perFeature.color)]).toEqual( [1, -1, 1, -1, 1].map(s => cssColorToABGR(s === 1 ? 'red' : 'blue')), ) expect(colorAt(perFeature, 1)).toBe(cssColorToABGR('blue')) expect(encodedChannelTransferables(perFeature)).toContain( colorLane(perFeature.color).buffer, ) expect(perFeature.scale).toBeUndefined() }) test('a scaled color stays a lane even where every feature takes one color', () => { const same = features.map((_, i) => feature(i, { type: 'gene', score: 10 })) const categorical = encodeFeatures( same, { color: { field: 'type', scale: 'ordinal' } }, ['color'], { jexl }, ) const threshold = encodeFeatures( same, { color: { field: 'score', scale: 'threshold', domain: [50] } }, ['color'], { jexl }, ) const ramp = encodeFeatures( same, { color: { field: 'score', scale: 'linear' } }, ['color'], { jexl }, ) for (const r of [categorical, threshold, ramp]) { expect(colorLane(r.color)).toHaveLength(5) expect(new Set(colorLane(r.color)).size).toBe(1) } }) test('an unpinned categorical scale colors by value, so two regions agree, and names the missing row', () => { const r = encodeFeatures( features, { color: { field: 'type', scale: 'ordinal' } }, ALL, { jexl }, ) const of = (label: string) => cssColorToABGR(categoricalValueColor(label, categoricalPalette)) expect(r.scale).toEqual({ kind: 'categorical', field: 'type', domain: [], entries: [ { value: 'cds', color: of('cds') }, { value: 'exon', color: of('exon') }, { value: 'gene', color: of('gene') }, ], }) expect([...colorLane(r.color)]).toEqual( ['gene', 'exon', 'gene', 'cds', 'gene'].map(of), ) const other = encodeFeatures( [feature(9, { type: 'gene' }), feature(10, {})], { color: { field: 'type', scale: 'ordinal' } }, ALL, { jexl }, ) expect(colorLane(other.color)[0]).toBe(of('gene')) expect(other.scale).toEqual({ kind: 'categorical', field: 'type', domain: [], entries: [ { value: 'gene', color: of('gene') }, { value: '', color: cssColorToABGR(NO_CATEGORY_COLOR) }, ], }) expect(colorLane(other.color)[1]).toBe(cssColorToABGR(NO_CATEGORY_COLOR)) }) test('a categorical domain pins the order and a palette the colors', () => { const r = encodeFeatures( features, { color: { field: 'strand', scale: 'ordinal', domain: [-1, 1], range: ['red', 'blue'], }, }, ALL, { jexl }, ) expect(r.scale).toEqual({ kind: 'categorical', field: 'strand', domain: ['-1', '1'], range: ['red', 'blue'], numericKeys: true, entries: [ { value: '-1', color: cssColorToABGR('red') }, { value: '1', color: cssColorToABGR('blue') }, ], }) }) test('strand brings its own order and colors where the encoding names none', () => { const r = encodeFeatures( features, { color: { field: 'strand', scale: 'ordinal' } }, ALL, { jexl }, ) expect(r.scale).toEqual({ kind: 'categorical', field: 'strand', domain: ['1', '-1', '0'], numericKeys: true, entries: [ { value: '1', color: cssColorToABGR('tomato') }, { value: '-1', color: cssColorToABGR('cornflowerblue') }, ], }) }) test('two regions agree on a value the domain leaves out, whatever else each met', () => { const encoding = { color: { field: 'type', scale: 'ordinal' as const, domain: ['gene'] }, } const busy = encodeFeatures( [ feature(0, { type: 'gene' }), feature(1, { type: 'exon' }), feature(2, { type: 'snoRNA' }), ], encoding, ALL, { jexl }, ) const sparse = encodeFeatures( [feature(3, { type: 'gene' }), feature(4, { type: 'snoRNA' })], encoding, ALL, { jexl }, ) expect(colorLane(sparse.color)[1]).toBe(colorLane(busy.color)[2]) expect(colorLane(busy.color)[2]).not.toBe(colorLane(busy.color)[0]) }) test('the table lists the values met, the domain first and the rest in facet order', () => { const mixed = [ feature(0, { type: 'exon' }), feature(1, { type: '' }), feature(2, { type: 'UTR' }), feature(3, { type: '10' }), feature(4, { type: '9' }), ] const labels = (domain?: string[]) => { const r = encodeFeatures( mixed, { color: { field: 'type', scale: 'ordinal', domain } }, ALL, { jexl }, ) return r.scale?.kind === 'categorical' ? r.scale.entries.map(e => e.value) : undefined } expect(labels()).toEqual(['9', '10', 'UTR', 'exon', '']) expect(labels(['exon', 'CDS'])).toEqual(['exon', '9', '10', 'UTR', '']) }) test('a ramp scale reads the field through its domain into the LUT', () => { const r = encodeFeatures( features, { color: { field: 'score', scale: 'linear', range: ['black', 'white'], }, }, ALL, { jexl }, ) expect(r.scale?.kind).toBe('ramp') if (r.scale?.kind === 'ramp') { expect(r.scale.domain).toEqual([10, 40]) expect(r.scale.lut.length).toBe(256 * 4) } // score 10 is the domain floor, 40 the ceiling, 25 halfway expect(colorLane(r.color)[0]).toBe(cssColorToABGR('black')) expect(colorLane(r.color)[1]).toBe(cssColorToABGR('white')) expect(colorLane(r.color)[2]).toBe(cssColorToABGR('rgb(128,128,128)')) // a feature with no value paints the no-value grey and stays in the payload expect(r.count).toBe(5) expect(colorLane(r.color)[3]).toBe(cssColorToABGR(NO_CATEGORY_COLOR)) }) test('domainMid puts the ramp middle stop at that value', () => { const r = encodeFeatures( features, { color: { field: 'score', scale: 'linear', domainMin: 0, domainMax: 40, range: ['black', 'white', 'black'], domainMid: 10, }, }, ALL, { jexl }, ) // score 10 is the middle stop, 40 the far end: the middle falls between two // entries of the straight table, so it is white to within one step const [red, green, blue] = [0, 8, 16].map( s => (colorLane(r.color)[0]! >>> s) & 255, ) for (const channel of [red, green, blue]) { expect(channel).toBeGreaterThanOrEqual(254) } expect(colorLane(r.color)[1]).toBe(cssColorToABGR('black')) if (r.scale?.kind === 'ramp') { expect(r.scale.domainMid).toBe(10) } }) test('a pinned ramp domain wins over the region extremes', () => { const r = encodeFeatures( features, { color: { field: 'score', scale: 'linear', domainMin: 0, domainMax: 100, range: ['black', 'white'], }, }, ALL, { jexl }, ) expect(colorLane(r.color)[1]).toBe(cssColorToABGR('rgb(102,102,102)')) }) test('a pinned ramp domain with no range steps at its value', () => { const r = encodeFeatures( features, { color: { field: 'score', scale: 'linear', domainMin: 25, domainMax: 25, range: ['black', 'white'], }, }, ALL, { jexl }, ) expect(colorLane(r.color)[0]).toBe(cssColorToABGR('black')) expect(colorLane(r.color)[1]).toBe(cssColorToABGR('white')) expect(colorLane(r.color)[2]).toBe(cssColorToABGR('black')) }) test('the colorValue lane ships the raw values and the region extent instead of colors', () => { const r = encodeFeatures( features, { color: { field: 'score', scale: 'linear', range: ['black', 'white'] } }, [...ALL, 'colorValue'], { jexl }, ) expect(r.color).toBeUndefined() expect([...r.colorValue]).toEqual([10, 40, 25, Number.NaN, Number.NaN]) expect(r.scale?.kind).toBe('ramp') if (r.scale?.kind === 'ramp') { expect(r.scale.extent).toEqual([10, 40]) expect(r.scale.pinned).toEqual([false, false]) expect(r.scale.lut.length).toBe(256 * 4) } expect(encodedChannelTransferables(r)).toContain(r.colorValue.buffer) }) test('a pinned domain says so, so the display leaves it alone', () => { const r = encodeFeatures( features, { color: { field: 'score', scale: 'log', domainMin: 1, domainMax: 100 }, }, [...ALL, 'colorValue'], { jexl }, ) expect(r.scale?.kind === 'ramp' && r.scale.pinned).toEqual([true, true]) expect(r.scale?.kind === 'ramp' && r.scale.domain).toEqual([1, 100]) }) const THRESHOLD_PALETTE = ['#357ebd', '#5cb85c', '#d43f3a'] const THRESHOLD = { field: 'score', scale: 'threshold' as const, domain: [20, 30], range: THRESHOLD_PALETTE, } test('a threshold color packs one palette entry per interval for a caller naming the color lane alone', () => { const palette = THRESHOLD_PALETTE const r = encodeFeatures(features, { color: THRESHOLD }, ALL, { jexl }) expect(r.colorValue).toBeUndefined() // scores 10, 40 and 25, then no score, then text that is no number: the // two keyless cases paint the greys the feature display's threshold paints // and file under its two rows const noValue = cssColorToABGR(NO_CATEGORY_COLOR) const notNumber = cssColorToABGR(MISCONFIGURED_COLOR) expect([...colorLane(r.color)]).toEqual([ cssColorToABGR(palette[0]!), cssColorToABGR(palette[2]!), cssColorToABGR(palette[1]!), noValue, notNumber, ]) expect(r.scale).toEqual({ kind: 'threshold', field: 'score', domain: [20, 30], range: palette, missing: true, notNumber: true, }) }) test('a threshold color ships its raw values to a caller that resolves it, marking the keyless cases as a ramp does', () => { const r = encodeFeatures( features, { color: THRESHOLD }, [...ALL, 'colorValue'], { jexl }, ) expect(r.color).toBeUndefined() const { colorValue } = r expect([...colorValue.slice(0, 3)]).toEqual([10, 40, 25]) const bits = new Uint32Array( colorValue.buffer, colorValue.byteOffset, colorValue.length, ) expect(bits[3]).toBe(RAMP_NO_VALUE_BITS) expect(Number.isNaN(colorValue[4])).toBe(true) expect(r.scale).toEqual({ kind: 'threshold', field: 'score', domain: [20, 30], range: THRESHOLD_PALETTE, missing: true, notNumber: true, }) }) test('a quantitative color over the plotted field is the y lane itself, so it costs no lane', () => { const plotted = features.slice(0, 3) for (const color of [ THRESHOLD, { field: 'score', scale: 'linear' as const }, { field: 'score', scale: 'log' as const }, ]) { const r = encodeFeatures( plotted, { y: 'score', color }, [...ALL, 'colorValue'], { jexl }, ) expect(r.colorValue).toBe(r.y) expect(r.color).toBeUndefined() expect(r.scale?.field).toBe('score') if (r.scale?.kind === 'ramp') { expect(r.scale.extent).toEqual([10, 40]) expect(r.scale.missing).toBeUndefined() } expect(new Set(encodedChannelTransferables(r)).size).toBe( encodedChannelTransferables(r).length, ) } // another field keeps its own lane const own = encodeFeatures( plotted, { y: 'score', color: { field: 'strand', scale: 'linear' } }, [...ALL, 'colorValue'], { jexl }, ) expect(own.colorValue).not.toBe(own.y) }) test('a threshold table flags only the keyless cases a region met', () => { const r = encodeFeatures( features.slice(0, 1), { color: { field: 'score', scale: 'threshold', domain: [20, 30] } }, ALL, { jexl }, ) expect(r.scale).toEqual({ kind: 'threshold', field: 'score', domain: [20, 30], }) }) test('a threshold domain written as strings cuts at the numbers it names', () => { const r = encodeFeatures( features, { color: { field: 'score', scale: 'threshold', domain: ['20'] } }, ALL, { jexl }, ) const [below, above] = thresholdPalette(2).map(c => cssColorToABGR(c)) expect(colorLane(r.color)[0]).toBe(below) expect(colorLane(r.color)[1]).toBe(above) expect(r.scale).toMatchObject({ kind: 'threshold', domain: [20] }) }) test('a categorical color resolves in the worker whatever lanes are named', () => { const r = encodeFeatures( features, { color: { field: 'strand', scale: 'ordinal' } }, [...ALL, 'colorValue'], { jexl }, ) expect(r.colorValue).toBeUndefined() expect(r.color).toBeDefined() }) test('y is a field name, read the same way a reader in its place is', () => { const named = encodeFeatures(features, { y: 'score' }, ['y'], { jexl }) const read = encodeFeatures(features, { y: f => f.get('score') }, ['y'], { jexl, }) expect([...read.y]).toEqual([...named.y]) expect(read.yMin).toBe(named.yMin) }) test('shape is a name or a jexl expression returning one', () => { const named = encodeFeatures(features, { shape: 'triangle-down' }, ALL, { jexl, }) expect(new Set(named.glyph)).toEqual(new Set([GLYPH_TRIANGLE])) const derived = encodeFeatures( features, { shape: "jexl:get(feature,'type')=='exon'?'triangle-down':'circle'" }, ALL, { jexl }, ) expect([...derived.glyph]).toEqual([ GLYPH_DISC, GLYPH_TRIANGLE, GLYPH_DISC, GLYPH_DISC, GLYPH_DISC, ]) }) const GLYPHS: ShapeName[] = ['circle', 'triangle-down', 'diamond'] const CODE: Record = { circle: GLYPH_DISC, 'triangle-down': GLYPH_TRIANGLE, diamond: GLYPH_DIAMOND, square: GLYPH_SQUARE, } test('an unpinned shape scale derives each shape from the value, so two regions agree', () => { const r = encodeFeatures( features, { shape: { field: 'type', scale: 'ordinal' } }, ALL, { jexl }, ) const of = (label: string) => categoricalValueColor(label, GLYPHS) expect(r.shapeScale).toEqual({ kind: 'shape', field: 'type', domain: [], entries: [ { value: 'cds', shape: of('cds') }, { value: 'exon', shape: of('exon') }, { value: 'gene', shape: of('gene') }, ], }) expect([...r.glyph]).toEqual( ['gene', 'exon', 'gene', 'cds', 'gene'].map(v => CODE[of(v)]), ) expect(r.scale).toBeUndefined() const other = encodeFeatures( [feature(9, { type: 'exon' }), feature(10, {})], { shape: { field: 'type', scale: 'ordinal' } }, ALL, { jexl }, ) expect(other.glyph[0]).toBe(CODE[of('exon')]) expect(other.glyph[1]).toBe(GLYPH_DISC) expect(other.shapeScale?.entries).toEqual([ { value: 'exon', shape: of('exon') }, { value: '', shape: 'circle' }, ]) }) test('a pinned shape domain walks the range in order', () => { const r = encodeFeatures( features, { shape: { field: 'strand', scale: 'ordinal', domain: [1, -1], range: ['triangle-down', 'diamond'], }, }, ALL, { jexl }, ) expect(r.shapeScale).toEqual({ kind: 'shape', field: 'strand', domain: ['1', '-1'], range: ['triangle-down', 'diamond'], entries: [ { value: '1', shape: 'triangle-down' }, { value: '-1', shape: 'diamond' }, ], }) expect([...r.glyph]).toEqual([ GLYPH_TRIANGLE, GLYPH_DIAMOND, GLYPH_TRIANGLE, GLYPH_DIAMOND, GLYPH_TRIANGLE, ]) }) test('a square draws where a constant or a range names it', () => { const constant = encodeFeatures(features, { shape: 'square' }, ALL, { jexl }) expect([...constant.glyph]).toEqual(features.map(() => GLYPH_SQUARE)) const ranged = encodeFeatures( features, { shape: { field: 'strand', scale: 'ordinal', domain: [1, -1], range: ['square', 'circle'], }, }, ALL, { jexl }, ) expect(ranged.shapeScale?.entries).toEqual([ { value: '1', shape: 'square' }, { value: '-1', shape: 'circle' }, ]) expect(ranged.glyph[0]).toBe(GLYPH_SQUARE) }) test('a value the shape domain leaves out takes a shape no listed value holds', () => { const r = encodeFeatures( features, { shape: { field: 'type', scale: 'ordinal', domain: ['gene'], range: ['diamond'], }, }, ALL, { jexl }, ) const shapeOf = new Map(r.shapeScale?.entries.map(e => [e.value, e.shape])) expect(shapeOf.get('gene')).toBe('diamond') expect(shapeOf.get('exon')).not.toBe('diamond') expect(shapeOf.get('cds')).not.toBe('diamond') }) test('a range longer than its domain gives every unlisted value its spare shapes', () => { const r = encodeFeatures( features, { shape: { field: 'type', scale: 'ordinal', domain: ['cds'], range: ['triangle-down', 'circle'], }, }, ALL, { jexl }, ) const shapeOf = new Map(r.shapeScale?.entries.map(e => [e.value, e.shape])) expect(shapeOf.get('cds')).toBe('triangle-down') expect(shapeOf.get('gene')).toBe('circle') expect(shapeOf.get('exon')).toBe('circle') }) test('color and shape scales over different fields resolve side by side', () => { const r = encodeFeatures( features, { color: { field: 'type', scale: 'ordinal', domain: ['gene', 'exon'] }, shape: { field: 'strand', scale: 'ordinal', domain: [1, -1] }, }, ALL, { jexl }, ) expect(r.scale?.kind).toBe('categorical') expect(r.shapeScale?.kind).toBe('shape') expect([...r.glyph]).toEqual([ GLYPH_DISC, GLYPH_TRIANGLE, GLYPH_DISC, GLYPH_TRIANGLE, GLYPH_DISC, ]) expect(colorLane(r.color)[0]).toBe(colorLane(r.color)[2]) expect(colorLane(r.color)[0]).not.toBe(colorLane(r.color)[1]) }) test('an empty feature list ships no index', () => { const r = encodeFeatures([], { y: 'score' }, ALL, { jexl }) expect(r.count).toBe(0) expect(r.flatbushData).toBeUndefined() }) test("a channel spelled as a reader is read in the field ref's place", () => { const r = encodeFeatures( features, { y: f => Number(f.get('score')) * 2, color: f => (f.get('strand') === 1 ? 0xff0000ff : 0xff00ff00), shape: f => (f.get('type') === 'exon' ? GLYPH_TRIANGLE : GLYPH_DISC), }, ALL, { jexl }, ) expect(r.count).toBe(3) expect([...r.y]).toEqual([20, 80, 50]) expect([...colorLane(r.color)]).toEqual([0xff0000ff, 0xff00ff00, 0xff0000ff]) expect([...r.glyph]).toEqual([GLYPH_DISC, GLYPH_TRIANGLE, GLYPH_DISC]) expect(r.scale).toBeUndefined() }) test('only the lanes asked for are filled, and the index only when named', () => { const r = encodeFeatures(features, { y: 'score' }, ['y'], { jexl }) expect(r.count).toBe(3) expect([...r.y]).toEqual([10, 40, 25]) expect(r.color).toBeUndefined() expect(r.glyph).toBeUndefined() expect(r.row).toBeUndefined() expect(r.flatbushData).toBeUndefined() expect(encodedChannelTransferables(r)).toHaveLength(4) // a declared y outside the lane set is not read: nothing is skipped const spans = encodeFeatures(features, { y: 'score' }, ['color', 'index'], { jexl, }) expect(spans.count).toBe(5) expect(spans.y).toBeUndefined() expect(spans.yMin).toBe(Infinity) expect(Flatbush.from(spans.flatbushData!).search(90, -1, 160, 1)).toEqual([1]) }) test('the tooltip lane holds the name of each admitted instance, skipping with the instances a y skips', () => { const r = encodeFeatures( [ feature(0, { score: 1, name: 'VCV1' }), feature(1, { score: 'n/a', name: 'VCV2' }), feature(2, { score: 3, id: 'id-3' }), ], { y: 'score', tooltip: 'name' }, ['y', 'tooltip'], { jexl }, ) expect(r.count).toBe(2) expect(r.tooltip).toEqual(['VCV1', 'id-3']) expect(encodedChannelTransferables(r)).toHaveLength(4) expect( encodeFeatures(features, { tooltip: 'type' }, ['y'], { jexl }).tooltip, ).toBeUndefined() }) test('a tooltip field that reads nothing or throws names the feature, and an empty one names nothing', () => { const named = [feature(0, { name: 'geneA' }), feature(1, { id: 'id-1' })] expect( encodeFeatures(named, { tooltip: 'product' }, ['tooltip'], { jexl }) .tooltip, ).toEqual(['geneA', 'id-1']) expect( encodeFeatures(named, { tooltip: 'jexl:feature.a.b.c' }, ['tooltip'], { jexl, }).tooltip, ).toEqual(['geneA', 'id-1']) expect( encodeFeatures(named, { tooltip: '' }, ['tooltip'], { jexl }).tooltip, ).toEqual(['', '']) }) test('text is a lane of strings, filled only when named, empty where the field holds nothing', () => { const r = encodeFeatures( [ feature(0, { name: 'geneA' }), feature(1, {}), feature(2, { name: ['a', 'b'] }), feature(3, { name: 7 }), ], { text: 'name' }, ['text'], { jexl }, ) expect(r.text).toEqual(['geneA', '', 'a,b', '7']) expect(encodedChannelTransferables(r)).toHaveLength(2) const derived = encodeFeatures( [feature(0, { score: 4 })], { text: 'jexl:"n="+feature.score' }, ['text'], { jexl }, ) expect(derived.text).toEqual(['n=4']) expect( encodeFeatures(features, { text: 'type' }, ['y'], { jexl }).text, ).toBeUndefined() expect(encodeFeatures(features, {}, ['text'], { jexl }).text).toEqual([ '', '', '', '', '', ]) }) test('row is an integer lane, 0 where the field is missing or negative', () => { const r = encodeFeatures( [ feature(0, { sampleIndex: 2 }), feature(1, {}), feature(2, { sampleIndex: -1 }), feature(3, { sampleIndex: '1' }), ], { row: 'sampleIndex' }, ['row'], { jexl }, ) expect([...r.row]).toEqual([2, 0, 0, 1]) const bare = encodeFeatures(features, {}, ['row'], { jexl }) expect([...bare.row]).toEqual([0, 0, 0, 0, 0]) }) test('a caller whose channels are readers or field names needs no jexl instance', () => { const r = encodeFeatures(features, { y: f => Number(f.get('score')) }, ['y']) expect([...r.y]).toEqual([10, 40, 25]) expect(() => encodeFeatures(features, { y: 'jexl:feature.score * 2' }, ['y']), ).toThrow(/jexl/) const bare = encodeFeatures(features, { y: 'jexl:feature.score' }, ['y']) expect([...bare.y]).toEqual([10, 40, 25]) }) test('a categorical table says whether every key it met was a number', () => { const of = (field: string, list = features) => encodeFeatures(list, { color: { field, scale: 'ordinal' } }, ALL, { jexl, }).scale expect(of('strand')).toMatchObject({ numericKeys: true }) expect(of('type')).not.toHaveProperty('numericKeys') // One key that is not a number is enough: `score` reads `n/a` on one // feature and nothing on another. expect(of('score')).not.toHaveProperty('numericKeys') expect(of('absent', [feature(9, {})])).not.toHaveProperty('numericKeys') }) test('size is a raw lane with a table, so every region strokes a value alike', () => { const out = encodeFeatures( features, { size: { field: 'score', scale: 'log', domainMax: 100, range: [2, 10] } }, ['size'], ) expect([...out.size]).toEqual([10, 40, 25, NaN, NaN]) expect(out.sizeScale).toEqual({ field: 'score', scale: 'log', domain: [10, 100], pinned: [false, true], range: [2, 10], extent: [10, 40], }) }) test('a log scale spans the positive values it met, so a 0 among them floors nothing at 1', () => { const list = [0, 0.5, 4].map((score, i) => feature(i, { score })) const size = encodeFeatures( list, { size: { field: 'score', scale: 'log' } }, ['size'], ) expect(size.sizeScale).toMatchObject({ domain: [0.5, 4], extent: [0.5, 4] }) const color = encodeFeatures( list, { color: { field: 'score', scale: 'log' } }, ALL, { jexl }, ) expect(color.scale).toMatchObject({ domain: [0.5, 4], extent: [0.5, 4] }) }) test('a bare field name is a linear size over the default range, and a number fills no lane', () => { const named = encodeFeatures(features, { size: 'score' }, ['size']) expect(named.sizeScale).toMatchObject({ field: 'score', scale: 'linear', range: [1, 6], pinned: [false, false], }) const constant = encodeFeatures(features, { size: 3 }, ['size']) expect(constant.size).toBeUndefined() expect(constant.sizeScale).toBeUndefined() expect(encodeFeatures(features, { size: 'score' }, []).size).toBeUndefined() }) const paired = [ feature(0, { mate: { refName: 'chr1', start: 5000, end: 5001 } }), feature(1, { mate: { refName: 'chr7', start: 300, end: 301 } }, 900, 950), feature(2, { mate: { refName: 'chr1', start: 20, end: 21 } }), feature(3, {}), ] test('a locus x2 reads its position and files its sequence in the refName dictionary', () => { const out = encodeFeatures( paired, { x2: { refName: 'mate.refName', pos: 'mate.start' } }, ['x2Ref'], ) expect([...out.x2]).toEqual([5000, 300, 20]) expect(out.x2RefNames).toEqual(['chr1', 'chr7']) expect([...out.x2Ref]).toEqual([0, 1, 0]) // the record with no mate has no position and is a skipped feature expect(out.skipped).toBe(1) expect(out.skippedPosition).toBe(1) }) test('a locus x2 packs the arm each end keeps into the feet lane', () => { const ends = [ feature(0, { mateDirection: -1, mate: { refName: 'chr1', start: 5000, mateDirection: 1 }, }), feature(1, { mateDirection: 1, mate: { refName: 'chr7', start: 300, mateDirection: 1 }, }), feature(2, { mate: { refName: 'chr1', start: 20 } }), ] const x2 = { refName: 'mate.refName', pos: 'mate.start' } const out = encodeFeatures(ends, { x2 }, ['x2Ref']) expect([...out.feet!]).toEqual([linkFeet(-1, 1), linkFeet(1, 1), 0]) expect(encodedChannelTransferables(out)).toContain(out.feet!.buffer) // no record states a direction, so there is no lane expect(encodeFeatures(paired, { x2 }, ['x2Ref']).feet).toBeUndefined() }) test('a plain x2 files every feature under its own sequence when the lane is asked for', () => { const out = encodeFeatures(features, {}, ['x2Ref']) expect(out.x2RefNames).toEqual(['chr1']) expect([...out.x2Ref]).toEqual([0, 0, 0, 0, 0]) }) test('the hit index boxes a link between its feet whichever way round', () => { const links = [ feature(0, { mate: { refName: 'chr1', start: 20 } }, 200, 250), feature(1, { mate: { refName: 'chr7', start: 300 } }, 900, 950), ] const encoding = { x2: { refName: 'mate.refName', pos: 'mate.start' } } const fb = Flatbush.from( encodeFeatures(links, encoding, ['index']).flatbushData!, ) // the upstream mate at 20 boxes from 20 to the feature's own 200 expect(fb.search(100, -1, 101, 1)).toEqual([0]) // a mate on another sequence boxes to the coordinate it names, since the // link shape spans the view and its index is asked unbounded expect(fb.search(500, -1, 501, 1)).toEqual([1]) expect(fb.search(9_000, -1, 9_001, 1)).toEqual([]) }) test('the size and x2Ref lanes ride the transfer list', () => { const out = encodeFeatures( paired, { x2: { refName: 'mate.refName', pos: 'mate.start' }, size: 'score' }, ['x2Ref', 'size'], ) const buffers = encodedChannelTransferables(out) expect(buffers).toContain(out.size.buffer) expect(buffers).toContain(out.x2Ref.buffer) }) // A bar, point or link mark's ramp resolves on the GPU or in the Canvas2D bake, // a span's in the worker through `continuousColorScale`: one value, one color. test('every ramp path paints no value, and text that is no number, one grey each', () => { const { colorOf } = continuousColorScale( { field: 'score', scale: 'linear' }, [0, 1], ) expect(colorOf(Number.NaN)).toBe(RAMP_NOT_A_NUMBER_COLOR) expect(RAMP_NO_VALUE_COLOR).toBe(cssColorToABGR(NO_CATEGORY_COLOR)) expect(colorOf(Infinity)).toBe(colorOf(1)) expect(colorOf(-Infinity)).toBe(colorOf(0)) }) // The encoder resolves a threshold in its own walk, a bin index per feature // rather than a key through the categorical path, so it is held to the // thresholdField the feature display, the variant cells and every threshold key // read: one value, one color, whichever of them paints it. test("the encoder's threshold paints each value as thresholdField colors it", () => { const domain = ['0.5', '2'] const range = ['#111111', '#222222'] const values: unknown[] = [ -Infinity, 0, 0.5, 1, 2, Infinity, '1.5', 'n/a', undefined, '', [undefined], ] const features = values.map( (v, i) => new SimpleFeature({ uniqueId: String(i), refName: 'ctgA', start: i, end: i + 1, ...(v === undefined ? {} : { v }), }), ) const { color } = encodeFeatures( features, { color: { field: 'v', scale: 'threshold', domain, range } }, ['color'], ) const field = thresholdField('v', { domain, range }) expect([...colorLane(color)]).toEqual( values.map(v => cssColorToABGR(field.color(field.key(v)))), ) }) test('a position before the first base stops at 0 rather than wrapping the lane', () => { const flank = feature(0, { flankStart: -400, flankEnd: 100 }) const enc = encodeFeatures([flank], { x: 'flankStart', x2: 'flankEnd' }, []) expect([...enc.x]).toEqual([0]) expect([...enc.x2]).toEqual([100]) expect(enc.skipped).toBe(0) }) test('a VCF missing value, `[undefined]`, files under the no-value row on every categorical channel', () => { const feats = [ feature(0, { INFO: { X: ['a'] } }), feature(1, { INFO: { X: [undefined] } }), feature(2, { INFO: {} }), ] const enc = encodeFeatures( feats, { color: { field: 'INFO.X', scale: 'ordinal' }, shape: { field: 'INFO.X', scale: 'ordinal' }, text: 'INFO.X', }, ['color', 'glyph', 'text'], ) const scale = enc.scale! expect( scale.kind === 'categorical' ? scale.entries.map(e => e.value) : [], ).toEqual(['a', '']) expect(enc.shapeScale!.entries.map(e => e.value)).toEqual(['a', '']) expect(enc.text).toEqual(['a', '', '']) }) function lane(values: NumberLane, at?: Uint32Array): Column { return { kind: 'number', values, at } } test('whole-number lanes place every row, so the payload ships no index', () => { const table = new ColumnTable( 3, new Map([ ['start', lane(Int32Array.from([5, -2, 30]))], ['end', lane(Uint32Array.from([9, 4, 40]))], ]), String, ) const r = encodeFeatures(table, { row: Uint32Array.from([2, 0, 1]) }, ['row']) expect(r.count).toBe(3) expect(r.featureIndex).toBeUndefined() expect([...r.x]).toEqual([5, 0, 30]) expect([...r.x2]).toEqual([9, 4, 40]) expect([...r.row]).toEqual([2, 0, 1]) expect(featureIndexAt(r, 2)).toBe(2) expect(encodedChannelTransferables(r)).toHaveLength(3) }) test('a text over a float32 lane prints the digits the lane holds', () => { const table = new ColumnTable( 3, new Map([ ['start', lane(Uint32Array.from([0, 10, 20]))], ['end', lane(Uint32Array.from([5, 15, 25]))], ['score', lane(Float32Array.from([0.3865, 100, -0.8213]))], ]), String, ) expect(new Float32Array([0.3865])[0]).not.toBe(0.3865) expect(encodeFeatures(table, { text: 'score' }, ['text']).text).toEqual([ '0.3865', '100', '-0.8213', ]) }) test('a lane read through its index, with rows skipped, names each instance by its row', () => { const at = Uint32Array.from([3, 2, 1, 0]) const table = new ColumnTable( 4, new Map([ ['start', lane(Uint32Array.from([0, 10, 20, 30]), at)], ['end', lane(Uint32Array.from([5, 15, 25, 35]), at)], ['score', lane(Float32Array.from([1, Number.NaN, 3, 4]), at)], [ 'state', { kind: 'category', codes: Uint8Array.from([0, 1, 0, 1]), labels: ['a', 'b'], at, }, ], ]), String, ) const r = encodeFeatures( table, { y: 'score', color: { field: 'state', scale: 'ordinal' } }, ['y', 'color'], ) expect(r.count).toBe(3) expect([...r.featureIndex!]).toEqual([0, 1, 3]) expect(featureIndexAt(r, 2)).toBe(3) expect([...r.x]).toEqual([30, 20, 0]) expect([...r.y]).toEqual([4, 3, 1]) const [b, a] = ['b', 'a'].map(v => cssColorToABGR(categoricalValueColor(v))) expect([...colorLane(r.color)]).toEqual([b, a, a]) }) test('lanes with no index skip a row whose y is not finite, and stop a negative position at 0', () => { const table = new ColumnTable( 4, new Map([ ['start', lane(Int32Array.from([-5, 10, 20, 30]))], ['end', lane(Int32Array.from([5, 15, 25, 35]))], ['score', lane(Float32Array.from([1, Number.NaN, Infinity, 4]))], ]), String, ) const r = encodeFeatures(table, { y: 'score' }, ['y']) expect(r.count).toBe(2) expect(r.skippedPosition).toBe(0) expect([...r.featureIndex!]).toEqual([0, 3]) expect([...r.x]).toEqual([0, 30]) expect([...r.x2]).toEqual([5, 35]) expect([...r.y]).toEqual([1, 4]) expect([r.yMin, r.yMax]).toEqual([1, 4]) }) test('a categorical over a category column lists only the labels its placed rows carry', () => { const table = new ColumnTable( 3, new Map([ ['start', lane(Float64Array.from([0, Number.NaN, 20]))], ['end', lane(Uint32Array.from([5, 15, 25]))], [ 'state', { kind: 'category', codes: Uint8Array.from([0, 1, 0]), labels: ['a', 'b', 'c'], at: undefined, }, ], ]), String, ) const r = encodeFeatures( table, { color: { field: 'state', scale: 'ordinal' } }, ['color'], ) expect(r.skippedPosition).toBe(1) expect( r.scale?.kind === 'categorical' ? r.scale.entries.map(e => e.value) : [], ).toEqual(['a']) }) test('a packed threshold compares in float32, so a float32 value at a cut takes the band above it, as the shader paints it', () => { const table = new ColumnTable( 2, new Map([ ['start', lane(Uint32Array.from([0, 10]))], ['end', lane(Uint32Array.from([5, 15]))], ['score', lane(Float32Array.from([0.7, 0.69]))], ]), String, ) const r = encodeFeatures( table, { color: { field: 'score', scale: 'threshold', domain: [0.7] } }, ['color'], ) const [below, above] = thresholdPalette(2).map(c => cssColorToABGR(c)) expect([...colorLane(r.color)]).toEqual([above, below]) }) test('a colorKey lane names each instance by its entry and paints nothing', () => { const r = encodeFeatures( features, { color: { field: 'type', scale: 'ordinal' } }, ['colorKey'], { jexl }, ) expect(r.color).toBeUndefined() const entries = r.scale?.kind === 'categorical' ? r.scale.entries.map(e => e.value) : [] expect(entries).toEqual(['cds', 'exon', 'gene']) expect([...r.colorKey].map(k => entries[k])).toEqual([ 'gene', 'exon', 'gene', 'cds', 'gene', ]) expect(encodedChannelTransferables(r)).toContain(r.colorKey.buffer) }) test('a colorKey lane over a category column indexes the entries its rows met', () => { const table = new ColumnTable( 4, new Map([ ['start', lane(Uint32Array.from([0, 10, 20, 30]))], ['end', lane(Uint32Array.from([5, 15, 25, 35]))], [ 'state', { kind: 'category', codes: Uint8Array.from([3, 1, 3, 1]), labels: ['a', 'b', 'c', 'd'], at: undefined, }, ], ]), String, ) const r = encodeFeatures( table, { color: { field: 'state', scale: 'ordinal' } }, ['colorKey'], ) const entries = r.scale?.kind === 'categorical' ? r.scale.entries.map(e => e.value) : [] expect(entries).toEqual(['b', 'd']) expect([...r.colorKey].map(k => entries[k])).toEqual(['d', 'b', 'd', 'b']) }) test('an identity color keys each feature by the BED color it carries, under the name its file gives the column', () => { const own = (reserved?: unknown) => new SimpleFeature({ uniqueId: `f${String(reserved)}`, refName: 'ctgA', start: 0, end: 10, ...(reserved === undefined ? {} : { reserved }), }) const r = encodeFeatures( [own('255,0,0'), own(), own(0xff0000), own('0,0,0'), own('not a color')], { color: { scale: 'identity' } }, ['colorKey'], ) expect(r.color).toBeUndefined() expect(r.scale?.kind).toBe('identity') const entries = r.scale?.kind === 'identity' ? r.scale.entries : [] expect(entries.map(e => e.value)).toEqual(['0,0,0', '255,0,0', '']) expect(entries.map(e => e.color)).toEqual([ cssColorToABGR('black'), cssColorToABGR('red'), cssColorToABGR(DEFAULT_MARK_COLOR), ]) expect([...r.colorKey].map(k => entries[k]!.value)).toEqual([ '255,0,0', '', '255,0,0', '0,0,0', '', ]) }) test('an identity color over a field paints each feature the CSS color the field holds', () => { const tinted = (color?: string) => new SimpleFeature({ uniqueId: `f${color}`, refName: 'ctgA', start: 0, end: 10, itemRgb: '255,0,0', ...(color === undefined ? {} : { color }), }) const r = encodeFeatures( [tinted('#0072b2'), tinted(), tinted('#e69f00')], { color: { scale: 'identity', field: 'color' } }, ['color'], ) expect([...colorLane(r.color)]).toEqual([ cssColorToABGR('#0072b2'), cssColorToABGR(DEFAULT_MARK_COLOR), cssColorToABGR('#e69f00'), ]) }) test('a strict identity color reads a placeholder black as no color, and an explicit one as black', () => { const own = (field8: unknown) => new SimpleFeature({ uniqueId: `f${String(field8)}`, refName: 'ctgA', start: 0, end: 10, field8, }) const features = [own('0,0,0'), own('0'), own(0), own('0,210,0')] const keysOf = (color: { scale: 'identity'; strict?: true }) => { const r = encodeFeatures(features, { color }, ['colorKey']) const entries = r.scale?.kind === 'identity' ? r.scale.entries : [] return [...r.colorKey].map(k => entries[k]!.value) } expect(keysOf({ scale: 'identity', strict: true })).toEqual([ '', '', '', '0,210,0', ]) expect(keysOf({ scale: 'identity' })).toEqual([ '0,0,0', '0,0,0', '0,0,0', '0,210,0', ]) }) test('an identity color asked for as a color lane paints each feature its own', () => { const r = encodeFeatures( [ new SimpleFeature({ uniqueId: 'a', refName: 'ctgA', start: 0, end: 10, field8: '0,128,0', }), new SimpleFeature({ uniqueId: 'b', refName: 'ctgA', start: 0, end: 10 }), ], { color: { scale: 'identity' } }, ['color'], ) expect([...colorLane(r.color)]).toEqual([ cssColorToABGR('rgb(0,128,0)'), cssColorToABGR(DEFAULT_MARK_COLOR), ]) }) test.each(['{"field":"score"}', '{"field":"score","scale":"sqrt"}'])( 'a color object with no known scale paints the invalid-color magenta and has no scale: %s', json => { const r = encodeFeatures( [feature(0, { score: 1 }), feature(1, { score: 2 })], { color: JSON.parse(json) }, ['color', 'colorValue'], { jexl }, ) expect(r.color).toBe(0xffff00ff) expect(r.colorValue).toBeUndefined() expect(r.scale).toBeUndefined() }, ) test('a jexl color that reads nothing is evaluated once', () => { let evals = 0 const counting = { compile: (code: string) => ({ eval: (context?: Record) => { evals++ return jexl.compile(code).eval(context) }, }), } const constant = colorEvaluator("jexl:'red'", counting) const perFeature = colorEvaluator( "jexl:feature.score > 20 ? 'red' : 'blue'", counting, ) for (const f of features) { expect(constant(f)).toBe(cssColorToABGR('red')) perFeature(f) } expect(evals).toBe(1 + features.length) })