js-draw
Version:
Draw pictures using a pen, touchscreen, or mouse! JS-draw is a drawing library for JavaScript and TypeScript.
64 lines (63 loc) • 2.47 kB
TypeScript
type ElementTagNames = keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap;
/**
* Maps from known elment tag names to options that can be set with .setAttribute.
* New elements/properties should be added as necessary.
*/
interface ElementToPropertiesMap {
path: {
d: string;
fill: string;
stroke: string;
'stroke-width': string;
transform: string;
};
rect: {
stroke: string;
fill: string;
x: number;
y: number;
width: number;
height: number;
transform: string;
};
pattern: {
viewBox: string;
width: string;
height: string;
patternUnits: 'userSpaceOnUse';
};
stop: {
offset: string;
'stop-color': string;
};
svg: {
viewBox: `${number} ${number} ${number} ${number}`;
};
}
type EmptyObject = Record<never, never>;
type ElementProperties<Tag extends ElementTagNames> = Tag extends keyof ElementToPropertiesMap ? Partial<ElementToPropertiesMap[Tag]> : EmptyObject;
/** Contains options for creating an element with tag = `Tag`. */
type ElementConfig<Tag extends ElementTagNames> = ElementProperties<Tag> & {
id?: string;
children?: (HTMLElement | SVGElement)[];
};
/**
* Maps from element tag names (e.g. `Tag='button'`) to the corresponding element type
* (e.g. `HTMLButtonElement`).
*/
type ElementTagToType<Tag extends ElementTagNames> = Tag extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[Tag] : Tag extends keyof SVGElementTagNameMap ? SVGElementTagNameMap[Tag] : never;
export declare enum ElementNamespace {
Html = "html",
Svg = "svg"
}
/**
* Shorthand for creating an element with `document.createElement`, then assigning properties.
*
* Non-HTML elements (e.g. `svg` elements) should use the `elementType` parameter to select
* the element namespace.
*/
declare const createElement: <Tag extends ElementTagNames>(tag: Tag, props: ElementConfig<Tag>, elementType?: ElementNamespace) => ElementTagToType<Tag>;
export declare const createSvgElement: <Tag extends keyof SVGElementTagNameMap>(tag: Tag, props: ElementConfig<Tag>) => ElementTagToType<Tag>;
export declare const createSvgElements: <Tag extends keyof SVGElementTagNameMap>(tag: Tag, elements: ElementConfig<Tag>[]) => ElementTagToType<Tag>[];
export declare const createSvgPaths: (...paths: ElementConfig<"path">[]) => SVGPathElement[];
export default createElement;