diverse änderungen

This commit is contained in:
marco committed 2026-11-05 15:16:54 +01:00
1 parent 3dc1ad623c
commit f51631100d
85 files changed
+1880 -56

No files matched your search

@@ -0,0 +1,65 @@
import { DrawEndschalter } from './drawEndschalter';
import { parseEndschalterRequest } from '../../_dto/endschalter.dto';
describe('DrawEndschalter', () => {
const generator = new DrawEndschalter();
it.each([
['unten', 20, 40, 'M 4 31', 'M 4,31'],
['oben', 20, 40, 'M 16 9', 'M 16,9'],
['rechts', 40, 20, 'M 31 16', 'M 31,16'],
['links', 40, 20, 'M 9 4', 'M 9,4'],
] as const)('richtet die Erfassungsbögen nach %s aus und passt den Zeichenbereich an', (direction, width, height, svgStart, xamlStart) => {
const result = generator.getObject({ scale: 2, raster: 4 }, { direction });
expect([result.width, result.height]).toEqual([width, height]);
for (const variant of result.varianten) {
expect(variant.svg).toContain(svgStart);
expect(variant.xaml).toContain(xamlStart);
}
const legacy = generator.getDrawObject({ direction });
expect([legacy.px_width, legacy.px_height]).toEqual([width, height]);
expect([legacy.length, legacy.height]).toEqual([width / 8, height / 8]);
});
it('behält unten als Standard und validiert die neue Option', () => {
expect(parseEndschalterRequest({ config: {} }).options.direction).toBe('unten');
expect(() => parseEndschalterRequest({ config: {}, options: { direction: 'diagonal' } })).toThrow();
expect(() => parseEndschalterRequest({ config: {}, options: { typo: 'oben' } })).toThrow();
});
it('liefert das schlanke Symbol mit drei Zuständen als SVG und XAML', () => {
const result = generator.getObject({ scale: 2, raster: 4 });
expect(result.name).toBe('endschalter');
expect(result.width).toBe(20);
expect(result.height).toBe(40);
expect(result.varianten.map(variant => variant.state)).toEqual(['inactive', 'active', 'error']);
for (const variant of result.varianten) {
expect(variant.svg).toContain('<svg xmlns=');
expect(variant.xaml).toContain('<Viewbox xmlns=');
expect(variant.svg.match(/<path /g)).toHaveLength(4);
expect(variant.xaml.match(/<Path /g)).toHaveLength(4);
expect(variant.svg).not.toMatch(/NaN|Infinity|undefined/);
expect(Buffer.from(variant.xamlBase64, 'base64').toString('utf8')).toBe(variant.xaml);
}
expect(result.varianten[1].svg).toContain('#00f000');
expect(result.varianten[2].xaml).toContain('#f00000');
});
it('skaliert Körper und Bögen und übernimmt die Zustandsfarben', () => {
const config = { scale: 4, raster: 4 };
const result = generator.getObject(config, { colorActive: '#123456' });
expect(result.width).toBe(40);
expect(result.height).toBe(80);
expect(result.varianten[1].svg).toContain('#123456');
expect(result.varianten[1].svg).toContain('stroke-width="2"');
expect(generator.getDrawObject({ state: 'active' }).px_height).toBe(40);
expect(generator.getSvg({ state: 'active', xaml: true })).toContain('<Viewbox');
});
it('verhindert ungültige Skalierungen und Farben', () => {
expect(() => generator.getObject({ scale: 0, raster: 4 })).toThrow();
expect(() => generator.getObject({ scale: 2, raster: 4 }, { colorActive: 'red' })).toThrow();
expect(() => generator.getObject({ scale: Number.MAX_VALUE / 4, raster: 1 })).toThrow();
});
});
+155
View File
@@ -0,0 +1,155 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import type { DrawDataDto, DrawDto, DrawShapeOptionenDto } from '../../_dto/draw.dto';
import { parseEndschalterRequest } from '../../_dto/endschalter.dto';
import { DrawGroup } from '../lib/drawGroup';
import { DrawHeader } from '../lib/drawHeader';
import { DrawPath } from '../lib/drawPath';
import type { PathCommand } from '../lib/types/path.types';
import type { GraphicGenerator } from './graphic-generator';
import type { EndschalterConfig, EndschalterOptions, EndschalterDirection } from './types';
@Injectable()
export class DrawEndschalter implements GraphicGenerator<EndschalterConfig, EndschalterOptions> {
private readonly defaultColors: EndschalterOptions = {
colorInactive: '#808080',
colorActive: '#00f000',
colorError: '#f00000',
};
/** Koordinaten direkt drehen, damit SVG und XAML dieselbe Geometrie erhalten. */
private orientPath(commands: PathCommand[], unit: number, direction: EndschalterDirection): PathCommand[] {
const width = 2.5 * unit;
const height = 5 * unit;
const point = (x: number, y: number) => {
switch (direction) {
case 'oben': return { x: width - x, y: height - y };
case 'rechts': return { x: y, y: width - x };
case 'links': return { x: height - y, y: x };
default: return { x, y };
}
};
return commands.map(command => {
if (command.type === 'Q') {
const control = point(command.x1, command.y1);
return { ...command, ...point(command.x, command.y), x1: control.x, y1: control.y };
}
if (command.type === 'M' || command.type === 'L') {
return { ...command, ...point(command.x, command.y) };
}
return command;
});
}
/** Abgerundeter Sensorkörper. Eine Einheit entspricht raster * scale. */
private createSensorBody(unit: number, color: string, direction: EndschalterDirection): DrawPath {
const left = 0.875 * unit;
const right = 1.625 * unit;
const top = unit;
const bottom = 3.125 * unit;
const radius = 0.125 * unit;
const outline: PathCommand[] = [
{ type: 'M', x: left + radius, y: top },
{ type: 'L', x: right - radius, y: top },
{ type: 'Q', x1: right, y1: top, x: right, y: top + radius },
{ type: 'L', x: right, y: bottom - radius },
{ type: 'Q', x1: right, y1: bottom, x: right - radius, y: bottom },
{ type: 'L', x: left + radius, y: bottom },
{ type: 'Q', x1: left, y1: bottom, x: left, y: bottom - radius },
{ type: 'L', x: left, y: top + radius },
{ type: 'Q', x1: left, y1: top, x: left + radius, y: top },
{ type: 'Z' },
];
const body = new DrawPath(this.orientPath(outline, unit, direction));
body.setAtrr({ fill: color, stroke: '#202020', strokeWidth: unit / 16 });
return body;
}
/** Drei nach unten gewölbte Erfassungsbögen wie in der Vorlage. */
private createDetectionArcs(unit: number, color: string, direction: EndschalterDirection): DrawPath[] {
const centerX = 1.25 * unit;
return [0, 1, 2].map(index => {
const halfWidth = (0.375 + index * 0.1875) * unit;
const top = (3.375 + index * 0.25) * unit;
const depth = (0.375 + index * 0.0625) * unit;
const arc = new DrawPath(this.orientPath([
{ type: 'M', x: centerX - halfWidth, y: top },
{ type: 'Q', x1: centerX, y1: top + depth, x: centerX + halfWidth, y: top },
], unit, direction));
arc.setAtrr({ fill: 'none', stroke: color, strokeWidth: unit / 8 });
return arc;
});
}
private create(unit: number, color: string, direction: EndschalterDirection): DrawGroup {
const group = new DrawGroup({});
group.add(this.createSensorBody(unit, color, direction));
for (const arc of this.createDetectionArcs(unit, color, direction)) {
group.add(arc);
}
return group;
}
getObject(config: EndschalterConfig, options?: Partial<EndschalterOptions>): DrawDataDto {
// Skalierung und Zustandsfarben verwenden die vorhandene Motor-Validierung.
const parsed = parseEndschalterRequest({ config, options });
const unit = parsed.config.scale * parsed.config.raster;
const direction = parsed.options.direction;
const horizontal = direction === 'links' || direction === 'rechts';
const width = (horizontal ? 5 : 2.5) * unit;
const height = (horizontal ? 2.5 : 5) * unit;
if (!Number.isFinite(width) || !Number.isFinite(height)) {
throw new BadRequestException('Die Endschalter-Abmessungen sind zu groß');
}
const colors = { ...this.defaultColors, ...parsed.options };
const states = [
{ state: 'inactive', color: colors.colorInactive },
{ state: 'active', color: colors.colorActive },
{ state: 'error', color: colors.colorError },
];
const varianten = states.map(({ state, color }) => {
const header = new DrawHeader({ lenght: width, height });
header.add(this.create(unit, color, direction));
const svg = header.getChildString(false, 0);
const xaml = header.getChildString(true, 0);
return { state, svg, xaml, xamlBase64: Buffer.from(xaml, 'utf8').toString('base64') };
});
return { name: 'endschalter', width, height, varianten };
}
private selectedVariant(options: DrawShapeOptionenDto = {}) {
const config = { scale: Number(options.scale ?? 2), raster: Number(options.raster ?? 4) };
const colors = {
direction: options.direction ?? 'unten',
colorInactive: options.colorInactive ?? this.defaultColors.colorInactive,
colorActive: options.colorActive ?? this.defaultColors.colorActive,
colorError: options.colorError ?? this.defaultColors.colorError,
};
const result = this.getObject(config, colors);
const variant = result.varianten.find(item => item.state === options.state) ?? result.varianten[0];
return { result, variant, config };
}
getDrawObject(options?: DrawShapeOptionenDto): DrawDto {
const { result, variant, config } = this.selectedVariant(options);
return {
name: result.name,
height: result.height / (config.raster * config.scale),
length: result.width / (config.raster * config.scale),
px_height: result.height,
px_width: result.width,
raster: config.raster,
scale: config.scale,
offset_x: 0,
offset_y: 0,
svg: variant.svg,
};
}
getSvg(options?: DrawShapeOptionenDto): string {
const { variant } = this.selectedVariant(options);
return options?.xaml ? variant.xaml : variant.svg;
}
}
+72
View File
@@ -0,0 +1,72 @@
import { DrawText } from './drawText';
import { parseTextRequest } from '../../_dto/text.dto';
describe('DrawText Grafikgenerator', () => {
const generator = new DrawText();
const config = { text: 'Anlage bereit', width: 160, height: 40, fontSize: 16 };
it('liefert inactive, active und error als vollständiges SVG und XAML', () => {
const result = generator.getObject(config);
expect(result.varianten.map(variant => variant.state)).toEqual(['inactive', 'active', 'error']);
expect([result.width, result.height]).toEqual([160, 40]);
for (const variant of result.varianten) {
expect(variant.svg).toContain('<svg xmlns=');
expect(variant.xaml).toContain('<Viewbox xmlns=');
expect(variant.svg).toContain('Anlage bereit');
expect(variant.xaml).toContain('Text="Anlage bereit"');
expect(Buffer.from(variant.xamlBase64, 'base64').toString('utf8')).toBe(variant.xaml);
expect(variant.svg).not.toContain('<path');
}
expect(result.varianten[0].svg).toContain('fill="#808080"');
expect(result.varianten[1].xaml).toContain('Foreground="#00f000"');
expect(result.varianten[2].svg).toContain('fill="#f00000"');
});
it('zeichnet den transparenten Rahmen hinter dem Text und innerhalb der Abmessungen', () => {
const result = generator.getObject(config, { frame: true, stroke: '#123456', strokeWidth: 2 });
for (const variant of result.varianten) {
expect(variant.svg).toContain('M 1 1');
expect(variant.svg).toContain('stroke="#123456"');
expect(variant.svg).toContain('fill="none"');
expect(variant.svg.indexOf('<path')).toBeLessThan(variant.svg.indexOf('<text'));
expect(variant.xaml.indexOf('<Path')).toBeLessThan(variant.xaml.indexOf('<TextBlock'));
expect(variant.xaml).not.toContain('Fill="none"');
}
});
it('unterstützt Füllfarbe ohne Rahmen und eigene Zustandsfarben', () => {
const result = generator.getObject(config, { frame: false, fill: '#ffffff', colorActive: '#123456' });
expect(result.varianten[1].svg).toContain('fill="#ffffff"');
expect(result.varianten[1].svg).toContain('stroke-width="0"');
expect(result.varianten[1].xaml).toContain('Foreground="#123456"');
});
it('maskiert Textzeichen in beiden Formaten und lässt keine XML-Elemente einschleusen', () => {
const result = generator.getObject({ ...config, text: 'A & B <Text> "Zitat"' });
for (const variant of result.varianten) {
expect(variant.svg).toContain('A &amp; B &lt;Text&gt; &quot;Zitat&quot;');
expect(variant.xaml).toContain('A &amp; B &lt;Text&gt; &quot;Zitat&quot;');
expect(variant.xaml).not.toContain('<Text>');
}
});
it('ordnet mehrzeiligen Text an und hält lange Texte durch kleinere Schrift im Rahmen', () => {
const result = generator.getObject({ ...config, text: 'Erste Zeile\r\nZweite Zeile mit langem Text', fontSize: 60 });
const svg = result.varianten[0].svg;
expect(svg.match(/<text /g)).toHaveLength(2);
const sizes = [...svg.matchAll(/font-size="([\d.]+)"/g)].map(match => Number(match[1]));
expect(sizes.every(size => size > 0 && size < 60)).toBe(true);
expect(svg).not.toMatch(/NaN|Infinity|undefined/);
});
it('validiert Parameter und erhält die bisherigen Zeichen-API-Konventionen', () => {
expect(parseTextRequest({ config: {} }).config.text).toBe('Text');
expect(() => parseTextRequest({ config: { fontSize: 0 } })).toThrow();
expect(() => parseTextRequest({ config: { text: '\u0000' } })).toThrow();
expect(() => parseTextRequest({ config: {}, options: { frame: 'true' } })).toThrow();
expect(() => parseTextRequest({ config: {}, options: { colorActive: 'green' } })).toThrow();
expect(() => parseTextRequest({ config: {}, options: { frame: true, strokeWidth: 100 } })).toThrow();
expect(generator.getDrawObject({ text: 'Test' }).name).toBe('text');
expect(generator.getSvg({ text: 'Test', xaml: true })).toContain('Text="Test"');
});
});
+107
View File
@@ -0,0 +1,107 @@
import { Injectable } from '@nestjs/common';
import type { DrawDataDto, DrawDto, DrawShapeOptionenDto } from '../../_dto/draw.dto';
import { parseTextRequest } from '../../_dto/text.dto';
import { DrawGroup } from '../lib/drawGroup';
import { DrawHeader } from '../lib/drawHeader';
import { DrawPath } from '../lib/drawPath';
import { DrawText as TextElement } from '../lib/drawText';
import type { GraphicGenerator } from './graphic-generator';
import type { TextConfig, TextOptions } from './types';
@Injectable()
export class DrawText implements GraphicGenerator<TextConfig, TextOptions> {
private createBackground(config: TextConfig, options: TextOptions): DrawPath {
const inset = options.strokeWidth / 2;
const background = new DrawPath([
{ type: 'M', x: inset, y: inset },
{ type: 'L', x: config.width - inset, y: inset },
{ type: 'L', x: config.width - inset, y: config.height - inset },
{ type: 'L', x: inset, y: config.height - inset },
{ type: 'Z' },
]);
background.setAtrr({
stroke: options.stroke === 'none' ? '#000000' : options.stroke,
strokeWidth: options.strokeWidth,
fill: options.fill === 'transparent' ? 'none' : options.fill,
});
return background;
}
private createText(config: TextConfig, options: TextOptions, color: string): DrawGroup {
const group = new DrawGroup({});
const lines = config.text.replace(/\r\n?/g, '\n').split('\n');
const padding = Math.min(4 + options.strokeWidth, config.width / 4, config.height / 4);
const availableWidth = config.width - padding * 2;
const availableHeight = config.height - padding * 2;
const longestLine = Math.max(1, ...lines.map(line => Array.from(line).length));
// Schrift bei langen oder mehrzeiligen Texten innerhalb der Zeichenfläche halten.
const fontSize = Math.min(config.fontSize, availableWidth / (longestLine * 0.75), availableHeight / (lines.length * 1.25));
const lineHeight = fontSize * 1.25;
const top = (config.height - lines.length * lineHeight) / 2;
lines.forEach((text, index) => {
group.add(new TextElement({
x: padding,
y: top + index * lineHeight,
text,
centeredBox: { width: availableWidth, height: lineHeight, fontSize, color },
}));
});
return group;
}
private create(config: TextConfig, options: TextOptions, color: string): DrawHeader {
const group = new DrawGroup({});
// DrawGroup gibt Elemente in umgekehrter Reihenfolge aus: Hintergrund zuerst zeichnen.
group.add(this.createText(config, options, color));
if (options.frame || options.fill !== 'transparent') group.add(this.createBackground(config, options));
const header = new DrawHeader({ lenght: config.width, height: config.height });
header.add(group);
return header;
}
getObject(config: TextConfig, options?: Partial<TextOptions>): DrawDataDto {
const parsed = parseTextRequest({ config, options });
const states = [
{ state: 'inactive', color: parsed.options.colorInactive },
{ state: 'active', color: parsed.options.colorActive },
{ state: 'error', color: parsed.options.colorError },
];
const varianten = states.map(({ state, color }) => {
const header = this.create(parsed.config, parsed.options, color);
const svg = header.getChildString(false, 0);
const xaml = header.getChildString(true, 0);
return { state, svg, xaml, xamlBase64: Buffer.from(xaml, 'utf8').toString('base64') };
});
return { name: 'text', width: parsed.config.width, height: parsed.config.height, varianten };
}
private selectedVariant(options: DrawShapeOptionenDto = {}) {
const parsed = parseTextRequest({
config: { text: options.text ?? 'Text', width: Number(options.width ?? 120), height: Number(options.height ?? 40), fontSize: Number(options.fontSize ?? 16) },
options: {
frame: options.frame === undefined ? false : String(options.frame) === 'true',
...(options.stroke !== undefined ? { stroke: options.stroke } : {}),
...(options.strokeWidth !== undefined ? { strokeWidth: Number(options.strokeWidth) } : {}),
...(options.fill !== undefined ? { fill: options.fill } : {}),
...(options.colorInactive !== undefined ? { colorInactive: options.colorInactive } : {}),
...(options.colorActive !== undefined ? { colorActive: options.colorActive } : {}),
...(options.colorError !== undefined ? { colorError: options.colorError } : {}),
},
});
const result = this.getObject(parsed.config, parsed.options);
const variant = result.varianten.find(item => item.state === options.state) ?? result.varianten[0];
return { result, variant };
}
getDrawObject(options?: DrawShapeOptionenDto): DrawDto {
const { result, variant } = this.selectedVariant(options);
return { name: result.name, height: result.height, length: result.width, px_height: result.height, px_width: result.width,
raster: 1, scale: 1, offset_x: 0, offset_y: 0, svg: variant.svg };
}
getSvg(options?: DrawShapeOptionenDto): string {
const { variant } = this.selectedVariant(options);
return options?.xaml ? variant.xaml : variant.svg;
}
}
+13
View File
@@ -17,7 +17,20 @@ export interface MotorConfig {
raster: number;
}
export interface EndschalterConfig extends MotorConfig {}
export type EndschalterDirection = 'oben' | 'unten' | 'rechts' | 'links';
export interface EndschalterOptions extends MotorOptions {
direction?: EndschalterDirection;
}
export interface PunktConfig { scale: number; raster: number }
export interface TextConfig { text: string; width: number; height: number; fontSize: number }
export interface TextOptions extends MotorOptions {
frame: boolean;
stroke: string;
strokeWidth: number;
fill: string;
}
export interface PunktOptions { colorInactive: string; colorActive: string }
export interface RechteckConfig { width: number; height: number }
export interface RechteckOptions { stroke: string; strokeWidth: number; fill: string }
+9 -5
View File
@@ -5,7 +5,7 @@ interface PropText {
x: number,
y: number,
text:string
centeredBox?: { width: number; height: number; fontSize: number };
centeredBox?: { width: number; height: number; fontSize: number; color?: string };
}
interface SvgOptions {
@@ -18,6 +18,10 @@ interface SvgOptions {
export class DrawText extends DrawElement {
private escapeText(value: string): string {
return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/"/g, '&quot;').replace(/'/g, '&apos;');
}
@@ -40,13 +44,13 @@ export class DrawText extends DrawElement {
drawSvg() {
const box = this.posAndText.centeredBox;
if (box) {
return `<text x="${this.posAndText.x + box.width / 2}" y="${this.posAndText.y + box.height / 2}" text-anchor="middle" dominant-baseline="central" font-family="Arial" font-size="${box.fontSize}" font-weight="bold" fill="#000000">${this.posAndText.text}</text>`;
return `<text x="${this.posAndText.x + box.width / 2}" y="${this.posAndText.y + box.height / 2}" text-anchor="middle" dominant-baseline="central" font-family="Arial" font-size="${box.fontSize}" font-weight="bold" fill="${box.color ?? '#000000'}">${this.escapeText(this.posAndText.text)}</text>`;
}
const paraStr = this.convertAttributesToString(this.attributes);
const posSvg = this.getSvgPositions(this.posAndText)
const posStr = this.convertAttributesToString(posSvg);
const shape = this.drawElementSvg(posStr,this.posAndText.text, paraStr);
const shape = this.drawElementSvg(posStr,this.escapeText(this.posAndText.text), paraStr);
return shape;
}
@@ -54,14 +58,14 @@ export class DrawText extends DrawElement {
drawXaml(): string {
const box = this.posAndText.centeredBox;
if (box) {
return `<Grid Canvas.Left="${this.posAndText.x}" Canvas.Top="${this.posAndText.y}" Width="${box.width}" Height="${box.height}"><TextBlock Text="${this.posAndText.text}" FontFamily="Arial" FontSize="${box.fontSize}" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>`;
return `<Grid Canvas.Left="${this.posAndText.x}" Canvas.Top="${this.posAndText.y}" Width="${box.width}" Height="${box.height}"><TextBlock Text="${this.escapeText(this.posAndText.text)}" FontFamily="Arial" FontSize="${box.fontSize}" FontWeight="Bold" Foreground="${box.color ?? '#000000'}" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>`;
}
const paraStr = this.convertAttributesToString(this.attributes, true);
//const posXaml = this.getXamlPositions(this.posAndText)
//const posStr = this.convertAttributesToString(posXaml, true);
const shape = this.drawElementXaml(this.posAndText.x,this.posAndText.y,this.posAndText.text, paraStr);
const shape = this.drawElementXaml(this.posAndText.x,this.posAndText.y,this.escapeText(this.posAndText.text), paraStr);
return shape;
}