anki/ts/image-occlusion/shapes/text.ts
Aristotelis c828a2eb6f
Add APIs for IO card rendering (#2739)
* Refactor: Add index to shapes package

* Add shape draw callback API to setupImageCloze

* Expose IO drawing API, switch away from image cloze naming

We currently use "image occlusion" in most places, but some references to "image cloze" still remain. For consistency's sake and to make it easier to quickly find IO-related code, this commit replaces all remaining references to "image cloze", only maintaining those required for backwards compatibility with existing note types.

* Add cloze ordinal to shapes

* Do not mutate original shapes during (de)normalization

Mutating shapes would be a recipe for trouble when combined with IO API use by external consumers.

(makeNormal(makeAbsolute(makeNormal())) is not idempotent,
and keeping track of the original state would introduce
additional complexity with no discernible performance benefit
or otherwise.)

* Tweak IO API, allowing modifications to ShapeProperties

* Tweak drawShape parameters

* Switch method order

For consistency with previous implementation

* Run Rust formatters

* Simplify position (de)normalization

---------

Co-authored-by: Glutanimate <glutanimate@users.noreply.github.com>
2023-10-20 09:36:46 +10:00

72 lines
2.0 KiB
TypeScript

// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { fabric } from "fabric";
import { TEXT_BACKGROUND_COLOR, TEXT_FONT_FAMILY, TEXT_PADDING } from "../tools/lib";
import type { ConstructorParams, Size } from "../types";
import type { ShapeDataForCloze } from "./base";
import { Shape } from "./base";
import { floatToDisplay } from "./floats";
import { xFromNormalized, xToNormalized, yFromNormalized, yToNormalized } from "./position";
export class Text extends Shape {
text: string;
scaleX: number;
scaleY: number;
constructor({
text = "",
scaleX = 1,
scaleY = 1,
...rest
}: ConstructorParams<Text> = {}) {
super(rest);
this.text = text;
this.scaleX = scaleX;
this.scaleY = scaleY;
}
toDataForCloze(): TextDataForCloze {
return {
...super.toDataForCloze(),
text: this.text,
// scaleX and scaleY are guaranteed to be equal since we lock the aspect ratio
scale: floatToDisplay(this.scaleX),
};
}
toFabric(size: Size): fabric.IText {
const absolute = this.toAbsolute(size);
return new fabric.IText(absolute.text, {
...absolute,
fontFamily: TEXT_FONT_FAMILY,
backgroundColor: TEXT_BACKGROUND_COLOR,
padding: TEXT_PADDING,
});
}
toNormal(size: Size): Text {
return new Text({
...this,
...super.normalPosition(size),
scaleX: xToNormalized(size, this.scaleX),
scaleY: yToNormalized(size, this.scaleY),
});
}
toAbsolute(size: Size): Text {
return new Text({
...this,
...super.absolutePosition(size),
scaleX: xFromNormalized(size, this.scaleX),
scaleY: yFromNormalized(size, this.scaleY),
});
}
}
interface TextDataForCloze extends ShapeDataForCloze {
text: string;
scale: string;
}