Skip to content
Open
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
11 changes: 5 additions & 6 deletions packages/core/components/FileRow/Cell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import interact from "interactjs";
import * as React from "react";

import Tooltip from "../Tooltip";
import { MINIMUM_COLUMN_WIDTH } from "../../entity/SearchParams";

import styles from "./Cell.module.css";

Expand Down Expand Up @@ -38,8 +39,6 @@ enum ResizeDirection {
* This component uses pixel-based widths for columns.
*/
export default class Cell extends React.Component<React.PropsWithChildren<CellProps>, CellState> {
public static MINIMUM_WIDTH = 50; // px; somewhat arbitrary

public state: CellState = {
resizeTargetClassName: styles.cursorResizeEitherDirection,
};
Expand Down Expand Up @@ -101,7 +100,7 @@ export default class Cell extends React.Component<React.PropsWithChildren<CellPr
onDoubleClick={this.onDoubleClick}
style={{
width: `${provisionalWidth || width}px`,
minWidth: Cell.MINIMUM_WIDTH,
minWidth: MINIMUM_COLUMN_WIDTH,
}}
>
<div className={styles.cellContent}>
Expand All @@ -125,7 +124,7 @@ export default class Cell extends React.Component<React.PropsWithChildren<CellPr
<div
className={classNames(styles.cell, this.props.className)}
onContextMenu={this.props.onContextMenu}
style={{ width: `${this.props.width}px`, minWidth: Cell.MINIMUM_WIDTH }}
style={{ width: `${this.props.width}px`, minWidth: MINIMUM_COLUMN_WIDTH }}
data-testid={NON_RESIZEABLE_CELL_TEST_ID}
>
<Tooltip content={this.props.title}>
Expand Down Expand Up @@ -176,7 +175,7 @@ export default class Cell extends React.Component<React.PropsWithChildren<CellPr
if (this.resizeIsAllowed(dx, allowedResizeDirection)) {
nextState = {
...nextState,
provisionalWidth: Math.max(nextWidth, Cell.MINIMUM_WIDTH),
provisionalWidth: Math.max(nextWidth, MINIMUM_COLUMN_WIDTH),
};
}

Expand Down Expand Up @@ -206,7 +205,7 @@ export default class Cell extends React.Component<React.PropsWithChildren<CellPr
return ResizeDirection.BIGGER_OR_SMALLER;
}

if (expectedWidth <= Cell.MINIMUM_WIDTH) {
if (expectedWidth <= MINIMUM_COLUMN_WIDTH) {
return ResizeDirection.BIGGER;
}

Expand Down
1 change: 1 addition & 0 deletions packages/core/entity/SearchParams/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Column } from "../../state/selection/actions";
// used as a fallback when calculating column widths based on content,
// and as the default width when resetting column widths
export const DEFAULT_COLUMN_WIDTH = 150;
export const MINIMUM_COLUMN_WIDTH = 50; // px; somewhat arbitrary;

// These values CANNOT change otherwise it would break compatibility
// with any existing URLs that use these in the encoding
Expand Down
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 {
Expand All @@ -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;
Comment thread
SeanDuHare marked this conversation as resolved.
}

constructor(
config: Config = { dataSourceNames: [], databaseService: new DatabaseServiceNoop() }
Expand Down Expand Up @@ -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
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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(
Comment thread
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.
*/
Expand Down
Loading
Loading