All files / src SlateControls.ts

16.92% Statements 77/455
100% Branches 0/0
0% Functions 0/17
16.92% Lines 77/455

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 4561x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x         1x 1x                                         1x 1x                                                                                                         1x 1x                                             1x 1x     1x 1x             1x 1x                                                                     1x 1x                                                       1x 1x                   1x 1x                           1x 1x                                                                       1x 1x 1x 1x 1x                                                           1x                                                                                   1x                                                                                 1x                                                                    
/*----------------------------------------------------------------------+
|    Title:  SlateControls.ts                                           |
|    UI overlay for geometry diagrams: reset, maximize, new window.     |
|    Buttons are canvas-drawn icons overlaid on each Slate canvas.      |
|    Keyboard shortcuts match the original Java applet:                 |
|      r / space  → reset                                               |
|      u / return → new window                                          |
|      m          → maximize/minimize                                   |
+----------------------------------------------------------------------*/
 
import {Slate} from "./Slate";
 
interface IInitConfig {
    background: string;
    title: string;
    align?: number;
    canvasid?: string;
    pivot?: string;
    elements: any[];
}
 
const BTN_SIZE = 20;
const BTN_GAP = 4;
const BTN_MARGIN = 8;
 
export function createControls(slate: Slate, canvas: HTMLCanvasElement, config: IInitConfig): void {
    // Skip in headless/test environments
    if (!canvas.parentElement) return;

    let controls = new SlateControls(slate, canvas, config);
    controls.init();
}
 
class SlateControls {
    private _slate: Slate;
    private _canvas: HTMLCanvasElement;
    private _config: IInitConfig;
    private _wrapper: HTMLDivElement;
    private _maximized: boolean = false;
    private _savedStyles: {
        wrapperPosition: string;
        wrapperTop: string;
        wrapperLeft: string;
        wrapperWidth: string;
        wrapperHeight: string;
        wrapperZIndex: string;
        wrapperBackground: string;
        canvasStyleWidth: string;
        canvasStyleHeight: string;
        canvasAttrWidth: number;
        canvasAttrHeight: number;
    } = null;
 
    constructor(slate: Slate, canvas: HTMLCanvasElement, config: IInitConfig) {
        this._slate = slate;
        this._canvas = canvas;
        this._config = config;
    }
 
    init(): void {
        this._wrapper = this.createWrapper();
        this.createButtons();
        this.addKeyboardShortcuts();
    }
 
    private createWrapper(): HTMLDivElement {
        let wrapper = document.createElement("div");
        wrapper.style.position = "relative";
        wrapper.style.display = "inline-block";

        // Insert wrapper before canvas, then move canvas into it
        this._canvas.parentElement.insertBefore(wrapper, this._canvas);
        wrapper.appendChild(this._canvas);

        // Make canvas focusable for keyboard shortcuts
        this._canvas.setAttribute("tabindex", "0");
        this._canvas.style.outline = "none"; // default no outline
        this._canvas.addEventListener("focus", () => {
            this._canvas.style.outline = "2px solid rgba(66,133,244,0.5)";
        });
        this._canvas.addEventListener("blur", () => {
            this._canvas.style.outline = "none";
        });

        return wrapper;
    }
 
    private createButtons(): void {
        let buttons = [
            { draw: drawResetIcon, action: () => this.onReset(), title: "Reset (r)" },
            { draw: drawMaximizeIcon, action: () => this.onMaximize(), title: "Maximize (m)" },
            { draw: drawNewWindowIcon, action: () => this.onNewWindow(), title: "New Window (u)" },
        ];

        for (let i = 0; i < buttons.length; i++) {
            let btn = document.createElement("button");
            btn.style.position = "absolute";
            btn.style.top = BTN_MARGIN + "px";
            btn.style.right = (BTN_MARGIN + i * (BTN_SIZE + BTN_GAP)) + "px";
            btn.style.width = BTN_SIZE + "px";
            btn.style.height = BTN_SIZE + "px";
            btn.style.padding = "0";
            btn.style.border = "none";
            btn.style.cursor = "pointer";
            btn.style.background = "rgba(0,0,0,0.12)";
            btn.style.borderRadius = "3px";
            btn.title = buttons[i].title;

            btn.addEventListener("mouseenter", () => {
                btn.style.background = "rgba(0,0,0,0.3)";
            });
            btn.addEventListener("mouseleave", () => {
                btn.style.background = "rgba(0,0,0,0.12)";
            });

            // Draw icon on a small canvas inside the button
            let iconCanvas = document.createElement("canvas");
            iconCanvas.width = BTN_SIZE;
            iconCanvas.height = BTN_SIZE;
            iconCanvas.style.display = "block";
            let ctx = iconCanvas.getContext("2d");
            buttons[i].draw(ctx, BTN_SIZE);
            btn.appendChild(iconCanvas);

            btn.addEventListener("click", (e) => {
                e.stopPropagation();
                buttons[i].action();
                // Return focus to the main canvas after button click
                this._canvas.focus();
            });

            // Store reference for maximize icon swap
            if (i === 1) {
                (this as any)._maxBtn = btn;
                (this as any)._maxIconCanvas = iconCanvas;
            }

            this._wrapper.appendChild(btn);
        }
    }
 
    private addKeyboardShortcuts(): void {
        this._canvas.addEventListener("keydown", (e: KeyboardEvent) => {
            switch (e.key) {
                case "r":
                case "R":
                case " ":
                    e.preventDefault();
                    this.onReset();
                    break;
                case "u":
                case "U":
                case "Enter":
                    e.preventDefault();
                    this.onNewWindow();
                    break;
                case "m":
                case "M":
                    e.preventDefault();
                    this.onMaximize();
                    break;
            }
        });
    }
 
    private onReset(): void {
        this._slate.reset();
    }
 
    private onMaximize(): void {
        if (this._maximized) {
            this.minimize();
        } else {
            this.maximize();
        }
    }
 
    private maximize(): void {
        // Save current styles AND canvas width/height attributes. The attrs
        // are the canvas bitmap resolution; resizeAndRedraw() overwrites them
        // to match the maximized CSS size, so minimize() must restore them.
        this._savedStyles = {
            wrapperPosition: this._wrapper.style.position,
            wrapperTop: this._wrapper.style.top,
            wrapperLeft: this._wrapper.style.left,
            wrapperWidth: this._wrapper.style.width,
            wrapperHeight: this._wrapper.style.height,
            wrapperZIndex: this._wrapper.style.zIndex,
            wrapperBackground: this._wrapper.style.background,
            canvasStyleWidth: this._canvas.style.width,
            canvasStyleHeight: this._canvas.style.height,
            canvasAttrWidth: this._canvas.width,
            canvasAttrHeight: this._canvas.height,
        };

        // Maximize wrapper to fill viewport
        this._wrapper.style.position = "fixed";
        this._wrapper.style.top = "0";
        this._wrapper.style.left = "0";
        this._wrapper.style.width = "100vw";
        this._wrapper.style.height = "100vh";
        this._wrapper.style.zIndex = "9999";
        this._wrapper.style.background = "white";

        // Expand canvas to fill wrapper
        this._canvas.style.width = "100%";
        this._canvas.style.height = "100%";

        this.resizeAndRedraw();
        this._maximized = true;
        this.updateMaximizeIcon();
    }
 
    private minimize(): void {
        if (!this._savedStyles) return;

        // Restore saved styles
        this._wrapper.style.position = this._savedStyles.wrapperPosition;
        this._wrapper.style.top = this._savedStyles.wrapperTop;
        this._wrapper.style.left = this._savedStyles.wrapperLeft;
        this._wrapper.style.width = this._savedStyles.wrapperWidth;
        this._wrapper.style.height = this._savedStyles.wrapperHeight;
        this._wrapper.style.zIndex = this._savedStyles.wrapperZIndex;
        this._wrapper.style.background = this._savedStyles.wrapperBackground;

        this._canvas.style.width = this._savedStyles.canvasStyleWidth;
        this._canvas.style.height = this._savedStyles.canvasStyleHeight;

        // Restore the canvas bitmap resolution to match its pre-maximize
        // intrinsic size. Without this, the canvas keeps the enlarged
        // width/height attributes from the maximize pass and (when style
        // width/height are empty) falls back to those attrs for its CSS
        // size — leaving the diagram rendered full-width.
        this._canvas.width = this._savedStyles.canvasAttrWidth;
        this._canvas.height = this._savedStyles.canvasAttrHeight;

        this.resizeAndRedraw();
        this._maximized = false;
        this._savedStyles = null;
        this.updateMaximizeIcon();
    }
 
    private resizeAndRedraw(): void {
        // Sync canvas internal resolution to CSS size
        let w = this._canvas.clientWidth;
        let h = this._canvas.clientHeight;
        if (this._canvas.width !== w || this._canvas.height !== h) {
            this._canvas.width = w;
            this._canvas.height = h;
        }
        this._slate.update();
    }
 
    private updateMaximizeIcon(): void {
        let iconCanvas = (this as any)._maxIconCanvas as HTMLCanvasElement;
        let btn = (this as any)._maxBtn as HTMLButtonElement;
        if (!iconCanvas) return;
        let ctx = iconCanvas.getContext("2d");
        ctx.clearRect(0, 0, BTN_SIZE, BTN_SIZE);
        if (this._maximized) {
            drawMinimizeIcon(ctx, BTN_SIZE);
            btn.title = "Minimize (m)";
        } else {
            drawMaximizeIcon(ctx, BTN_SIZE);
            btn.title = "Maximize (m)";
        }
    }
 
    private onNewWindow(): void {
        // Find the bundle.js script path from the current page
        let scripts = document.querySelectorAll("script[src]");
        let bundleSrc = "bundle.js";
        for (let i = 0; i < scripts.length; i++) {
            let src = (scripts[i] as HTMLScriptElement).src;
            if (src.indexOf("bundle.js") >= 0) {
                bundleSrc = src;
                break;
            }
        }

        // Override the config's canvasid so geomlib.init() targets the
        // new window's canvas (id="canvasId"), not the source page's canvas
        // which doesn't exist in the new document. Without the override,
        // init() would look up this._config.canvasid (e.g. "canvas_0") in
        // the new document, get null, and throw in resizeCanvasToDisplaySize.
        let newWinConfig = Object.assign({}, this._config, { canvasid: "canvasId" });
        let configJSON = JSON.stringify(newWinConfig);
        let title = this._config.title || "Geometry";

        // Open maximized: use full screen dimensions, canvas fills viewport
        let html = `<!DOCTYPE html>
<html><head><title>${title}</title></head>
<body style="margin:0;padding:0;overflow:hidden;">
<canvas id="canvasId" style="width:100vw;height:100vh;"></canvas>
<script src="${bundleSrc}"><\/script>
<script>geomlib.init(${configJSON});<\/script>
</body></html>`;

        let newWin = window.open("", "_blank");
        if (newWin) {
            newWin.document.write(html);
            newWin.document.close();
        }
    }
}
 
// --- Icon drawing functions ---
// All draw on a size×size canvas with 3px padding
 
function drawResetIcon(ctx: CanvasRenderingContext2D, size: number): void {
    let cx = size / 2;
    let cy = size / 2;
    let r = size * 0.32;
    let pad = 2;

    ctx.strokeStyle = "rgba(0,0,0,0.7)";
    ctx.fillStyle = "rgba(0,0,0,0.7)";
    ctx.lineWidth = 1.5;

    // Circular arc (270 degrees)
    ctx.beginPath();
    ctx.arc(cx, cy, r, -Math.PI * 0.5, Math.PI * 0.75);
    ctx.stroke();

    // Arrowhead at the end of the arc
    let endAngle = Math.PI * 0.75;
    let ax = cx + r * Math.cos(endAngle);
    let ay = cy + r * Math.sin(endAngle);
    let headLen = 4;
    let a1 = endAngle + Math.PI * 0.3;
    let a2 = endAngle + Math.PI * 0.9;
    ctx.beginPath();
    ctx.moveTo(ax, ay);
    ctx.lineTo(ax + headLen * Math.cos(a1), ay + headLen * Math.sin(a1));
    ctx.lineTo(ax + headLen * Math.cos(a2), ay + headLen * Math.sin(a2));
    ctx.closePath();
    ctx.fill();
}
 
function drawMaximizeIcon(ctx: CanvasRenderingContext2D, size: number): void {
    let pad = 4;
    let s = size - pad * 2;

    ctx.strokeStyle = "rgba(0,0,0,0.7)";
    ctx.fillStyle = "rgba(0,0,0,0.7)";
    ctx.lineWidth = 1.5;

    // Top-right outward arrow
    let ax = pad + s * 0.55;
    let ay = pad + s * 0.45;
    let bx = pad + s;
    let by = pad;
    ctx.beginPath();
    ctx.moveTo(ax, ay);
    ctx.lineTo(bx, by);
    ctx.stroke();
    // Arrowhead
    ctx.beginPath();
    ctx.moveTo(bx, by);
    ctx.lineTo(bx - 5, by);
    ctx.lineTo(bx, by + 5);
    ctx.closePath();
    ctx.fill();

    // Bottom-left outward arrow
    ax = pad + s * 0.45;
    ay = pad + s * 0.55;
    bx = pad;
    by = pad + s;
    ctx.beginPath();
    ctx.moveTo(ax, ay);
    ctx.lineTo(bx, by);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(bx, by);
    ctx.lineTo(bx + 5, by);
    ctx.lineTo(bx, by - 5);
    ctx.closePath();
    ctx.fill();
}
 
function drawMinimizeIcon(ctx: CanvasRenderingContext2D, size: number): void {
    let pad = 4;
    let s = size - pad * 2;

    ctx.strokeStyle = "rgba(0,0,0,0.7)";
    ctx.fillStyle = "rgba(0,0,0,0.7)";
    ctx.lineWidth = 1.5;

    // Top-right inward arrow
    let ax = pad + s;
    let ay = pad;
    let bx = pad + s * 0.55;
    let by = pad + s * 0.45;
    ctx.beginPath();
    ctx.moveTo(ax, ay);
    ctx.lineTo(bx, by);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(bx, by);
    ctx.lineTo(bx + 5, by);
    ctx.lineTo(bx, by - 5);
    ctx.closePath();
    ctx.fill();

    // Bottom-left inward arrow
    ax = pad;
    ay = pad + s;
    bx = pad + s * 0.45;
    by = pad + s * 0.55;
    ctx.beginPath();
    ctx.moveTo(ax, ay);
    ctx.lineTo(bx, by);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(bx, by);
    ctx.lineTo(bx - 5, by);
    ctx.lineTo(bx, by + 5);
    ctx.closePath();
    ctx.fill();
}
 
function drawNewWindowIcon(ctx: CanvasRenderingContext2D, size: number): void {
    let pad = 4;
    let s = size - pad * 2;

    ctx.strokeStyle = "rgba(0,0,0,0.7)";
    ctx.fillStyle = "rgba(0,0,0,0.7)";
    ctx.lineWidth = 1.5;

    // Small rectangle (the window)
    let rx = pad;
    let ry = pad + s * 0.3;
    let rw = s * 0.65;
    let rh = s * 0.7;
    ctx.strokeRect(rx, ry, rw, rh);

    // Arrow pointing up-right out of the rectangle
    let arrowStartX = pad + s * 0.4;
    let arrowStartY = pad + s * 0.6;
    let arrowEndX = pad + s;
    let arrowEndY = pad;
    ctx.beginPath();
    ctx.moveTo(arrowStartX, arrowStartY);
    ctx.lineTo(arrowEndX, arrowEndY);
    ctx.stroke();

    // Arrowhead
    ctx.beginPath();
    ctx.moveTo(arrowEndX, arrowEndY);
    ctx.lineTo(arrowEndX - 5, arrowEndY);
    ctx.lineTo(arrowEndX, arrowEndY + 5);
    ctx.closePath();
    ctx.fill();
}