Skip to content

Commit

Permalink
Ensure temporal field propagates to time expression
Browse files Browse the repository at this point in the history
  • Loading branch information
marr authored and David Marr committed Oct 31, 2023
1 parent 1263d66 commit c655a5f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/compile/format.ts
Expand Up @@ -95,14 +95,25 @@ export function formatSignalRef({
}
}

function getTimeDef(def: FieldDef<string> | DatumDef<string>) {
if (!isFieldDef(def)) {
return {
unit: undefined,
utc: undefined
};
}
return normalizeTimeUnit(def.timeUnit) || {};
}

if (isFieldOrDatumDefForTimeFormat(fieldOrDatumDef)) {
const {unit: timeUnit, utc: isUTCUnit} = getTimeDef(fieldOrDatumDef);
const signal = timeFormatExpression({
field,
timeUnit: isFieldDef(fieldOrDatumDef) ? normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit : undefined,
timeUnit,
format,
formatType: config.timeFormatType,
rawTimeFormat: config.timeFormat,
isUTCScale: isScaleFieldDef(fieldOrDatumDef) && fieldOrDatumDef.scale?.type === ScaleType.UTC
isUTCScale: isUTCUnit || (isScaleFieldDef(fieldOrDatumDef) && fieldOrDatumDef.scale?.type === ScaleType.UTC)
});
return signal ? {signal} : undefined;
}
Expand Down
24 changes: 24 additions & 0 deletions test/compile/format.test.ts
Expand Up @@ -70,6 +70,17 @@ describe('Format', () => {
expect(expression).toBe(`utcFormat(datum["yearmonth_a"], '%Y')`);
});

it('should get the right time expression for utcyearmonth', () => {
const fieldDef = {timeUnit: 'utcyearmonth', field: 'a', type: TEMPORAL} as const;
const expression = timeFormatExpression({
field: vgField(fieldDef, {expr: 'datum'}),
timeUnit: 'month',
format: '%Y',
isUTCScale: true
});
expect(expression).toBe(`utcFormat(datum["utcyearmonth_a"], '%Y')`);
});

it('should get the right time expression for with a custom timeFormatType', () => {
const fieldDef = {field: 'a', type: TEMPORAL} as const;
const expression = timeFormatExpression({
Expand Down Expand Up @@ -157,6 +168,19 @@ describe('Format', () => {
});

describe('formatSignalRef()', () => {
it('should derive the correct temporal unit', () => {
expect(
formatSignalRef({
fieldOrDatumDef: {field: 'foo', type: TEMPORAL, timeUnit: 'utcdate'},
format: undefined,
formatType: undefined,
config: {}
})
).toEqual({
signal:
'utcFormat(utcdate_foo, timeUnitSpecifier(["date"], {"year-month":"%b %Y ","year-month-date":"%b %d, %Y "}))'
});
});
it('should format ordinal field defs if format is present', () => {
expect(
formatSignalRef({
Expand Down

0 comments on commit c655a5f

Please sign in to comment.