2023-07-07 17:40:59 -06:00

62 lines
2.0 KiB
TypeScript

import { CanvasRenderingContext2D } from "https://deno.land/x/skia_canvas@0.4.1/mod.ts";
import { styleTypeAccessor, TextStyle } from "./textStyle.ts";
import { wordWrap } from "./wordWrap.ts";
type line = { value: string, style: TextStyle, type: styleTypeAccessor, newLine?: boolean, combine?: boolean }
export const flexRow = (ctx: CanvasRenderingContext2D, sections: string[], maxWidth: number) => {
const totalWidth = sections.map(s => ctx.measureText(s).width).reduce((a, b) => a + b, 0);
const gap = (maxWidth - totalWidth) / (sections.length - 1);
ctx.save()
for (const section of sections) {
ctx.fillText(section, 0, 0);
ctx.translate(ctx.measureText(section).width + gap, 0);
}
ctx.restore();
}
export const inlineRow = (ctx: CanvasRenderingContext2D, sections: line[], maxWidth: number) => {
const lines: line[] = [];
for (const [i, section] of sections.entries()) {
if (!section.newLine) {
const last = lines[i - 1];
if (last) {
ctx.font = last.style[last.type];
const lastWidth = ctx.measureText(last.value).width;
ctx.font = section.style[section.type];
lines.push(...wordWrap(ctx, section.value, maxWidth, maxWidth - lastWidth).map((e, i): line => ({
...section,
value: e,
combine: i === 0
})));
continue;
}
}
ctx.font = section.style[section.type];
lines.push(...wordWrap(ctx, section.value, maxWidth).map((e): line => ({
...section,
value: e
})));
}
return lines;
}
export const drawRow = (ctx: CanvasRenderingContext2D, lines: line[]) => {
for (const [i, line] of lines.entries()) {
const last = lines[i - 1];
if (line.combine && last) {
ctx.save();
ctx.font = last.style[last.type];
ctx.translate(ctx.measureText(last.value).width, 0);
ctx.font = line.style[line.type];
ctx.fillText(line.value, 0, 0);
ctx.restore();
} else {
ctx.translate(0, line.style.lineHeight);
ctx.font = line.style[line.type];
ctx.fillText(line.value, 0, 0);
}
}
}