-
Notifications
You must be signed in to change notification settings - Fork 85
Add interpolated-intent and fallback-list render modes #1015
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lorisleiva
wants to merge
1
commit into
06-24-add_display_value_formatting_and_provide_inject_resolution
Choose a base branch
from
06-25-add_interpolated-intent_and_fallback-list_render_modes
base: 06-24-add_display_value_formatting_and_provide_inject_resolution
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
112 changes: 112 additions & 0 deletions
112
packages/dynamic-instructions/src/display/format-argument-value.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| import { | ||
| type EnumTypeNode, | ||
| isNode, | ||
| isScalarEnum, | ||
| pascalCase, | ||
| resolveNestedTypeNode, | ||
| titleCase, | ||
| type TypeNode, | ||
| } from 'codama'; | ||
|
|
||
| import { isObjectRecord } from '../shared/util'; | ||
| import { formatAmountValue, formatDateTimeValue, formatDurationValue, formatStringValue } from './format-value'; | ||
| import type { DisplayContext } from './types'; | ||
|
|
||
| /** | ||
| * Formats a single decoded value according to the presentation metadata on its type. | ||
| * | ||
| * Numbers, strings, and enum variants are rendered through their value-display nodes when | ||
| * present; `definedTypeLinkNode`s are followed via the context's link resolver so linked | ||
| * enums resolve to their variants. Any value without applicable display metadata — and any | ||
| * value whose formatter cannot resolve its inputs — falls back to a raw string form. | ||
| */ | ||
| export async function formatArgumentValue( | ||
| type: TypeNode, | ||
| value: unknown, | ||
| displayContext: DisplayContext, | ||
| ): Promise<string> { | ||
| const resolvedType = resolveDisplayType(type, displayContext); | ||
|
|
||
| if (isNode(resolvedType, 'numberTypeNode') && resolvedType.display && isNumeric(value)) { | ||
| const formatted = await formatNumber(resolvedType.display, value, displayContext); | ||
| if (formatted !== null) return formatted; | ||
| } | ||
|
|
||
| if (isNode(resolvedType, 'stringTypeNode') && resolvedType.display && typeof value === 'string') { | ||
| return formatStringValue(value, resolvedType.display); | ||
| } | ||
|
|
||
| if (isNode(resolvedType, 'enumTypeNode')) { | ||
| return formatEnumValue(resolvedType, value); | ||
| } | ||
|
|
||
| return rawValue(value); | ||
| } | ||
|
|
||
| /** | ||
| * Resolves nested type wrappers and follows a single `definedTypeLinkNode` to its underlying type. | ||
| * Shared by the value formatter and the fallback list so links resolve identically in both. | ||
| */ | ||
| export function resolveDisplayType(type: TypeNode, displayContext: DisplayContext): TypeNode { | ||
| const resolved = resolveNestedTypeNode(type); | ||
| if (isNode(resolved, 'definedTypeLinkNode')) { | ||
| const definedType = displayContext.resolveDefinedType(resolved); | ||
| if (definedType) return resolveNestedTypeNode(definedType.type); | ||
| } | ||
| return resolved; | ||
| } | ||
|
|
||
| /** Dispatches a number to the matching number-display formatter. */ | ||
| async function formatNumber( | ||
| display: NonNullable<Extract<TypeNode, { kind: 'numberTypeNode' }>['display']>, | ||
| value: bigint | number, | ||
| displayContext: DisplayContext, | ||
| ): Promise<string | null> { | ||
| switch (display.kind) { | ||
| case 'amountNumberDisplayNode': | ||
| return await formatAmountValue(value, display, displayContext); | ||
| case 'dateTimeNumberDisplayNode': | ||
| return formatDateTimeValue(value, display); | ||
| case 'durationNumberDisplayNode': | ||
| return formatDurationValue(value, display); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Formats an enum value using the matched variant's display label. | ||
| * Scalar enums decode to the variant name; data enums decode to `{ __kind: 'PascalVariant', ... }`. | ||
| */ | ||
| function formatEnumValue(enumType: EnumTypeNode, value: unknown): string { | ||
| const decodedName = enumVariantName(value); | ||
| if (decodedName === null) return rawValue(value); | ||
|
|
||
| // Scalar enums decode to the variant name as-is; data enum `__kind` is the PascalCase form. | ||
| const variant = enumType.variants.find(candidate => | ||
| isScalarEnum(enumType) ? candidate.name === decodedName : pascalCase(candidate.name) === decodedName, | ||
| ); | ||
| if (!variant) return rawValue(value); | ||
|
|
||
| return variant.display?.label ?? titleCase(variant.name); | ||
| } | ||
|
|
||
| /** Extracts the variant name from a decoded enum value (scalar name string or data enum `__kind`). */ | ||
| function enumVariantName(value: unknown): string | null { | ||
| if (typeof value === 'string') return value; | ||
| if (isObjectRecord(value) && typeof value.__kind === 'string') return value.__kind; | ||
| return null; | ||
| } | ||
|
|
||
| /** Renders a value without any display metadata as a safe, human-readable string. */ | ||
| function rawValue(value: unknown): string { | ||
| if (value === null || value === undefined) return ''; | ||
| if (typeof value === 'string') return value; | ||
| if (typeof value === 'bigint' || typeof value === 'number' || typeof value === 'boolean') { | ||
| return value.toString(); | ||
| } | ||
| if (isObjectRecord(value) && typeof value.__kind === 'string') return titleCase(value.__kind); | ||
| return JSON.stringify(value, (_key, v: unknown) => (typeof v === 'bigint' ? v.toString() : v)); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think when I guess, this could happen when some key of context data is set to |
||
| } | ||
|
|
||
| function isNumeric(value: unknown): value is bigint | number { | ||
| return typeof value === 'bigint' || typeof value === 'number'; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,6 @@ | ||
| export * from './format-argument-value'; | ||
| export * from './format-value'; | ||
| export * from './interpolate-intent'; | ||
| export * from './list-fallback'; | ||
| export * from './resolve-injected-value'; | ||
| export * from './types'; |
54 changes: 54 additions & 0 deletions
54
packages/dynamic-instructions/src/display/interpolate-intent.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| import { getLastNodeFromPath } from 'codama'; | ||
|
|
||
| import { formatArgumentValue } from './format-argument-value'; | ||
| import type { DisplayContext } from './types'; | ||
|
|
||
| /** Matches a `${root.path}` placeholder, capturing the root and the (flat) path after it. */ | ||
| const PLACEHOLDER_PATTERN = /\$\{\s*(data|accounts)\.([a-zA-Z0-9_]+)\s*\}/g; | ||
|
|
||
| /** | ||
| * Renders an instruction's `interpolatedIntent` template into a concrete sentence. | ||
| * | ||
| * Placeholders use the flat form `${data.<argument>}` and `${accounts.<account>}`. Each is | ||
| * replaced by the referent's own presentation: arguments through their value-display nodes, | ||
| * accounts by their address. | ||
| * | ||
| * Returns `null` when the instruction has no `interpolatedIntent`, or when any placeholder | ||
| * cannot be resolved (an unknown name, or a value whose formatting fails). A `null` result | ||
| * signals the caller to fall back to the structured field list. | ||
|
Comment on lines
+16
to
+18
|
||
| */ | ||
| export async function interpolateIntent(displayContext: DisplayContext): Promise<string | null> { | ||
| const instruction = getLastNodeFromPath(displayContext.parsedInstruction.path); | ||
| const template = instruction.display?.interpolatedIntent; | ||
| if (template === undefined) return null; | ||
|
|
||
| // Resolve each distinct placeholder in parallel, then substitute them back into the template. | ||
| const placeholders = [...template.matchAll(PLACEHOLDER_PATTERN)].filter( | ||
| ([token], index, all) => all.findIndex(([other]) => other === token) === index, | ||
| ); | ||
| const resolved = await Promise.all( | ||
| placeholders.map(async ([token, root, name]) => { | ||
| return [token, await resolvePlaceholder(root, name, displayContext)] as const; | ||
| }), | ||
| ); | ||
|
|
||
| if (resolved.some(([, value]) => value === null)) return null; | ||
| const replacements = new Map(resolved); | ||
|
|
||
| return template.replace(PLACEHOLDER_PATTERN, match => replacements.get(match) ?? match); | ||
| } | ||
|
|
||
| /** Resolves a single placeholder to its rendered string, or `null` when it cannot be resolved. */ | ||
| async function resolvePlaceholder(root: string, name: string, displayContext: DisplayContext): Promise<string | null> { | ||
| const { data, path } = displayContext.parsedInstruction; | ||
| if (root === 'data') { | ||
| const instruction = getLastNodeFromPath(path); | ||
| const argument = instruction.arguments.find(arg => arg.name === name); | ||
| const decodedData = data as Record<string, unknown>; | ||
| if (!argument || !(name in decodedData)) return null; | ||
| return await formatArgumentValue(argument.type, decodedData[name], displayContext); | ||
| } | ||
|
|
||
| // root === 'accounts' | ||
| return displayContext.parsedInstruction.accounts.find(account => account.name === name)?.address ?? null; | ||
| } | ||
88 changes: 88 additions & 0 deletions
88
packages/dynamic-instructions/src/display/list-fallback.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| import { | ||
| type DisplaySkip, | ||
| getLastNodeFromPath, | ||
| type InstructionArgumentNode, | ||
| isNode, | ||
| type StructTypeNode, | ||
| titleCase, | ||
| } from 'codama'; | ||
|
|
||
| import { isObjectRecord } from '../shared/util'; | ||
| import { formatArgumentValue, resolveDisplayType } from './format-argument-value'; | ||
| import type { DisplayContext, DisplayField } from './types'; | ||
|
|
||
| /** | ||
| * Builds the fallback display: a flat, ordered list of labelled fields for an instruction's | ||
| * arguments and accounts. | ||
| * | ||
| * Honours each member's display metadata — `skip` (hidden when `'always'`, or when | ||
| * `'whenInjected'` and the value was surfaced through the provide/inject graph), `label` | ||
| * overrides, and struct `flatten`/`flattenPrefix`. The instruction's intent/title is not | ||
| * included here; the caller composes it around this list. | ||
| */ | ||
| export async function listFallback(displayContext: DisplayContext): Promise<DisplayField[]> { | ||
| const instruction = getLastNodeFromPath(displayContext.parsedInstruction.path); | ||
| const argumentFieldGroups = await Promise.all( | ||
| instruction.arguments.map(argument => argumentFields(argument, displayContext)), | ||
| ); | ||
| return [...argumentFieldGroups.flat(), ...accountFields(displayContext)]; | ||
| } | ||
|
|
||
| /** Produces the display fields for a single instruction argument (one field, or many when flattened). */ | ||
| async function argumentFields( | ||
| argument: InstructionArgumentNode, | ||
| displayContext: DisplayContext, | ||
| ): Promise<DisplayField[]> { | ||
| if (isSkipped(argument.display?.skip, argument.name, displayContext)) return []; | ||
|
|
||
| const value = (displayContext.parsedInstruction.data as Record<string, unknown>)[argument.name]; | ||
| const resolvedType = resolveDisplayType(argument.type, displayContext); | ||
| const structType = isNode(resolvedType, 'structTypeNode') ? resolvedType : undefined; | ||
|
|
||
| if (argument.display?.flatten && structType && isObjectRecord(value)) { | ||
| return await flattenedFields(structType, value, argument.display.flattenPrefix, displayContext); | ||
| } | ||
|
|
||
| const label = argument.display?.label ?? titleCase(argument.name); | ||
| return [{ label, value: await formatArgumentValue(argument.type, value, displayContext) }]; | ||
| } | ||
|
|
||
| /** Lifts a struct's fields into the parent list, prefixing each label and reading nested values. */ | ||
| async function flattenedFields( | ||
| struct: StructTypeNode, | ||
| value: Record<string, unknown>, | ||
| prefix: string | undefined, | ||
| displayContext: DisplayContext, | ||
| ): Promise<DisplayField[]> { | ||
| const visibleFields = struct.fields.filter(field => !isSkipped(field.display?.skip, field.name, displayContext)); | ||
| return await Promise.all( | ||
| visibleFields.map(async field => { | ||
| const label = `${prefix ?? ''}${field.display?.label ?? titleCase(field.name)}`; | ||
| const formatted = await formatArgumentValue(field.type, value[field.name], displayContext); | ||
| return { label, value: formatted }; | ||
| }), | ||
| ); | ||
| } | ||
|
|
||
| /** Produces the display fields for the instruction's accounts. */ | ||
| function accountFields(displayContext: DisplayContext): DisplayField[] { | ||
| const instruction = getLastNodeFromPath(displayContext.parsedInstruction.path); | ||
| return instruction.accounts.flatMap(account => { | ||
| if (isSkipped(account.display?.skip, account.name, displayContext)) return []; | ||
| const address = displayContext.parsedInstruction.accounts.find(a => a.name === account.name)?.address; | ||
| if (!address) return []; | ||
| const label = account.display?.label ?? titleCase(account.name); | ||
| return [{ label, value: address }]; | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Determines whether a member is hidden from the fallback list given its `skip` strategy. | ||
| * `'always'` always hides; `'whenInjected'` hides when a provider exposes the member's name | ||
| * (its value is surfaced elsewhere through the provide/inject graph); `'never'`/absent shows. | ||
| */ | ||
| function isSkipped(skip: DisplaySkip | undefined, name: string, displayContext: DisplayContext): boolean { | ||
| if (skip === 'always') return true; | ||
| if (skip === 'whenInjected') return displayContext.provides.has(name); | ||
| return false; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just in case, there is safeStringify in shared/util.
However, not sure it will be acceptable in this case to return
non-serializable <value_type>instead of throwing and error when JSON.stringify fails.