-
Notifications
You must be signed in to change notification settings - Fork 7
Optimize column width based on text length #784
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
SeanDuHare
wants to merge
6
commits into
feature/show-all-columns-at-once
Choose a base branch
from
feature/optimize-column-width
base: feature/show-all-columns-at-once
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
Show all changes
6 commits
Select commit
Hold shift + click to select a range
2339e8f
Optimize column width based on text length
SeanDuHare f36db58
Add test for fetchOptimalWidthForAnnotations
SeanDuHare 2fe2951
Set minimum for width calc
SeanDuHare e5b4f0c
DatabaseQuery -> CancellablePromise; use consistently
SeanDuHare 4f9d84a
Fix optimal width test calc; adjust default for no canvas
SeanDuHare 04f2663
Merge branch 'feature/show-all-columns-at-once' into feature/optimize…
BrianWhitneyAI 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
There are no files selected for viewing
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
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,13 +1,14 @@ | ||
| import { isNil, uniq } from "lodash"; | ||
|
|
||
| import AnnotationService, { AnnotationDetails, AnnotationValue } from ".."; | ||
| import DatabaseService from "../../DatabaseService"; | ||
| import DatabaseService, { CancellablePromise } from "../../DatabaseService"; | ||
| import DatabaseServiceNoop from "../../DatabaseService/DatabaseServiceNoop"; | ||
| import { TOP_LEVEL_FILE_ANNOTATIONS } from "../../../constants"; | ||
| import { AnnotationType } from "../../../entity/AnnotationFormatter"; | ||
| import Annotation from "../../../entity/Annotation"; | ||
| import FileFilter from "../../../entity/FileFilter"; | ||
| import IncludeFilter from "../../../entity/FileFilter/IncludeFilter"; | ||
| import { Source } from "../../../entity/SearchParams"; | ||
| import { DEFAULT_COLUMN_WIDTH, MINIMUM_COLUMN_WIDTH, Source } from "../../../entity/SearchParams"; | ||
| import SQLBuilder from "../../../entity/SQLBuilder"; | ||
|
|
||
| interface Config { | ||
|
|
@@ -27,6 +28,29 @@ export default class DatabaseAnnotationService implements AnnotationService { | |
| private readonly databaseService: DatabaseService; | ||
| private readonly dataSourceNames: string[]; | ||
| private readonly metadataSource: Source | undefined; | ||
| // Get sample character width for computing column widths based on content length. | ||
| // This is a bit hacky but it's nontrivial to get character width without rendering text | ||
| // into the DOM, and we need it to compute column widths before rendering. | ||
| // Grab this one at import to avoid having to re-measure it every time we want | ||
| // to compute optimal column widths for annotations | ||
| private readonly sampleCharWidthInPx = DatabaseAnnotationService.measureTextWidth( | ||
| "S", | ||
| "16px Open Sans" | ||
| ); | ||
|
|
||
| /** | ||
| * Measures the width in pixels of the given text rendered with the specified | ||
| * CSS font shorthand (e.g. "14px Arial", "bold 12px sans-serif"). | ||
| */ | ||
| private static measureTextWidth(text: string, font: string): number { | ||
| const canvas = document.createElement("canvas"); | ||
| const context = canvas.getContext("2d"); | ||
| if (!context) { | ||
| return 1; // Fallback width if canvas context can't be created | ||
| } | ||
| context.font = font; | ||
| return context.measureText(text).width; | ||
| } | ||
|
|
||
| constructor( | ||
| config: Config = { dataSourceNames: [], databaseService: new DatabaseServiceNoop() } | ||
|
|
@@ -170,6 +194,100 @@ export default class DatabaseAnnotationService implements AnnotationService { | |
| return results.filter((result) => result.length > 0).map((result) => result[0].column_name); | ||
| } | ||
|
|
||
| /** | ||
| * Fetch the length of the longest value for each annotation, which can be used to compute optimal column widths in the UI. | ||
| * This is a bit of a hack, but it allows us to avoid fetching all values for an annotation just to compute column widths. | ||
| */ | ||
|
Comment on lines
+197
to
+200
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 this might be an accidental copy of the comment for the function below |
||
| public async fetchOptimalWidthForAnnotations( | ||
| annotationNames: string[], | ||
| ignoreWidthLimit = false | ||
| ): Promise<Record<string, number>> { | ||
| // Try to fetch values for new annotations to compute optimal column widths | ||
| const widthByAnnotation: Record<string, number> = {}; | ||
| try { | ||
| const fetchQuery = this.fetchLengthiestValues(annotationNames); | ||
| // Set a timeout on this query in case it takes too long to return, | ||
| // since it could potentially be slow for annotations with very long values | ||
| // which is fine and we will just cancel it and fall back to default column widths in that case | ||
| const timeoutPromise = new Promise<never>((_, reject) => | ||
| setTimeout(() => { | ||
| fetchQuery.cancel?.(); | ||
| reject(new Error("Timeout fetching annotation values")); | ||
| }, 1000) | ||
| ); | ||
| const annotationToLength = await Promise.race([fetchQuery.promise, timeoutPromise]); | ||
| for (const [annotation, length] of Object.entries(annotationToLength)) { | ||
| // Grab whichever is longer, the longest value or the header | ||
| // to compute the column width needed to fit this column without truncation | ||
| const maxLengthOfColumn = Math.max(length, annotation.length); | ||
| // Convert this length to a pixel width using our sample character width | ||
| // + some extra pixels for padding | ||
| const maxLengthOfColumnInPx = | ||
| Math.ceil(maxLengthOfColumn * this.sampleCharWidthInPx) + 8; | ||
| // Avoid letting width get too large for extremely long values by capping it | ||
| const minOptimalWidth = ignoreWidthLimit | ||
| ? maxLengthOfColumnInPx | ||
| : Math.min(maxLengthOfColumnInPx, DEFAULT_COLUMN_WIDTH * 3); | ||
| // Avoid letting width get too small by setting a minimum width | ||
| // like in the case of canvas measurement failing | ||
| const width = Math.max(minOptimalWidth, MINIMUM_COLUMN_WIDTH); | ||
| widthByAnnotation[annotation] = width; | ||
| } | ||
| } catch { | ||
| // If fetching values fails entirely, fall through to default widths | ||
| } | ||
| for (const annotationName of annotationNames) { | ||
| if (!widthByAnnotation.hasOwnProperty(annotationName)) { | ||
| widthByAnnotation[annotationName] = DEFAULT_COLUMN_WIDTH; | ||
| } | ||
| } | ||
| for (const annotation of TOP_LEVEL_FILE_ANNOTATIONS) { | ||
| if (!widthByAnnotation.hasOwnProperty(annotation.name)) { | ||
| widthByAnnotation[annotation.name] = DEFAULT_COLUMN_WIDTH; | ||
| } | ||
| } | ||
| return widthByAnnotation; | ||
| } | ||
|
|
||
| /** | ||
| * Fetch the length of the longest value for each annotation, which can be used to compute optimal column widths in the UI. | ||
| * This is a bit of a hack, but it allows us to avoid fetching all values for an annotation just to compute column widths. | ||
| */ | ||
| private fetchLengthiestValues( | ||
| annotationNames: string[] | ||
| ): CancellablePromise<{ [annotation: string]: number }> { | ||
| if (!this.dataSourceNames.length || annotationNames.length === 0) { | ||
| return { promise: Promise.resolve({}) }; | ||
| } | ||
|
|
||
| const aggregateDataSourceName = this.dataSourceNames.sort().join(", "); | ||
| const sql = new SQLBuilder() | ||
| .select( | ||
|
SeanDuHare marked this conversation as resolved.
|
||
| annotationNames | ||
| .map( | ||
| (annotation) => | ||
| `MAX(LENGTH(CAST("${annotation}" AS VARCHAR))) AS "${annotation}"` | ||
| ) | ||
| .join(", ") | ||
| ) | ||
| .from(aggregateDataSourceName) | ||
| .toSQL(); | ||
|
|
||
| const query = this.databaseService.query<{ [annotation: string]: number }>(sql); | ||
| return { | ||
| promise: query.promise.then((results): { [annotation: string]: number } => { | ||
| const annotationToLength: { [annotation: string]: number } = {}; | ||
| for (const row of results) { | ||
| for (const [annotation, length] of Object.entries(row)) { | ||
| annotationToLength[annotation] = length; | ||
| } | ||
| } | ||
| return annotationToLength; | ||
| }), | ||
| cancel: query.cancel, | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Validate annotation values according the type the annotation they belong to. | ||
| */ | ||
|
|
||
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.
Uh oh!
There was an error while loading. Please reload this page.