gradio/js/highlightedtext/utils.ts
Hannah d112e2611b
Allow interactive input in gr.HighlightedText (#5400)
* add preprocess param to highlighted_text.py

* add params

* static tweaks

* add interactive highlight container

* highlight selection logic

* allow editing label value and move shared funcs

* add changeset

* remove py code

* wait for input render

* remove redundant event listeners

* accessibility enhancements and remove label logic

* add keyboard navigation and interaction

* merge adjacent empty elements and split input element

* add interactive support for scores mode

* remove merge adjacent logic and move to frontend

* tweak

* add changeset

* format backend

* tweaks

* backend test tweaks

* set the interactive default to None

* BE tweak

* unit tests and stories

* be formatting

* fix label errors

* tweak

* fix tests

* fix tests

* fix test

---------

Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com>
Co-authored-by: Abubakar Abid <abubakar@huggingface.co>
2023-09-12 18:47:16 -07:00

74 lines
1.7 KiB
TypeScript

import { colors } from "@gradio/theme";
type HighlightValueType = [string, string | number | null];
export function name_to_rgba(
name: string,
a: number,
ctx: CanvasRenderingContext2D | null
): string {
if (!ctx) {
var canvas = document.createElement("canvas");
ctx = canvas.getContext("2d")!;
}
ctx.fillStyle = name;
ctx.fillRect(0, 0, 1, 1);
const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data;
ctx.clearRect(0, 0, 1, 1);
return `rgba(${r}, ${g}, ${b}, ${255 / a})`;
}
export function correct_color_map(
color_map: Record<string, string>,
_color_map: Record<string, { primary: string; secondary: string }>,
browser: any,
ctx: CanvasRenderingContext2D | null
): void {
for (const col in color_map) {
const _c = color_map[col].trim();
if (_c in colors) {
_color_map[col] = colors[_c as keyof typeof colors];
} else {
_color_map[col] = {
primary: browser
? name_to_rgba(color_map[col], 1, ctx)
: color_map[col],
secondary: browser
? name_to_rgba(color_map[col], 0.5, ctx)
: color_map[col]
};
}
}
}
export function merge_elements(
value: HighlightValueType[],
mergeMode: "empty" | "equal"
): HighlightValueType[] {
let result: HighlightValueType[] = [];
let tempStr: string | null = null;
let tempVal: string | number | null = null;
for (const [str, val] of value) {
if (
(mergeMode === "empty" && val === null) ||
(mergeMode === "equal" && tempVal === val)
) {
tempStr = tempStr ? tempStr + str : str;
} else {
if (tempStr !== null) {
result.push([tempStr, tempVal as string | number]);
}
tempStr = str;
tempVal = val;
}
}
if (tempStr !== null) {
result.push([tempStr, tempVal as string | number]);
}
return result;
}