bidi-shaper
Version:
Logical→visual Unicode BiDi (UAX #9) reordering + Arabic contextual shaping for renderers outside the browser (PDF, canvas, WebGL, SVG, terminals, games). Zero dependencies.
54 lines (50 loc) • 2.5 kB
TypeScript
import { R as RenderOptions, D as Direction } from '../render-BhplWt64.js';
/**
* Canvas 2D adapter (`bidi-shaper/canvas`).
*
* Browsers shape Arabic in fillText for you — this adapter is for canvas
* implementations that don't: minimal/embedded 2D contexts, custom
* rasterizers, bitmap-font engines, and game frameworks that draw glyph
* runs naively left-to-right.
*
* Types are structural, so any object with fillText/strokeText/measureText
* works (node-canvas, skia-canvas, OffscreenCanvas, mocks).
*/
/** The slice of CanvasRenderingContext2D this adapter touches. */
interface MinimalCanvasContext {
fillText(text: string, x: number, y: number, maxWidth?: number): void;
strokeText(text: string, x: number, y: number, maxWidth?: number): void;
measureText(text: string): {
width: number;
};
textAlign: 'left' | 'right' | 'center' | 'start' | 'end';
font?: string;
}
interface CanvasTextOptions extends RenderOptions {
/**
* Logical alignment. 'start'/'end' resolve against each line's detected
* direction ('start' = right edge for an RTL line). Default: the context's
* current textAlign.
*/
align?: 'left' | 'right' | 'center' | 'start' | 'end';
/** Distance between baselines for multi-line text. Default: 1.25 × the px size parsed from ctx.font. */
lineHeight?: number;
}
/** One processed line, ready to draw. */
interface PreparedCanvasLine {
/** Visual-order, shaped text. */
text: string;
/** Resolved direction of the line. */
direction: Direction;
}
/** Process text into visual-order lines plus each line's resolved direction. */
declare function prepareCanvasText(text: string, options?: RenderOptions): PreparedCanvasLine[];
/** Drop-in fillText: shapes, reorders, handles \n and start/end alignment. */
declare function fillTextBidi(ctx: MinimalCanvasContext, text: string, x: number, y: number, options?: CanvasTextOptions): void;
/** Drop-in strokeText counterpart of {@link fillTextBidi}. */
declare function strokeTextBidi(ctx: MinimalCanvasContext, text: string, x: number, y: number, options?: CanvasTextOptions): void;
/** Measure the processed (shaped, visual-order) text — single line. */
declare function measureTextBidi(ctx: MinimalCanvasContext, text: string, options?: RenderOptions): {
width: number;
};
export { type CanvasTextOptions, type MinimalCanvasContext, type PreparedCanvasLine, fillTextBidi, measureTextBidi, prepareCanvasText, strokeTextBidi };