Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/printer/src/formatters/arrayFormatter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const makeCtx = (
colorConfig: colorlessConfig,
seen: new WeakSet(),
quotes: '"',
keys: [],
prefix: '',
}
}
Expand Down
17 changes: 17 additions & 0 deletions packages/printer/src/formatters/objectFormatter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const makeCtx = (
colorConfig: colorlessConfig,
seen: new WeakSet(),
quotes: '"',
keys: [],
prefix: '',
}
}
Expand Down Expand Up @@ -118,4 +119,20 @@ b: 2`)
// Entries still present
expect(out).toContain('"a": 1')
})

it('tracks keys in context during formatting', () => {
const ctx = makeCtx()
const recorder: string[] = []
const numberFormatter = {
canFormat: (value: unknown) => typeof value === 'number',
format: (value: unknown, ctx: PrintContext) => {
recorder.push(ctx.keys.join('.'))
return String(value)
},
}
const printer = new Printer([new ObjectFormatter(), numberFormatter])
printer.print({ a: { b: 1 }, c: 2 }, ctx)
expect(recorder).toEqual(['a.b', 'c'])
expect(ctx.keys).toEqual([])
})
})
9 changes: 6 additions & 3 deletions packages/printer/src/formatters/objectFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,12 @@ export class ObjectFormatter implements IFormatter {
const orgIndent = ctx.indent
ctx.indent += ' '.repeat(orgPrefix.length)
ctx.prefix = ''
const entries = displayed.map((k) =>
getText(ctx, this.formatEntry(k, obj[k], ctx, printer))
)
const entries = displayed.map((k) => {
ctx.keys.push(k)
const entry = getText(ctx, this.formatEntry(k, obj[k], ctx, printer))
ctx.keys.pop()
return entry
})

const remaining = ordered.length - displayed.length
if (remaining > 0) {
Expand Down
1 change: 1 addition & 0 deletions packages/printer/src/print.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export function print(
indentString,
colorConfig: mergedColors,
quotes: options?.quotes ?? '"',
keys: [],
prefix: '',
}
return printer.print(value, ctx)
Expand Down
5 changes: 5 additions & 0 deletions packages/printer/src/printContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ export interface PrintContext {
*/
quotes: string

/**
* Stack of object keys representing the current traversal path.
*/
keys: string[]

/**
* Prefix inserted before each line when printing multi-line values
* (useful for nested or list items).
Expand Down