diff --git a/__tests__/unit/plots/column/index-spec.ts b/__tests__/unit/plots/column/index-spec.ts index 633a4eaae8..28b6c0f65f 100644 --- a/__tests__/unit/plots/column/index-spec.ts +++ b/__tests__/unit/plots/column/index-spec.ts @@ -83,6 +83,32 @@ describe('column', () => { column.destroy(); }); + it('x*y with color callback', () => { + const column = new Column(createDiv('x*y with color callback'), { + width: 400, + height: 300, + data: salesByArea, + xField: 'area', + yField: 'sales', + slider: { + start: 0, + end: 0.5, + }, + color: (datum) => (datum.sales > 100 ? 'red' : 'green'), + }); + + column.render(); + + const geometry = column.chart.geometries[0]; + + expect(geometry.getAttribute('color')).toBeUndefined(); + expect(geometry.getAttribute('style').getFields()).toEqual(['area']); + expect(column.chart.getGroupScales()).toHaveLength(0); + expect(geometry.elements[0].shape.attr('fill')).toBe('green'); + + column.destroy(); + }); + it('grouped column', () => { const column = new Column(createDiv('grouped column'), { width: 400, diff --git a/src/adaptor/geometries/base.ts b/src/adaptor/geometries/base.ts index 6eb6b8d7a4..a17518054a 100644 --- a/src/adaptor/geometries/base.ts +++ b/src/adaptor/geometries/base.ts @@ -126,17 +126,22 @@ export function getMappingFunction(mappingFields: string[], func: (datum: Datum) if (!func) return undefined; // 返回函数 return (...args: any[]) => { - const params: Datum = {}; + const params = getMappingDatum(mappingFields, args); + return func(params); + }; +} - mappingFields.forEach((f: string, idx: number) => { - params[f] = args[idx]; - }); +function getMappingDatum(mappingFields: string[], args: any[]): Datum { + const params: Datum = {}; - // 删除 undefined - delete params['undefined']; + mappingFields.forEach((f: string, idx: number) => { + params[f] = args[idx]; + }); - return func(params); - }; + // 删除 undefined + delete params['undefined']; + + return params; } /** @@ -170,6 +175,9 @@ export function geometry(params: Params): Params string; /** * color 的几种情况 @@ -182,7 +190,13 @@ export function geometry(params: Params): Params(params: Params): Params ({ fill: 'red' })); */ - if (isFunction(style)) { + if (!isEmpty(colorStyleFields)) { + if (isFunction(style)) { + const { mappingFields } = getMappingField(options, 'style'); + const fields = uniq([...colorStyleFields, ...mappingFields]); + geometry.style(fields.join('*'), (...args: any[]) => { + const datum = getMappingDatum(fields, args); + return { + fill: colorStyleCallback(datum), + ...style(datum), + }; + }); + } else { + geometry.style(colorStyleMappingField, (...args: any[]) => ({ + fill: colorStyleCallback(getMappingDatum(colorStyleFields, args)), + ...(isObject(style) ? style : {}), + })); + } + } else if (isFunction(style)) { const { mappingFields, tileMappingField } = getMappingField(options, 'style'); geometry.style(tileMappingField, getMappingFunction(mappingFields, style)); } else if (isObject(style)) {