From 17efe6efe6f648dc1ecdee51e1fec2fefb460c5d Mon Sep 17 00:00:00 2001 From: Mohammad Date: Thu, 22 Oct 2026 16:53:35 +0330 Subject: [PATCH] feat: add responsive anchored template layout --- docs/INVOICE_TEMPLATE_STUDIO_ARCHITECTURE.md | 43 +- .../app/services/report_template_service.py | 34 + .../services/report_template_v4_service.py | 200 ++- .../services/template_design_v4_compiler.py | 236 +++- .../tests/test_template_design_v2_compiler.py | 546 ++++++++ .../report_template_studio_v3_builder.dart | 1159 ++++++++++++++--- .../report_template_studio_v4_adapter.dart | 7 +- .../report_template_studio_v4_test.dart | 502 +++++++ 8 files changed, 2558 insertions(+), 169 deletions(-) diff --git a/docs/INVOICE_TEMPLATE_STUDIO_ARCHITECTURE.md b/docs/INVOICE_TEMPLATE_STUDIO_ARCHITECTURE.md index 935685ac..20e3dd8a 100644 --- a/docs/INVOICE_TEMPLATE_STUDIO_ARCHITECTURE.md +++ b/docs/INVOICE_TEMPLATE_STUDIO_ARCHITECTURE.md @@ -54,6 +54,9 @@ PDF Renderer موجود - RTL/LTR و تراز متن؛ - گرید میلی‌متری یکپارچه روی کل سطح قابل چاپ؛ - حرکت و تغییر اندازهٔ همهٔ بلوک‌ها در دو محور؛ +- Anchor پایدار بلوک‌به‌بلوک با فاصلهٔ میلی‌متری و offset مستقل هر variant؛ +- Pin به چپ، راست، بالا، پایین و مرکز صفحهٔ قابل چاپ؛ +- زوم بوم با کنترل‌های UI و `Ctrl + Wheel` بدون اثر بر اندازهٔ چاپ؛ - HTML preview و PDF بر پایه compiler موجود؛ - سازگاری با قالب‌های قبلی. @@ -61,8 +64,6 @@ PDF Renderer موجود - containerهای تو‌در‌تو؛ - freeform layout محدود و امن؛ -- Snap هوشمند به عناصر، حاشیه و guideها؛ -- variant مستقل برای A4، A5 و رول؛ - عملیات patch اتمیک و revision-based؛ - API دامنه‌ای مناسب برای اتصال MCP؛ - audit منشأ تغییرات کاربر یا AI. @@ -155,12 +156,14 @@ Design Document باید یک درخت از container و component باشد: ## ۵. محدودیت مهم محتوای پویا -همه اجزای فاکتور، از جمله جدول اقلام، روی گرید تمام‌صفحه جای‌گذاری می‌شوند. component پویا درون خانهٔ گرید می‌تواند از حداقل ارتفاع طراحی‌شده بزرگ‌تر شود و موتور HTML/CSS باید ردیف‌های بعدی را جابه‌جا کند. +همه اجزای فاکتور، از جمله جدول اقلام، روی گرید تمام‌صفحه جای‌گذاری می‌شوند. component پویا درون خانهٔ گرید می‌تواند از حداقل ارتفاع طراحی‌شده بزرگ‌تر شود. جابه‌جایی بلوک‌های وابسته نباید به هم‌پوشانی اتفاقی خانه‌های CSS Grid متکی باشد؛ رابطه باید به‌صورت Anchor صریح در Design Document ذخیره شود. قواعد پیشنهادی: - جدول اقلام یک component پویا روی `page_grid` است و ارتفاع تنظیم‌شده برای آن حداقل ارتفاع محسوب می‌شود. -- جمع‌بندی، توضیحات و امضا در خانه‌های بعدی گرید قرار می‌گیرند و با رشد جدول توسط CSS Grid جابه‌جا می‌شوند. +- اتصال `top` یک بلوک به `bottom` بلوک دیگر یک زنجیرهٔ محتوایی می‌سازد؛ compiler آن را به ترتیب طبیعی HTML تبدیل می‌کند تا ارتفاع واقعی داده در زمان چاپ تعیین‌کننده باشد. +- فاصلهٔ اتصال با `offset_mm` و override هر media profile ذخیره می‌شود؛ مثلاً پرداخت همیشه ۵ میلی‌متر بعد از انتهای واقعی جدول قرار می‌گیرد. +- جمع‌بندی، پرداخت، توضیحات و امضا می‌توانند زنجیره شوند و بلوک‌های مستقل همچنان مختصات آزاد خود را حفظ کنند. - header و footer تکرارشونده توسط compiler و CSS چاپ مدیریت شوند. - ردیف جدول تا حد امکان با `break-inside: avoid` نصف نشود. - عنوان ستون‌ها در صفحه بعد تکرار شود. @@ -248,7 +251,37 @@ Guide دستی → گرید ``` -در MVP، نتیجه Snap به مختصات عددی تبدیل می‌شود. برای آینده یک فیلد اختیاری `constraints` در schema رزرو می‌شود، ولی constraint solver در MVP ساخته نمی‌شود. +Snap معمولی همچنان فقط مختصات عددی تولید می‌کند. اتصال پایدار فقط از دستگیره‌های Anchor ساخته می‌شود تا هم‌ترازی ساده ناخواسته به وابستگی تبدیل نشود. هر component می‌تواند یک `constraints` اختیاری داشته باشد: + +```json +{ + "constraints": { + "links": [ + { + "axis": "vertical", + "source_anchor": "top", + "target": { + "type": "node", + "id": "invoice-lines", + "anchor": "bottom" + }, + "offset_mm": 5, + "variant_offsets": { + "a4_portrait": 5, + "roll_80": 2 + } + } + ], + "pins": { + "left": true, + "right": true + }, + "keep_together": true + } +} +``` + +روابط یک گراف بدون دور هستند. validator هدف حذف‌شده، نقطهٔ نامعتبر، چند رابطهٔ متناقض روی یک محور و cycle را رد می‌کند. اتصال چپ و راست هم‌زمان عرض responsive می‌سازد و اتصال بالا و پایین هم‌زمان ارتفاع ناحیه را Stretch می‌کند. ## ۹. compiler رسمی HTML/CSS diff --git a/hesabixAPI/app/services/report_template_service.py b/hesabixAPI/app/services/report_template_service.py index 378ed8ad..21bd68f9 100755 --- a/hesabixAPI/app/services/report_template_service.py +++ b/hesabixAPI/app/services/report_template_service.py @@ -227,6 +227,29 @@ class ReportTemplateService: return validate_v3_design(module_key, subtype, design) return validate_v2_design(module_key, subtype, design) + @staticmethod + def _validate_v4_assets_before_write( + module_key: str, + subtype: Optional[str], + assets: Any, + ) -> None: + if not isinstance(assets, dict): + return + design = assets.get("template_design") or assets.get("design") + if not isinstance(design, dict) or not is_v4_design(design): + return + validation = validate_v4_design(module_key, subtype, design) + if validation.get("errors"): + raise ApiError( + "VALIDATION_ERROR", + "Invalid template design v4: " + "; ".join(validation["errors"]), + http_status=400, + details={ + "errors": validation["errors"], + "warnings": validation.get("warnings") or [], + }, + ) + @staticmethod def validate_template_payload(data: Dict[str, Any], *, is_update: bool) -> None: """اعتبارسنجی ورودی ایجاد/ویرایش قالب (واردات JSON و فرم).""" @@ -350,6 +373,11 @@ class ReportTemplateService: str(data.get("module_key") or ""), (data.get("subtype") or None), ) + ReportTemplateService._validate_v4_assets_before_write( + str(data.get("module_key") or ""), + (data.get("subtype") or None), + data.get("assets"), + ) entity = ReportTemplate( business_id=int(data["business_id"]), module_key=str(data["module_key"]), @@ -386,6 +414,12 @@ class ReportTemplateService: next_module_key = str(data.get("module_key") if "module_key" in data else entity.module_key) next_subtype = (data.get("subtype") if "subtype" in data else entity.subtype) or None ReportTemplateService._validate_known_scope(next_module_key, next_subtype) + if "assets" in data or "module_key" in data or "subtype" in data: + ReportTemplateService._validate_v4_assets_before_write( + next_module_key, + next_subtype, + data.get("assets") if "assets" in data else entity.assets, + ) for field in [ "module_key", "subtype", "name", "description", "engine", "status", "content_html", "content_css", "header_html", "footer_html", diff --git a/hesabixAPI/app/services/report_template_v4_service.py b/hesabixAPI/app/services/report_template_v4_service.py index 5e9e8e84..d2a4a291 100644 --- a/hesabixAPI/app/services/report_template_v4_service.py +++ b/hesabixAPI/app/services/report_template_v4_service.py @@ -1,6 +1,7 @@ from __future__ import annotations from copy import deepcopy +import math from typing import Any, Iterable from app.services.report_template_gallery import get_family @@ -38,6 +39,8 @@ _FREEFORM_COMPONENTS = { "divider", "spacer", } +_ANCHOR_POINTS = {"top", "right", "bottom", "left", "center_x", "center_y"} +_PIN_EDGES = {"top", "right", "bottom", "left", "center_x", "center_y"} def is_v4_design(design: dict[str, Any]) -> bool: @@ -155,6 +158,13 @@ def studio_v4_contract(module_key: str, subtype: str | None) -> dict[str, Any]: "snap_targets": ["grid", "safe_margin", "sibling_edge", "sibling_center"], "position_unit": "mm", "dynamic_components_allowed": True, + "persistent_anchors": { + "points": sorted(_ANCHOR_POINTS), + "link_targets": ["node"], + "offset_unit": "mm", + "responsive_offsets": True, + "page_pins": sorted(_PIN_EDGES), + }, }, "components": component_catalog(module_key, subtype), "bindings": binding_catalog(module_key, subtype), @@ -196,8 +206,54 @@ def _json_schema() -> dict[str, Any]: "component": {"type": "string"}, "layout": {"type": "object"}, "placement": {"type": "object"}, + "constraints": {"$ref": "#/$defs/constraints"}, }, }, + "anchor_target": { + "type": "object", + "required": ["type", "id", "anchor"], + "properties": { + "type": {"const": "node"}, + "id": {"type": "string", "pattern": "^[a-zA-Z0-9_-]{1,80}$"}, + "anchor": {"enum": sorted(_ANCHOR_POINTS)}, + }, + "additionalProperties": False, + }, + "anchor_link": { + "type": "object", + "required": ["axis", "source_anchor", "target"], + "properties": { + "id": {"type": "string"}, + "axis": {"enum": ["horizontal", "vertical"]}, + "source_anchor": {"enum": sorted(_ANCHOR_POINTS)}, + "target": {"$ref": "#/$defs/anchor_target"}, + "offset_mm": {"type": "number", "minimum": -1000, "maximum": 1000}, + "variant_offsets": { + "type": "object", + "additionalProperties": {"type": "number", "minimum": -1000, "maximum": 1000}, + }, + }, + "additionalProperties": False, + }, + "constraints": { + "type": "object", + "properties": { + "links": {"type": "array", "maxItems": 2, "items": {"$ref": "#/$defs/anchor_link"}}, + "pins": { + "type": "object", + "properties": {key: {"type": "boolean"} for key in sorted(_PIN_EDGES)}, + "additionalProperties": False, + }, + "pin_offsets_mm": {"type": "object", "additionalProperties": {"type": "number"}}, + "variant_pin_offsets": { + "type": "object", + "additionalProperties": {"type": "object", "additionalProperties": {"type": "number"}}, + }, + "bottom_mode": {"enum": ["last_page", "every_page"]}, + "keep_together": {"type": "boolean"}, + }, + "additionalProperties": False, + }, "variant": { "type": "object", "required": ["media", "node_overrides"], @@ -481,12 +537,144 @@ def resolved_root(design: dict[str, Any]) -> dict[str, Any]: overrides = variant.get("node_overrides") or {} for node in _iter_nodes(root): override = overrides.get(str(node.get("id") or "")) or {} - for key in ("layout", "placement", "style"): + for key in ("layout", "placement", "style", "constraints"): if isinstance(override.get(key), dict): node[key] = {**(node.get(key) or {}), **deepcopy(override[key])} return root +def _validate_constraints(root: dict[str, Any], component_ids: set[str]) -> tuple[list[str], list[str]]: + errors: list[str] = [] + warnings: list[str] = [] + dependencies: dict[str, list[str]] = {} + dynamic_followers: dict[str, list[str]] = {} + for node in _iter_nodes(root): + if node.get("kind") != "component": + continue + node_id = str(node.get("id") or "") + constraints = node.get("constraints") or {} + if not isinstance(constraints, dict): + errors.append(f"Component '{node_id}' constraints must be an object") + continue + unknown_constraint_keys = set(constraints).difference( + {"links", "pins", "pin_offsets_mm", "variant_pin_offsets", "bottom_mode", "keep_together"} + ) + if unknown_constraint_keys: + errors.append(f"Unknown constraint field in '{node_id}'") + links = constraints.get("links") or [] + if not isinstance(links, list): + errors.append(f"Component '{node_id}' constraint links must be a list") + continue + seen_axes: set[str] = set() + for link in links: + if not isinstance(link, dict): + errors.append(f"Invalid anchor link in '{node_id}'") + continue + axis = str(link.get("axis") or "") + if axis not in ("horizontal", "vertical"): + errors.append(f"Invalid anchor axis in '{node_id}'") + continue + if axis in seen_axes: + errors.append(f"Component '{node_id}' has more than one {axis} anchor") + seen_axes.add(axis) + source_anchor = str(link.get("source_anchor") or "") + target = link.get("target") or {} + target_anchor = str(target.get("anchor") or "") if isinstance(target, dict) else "" + if source_anchor not in _ANCHOR_POINTS or target_anchor not in _ANCHOR_POINTS: + errors.append(f"Invalid anchor point in '{node_id}'") + continue + if axis == "horizontal" and ( + source_anchor not in {"left", "right", "center_x"} + or target_anchor not in {"left", "right", "center_x"} + ): + errors.append(f"Horizontal anchor uses a vertical point in '{node_id}'") + if axis == "vertical" and ( + source_anchor not in {"top", "bottom", "center_y"} + or target_anchor not in {"top", "bottom", "center_y"} + ): + errors.append(f"Vertical anchor uses a horizontal point in '{node_id}'") + if not isinstance(target, dict) or target.get("type") != "node": + errors.append(f"Anchor target in '{node_id}' must be a node") + continue + target_id = str(target.get("id") or "") + if target_id == node_id or target_id not in component_ids: + errors.append(f"Invalid anchor target '{target_id}' in '{node_id}'") + continue + dependencies.setdefault(node_id, []).append(target_id) + if axis == "vertical" and source_anchor == "top" and target_anchor == "bottom": + dynamic_followers.setdefault(target_id, []).append(node_id) + for raw_offset in [link.get("offset_mm"), *((link.get("variant_offsets") or {}).values() if isinstance(link.get("variant_offsets"), dict) else [])]: + try: + offset = float(raw_offset or 0) + except (TypeError, ValueError): + offset = 1001 + if not math.isfinite(offset) or abs(offset) > 1000: + errors.append(f"Invalid anchor offset in '{node_id}'") + pins = constraints.get("pins") or {} + if not isinstance(pins, dict): + errors.append(f"Component '{node_id}' pins must be an object") + else: + unknown_pins = set(pins).difference(_PIN_EDGES) + if unknown_pins: + errors.append(f"Unknown page pin in '{node_id}'") + if any(not isinstance(value, bool) for value in pins.values()): + errors.append(f"Page pins in '{node_id}' must be booleans") + if pins.get("left") and pins.get("right") and pins.get("center_x"): + errors.append(f"Conflicting horizontal page pins in '{node_id}'") + if pins.get("top") and pins.get("bottom") and pins.get("center_y"): + errors.append(f"Conflicting vertical page pins in '{node_id}'") + if pins.get("top") and pins.get("bottom") and node.get("component") in { + "invoice_lines", + "invoice_totals", + "payments", + "note", + }: + warnings.append( + f"Dynamic component '{node_id}' is stretched between top and bottom pins" + ) + for offsets in [ + constraints.get("pin_offsets_mm") or {}, + *((constraints.get("variant_pin_offsets") or {}).values() if isinstance(constraints.get("variant_pin_offsets"), dict) else []), + ]: + if not isinstance(offsets, dict): + errors.append(f"Invalid page pin offsets in '{node_id}'") + continue + for key, raw_offset in offsets.items(): + if key not in _PIN_EDGES: + errors.append(f"Unknown page pin offset in '{node_id}'") + continue + try: + offset = float(raw_offset) + except (TypeError, ValueError): + offset = math.inf + if not math.isfinite(offset) or abs(offset) > 5000: + errors.append(f"Invalid page pin offset in '{node_id}'") + bottom_mode = str(constraints.get("bottom_mode") or "last_page") + if bottom_mode not in ("last_page", "every_page"): + errors.append(f"Invalid bottom pin mode in '{node_id}'") + for target_id, followers in dynamic_followers.items(): + if len(followers) > 1: + errors.append( + f"Multiple dynamic followers of '{target_id}' must be chained explicitly" + ) + visiting: set[str] = set() + visited: set[str] = set() + def visit(node_id: str) -> None: + if node_id in visited: + return + if node_id in visiting: + errors.append("Anchor constraints contain a cycle") + return + visiting.add(node_id) + for target_id in dependencies.get(node_id, []): + visit(target_id) + visiting.remove(node_id) + visited.add(node_id) + for node_id in dependencies: + visit(node_id) + return errors, warnings + + def v4_to_v3_projection(design: dict[str, Any]) -> dict[str, Any]: root = resolved_root(design) regions: dict[str, list[dict[str, Any]]] = {key: [] for key in _REGIONS} @@ -619,7 +807,7 @@ def validate_v4_design(module_key: str, subtype: str | None, design: dict[str, A errors.append("Page grid size must be 1, 3 or 5 millimeters") elif kind == "component": component = str(node.get("component") or "") - for field in ("props", "style", "placement"): + for field in ("props", "style", "placement", "constraints"): if node.get(field) is not None and not isinstance(node.get(field), dict): errors.append(f"Component '{node_id}' {field} must be an object") definition = definitions.get(component) @@ -629,6 +817,14 @@ def validate_v4_design(module_key: str, subtype: str | None, design: dict[str, A component_counts[component] = component_counts.get(component, 0) + 1 else: errors.append(f"Invalid node kind in '{node_id}'") + component_ids = { + str(node.get("id") or "") + for node in _iter_nodes(root) + if node.get("kind") == "component" + } + constraint_errors, constraint_warnings = _validate_constraints(root, component_ids) + errors.extend(constraint_errors) + warnings.extend(constraint_warnings) variants = design.get("variants") if not isinstance(variants, dict): errors.append("variants must be an object") diff --git a/hesabixAPI/app/services/template_design_v4_compiler.py b/hesabixAPI/app/services/template_design_v4_compiler.py index 825a43d5..7447d5b9 100644 --- a/hesabixAPI/app/services/template_design_v4_compiler.py +++ b/hesabixAPI/app/services/template_design_v4_compiler.py @@ -138,6 +138,91 @@ def _page_grid_components( return items +def _anchor_coordinate(rect: dict[str, float], anchor: str) -> float: + if anchor == "left": + return rect["x"] + if anchor == "right": + return rect["x"] + rect["width"] + if anchor == "center_x": + return rect["x"] + rect["width"] / 2 + if anchor == "top": + return rect["y"] + if anchor == "bottom": + return rect["y"] + rect["height"] + return rect["y"] + rect["height"] / 2 + + +def _link_offset(link: dict[str, Any], profile: str) -> float: + variant_offsets = link.get("variant_offsets") or {} + return _number( + variant_offsets.get(profile) if isinstance(variant_offsets, dict) else None, + _number(link.get("offset_mm"), 0, -1000, 1000), + -1000, + 1000, + ) + + +def _page_pin_offsets(constraints: dict[str, Any], profile: str) -> dict[str, float]: + offsets = constraints.get("pin_offsets_mm") or {} + variant_offsets = constraints.get("variant_pin_offsets") or {} + if isinstance(variant_offsets, dict) and isinstance(variant_offsets.get(profile), dict): + offsets = {**offsets, **variant_offsets[profile]} + return { + key: _number(offsets.get(key), 0, -5000, 5000) + for key in ("left", "right", "top", "bottom", "center_x", "center_y") + } + + +def _resolved_page_rect( + component: dict[str, Any], + *, + width_mm: float, + height_mm: float, + profile: str, +) -> dict[str, float]: + placement = component.get("placement") or {} + rect = { + "x": _number(placement.get("x_mm"), 0, 0, width_mm), + "y": _number(placement.get("y_mm"), 0, 0, height_mm), + "width": _number(placement.get("width_mm"), 30, 1, width_mm), + "height": _number(placement.get("height_mm"), 15, 1, height_mm), + } + constraints = component.get("constraints") or {} + pins = constraints.get("pins") or {} + if not isinstance(pins, dict): + return rect + offsets = _page_pin_offsets(constraints, profile) + if pins.get("left") and pins.get("right"): + rect["x"] = offsets["left"] + rect["width"] = max(1, width_mm - offsets["left"] - offsets["right"]) + elif pins.get("right"): + rect["x"] = width_mm - offsets["right"] - rect["width"] + elif pins.get("left"): + rect["x"] = offsets["left"] + elif pins.get("center_x"): + rect["x"] = (width_mm - rect["width"]) / 2 + offsets["center_x"] + if pins.get("top") and pins.get("bottom"): + rect["y"] = offsets["top"] + rect["height"] = max(1, height_mm - offsets["top"] - offsets["bottom"]) + elif pins.get("bottom"): + rect["y"] = height_mm - offsets["bottom"] - rect["height"] + elif pins.get("top"): + rect["y"] = offsets["top"] + elif pins.get("center_y"): + rect["y"] = (height_mm - rect["height"]) / 2 + offsets["center_y"] + rect["x"] = max(0, min(width_mm - rect["width"], rect["x"])) + rect["y"] = max(0, min(height_mm - rect["height"], rect["y"])) + return rect + + +def _grid_position(rect: dict[str, float], *, grid_mm: float, columns: int, rows: int) -> tuple[int, int, int, int]: + column_start = max(1, min(columns, math.floor(rect["x"] / grid_mm) + 1)) + row_start = max(1, min(rows, math.floor(rect["y"] / grid_mm) + 1)) + column_span = max(1, min(columns - column_start + 1, math.ceil(rect["width"] / grid_mm))) + row_span = max(1, min(rows - row_start + 1, math.ceil(rect["height"] / grid_mm))) + return column_start, row_start, column_span, row_span + + def _page_grid_container(design: dict[str, Any], root: dict[str, Any], *, receipt: bool) -> str: layout = root.get("layout") or {} grid_mm = int(_number(layout.get("grid_mm"), 1, 1, 5)) @@ -145,29 +230,139 @@ def _page_grid_container(design: dict[str, Any], root: dict[str, Any], *, receip height_mm = _number(layout.get("height_mm"), 277, 20, 5000) columns = max(1, math.ceil(width_mm / grid_mm)) rows = max(1, math.ceil(height_mm / grid_mm)) + profile = active_variant_key(design) + components = [ + (region, component) + for region, component in _page_grid_components(root) + if component.get("visible", True) is not False + ] + by_id = {str(component.get("id") or ""): component for _, component in components} + regions = {str(component.get("id") or ""): region for region, component in components} + rects = { + node_id: _resolved_page_rect(component, width_mm=width_mm, height_mm=height_mm, profile=profile) + for node_id, component in by_id.items() + } + # Static sibling anchors are resolved from variant geometry. A top-to-bottom + # vertical anchor is intentionally left for normal HTML flow below, because + # the target may grow after Jinja data is rendered. + for _ in range(max(1, len(by_id))): + changed = False + for node_id, component in by_id.items(): + constraints = component.get("constraints") or {} + for link in constraints.get("links") or []: + if not isinstance(link, dict): + continue + target = link.get("target") or {} + target_id = str(target.get("id") or "") + if target_id not in rects: + continue + axis = str(link.get("axis") or "") + source_anchor = str(link.get("source_anchor") or "") + target_anchor = str(target.get("anchor") or "") + if axis == "vertical" and source_anchor == "top" and target_anchor == "bottom": + continue + desired = _anchor_coordinate(rects[target_id], target_anchor) + _link_offset(link, profile) + current = _anchor_coordinate(rects[node_id], source_anchor) + if abs(desired - current) < 0.001: + continue + if axis == "horizontal": + rects[node_id]["x"] += desired - current + rects[node_id]["x"] = max(0, min(width_mm - rects[node_id]["width"], rects[node_id]["x"])) + elif axis == "vertical": + rects[node_id]["y"] += desired - current + rects[node_id]["y"] = max(0, min(height_mm - rects[node_id]["height"], rects[node_id]["y"])) + changed = True + if not changed: + break + # Dynamic follow links form normal-flow chains. This is the essential part: + # a follower is emitted after the target, so rendered content height—not the + # design-time rectangle—determines its print position. + follows: dict[str, tuple[str, dict[str, Any]]] = {} + followers: dict[str, list[str]] = {} + for node_id, component in by_id.items(): + for link in (component.get("constraints") or {}).get("links") or []: + if not isinstance(link, dict) or link.get("axis") != "vertical": + continue + target = link.get("target") or {} + if link.get("source_anchor") == "top" and target.get("anchor") == "bottom": + target_id = str(target.get("id") or "") + if target_id in by_id: + follows[node_id] = (target_id, link) + followers.setdefault(target_id, []).append(node_id) + emitted: set[str] = set() items: list[str] = [] - for region, component in _page_grid_components(root): - if component.get("visible", True) is False: - continue - placement = component.get("placement") or {} - x = _number(placement.get("x_mm"), 0, 0, width_mm) - y = _number(placement.get("y_mm"), 0, 0, height_mm) - width = _number(placement.get("width_mm"), 30, 1, width_mm) - height = _number(placement.get("height_mm"), 15, 1, height_mm) - column_start = max(1, min(columns, math.floor(x / grid_mm) + 1)) - row_start = max(1, min(rows, math.floor(y / grid_mm) + 1)) - column_span = max(1, min(columns - column_start + 1, math.ceil(width / grid_mm))) - row_span = max(1, min(rows - row_start + 1, math.ceil(height / grid_mm))) + def component_markup(node_id: str, *, chain_x: float | None = None, gap: float = 0) -> str: + component = by_id[node_id] component_html = _component_html(design, component, receipt=receipt) if not component_html: - continue + return "" component_type = str(component.get("component") or "") dynamic_class = " rt-page-grid-item-dynamic" if component_type in ("invoice_lines", "invoice_totals", "payments", "note") else "" - items.append( - f'
{component_html}
' + ) + column_start, row_start, column_span, row_span = _grid_position(rect, grid_mm=grid_mm, columns=columns, rows=rows) + constraints = component.get("constraints") or {} + bottom_mode = str(constraints.get("bottom_mode") or "last_page") + bottom_pinned = (constraints.get("pins") or {}).get("bottom") + bottom_class = f" rt-pin-bottom-{bottom_mode.replace('_', '-')}" if bottom_pinned else "" + fixed_style = "" + if bottom_pinned and bottom_mode == "every_page": + bottom_offset = _page_pin_offsets(constraints, profile)["bottom"] + fixed_style = f"left:{rect['x']:g}mm;bottom:{bottom_offset:g}mm;width:{rect['width']:g}mm;" + return ( + f'
{component_html}
' + f'min-height:{rect["height"]:g}mm;{fixed_style}">{component_html}' ) + + for node_id in by_id: + if node_id in emitted or node_id in follows: + continue + chain = [node_id] + cursor = node_id + while len(followers.get(cursor, [])) == 1: + next_id = followers[cursor][0] + if next_id in chain: + break + chain.append(next_id) + cursor = next_id + if len(chain) == 1: + markup = component_markup(node_id) + if markup: + items.append(markup) + emitted.add(node_id) + continue + chain_x = min(rects[item_id]["x"] for item_id in chain) + chain_right = max(rects[item_id]["x"] + rects[item_id]["width"] for item_id in chain) + root_rect = rects[node_id] + chain_rect = {"x": chain_x, "y": root_rect["y"], "width": chain_right - chain_x, "height": root_rect["height"]} + column_start, row_start, column_span, row_span = _grid_position(chain_rect, grid_mm=grid_mm, columns=columns, rows=rows) + members: list[str] = [] + for index, item_id in enumerate(chain): + gap = 0 if index == 0 else _link_offset(follows[item_id][1], profile) + members.append(component_markup(item_id, chain_x=chain_x, gap=gap)) + emitted.add(item_id) + items.append( + f'
{"".join(members)}
' + ) + # Invalid/legacy branched followers are emitted independently as a safe + # fallback. Validation requires authors to express them as a serial chain. + for node_id in by_id: + if node_id not in emitted: + markup = component_markup(node_id) + if markup: + items.append(markup) return ( f'
None: + nodes[source_id]["constraints"] = { + "links": [ + { + "id": "vertical-anchor", + "axis": "vertical", + "source_anchor": "top", + "target": {"type": "node", "id": target_id, "anchor": "bottom"}, + "offset_mm": gap_mm, + "variant_offsets": {"a4_portrait": gap_mm, "roll_80": 2}, + } + ], + "keep_together": source_id != "invoice-lines", + } + follow("invoice-totals", "invoice-lines", 5) + follow("payments", "invoice-totals", 3) + assert validate_v4_design("invoices", "detail", design)["errors"] == [] + html, css, _, _ = compile_v4_design_to_jinja_html(design) + assert 'data-template-anchor-chain="invoice-lines"' in html + assert 'data-template-node-ref="invoice-totals"' in html + assert "margin-top:5mm" in html + assert "margin-top:3mm" in html + assert ".rt-anchor-keep-together" in css + + template = type( + "Template", + (), + { + "engine": "template_v2", + "assets": {"template_design": design}, + "content_html": "", + "content_css": "", + "header_html": "", + "footer_html": "", + "paper_size": "A4", + "orientation": "portrait", + "margins": None, + }, + )() + context = _sample_invoice_context() + base_line = context["lines"][0] + context["lines"] = [{**base_line, "product_name": f"کالای شماره {index}"} for index in range(1, 41)] + context["payments"] = [{"method_name": "نقدی", "amount": 100}] + document = HTML(string=ReportTemplateService.render_with_template(template, context)).render() + assert len(document.pages) >= 2 + last_page_classes: list[tuple[str, float, float]] = [] + def collect(box) -> None: + element = getattr(box, "element", None) + if element is not None: + classes = element.get("class", "") + if any(name in classes for name in ("rt-component-invoice-lines", "rt-component-invoice-totals", "rt-component-payments")): + last_page_classes.append((classes, box.position_y, box.height)) + for child in getattr(box, "children", []): + collect(child) + collect(document.pages[-1]._page_box) + line_box = next(item for item in last_page_classes if "rt-component-invoice-lines" in item[0]) + total_box = next(item for item in last_page_classes if "rt-component-invoice-totals" in item[0]) + payment_box = next(item for item in last_page_classes if "rt-component-payments" in item[0]) + assert total_box[1] >= line_box[1] + line_box[2] + assert payment_box[1] >= total_box[1] + total_box[2] + + design["media"] = __import__("copy").deepcopy(design["variants"]["roll_80"]["media"]) + roll_html, _, _, _ = compile_v4_design_to_jinja_html(design) + assert 'data-template-variant="roll_80"' in roll_html + assert "margin-top:2mm" in roll_html + + +def test_v4_anchor_validation_rejects_cycles_and_bad_points(): + design_v2 = default_design_for_family("invoice_classic") + assert design_v2 is not None + design = migrate_v3_design_to_v4(migrate_v2_design_to_v3(design_v2)) + def walk(node): + yield node + for child in node.get("children") or []: + yield from walk(child) + nodes = {str(node.get("id") or ""): node for node in walk(design["root"])} + nodes["invoice-lines"]["constraints"] = { + "links": [{"axis": "vertical", "source_anchor": "top", "target": {"type": "node", "id": "payments", "anchor": "bottom"}}] + } + nodes["payments"]["constraints"] = { + "links": [{"axis": "vertical", "source_anchor": "left", "target": {"type": "node", "id": "invoice-lines", "anchor": "bottom"}}] + } + errors = validate_v4_design("invoices", "detail", design)["errors"] + assert "Anchor constraints contain a cycle" in errors + assert any("horizontal point" in error.lower() for error in errors) + + +def _service_v4_design() -> dict: + design_v2 = default_design_for_family("invoice_classic") + assert design_v2 is not None + return migrate_v3_design_to_v4(migrate_v2_design_to_v3(design_v2)) + + +def _service_v4_nodes(design: dict) -> dict[str, dict]: + def walk(node): + yield node + for child in node.get("children") or []: + yield from walk(child) + + return {str(node.get("id") or ""): node for node in walk(design["root"])} + + +def _anchor_link(target_id: str, *, axis: str = "vertical", source: str = "top", target: str = "bottom") -> dict: + return { + "id": f"{axis}-anchor", + "axis": axis, + "source_anchor": source, + "target": {"type": "node", "id": target_id, "anchor": target}, + "offset_mm": 5, + } + + +def _invalid_service_v4_design(case: str) -> dict: + design = _service_v4_design() + nodes = _service_v4_nodes(design) + if case == "cycle": + nodes["invoice-lines"]["constraints"] = {"links": [_anchor_link("payments")]} + nodes["payments"]["constraints"] = {"links": [_anchor_link("invoice-lines")]} + elif case == "missing_target": + nodes["payments"]["constraints"] = {"links": [_anchor_link("deleted-node")]} + elif case == "duplicate_axis": + nodes["payments"]["constraints"] = { + "links": [_anchor_link("invoice-lines"), _anchor_link("invoice-totals")], + } + elif case == "multiple_followers": + nodes["invoice-totals"]["constraints"] = {"links": [_anchor_link("invoice-lines")]} + nodes["payments"]["constraints"] = {"links": [_anchor_link("invoice-lines")]} + elif case == "invalid_axis": + nodes["payments"]["constraints"] = {"links": [_anchor_link("invoice-lines", axis="diagonal")]} + elif case == "invalid_point": + nodes["payments"]["constraints"] = { + "links": [_anchor_link("invoice-lines", source="left")], + } + else: + raise AssertionError(case) + return design + + +def _valid_service_anchor_chain() -> dict: + design = _service_v4_design() + nodes = _service_v4_nodes(design) + for source_id, target_id, gap in ( + ("invoice-totals", "invoice-lines", 5), + ("payments", "invoice-totals", 3), + ("signatures", "payments", 5), + ): + link = _anchor_link(target_id) + link["offset_mm"] = gap + link["variant_offsets"] = {"a4_portrait": gap, "roll_80": 2} + nodes[source_id]["constraints"] = {"links": [link], "keep_together": True} + return design + + +def _node_by_component(design: dict, component: str) -> dict: + return next( + node + for node in _service_v4_nodes(design).values() + if node.get("component") == component + ) + + +def _template_for_v4_design(design: dict, *, paper_size: str = "A4") -> SimpleNamespace: + return SimpleNamespace( + engine="template_v2", + assets={"template_design": design}, + content_html="", + content_css="", + header_html="", + footer_html="", + paper_size=paper_size, + orientation="portrait", + margins=None, + ) + + +def _context_with_line_count(count: int) -> dict: + context = _sample_invoice_context() + base_line = context["lines"][0] + context["lines"] = [ + {**base_line, "product_name": f"کالای شماره {index}"} + for index in range(1, count + 1) + ] + context["payments"] = [{"method_name": "نقدی", "amount": 100}] + return context + + +def _render_v4_pdf(design: dict, line_count: int): + from weasyprint import HTML + + rendered = ReportTemplateService.render_with_template( + _template_for_v4_design(design), + _context_with_line_count(line_count), + ) + return HTML(string=rendered).render() + + +def _boxes_with_attribute(document, attribute: str, value: str): + result = [] + for page_index, page in enumerate(document.pages): + def collect(box) -> None: + element = getattr(box, "element", None) + if element is not None and element.get(attribute) == value: + result.append((page_index, box)) + for child in getattr(box, "children", []): + collect(child) + collect(page._page_box) + return result + + +def _page_text(page) -> str: + parts: list[str] = [] + def collect(box) -> None: + text = getattr(box, "text", None) + if text: + parts.append(str(text)) + for child in getattr(box, "children", []): + collect(child) + collect(page._page_box) + return " ".join(parts) + + +def _service_template_payload(design: dict) -> dict: + return { + "business_id": 1, + "module_key": "invoices", + "subtype": "detail", + "name": "قالب تست", + "engine": "template_v2", + "content_html": "generated by template design", + "assets": {"template_design": design}, + } + + +@pytest.mark.parametrize( + "case", + ("cycle", "missing_target", "duplicate_axis", "multiple_followers", "invalid_axis", "invalid_point"), +) +@pytest.mark.parametrize("operation", ("create", "update")) +def test_v4_invalid_assets_are_rejected_before_create_or_update(case, operation, monkeypatch): + db = MagicMock() + invalid_assets = {"template_design": _invalid_service_v4_design(case)} + if operation == "create": + payload = _service_template_payload(invalid_assets["template_design"]) + with pytest.raises(ApiError) as exc: + ReportTemplateService.create_template(db, payload, user_id=1) + else: + original_assets = {"template_design": _service_v4_design()} + entity = SimpleNamespace( + module_key="invoices", + subtype="detail", + assets=deepcopy(original_assets), + version=7, + ) + monkeypatch.setattr( + ReportTemplateService, + "get_template", + staticmethod(lambda _db, _template_id, _business_id: entity), + ) + with pytest.raises(ApiError) as exc: + ReportTemplateService.update_template( + db, + template_id=10, + data={"assets": invalid_assets}, + business_id=1, + ) + assert entity.assets == original_assets + assert entity.version == 7 + assert exc.value.code == "VALIDATION_ERROR" + db.add.assert_not_called() + db.commit.assert_not_called() + + +def test_v4_after_content_bottom_mode_is_rejected_before_write(): + design = _service_v4_design() + nodes = _service_v4_nodes(design) + nodes["payments"]["constraints"] = { + "pins": {"bottom": True}, + "bottom_mode": "after_content", + } + assert any( + "Invalid bottom pin mode" in error + for error in validate_v4_design("invoices", "detail", design)["errors"] + ) + db = MagicMock() + with pytest.raises(ApiError) as exc: + ReportTemplateService.create_template(db, _service_template_payload(design), user_id=1) + assert exc.value.code == "VALIDATION_ERROR" + db.add.assert_not_called() + db.commit.assert_not_called() + + +def test_v4_explicit_anchor_chain_is_accepted_and_stored(): + design = _valid_service_anchor_chain() + assert validate_v4_design("invoices", "detail", design)["errors"] == [] + db = MagicMock() + entity = ReportTemplateService.create_template( + db, + _service_template_payload(design), + user_id=1, + ) + assert entity.assets == {"template_design": design} + db.add.assert_called_once_with(entity) + db.commit.assert_called_once() + html, _, _, _ = compile_v4_design_to_jinja_html(entity.assets["template_design"]) + assert 'data-template-anchor-chain="invoice-lines"' in html + assert 'data-template-node-ref="signatures"' in html + + +@pytest.mark.parametrize("schema_version", (3, 4)) +def test_service_still_accepts_constraintless_v3_and_v4_designs(schema_version): + design_v2 = default_design_for_family("invoice_classic") + assert design_v2 is not None + design_v3 = migrate_v2_design_to_v3(design_v2) + design = design_v3 if schema_version == 3 else migrate_v3_design_to_v4(design_v3) + assert all("constraints" not in node for node in _service_v4_nodes(design)) if schema_version == 4 else True + db = MagicMock() + entity = ReportTemplateService.create_template( + db, + _service_template_payload(design), + user_id=1, + ) + rendered = ReportTemplateService.render_with_template(entity, _sample_invoice_context()) + assert "INV-1" in rendered + db.commit.assert_called_once() + + +def test_service_v3_to_v4_copy_on_write_remains_intact_during_update(monkeypatch): + design_v2 = default_design_for_family("invoice_classic") + assert design_v2 is not None + design_v3 = migrate_v2_design_to_v3(design_v2) + original_v3 = deepcopy(design_v3) + design_v4 = migrate_v3_design_to_v4(design_v3) + assert design_v3 == original_v3 + entity = SimpleNamespace( + module_key="invoices", + subtype="detail", + assets={"template_design": design_v3}, + version=3, + ) + monkeypatch.setattr( + ReportTemplateService, + "get_template", + staticmethod(lambda _db, _template_id, _business_id: entity), + ) + db = MagicMock() + ReportTemplateService.update_template( + db, + template_id=11, + data={"assets": {"template_design": design_v4}}, + business_id=1, + ) + assert design_v3 == original_v3 + assert entity.assets["template_design"]["schema_version"] == 4 + assert entity.assets["template_design"] is design_v4 + db.commit.assert_called_once() + + +def test_v4_compiler_contract_is_exact(): + design = _service_v4_design() + assert design["schema_version"] == 4 + assert design["compiler_contract"] == { + "name": "hesabix-template-html-css", + "version": 1, + "output": "html_css", + } + contract = studio_v4_contract("invoices", "detail") + assert contract["schema_version"] == 4 + assert contract["compiler"] == design["compiler_contract"] + + +@pytest.mark.parametrize("line_count", (1, 5, 40)) +def test_v4_complete_dynamic_chain_follows_real_table_height(line_count): + design = _valid_service_anchor_chain() + document = _render_v4_pdf(design, line_count) + chain = ( + ("invoice-lines", None), + ("invoice-totals", 5), + ("payments", 3), + ("signatures", 5), + ) + previous_last = None + for node_id, gap_mm in chain: + boxes = _boxes_with_attribute(document, "data-template-node-ref", node_id) + assert boxes, f"{node_id} was not rendered" + first = min(boxes, key=lambda item: (item[0], item[1].position_y)) + last = max(boxes, key=lambda item: (item[0], item[1].position_y)) + if gap_mm is not None: + assert first[1].margin_top * 25.4 / 96 == pytest.approx(gap_mm, abs=0.15) + assert previous_last is not None + assert first[0] > previous_last[0] or ( + first[0] == previous_last[0] + and first[1].position_y >= previous_last[1].position_y + previous_last[1].height + ) + previous_last = last + + +def test_v4_dynamic_table_grows_beyond_its_designed_minimum_height(): + design = _valid_service_anchor_chain() + line_node = _node_by_component(design, "invoice_lines") + minimum_mm = float(line_node["placement"]["height_mm"]) + one_line = _render_v4_pdf(design, 1) + forty_lines = _render_v4_pdf(design, 40) + one_boxes = _boxes_with_attribute(one_line, "data-template-node-ref", "invoice-lines") + forty_boxes = _boxes_with_attribute(forty_lines, "data-template-node-ref", "invoice-lines") + assert sum(box.height for _, box in one_boxes) * 25.4 / 96 >= minimum_mm - 0.2 + assert sum(box.height for _, box in forty_boxes) > sum(box.height for _, box in one_boxes) + + +def test_v4_roll_80_uses_two_millimeter_offsets_for_the_same_chain(): + design = _valid_service_anchor_chain() + design["media"] = deepcopy(design["variants"]["roll_80"]["media"]) + html, _, _, _ = compile_v4_design_to_jinja_html(design) + assert 'data-template-variant="roll_80"' in html + assert html.count("margin-top:2mm") == 3 + assert "margin-top:5mm" not in html + assert "margin-top:3mm" not in html + + +def test_v4_horizontal_anchor_stays_geometric_when_invoice_lines_grow(): + design = _service_v4_design() + payments = _node_by_component(design, "payments") + payments["constraints"] = { + "links": [{ + "id": "horizontal-anchor", + "axis": "horizontal", + "source_anchor": "left", + "target": {"type": "node", "id": "invoice-lines", "anchor": "right"}, + "offset_mm": 2, + }], + } + assert validate_v4_design("invoices", "detail", design)["errors"] == [] + one_line = _render_v4_pdf(design, 1) + forty_lines = _render_v4_pdf(design, 40) + positions = [] + for document in (one_line, forty_lines): + boxes = _boxes_with_attribute(document, "data-template-node-id", "payments") + assert boxes + positions.append((boxes[0][0], boxes[0][1].position_x, boxes[0][1].position_y)) + assert positions[1] == pytest.approx(positions[0], abs=0.2) + + +def test_v4_left_and_right_pins_stretch_width_per_variant(): + design = _service_v4_design() + totals = _node_by_component(design, "invoice_totals") + totals["constraints"] = { + "pins": {"left": True, "right": True}, + "pin_offsets_mm": {"left": 5, "right": 5}, + "variant_pin_offsets": { + "a4_portrait": {"left": 5, "right": 5}, + "roll_80": {"left": 2, "right": 2}, + }, + } + a4_html, _, _, _ = compile_v4_design_to_jinja_html(design) + assert "grid-column:6/span 180" in a4_html + design["media"] = deepcopy(design["variants"]["roll_80"]["media"]) + roll_html, _, _, _ = compile_v4_design_to_jinja_html(design) + assert "grid-column:3/span 72" in roll_html + + +@pytest.mark.parametrize( + ("bottom_mode", "expected_pages"), + (("last_page", "last"), ("every_page", "all")), +) +def test_v4_bottom_pin_modes_place_footer_on_expected_pages(bottom_mode, expected_pages): + design = _service_v4_design() + footer = _node_by_component(design, "footer_meta") + footer["placement"] = { + **footer["placement"], + "x_mm": 10, + "y_mm": 260, + "width_mm": 100, + "height_mm": 12, + } + footer["constraints"] = { + "pins": {"bottom": True}, + "pin_offsets_mm": {"bottom": 5}, + "bottom_mode": bottom_mode, + "keep_together": True, + } + document = _render_v4_pdf(design, 80) + assert len(document.pages) >= 2 + boxes = _boxes_with_attribute(document, "data-template-node-id", footer["id"]) + pages = sorted({page for page, _ in boxes}) + assert pages == ([len(document.pages) - 1] if expected_pages == "last" else list(range(len(document.pages)))) + + +def test_v4_keep_together_css_covers_totals_payments_and_signatures(): + design = _service_v4_design() + html, css, _, _ = compile_v4_design_to_jinja_html(design) + assert ".rt-anchor-keep-together { break-inside:avoid; page-break-inside:avoid; }" in css + for node_id in ("invoice-totals", "payments", "signatures"): + pattern = rf'class="[^"]*rt-anchor-keep-together[^"]*"[^>]*>.*?data-template-node-id="{node_id}"' + assert re.search(pattern, html, re.DOTALL), node_id + + +def test_v4_table_header_repeats_and_designed_height_is_a_minimum(): + design = _valid_service_anchor_chain() + header = str(_node_by_component(design, "invoice_lines")["props"]["columns"][0]["title"]) + document = _render_v4_pdf(design, 80) + assert len(document.pages) >= 2 + line_pages = [] + for page_index, page in enumerate(document.pages): + if _boxes_with_attribute(type("D", (), {"pages": [page]})(), "data-template-node-id", "invoice-lines"): + line_pages.append(page_index) + assert header in _page_text(page) + assert len(line_pages) >= 2 + + +def test_v4_editor_zoom_metadata_does_not_change_html_or_css(): + design = _service_v4_design() + baseline = compile_v4_design_to_jinja_html(design) + zoomed = deepcopy(design) + zoomed["editor_state"] = {"zoom": 2.0} + assert compile_v4_design_to_jinja_html(zoomed) == baseline + + +def test_v4_direction_does_not_mirror_physical_grid_geometry(): + rtl = _service_v4_design() + ltr = deepcopy(rtl) + ltr["theme"] = {**ltr.get("theme", {}), "direction": "ltr"} + rtl_html, _, _, _ = compile_v4_design_to_jinja_html(rtl) + ltr_html, _, _, _ = compile_v4_design_to_jinja_html(ltr) + assert '>.from( + (regions[region] as List?) ?? const [], + ); + for (var index = 0; index < candidates.length; index++) { + final candidate = Map.from(candidates[index]); + final style = + (candidate['style'] as Map?)?.cast() ?? const {}; + final constraints = (style['anchor_constraints'] as Map?) + ?.cast(); + if (constraints == null) continue; + final nextConstraints = _clone(constraints); + final links = + List>.from( + (nextConstraints['links'] as List?) ?? const [], + )..removeWhere( + (link) => + ((link['target'] as Map?)?['id'] ?? '').toString() == id, + ); + nextConstraints['links'] = links; + candidate['style'] = { + ...style, + 'anchor_constraints': nextConstraints, + }; + candidates[index] = candidate; + } + regions[region] = candidates; + } _setRegions(design, regions); if (_selectedBlockId == id) _selectedBlockId = null; _commit(design); @@ -581,6 +618,11 @@ class _ReportTemplateStudioV3BuilderState return (_definition(type)?['label_fa'] ?? type).toString(); } + String _labelForBlockId(String id) { + final block = _findBlock(id)?.block; + return block == null ? id : _labelForType(block['type'].toString()); + } + IconData _iconForType(String type) { return switch (type) { 'brand_header' => Icons.branding_watermark_outlined, @@ -674,6 +716,8 @@ class _ReportTemplateStudioV3BuilderState _showLivePreview ? 'پیش‌نمایش واقعی خروجی' : 'بوم طراحی تعاملی', + maxLines: 1, + overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.titleSmall?.copyWith( fontWeight: FontWeight.bold, ), @@ -681,6 +725,14 @@ class _ReportTemplateStudioV3BuilderState ), SegmentedButton( showSelectedIcon: false, + style: const ButtonStyle( + visualDensity: VisualDensity.compact, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + minimumSize: WidgetStatePropertyAll(Size(0, 34)), + padding: WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 5), + ), + ), segments: const [ ButtonSegment( value: false, @@ -712,10 +764,68 @@ class _ReportTemplateStudioV3BuilderState ); } - List> _allPageGridBlocks() => [ - for (final region in const ['header', 'body', 'footer']) - ..._regionBlocks(widget.design, region), - ]; + void _setCanvasZoom(double value) { + setState(() => _canvasZoom = value.clamp(0.5, 2.5).toDouble()); + } + + Widget _zoomControls(BuildContext context) { + return Material( + color: Theme.of(context).colorScheme.surface.withValues(alpha: 0.94), + elevation: 3, + borderRadius: BorderRadius.circular(8), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + key: const ValueKey('studio-zoom-out'), + visualDensity: VisualDensity.compact, + tooltip: 'کوچک‌نمایی', + onPressed: _canvasZoom <= 0.5 + ? null + : () => _setCanvasZoom(_canvasZoom - 0.1), + icon: const Icon(Icons.remove, size: 18), + ), + InkWell( + key: const ValueKey('studio-zoom-reset'), + onTap: () => _setCanvasZoom(1), + borderRadius: BorderRadius.circular(6), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4), + child: Text('${(_canvasZoom * 100).round()}٪'), + ), + ), + IconButton( + key: const ValueKey('studio-zoom-in'), + visualDensity: VisualDensity.compact, + tooltip: 'بزرگ‌نمایی', + onPressed: _canvasZoom >= 2.5 + ? null + : () => _setCanvasZoom(_canvasZoom + 0.1), + icon: const Icon(Icons.add, size: 18), + ), + ], + ), + ); + } + + void _handleCanvasPointerSignal(PointerSignalEvent event) { + if (event is! PointerScrollEvent || + !HardwareKeyboard.instance.isControlPressed) { + return; + } + _setCanvasZoom(_canvasZoom + (event.scrollDelta.dy < 0 ? 0.1 : -0.1)); + } + + List> _allPageGridBlocks() { + final regions = _regions(widget.design); + _resolveProjectionAnchors(widget.design, regions); + return [ + for (final region in const ['header', 'body', 'footer']) + ...List>.from( + (regions[region] as List?) ?? const [], + ), + ]; + } double _pageGridDefaultWidth(String type, double canvasWidthMm) => switch (type) { @@ -907,157 +1017,208 @@ class _ReportTemplateStudioV3BuilderState final availableWidth = constraints.maxWidth.isFinite ? constraints.maxWidth : 800.0; - final pageWidthPx = (availableWidth - 48) + final fittedPageWidthPx = (availableWidth - 48) .clamp(280.0, 760.0) .toDouble(); + final pageWidthPx = fittedPageWidthPx * _canvasZoom; final pixelsPerMm = pageWidthPx / mediaSize.width; final pageHeightPx = (topMm + canvasHeightMm + bottomMm) * pixelsPerMm; - return ColoredBox( - color: const Color(0xffe5e7eb), - child: SingleChildScrollView( - padding: const EdgeInsets.all(24), - child: Center( - child: Container( - width: pageWidthPx, - height: pageHeightPx, - padding: EdgeInsets.fromLTRB( - leftMm * pixelsPerMm, - topMm * pixelsPerMm, - rightMm * pixelsPerMm, - bottomMm * pixelsPerMm, - ), - decoration: const BoxDecoration( - color: Colors.white, - boxShadow: [ - BoxShadow( - color: Color(0x26000000), - blurRadius: 18, - offset: Offset(0, 6), - ), - ], - ), - child: Directionality( - textDirection: direction, - child: Builder( - builder: (canvasContext) => DragTarget<_BlockDragData>( - onWillAcceptWithDetails: (details) => - _canDropOnPageGrid(details.data), - onAcceptWithDetails: (details) { - final box = - _pageGridCanvasKey.currentContext - ?.findRenderObject() - as RenderBox?; - if (box == null) return; - final local = box.globalToLocal(details.offset); - _dropOnPageGrid( - details.data, - local.dx / pixelsPerMm, - local.dy / pixelsPerMm, - canvasWidthMm, - canvasHeightMm, - ); - }, - builder: (context, candidates, rejected) => Container( - key: _pageGridCanvasKey, - width: canvasWidthMm * pixelsPerMm, - height: canvasHeightMm * pixelsPerMm, - decoration: BoxDecoration( - border: Border.all( - color: candidates.isNotEmpty - ? Theme.of(context).colorScheme.primary - : Theme.of(context).colorScheme.outlineVariant, + return Listener( + onPointerSignal: _handleCanvasPointerSignal, + child: ColoredBox( + color: const Color(0xffe5e7eb), + child: Stack( + children: [ + Positioned.fill( + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SizedBox( + width: math.max(availableWidth, pageWidthPx + 48), + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Center( + child: Container( + width: pageWidthPx, + height: pageHeightPx, + padding: EdgeInsets.fromLTRB( + leftMm * pixelsPerMm, + topMm * pixelsPerMm, + rightMm * pixelsPerMm, + bottomMm * pixelsPerMm, + ), + decoration: const BoxDecoration( + color: Colors.white, + boxShadow: [ + BoxShadow( + color: Color(0x26000000), + blurRadius: 18, + offset: Offset(0, 6), + ), + ], + ), + child: Directionality( + textDirection: direction, + child: Builder( + builder: (canvasContext) => DragTarget<_BlockDragData>( + onWillAcceptWithDetails: (details) => + _canDropOnPageGrid(details.data), + onAcceptWithDetails: (details) { + final box = + _pageGridCanvasKey.currentContext + ?.findRenderObject() + as RenderBox?; + if (box == null) return; + final local = box.globalToLocal( + details.offset, + ); + _dropOnPageGrid( + details.data, + local.dx / pixelsPerMm, + local.dy / pixelsPerMm, + canvasWidthMm, + canvasHeightMm, + ); + }, + builder: (context, candidates, rejected) => + Container( + key: _pageGridCanvasKey, + width: canvasWidthMm * pixelsPerMm, + height: canvasHeightMm * pixelsPerMm, + decoration: BoxDecoration( + border: Border.all( + color: candidates.isNotEmpty + ? Theme.of( + context, + ).colorScheme.primary + : Theme.of( + context, + ).colorScheme.outlineVariant, + ), + ), + child: Stack( + clipBehavior: Clip.none, + children: [ + Positioned.fill( + child: CustomPaint( + painter: _MillimeterGridPainter( + pixelsPerMm: pixelsPerMm, + gridMm: gridMm, + color: Theme.of(context) + .colorScheme + .outlineVariant + .withValues(alpha: 0.5), + ), + ), + ), + for (final block in blocks) + _freeformCanvasBlock( + context, + block, + siblings: blocks + .where( + (candidate) => + candidate['id'] + ?.toString() != + block['id'] + ?.toString(), + ) + .map(_freeformRect) + .toList(), + widthMm: canvasWidthMm, + heightMm: canvasHeightMm, + pixelsPerMm: pixelsPerMm, + gridMm: gridMm, + snapEnabled: snapEnabled, + ), + Positioned.fill( + child: IgnorePointer( + child: CustomPaint( + painter: _AnchorLinksPainter( + segments: + _canvasAnchorSegments( + blocks, + ), + pixelsPerMm: pixelsPerMm, + color: + Colors.green.shade700, + ), + ), + ), + ), + for (final guide in _freeformGuides) + if (guide.vertical) + Positioned( + left: + guide.positionMm * + pixelsPerMm, + top: 0, + bottom: 0, + child: Container( + width: 1, + color: Theme.of( + context, + ).colorScheme.tertiary, + ), + ) + else + Positioned( + top: + guide.positionMm * + pixelsPerMm, + left: 0, + right: 0, + child: Container( + height: 1, + color: Theme.of( + context, + ).colorScheme.tertiary, + ), + ), + PositionedDirectional( + top: 4, + end: 4, + child: DecoratedBox( + decoration: BoxDecoration( + color: Theme.of(context) + .colorScheme + .surfaceContainerHighest + .withValues(alpha: 0.9), + borderRadius: + BorderRadius.circular(10), + ), + child: Padding( + padding: + const EdgeInsets.symmetric( + horizontal: 8, + vertical: 3, + ), + child: Text( + 'گرید کل صفحه · ${gridMm.toStringAsFixed(0)}mm${snapEnabled ? ' · Snap' : ''}', + style: Theme.of( + context, + ).textTheme.labelSmall, + ), + ), + ), + ), + ], + ), + ), + ), + ), + ), ), ), - child: Stack( - clipBehavior: Clip.none, - children: [ - Positioned.fill( - child: CustomPaint( - painter: _MillimeterGridPainter( - pixelsPerMm: pixelsPerMm, - gridMm: gridMm, - color: Theme.of(context) - .colorScheme - .outlineVariant - .withValues(alpha: 0.5), - ), - ), - ), - for (final block in blocks) - _freeformCanvasBlock( - context, - block, - siblings: blocks - .where( - (candidate) => - candidate['id']?.toString() != - block['id']?.toString(), - ) - .map(_freeformRect) - .toList(), - widthMm: canvasWidthMm, - heightMm: canvasHeightMm, - pixelsPerMm: pixelsPerMm, - gridMm: gridMm, - snapEnabled: snapEnabled, - ), - for (final guide in _freeformGuides) - if (guide.vertical) - Positioned( - left: guide.positionMm * pixelsPerMm, - top: 0, - bottom: 0, - child: Container( - width: 1, - color: Theme.of( - context, - ).colorScheme.tertiary, - ), - ) - else - Positioned( - top: guide.positionMm * pixelsPerMm, - left: 0, - right: 0, - child: Container( - height: 1, - color: Theme.of( - context, - ).colorScheme.tertiary, - ), - ), - PositionedDirectional( - top: 4, - end: 4, - child: DecoratedBox( - decoration: BoxDecoration( - color: Theme.of(context) - .colorScheme - .surfaceContainerHighest - .withValues(alpha: 0.9), - borderRadius: BorderRadius.circular(10), - ), - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 8, - vertical: 3, - ), - child: Text( - 'گرید کل صفحه · ${gridMm.toStringAsFixed(0)}mm${snapEnabled ? ' · Snap' : ''}', - style: Theme.of( - context, - ).textTheme.labelSmall, - ), - ), - ), - ), - ], - ), ), ), ), ), - ), + PositionedDirectional( + start: 12, + bottom: 12, + child: _zoomControls(context), + ), + ], ), ), ); @@ -1417,6 +1578,453 @@ class _ReportTemplateStudioV3BuilderState ); } + Map _anchorConstraints(Map block) { + final style = (block['style'] as Map?)?.cast() ?? const {}; + return (style['anchor_constraints'] as Map?)?.cast() ?? + const {}; + } + + List> _anchorLinks(Map block) { + return List>.from( + (_anchorConstraints(block)['links'] as List?) ?? const [], + ); + } + + double _anchorCoordinate(StudioMmRect rect, String point) => switch (point) { + 'left' => rect.x, + 'right' => rect.right, + 'center_x' => rect.centerX, + 'top' => rect.y, + 'bottom' => rect.bottom, + _ => rect.centerY, + }; + + double _activeAnchorOffset(Map link) { + final offsets = (link['variant_offsets'] as Map?)?.cast(); + final value = + offsets?[reportTemplateV4ProfileKey(widget.design)] ?? + link['offset_mm']; + return (value as num?)?.toDouble() ?? double.tryParse('$value') ?? 0; + } + + void _resolveProjectionAnchors( + Map design, + Map regions, + ) { + final blocks = >[ + for (final region in const ['header', 'body', 'footer']) + ...List>.from( + (regions[region] as List?) ?? const [], + ), + ]; + final byId = >{ + for (final block in blocks) block['id'].toString(): block, + }; + final media = normalizedReportTemplateMedia(design); + final size = reportTemplateMediaSizeMm(media); + final margins = + (media['margins_mm'] as Map?)?.cast() ?? const {}; + final width = + (size.width - + ((margins['left'] as num?)?.toDouble() ?? 0) - + ((margins['right'] as num?)?.toDouble() ?? 0)) + .clamp(10, 1000) + .toDouble(); + final height = + (size.height - + ((margins['top'] as num?)?.toDouble() ?? 0) - + ((margins['bottom'] as num?)?.toDouble() ?? 0)) + .clamp(20, 5000) + .toDouble(); + final profile = reportTemplateV4ProfileKey(design); + for (final block in blocks) { + final constraints = _anchorConstraints(block); + final pins = + (constraints['pins'] as Map?)?.cast() ?? const {}; + final baseOffsets = + (constraints['pin_offsets_mm'] as Map?)?.cast() ?? + const {}; + final variantOffsets = + ((constraints['variant_pin_offsets'] as Map?)?[profile] as Map?) + ?.cast(); + double offset(String edge) => + ((variantOffsets?[edge] ?? baseOffsets[edge]) as num?)?.toDouble() ?? + 0; + var rect = _freeformRect(block); + if (pins['left'] == true && pins['right'] == true) { + rect = StudioMmRect( + offset('left'), + rect.y, + math.max(1, width - offset('left') - offset('right')), + rect.height, + ); + } else if (pins['right'] == true) { + rect = StudioMmRect( + width - offset('right') - rect.width, + rect.y, + rect.width, + rect.height, + ); + } else if (pins['left'] == true) { + rect = StudioMmRect(offset('left'), rect.y, rect.width, rect.height); + } else if (pins['center_x'] == true) { + rect = StudioMmRect( + (width - rect.width) / 2 + offset('center_x'), + rect.y, + rect.width, + rect.height, + ); + } + if (pins['top'] == true && pins['bottom'] == true) { + rect = StudioMmRect( + rect.x, + offset('top'), + rect.width, + math.max(1, height - offset('top') - offset('bottom')), + ); + } else if (pins['bottom'] == true) { + rect = StudioMmRect( + rect.x, + height - offset('bottom') - rect.height, + rect.width, + rect.height, + ); + } else if (pins['top'] == true) { + rect = StudioMmRect(rect.x, offset('top'), rect.width, rect.height); + } else if (pins['center_y'] == true) { + rect = StudioMmRect( + rect.x, + (height - rect.height) / 2 + offset('center_y'), + rect.width, + rect.height, + ); + } + final style = (block['style'] as Map).cast(); + block['style'] = { + ...style, + 'x_mm': rect.x, + 'y_mm': rect.y, + 'width_mm': rect.width, + 'height_mm': rect.height, + }; + } + for (var pass = 0; pass < blocks.length; pass++) { + var changed = false; + for (final block in blocks) { + var rect = _freeformRect(block); + for (final link in _anchorLinks(block)) { + final target = (link['target'] as Map?)?.cast(); + final targetBlock = byId[target?['id']?.toString()]; + if (targetBlock == null) continue; + final sourcePoint = (link['source_anchor'] ?? '').toString(); + final targetPoint = (target?['anchor'] ?? '').toString(); + final desired = + _anchorCoordinate(_freeformRect(targetBlock), targetPoint) + + _activeAnchorOffset(link); + final current = _anchorCoordinate(rect, sourcePoint); + if ((desired - current).abs() < 0.001) continue; + if (link['axis'] == 'horizontal') { + rect = StudioMmRect( + rect.x + desired - current, + rect.y, + rect.width, + rect.height, + ).clampInside(width, height); + } else { + rect = StudioMmRect( + rect.x, + rect.y + desired - current, + rect.width, + rect.height, + ).clampInside(width, height); + } + changed = true; + } + final style = (block['style'] as Map).cast(); + block['style'] = { + ...style, + 'x_mm': rect.x, + 'y_mm': rect.y, + }; + } + if (!changed) break; + } + } + + String? _anchorAxis(String point) { + if (_horizontalAnchorPoints.contains(point)) return 'horizontal'; + if (_verticalAnchorPoints.contains(point)) return 'vertical'; + return null; + } + + void _onAnchorHandleTap(String blockId, String point) { + final pendingId = _pendingAnchorBlockId; + final pendingPoint = _pendingAnchorPoint; + if (pendingId == null || pendingPoint == null || pendingId == blockId) { + setState(() { + _selectedBlockId = blockId; + _pendingAnchorBlockId = blockId; + _pendingAnchorPoint = point; + }); + return; + } + final axis = _anchorAxis(pendingPoint); + if (axis == null || axis != _anchorAxis(point)) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('نقطه‌های اتصال باید روی یک محور باشند.')), + ); + return; + } + final resolvedBlocks = _allPageGridBlocks(); + Map? resolvedBlock(String id) { + for (final block in resolvedBlocks) { + if (block['id']?.toString() == id) return block; + } + return null; + } + + final source = resolvedBlock(pendingId); + final target = resolvedBlock(blockId); + if (source == null || target == null) return; + if (_wouldCreateAnchorCycle(pendingId, blockId)) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('این اتصال یک چرخه ایجاد می‌کند.')), + ); + setState(() { + _pendingAnchorBlockId = null; + _pendingAnchorPoint = null; + }); + return; + } + if (axis == 'vertical' && pendingPoint == 'top' && point == 'bottom') { + final alreadyFollowed = _allPageGridBlocks().any( + (candidate) => + candidate['id']?.toString() != pendingId && + _anchorLinks(candidate).any((link) { + final target = (link['target'] as Map?); + return link['axis'] == 'vertical' && + link['source_anchor'] == 'top' && + target?['anchor'] == 'bottom' && + target?['id']?.toString() == blockId; + }), + ); + if (alreadyFollowed) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text( + 'این نقطه یک دنبال‌کننده دارد؛ بلوک جدید را به انتهای همان زنجیره وصل کنید.', + ), + ), + ); + return; + } + } + final offset = + _anchorCoordinate(_freeformRect(source), pendingPoint) - + _anchorCoordinate(_freeformRect(target), point); + final profile = reportTemplateV4ProfileKey(widget.design); + final constraints = _clone(_anchorConstraints(source)); + final links = List>.from( + (constraints['links'] as List?) ?? const [], + )..removeWhere((link) => link['axis'] == axis); + links.add({ + 'id': '$axis-anchor', + 'axis': axis, + 'source_anchor': pendingPoint, + 'target': {'type': 'node', 'id': blockId, 'anchor': point}, + 'offset_mm': double.parse(offset.toStringAsFixed(2)), + 'variant_offsets': {profile: double.parse(offset.toStringAsFixed(2))}, + }); + constraints['links'] = links; + final pins = + (constraints['pins'] as Map?)?.cast() ?? + {}; + for (final edge + in axis == 'horizontal' + ? const ['left', 'right', 'center_x'] + : const ['top', 'bottom', 'center_y']) { + pins[edge] = false; + } + constraints['pins'] = pins; + _patchBlockStyle(pendingId, {'anchor_constraints': constraints}); + setState(() { + _selectedBlockId = pendingId; + _pendingAnchorBlockId = null; + _pendingAnchorPoint = null; + }); + } + + bool _wouldCreateAnchorCycle(String sourceId, String targetId) { + final dependencies = >{}; + for (final block in _allPageGridBlocks()) { + dependencies[block['id'].toString()] = _anchorLinks(block) + .map((link) => ((link['target'] as Map?)?['id'] ?? '').toString()) + .where((id) => id.isNotEmpty) + .toList(); + } + dependencies[sourceId] = [ + ...(dependencies[sourceId] ?? const []), + targetId, + ]; + final seen = {}; + bool reachesSource(String id) { + if (id == sourceId) return true; + if (!seen.add(id)) return false; + return (dependencies[id] ?? const []).any(reachesSource); + } + + return reachesSource(targetId); + } + + void _removeAnchorAxis(String id, String axis) { + final block = _findBlock(id)?.block; + if (block == null) return; + final constraints = _clone(_anchorConstraints(block)); + final links = List>.from( + (constraints['links'] as List?) ?? const [], + )..removeWhere((link) => link['axis'] == axis); + constraints['links'] = links; + _patchBlockStyle(id, {'anchor_constraints': constraints}); + } + + void _setAnchorGap(String id, Map link, double value) { + final block = _findBlock(id)?.block; + if (block == null) return; + final constraints = _clone(_anchorConstraints(block)); + final links = List>.from( + (constraints['links'] as List?) ?? const [], + ); + final index = links.indexWhere((item) => item['axis'] == link['axis']); + if (index < 0) return; + final next = Map.from(links[index]); + final offsets = + (next['variant_offsets'] as Map?)?.cast() ?? + {}; + next['variant_offsets'] = { + ...offsets, + reportTemplateV4ProfileKey(widget.design): value, + }; + links[index] = next; + constraints['links'] = links; + _patchBlockStyle(id, {'anchor_constraints': constraints}); + } + + void _togglePagePin( + String id, + String edge, + bool enabled, + double canvasWidthMm, + double canvasHeightMm, + ) { + Map? block; + for (final candidate in _allPageGridBlocks()) { + if (candidate['id']?.toString() == id) { + block = candidate; + break; + } + } + if (block == null) return; + final rect = _freeformRect(block); + final constraints = _clone(_anchorConstraints(block)); + final pins = + (constraints['pins'] as Map?)?.cast() ?? + {}; + pins[edge] = enabled; + if (enabled && edge == 'center_x') { + pins['left'] = false; + pins['right'] = false; + } else if (enabled && const {'left', 'right'}.contains(edge)) { + pins['center_x'] = false; + } + if (enabled && edge == 'center_y') { + pins['top'] = false; + pins['bottom'] = false; + } else if (enabled && const {'top', 'bottom'}.contains(edge)) { + pins['center_y'] = false; + } + if (enabled) { + final axis = const {'left', 'right', 'center_x'}.contains(edge) + ? 'horizontal' + : 'vertical'; + final links = List>.from( + (constraints['links'] as List?) ?? const [], + )..removeWhere((link) => link['axis'] == axis); + constraints['links'] = links; + } + constraints['pins'] = pins; + if (edge == 'bottom' && enabled && constraints['bottom_mode'] == null) { + constraints['bottom_mode'] = 'last_page'; + } + final profile = reportTemplateV4ProfileKey(widget.design); + final allVariantOffsets = + (constraints['variant_pin_offsets'] as Map?)?.cast() ?? + {}; + final offsets = + (allVariantOffsets[profile] as Map?)?.cast() ?? + {}; + final edgeOffset = switch (edge) { + 'left' => rect.x, + 'right' => canvasWidthMm - rect.right, + 'top' => rect.y, + 'bottom' => canvasHeightMm - rect.bottom, + 'center_x' => rect.centerX - canvasWidthMm / 2, + 'center_y' => rect.centerY - canvasHeightMm / 2, + _ => 0, + }; + offsets[edge] = edgeOffset; + final baseOffsets = + (constraints['pin_offsets_mm'] as Map?)?.cast() ?? + {}; + baseOffsets.putIfAbsent(edge, () => edgeOffset); + constraints['pin_offsets_mm'] = baseOffsets; + allVariantOffsets[profile] = offsets; + constraints['variant_pin_offsets'] = allVariantOffsets; + _patchBlockStyle(id, {'anchor_constraints': constraints}); + } + + void _setAnchorConstraintValue(String id, String key, dynamic value) { + final block = _findBlock(id)?.block; + if (block == null) return; + final constraints = _clone(_anchorConstraints(block)); + constraints[key] = value; + _patchBlockStyle(id, {'anchor_constraints': constraints}); + } + + List<_CanvasAnchorSegment> _canvasAnchorSegments( + List> blocks, + ) { + final byId = >{ + for (final block in blocks) block['id'].toString(): block, + }; + final segments = <_CanvasAnchorSegment>[]; + for (final block in blocks) { + final sourceRect = _freeformRect(block); + for (final link in _anchorLinks(block)) { + final target = (link['target'] as Map?)?.cast(); + final targetBlock = byId[target?['id']?.toString()]; + if (targetBlock == null) continue; + final targetRect = _freeformRect(targetBlock); + final sourcePoint = (link['source_anchor'] ?? '').toString(); + final targetPoint = (target?['anchor'] ?? '').toString(); + Offset point(StudioMmRect rect, String anchor) => switch (anchor) { + 'left' => Offset(rect.x, rect.centerY), + 'right' => Offset(rect.right, rect.centerY), + 'top' => Offset(rect.centerX, rect.y), + 'bottom' => Offset(rect.centerX, rect.bottom), + 'center_x' => Offset(rect.centerX, rect.centerY), + _ => Offset(rect.centerX, rect.centerY), + }; + segments.add( + _CanvasAnchorSegment( + point(sourceRect, sourcePoint), + point(targetRect, targetPoint), + ), + ); + } + } + return segments; + } + void _finishFreeformGesture(String id) { final rect = _freeformPreviewRect; _freeformGestureId = null; @@ -1689,6 +2297,44 @@ class _ReportTemplateStudioV3BuilderState child: ClipRect(child: _canvasBlockContent(context, block)), ), ), + if (selected || _pendingAnchorBlockId != null) + for (final entry in const { + 'top': Alignment.topCenter, + 'right': Alignment.centerRight, + 'bottom': Alignment.bottomCenter, + 'left': Alignment.centerLeft, + }.entries) + Positioned.fill( + child: Align( + alignment: entry.value, + child: Tooltip( + message: _pendingAnchorBlockId == null + ? 'شروع اتصال از ${_anchorPointLabel(entry.key)}' + : 'اتصال به ${_anchorPointLabel(entry.key)}', + child: GestureDetector( + key: ValueKey('anchor-handle-$id-${entry.key}'), + behavior: HitTestBehavior.opaque, + onTap: () => _onAnchorHandleTap(id, entry.key), + child: Container( + width: 13, + height: 13, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: + _pendingAnchorBlockId == id && + _pendingAnchorPoint == entry.key + ? Colors.green + : Theme.of(context).colorScheme.surface, + border: Border.all( + color: Colors.green.shade700, + width: 2, + ), + ), + ), + ), + ), + ), + ), if (selected) Positioned( right: 0, @@ -1765,6 +2411,15 @@ class _ReportTemplateStudioV3BuilderState ); } + String _anchorPointLabel(String point) => switch (point) { + 'top' => 'بالا', + 'right' => 'راست', + 'bottom' => 'پایین', + 'left' => 'چپ', + 'center_x' => 'مرکز افقی', + _ => 'مرکز عمودی', + }; + bool _canDropOnRegion(_BlockDragData data, String region) { final type = data.blockType ?? @@ -2737,6 +3392,10 @@ class _ReportTemplateStudioV3BuilderState mediaSize.height - ((mediaMargins['top'] as num?)?.toDouble() ?? 0) - ((mediaMargins['bottom'] as num?)?.toDouble() ?? 0); + final defaultCanvasWidth = + mediaSize.width - + ((mediaMargins['left'] as num?)?.toDouble() ?? 0) - + ((mediaMargins['right'] as num?)?.toDouble() ?? 0); final freeformHeight = ((style[pageGrid ? 'page_height_mm' : 'freeform_height_mm'] as num?) ?.toDouble() ?? @@ -2744,6 +3403,16 @@ class _ReportTemplateStudioV3BuilderState .clamp(10, 5000) .toDouble(); final freeformRect = _freeformRect(block); + final anchorConstraints = _anchorConstraints(block); + final links = _anchorLinks(block); + final pins = + (anchorConstraints['pins'] as Map?)?.cast() ?? + const {}; + final rawBottomMode = (anchorConstraints['bottom_mode'] ?? 'last_page') + .toString(); + final bottomMode = const {'last_page', 'every_page'}.contains(rawBottomMode) + ? rawBottomMode + : 'last_page'; const alignableTypes = { 'brand_header', 'party_info', @@ -2813,6 +3482,153 @@ class _ReportTemplateStudioV3BuilderState style: Theme.of(context).textTheme.bodySmall, ), const SizedBox(height: 14), + const Divider(), + Row( + children: [ + const Icon(Icons.hub_outlined, size: 18), + const SizedBox(width: 6), + const Expanded( + child: Text( + 'Anchor و اتصال داینامیک', + style: TextStyle(fontWeight: FontWeight.bold), + ), + ), + if (_pendingAnchorBlockId == id) + TextButton( + onPressed: () => setState(() { + _pendingAnchorBlockId = null; + _pendingAnchorPoint = null; + }), + child: const Text('لغو'), + ), + ], + ), + Text( + _pendingAnchorBlockId == id + ? 'حالا نقطه هم‌محور روی بلوک مقصد را انتخاب کنید.' + : 'یکی از نقطه‌های سبز بلوک را بزنید، سپس نقطهٔ مقصد را انتخاب کنید.', + style: Theme.of(context).textTheme.bodySmall, + ), + if (links.isNotEmpty) ...[ + const SizedBox(height: 8), + for (final link in links) + Card( + margin: const EdgeInsets.only(bottom: 6), + child: Padding( + padding: const EdgeInsets.all(8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + const Icon(Icons.link, size: 17), + const SizedBox(width: 6), + Expanded( + child: Text( + '${_anchorPointLabel((link['source_anchor'] ?? '').toString())} ← ${_labelForBlockId((((link['target'] as Map?)?['id']) ?? '').toString())} (${_anchorPointLabel((((link['target'] as Map?)?['anchor']) ?? '').toString())})', + ), + ), + IconButton( + visualDensity: VisualDensity.compact, + tooltip: 'قطع اتصال', + onPressed: () => _removeAnchorAxis( + id, + (link['axis'] ?? '').toString(), + ), + icon: const Icon(Icons.link_off, size: 18), + ), + ], + ), + Text( + 'فاصله در این اندازه کاغذ: ${_activeAnchorOffset(link).toStringAsFixed(1)} mm', + ), + if (link['axis'] == 'vertical' && + link['source_anchor'] == 'top' && + (link['target'] as Map?)?['anchor'] == 'bottom') + Text( + 'در چاپ بعد از ارتفاع واقعی محتوای مقصد قرار می‌گیرد.', + style: Theme.of(context).textTheme.bodySmall, + ), + Slider( + min: -20, + max: 40, + divisions: 120, + value: _activeAnchorOffset(link).clamp(-20, 40), + onChanged: (value) => + _setAnchorGap(id, link, value), + ), + ], + ), + ), + ), + ], + const SizedBox(height: 8), + const Text('نقاط ثابت نسبت به صفحه'), + const SizedBox(height: 6), + Wrap( + spacing: 6, + runSpacing: 6, + children: [ + for (final edge in const [ + 'top', + 'right', + 'bottom', + 'left', + 'center_x', + 'center_y', + ]) + FilterChip( + label: Text(_anchorPointLabel(edge)), + selected: pins[edge] == true, + onSelected: (selected) => _togglePagePin( + id, + edge, + selected, + defaultCanvasWidth, + defaultCanvasHeight, + ), + ), + ], + ), + if (pins['bottom'] == true) ...[ + const SizedBox(height: 8), + DropdownButtonFormField( + initialValue: bottomMode, + decoration: const InputDecoration( + labelText: 'رفتار اتصال پایین در چاپ', + isDense: true, + ), + items: const [ + DropdownMenuItem( + value: 'last_page', + child: Text('پایین صفحه آخر'), + ), + DropdownMenuItem( + value: 'every_page', + child: Text('پایین همه صفحات'), + ), + ], + onChanged: (value) => value == null + ? null + : _setAnchorConstraintValue(id, 'bottom_mode', value), + ), + ], + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('بلوک هنگام شکست صفحه یکپارچه بماند'), + subtitle: const Text('برای پرداخت، جمع‌بندی و امضا مناسب است.'), + value: + anchorConstraints['keep_together'] == true || + (anchorConstraints['keep_together'] == null && + const { + 'invoice_totals', + 'payments', + 'signatures', + }.contains(type)), + onChanged: (value) => + _setAnchorConstraintValue(id, 'keep_together', value), + ), + const Divider(), ], if (layoutType == 'freeform' || pageGrid) ...[ Text(pageGrid ? 'شبکه کل صفحه و Snap' : 'شبکه و Snap'), @@ -3281,6 +4097,59 @@ class _ReportTemplateStudioV3BuilderState } } +class _CanvasAnchorSegment { + final Offset sourceMm; + final Offset targetMm; + + const _CanvasAnchorSegment(this.sourceMm, this.targetMm); +} + +class _AnchorLinksPainter extends CustomPainter { + final List<_CanvasAnchorSegment> segments; + final double pixelsPerMm; + final Color color; + + const _AnchorLinksPainter({ + required this.segments, + required this.pixelsPerMm, + required this.color, + }); + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = color + ..strokeWidth = 1.5 + ..style = PaintingStyle.stroke; + for (final segment in segments) { + final source = segment.sourceMm * pixelsPerMm; + final target = segment.targetMm * pixelsPerMm; + final middle = Offset(source.dx, (source.dy + target.dy) / 2); + final second = Offset(target.dx, middle.dy); + final path = Path() + ..moveTo(source.dx, source.dy) + ..lineTo(middle.dx, middle.dy) + ..lineTo(second.dx, second.dy) + ..lineTo(target.dx, target.dy); + canvas.drawPath(path, paint); + canvas.drawCircle(source, 3, paint); + canvas.drawCircle(target, 3, paint); + } + } + + @override + bool shouldRepaint(covariant _AnchorLinksPainter oldDelegate) => + oldDelegate.pixelsPerMm != pixelsPerMm || + oldDelegate.color != color || + oldDelegate.segments.length != segments.length || + !List.generate( + segments.length, + (index) => + oldDelegate.segments[index].sourceMm == segments[index].sourceMm && + oldDelegate.segments[index].targetMm == segments[index].targetMm, + ).every((same) => same); +} + class _CanvasTotalRow extends StatelessWidget { final String label; final String value; diff --git a/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_v4_adapter.dart b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_v4_adapter.dart index 0e8f9bf0..def1712e 100644 --- a/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_v4_adapter.dart +++ b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_v4_adapter.dart @@ -99,7 +99,7 @@ Map _mergedNode( ) { final result = _cloneMap(node); final override = _map(overrides[(node['id'] ?? '').toString()]); - for (final key in const ['layout', 'placement', 'style']) { + for (final key in const ['layout', 'placement', 'style', 'constraints']) { if (override[key] is Map) { result[key] = { ..._map(result[key]), @@ -151,6 +151,7 @@ Map reportTemplateV4StudioProjection( final fallbackWidth = pageWidth * span / 60; final style = { ..._map(component['style']), + 'anchor_constraints': _cloneMap(_map(component['constraints'])), 'row_id': row['id'], 'layout_type': 'page_grid', 'grid_span': placement['column_span'] ?? 60, @@ -239,6 +240,7 @@ Map _layoutFromBlocks(List> blocks) { Map _componentFromBlock(Map block) { final style = _cloneMap(_map(block['style'])); + final constraints = _cloneMap(_map(style.remove('anchor_constraints'))); final layoutType = (style['layout_type'] ?? 'grid').toString(); final placement = layoutType == 'freeform' || layoutType == 'page_grid' ? { @@ -277,6 +279,7 @@ Map _componentFromBlock(Map block) { 'props': _cloneMap(_map(block['props'])), 'style': style, 'placement': placement, + if (constraints.isNotEmpty) 'constraints': constraints, }; } @@ -468,8 +471,10 @@ Map applyStudioProjectionToReportTemplateV4( 'height_mm': height, }; } + final constraints = _cloneMap(_map(node['constraints'])); nextOverrides[nodeEntry.key] = { 'placement': placement, + if (constraints.isNotEmpty) 'constraints': constraints, }; } } diff --git a/hesabixUI/hesabix_ui/test/widgets/report_template_studio_v4_test.dart b/hesabixUI/hesabix_ui/test/widgets/report_template_studio_v4_test.dart index 98d1b7d8..1d939759 100644 --- a/hesabixUI/hesabix_ui/test/widgets/report_template_studio_v4_test.dart +++ b/hesabixUI/hesabix_ui/test/widgets/report_template_studio_v4_test.dart @@ -1,4 +1,6 @@ +import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hesabix_ui/widgets/report_template/studio/report_template_snap_engine.dart'; import 'package:hesabix_ui/widgets/report_template/studio/report_template_studio_v3_builder.dart'; @@ -50,6 +52,15 @@ Map _design() { 'style': {}, 'placement': placement, }, + { + 'id': 'text-two', + 'kind': 'component', + 'component': 'custom_text', + 'visible': true, + 'props': {'text': 'متن دوم'}, + 'style': {}, + 'placement': {...placement, 'y_mm': 50}, + }, ], }, ] @@ -80,6 +91,9 @@ Map _design() { 'text-one': { 'placement': {...placement, 'x_mm': x, 'width_mm': width}, }, + 'text-two': { + 'placement': {...placement, 'x_mm': x, 'y_mm': 50, 'width_mm': width}, + }, }; return { 'schema_version': 4, @@ -109,6 +123,73 @@ Map _design() { }; } +Map? _findNode(Map node, String id) { + if (node['id'] == id) return node; + for (final child in (node['children'] as List?) ?? const []) { + if (child is Map) { + final found = _findNode(child.cast(), id); + if (found != null) return found; + } + } + return null; +} + +Map _designWithExistingAnchor() { + final design = _design(); + final node = _findNode( + (design['root'] as Map).cast(), + 'text-two', + )!; + node['constraints'] = { + 'links': [ + { + 'id': 'vertical-anchor', + 'axis': 'vertical', + 'source_anchor': 'top', + 'target': {'type': 'node', 'id': 'text-one', 'anchor': 'bottom'}, + 'offset_mm': 5, + 'variant_offsets': {'a4_portrait': 5, 'roll_80': 2}, + }, + ], + }; + return design; +} + +Map _designWithThirdBlock() { + final design = _designWithExistingAnchor(); + final row = _findNode( + (design['root'] as Map).cast(), + 'row-text', + )!; + (row['children'] as List).add({ + 'id': 'text-three', + 'kind': 'component', + 'component': 'custom_text', + 'visible': true, + 'props': {'text': 'متن سوم'}, + 'style': {}, + 'placement': { + 'column_span': 30, + 'x_mm': 80, + 'y_mm': 80, + 'width_mm': 60, + 'height_mm': 24, + }, + }); + for (final variant in (design['variants'] as Map).values) { + ((variant as Map)['node_overrides'] as Map)['text-three'] = { + 'placement': { + 'column_span': 30, + 'x_mm': 80, + 'y_mm': 80, + 'width_mm': 60, + 'height_mm': 24, + }, + }; + } + return design; +} + void main() { test('responsive paper variants are projected and edited independently', () { final design = _design(); @@ -226,6 +307,21 @@ void main() { final block = find.byKey(const ValueKey('freeform-block-text-one')); expect(block, findsOneWidget); expect(find.text('متن تست'), findsOneWidget); + final beforeZoom = tester.getSize(block); + await tester.tap(find.byKey(const ValueKey('studio-zoom-in'))); + await tester.pumpAndSettle(); + expect(find.text('110٪'), findsOneWidget); + expect(tester.getSize(block).width, greaterThan(beforeZoom.width)); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendEventToBinding( + PointerScrollEvent( + position: tester.getCenter(block), + scrollDelta: const Offset(0, -20), + ), + ); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pumpAndSettle(); + expect(find.text('120٪'), findsOneWidget); final beforeMove = tester.getTopLeft(block); final moveGesture = await tester.startGesture(tester.getCenter(block)); await moveGesture.moveBy(const Offset(30, 0)); @@ -249,4 +345,410 @@ void main() { expect(changed, isNotNull); expect(changed!['schema_version'], 4); }); + + testWidgets('anchor handles persist a responsive node constraint', ( + tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1600, 1000)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + Map? changed; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 1500, + height: 900, + child: ReportTemplateStudioV3Builder( + design: _design(), + blockCatalog: const [ + { + 'type': 'custom_text', + 'label_fa': 'متن دلخواه', + 'allowed_regions': ['header', 'body', 'footer'], + 'default_props': {'text': 'متن'}, + }, + ], + onDesignChanged: (value) => changed = value, + previewPane: const ColoredBox(color: Colors.white), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final second = find.byKey(const ValueKey('freeform-block-text-two')); + await tester.tapAt(tester.getCenter(second)); + await tester.pump(); + await tester.tap(find.byKey(const ValueKey('anchor-handle-text-two-top'))); + await tester.pump(); + await tester.tap( + find.byKey(const ValueKey('anchor-handle-text-one-bottom')), + ); + await tester.pumpAndSettle(); + expect(changed, isNotNull); + + Map? findNode(Map node, String id) { + if (node['id'] == id) return node; + for (final child in (node['children'] as List?) ?? const []) { + if (child is Map) { + final found = findNode(child, id); + if (found != null) return found; + } + } + return null; + } + + final node = findNode(changed!['root'] as Map, 'text-two')!; + final links = ((node['constraints'] as Map)['links'] as List); + expect(links, hasLength(1)); + expect((links.first as Map)['source_anchor'], 'top'); + expect(((links.first as Map)['target'] as Map)['id'], 'text-one'); + expect( + ((links.first as Map)['variant_offsets'] as Map), + contains('a4_portrait'), + ); + final variants = changed!['variants'] as Map; + for (final variant in variants.values) { + final overrides = (variant as Map)['node_overrides'] as Map; + final responsiveConstraints = + (overrides['text-two'] as Map)['constraints'] as Map; + final responsiveLink = + (responsiveConstraints['links'] as List).single as Map; + expect(responsiveLink['source_anchor'], 'top'); + expect((responsiveLink['target'] as Map)['id'], 'text-one'); + expect(responsiveLink['variant_offsets'], contains('a4_portrait')); + } + }); + + test('grid snapping supports 1, 3, and 5 millimeters and hard bounds', () { + for (final grid in const [1.0, 3.0, 5.0]) { + final result = snapStudioMove( + proposed: const StudioMmRect(107.8, 107.8, 10, 10), + siblings: const [], + containerWidthMm: 1000, + containerHeightMm: 1000, + gridMm: grid, + thresholdMm: grid, + ); + expect(result.rect.x % grid, closeTo(0, 0.0001)); + expect(result.rect.y % grid, closeTo(0, 0.0001)); + } + + final exactBoundary = snapStudioMove( + proposed: const StudioMmRect(70, 30, 10, 10), + siblings: const [], + containerWidthMm: 80, + containerHeightMm: 40, + gridMm: 1, + thresholdMm: 0, + enabled: false, + ); + expect(exactBoundary.rect.x, 70); + expect(exactBoundary.rect.y, 30); + + final outsideBoundary = snapStudioResize( + proposed: const StudioMmRect(70, 30, 11, 11), + siblings: const [], + containerWidthMm: 80, + containerHeightMm: 40, + gridMm: 1, + thresholdMm: 0, + enabled: false, + ); + expect(outsideBoundary.rect.right, 80); + expect(outsideBoundary.rect.bottom, 40); + }); + + testWidgets('page grid keeps sibling blocks side by side', (tester) async { + await tester.binding.setSurfaceSize(const Size(1600, 1000)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + final design = _design(); + for (final variant in (design['variants'] as Map).values) { + final overrides = (variant as Map)['node_overrides'] as Map; + (overrides['text-one'] as Map)['placement'] = { + ...Map.from( + (overrides['text-one'] as Map)['placement'] as Map, + ), + 'x_mm': 5, + 'y_mm': 8, + 'width_mm': 60, + }; + (overrides['text-two'] as Map)['placement'] = { + ...Map.from( + (overrides['text-two'] as Map)['placement'] as Map, + ), + 'x_mm': 70, + 'y_mm': 8, + 'width_mm': 60, + }; + } + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ReportTemplateStudioV3Builder( + design: design, + blockCatalog: const [ + { + 'type': 'custom_text', + 'label_fa': 'متن دلخواه', + 'allowed_regions': ['header', 'body', 'footer'], + 'default_props': {'text': 'متن'}, + }, + ], + onDesignChanged: (_) {}, + previewPane: const ColoredBox(color: Colors.white), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final first = find.byKey(const ValueKey('freeform-block-text-one')); + final second = find.byKey(const ValueKey('freeform-block-text-two')); + expect( + tester.getTopLeft(first).dy, + closeTo(tester.getTopLeft(second).dy, 0.5), + ); + expect(tester.getTopLeft(first).dx, lessThan(tester.getTopLeft(second).dx)); + }); + + testWidgets('studio persists page grid choices 1, 3, and 5', (tester) async { + await tester.binding.setSurfaceSize(const Size(1600, 1000)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + var current = _design(); + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (context, setState) => Scaffold( + body: ReportTemplateStudioV3Builder( + design: current, + blockCatalog: const [ + { + 'type': 'custom_text', + 'label_fa': 'متن دلخواه', + 'allowed_regions': ['header', 'body', 'footer'], + 'default_props': {'text': 'متن'}, + }, + ], + onDesignChanged: (value) => setState(() => current = value), + previewPane: const ColoredBox(color: Colors.white), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tapAt( + tester.getCenter(find.byKey(const ValueKey('freeform-block-text-one'))), + ); + await tester.pumpAndSettle(); + for (final grid in const [3, 5, 1]) { + await tester.tap( + find.text( + '$grid mm' + .replaceAll('1', '۱') + .replaceAll('3', '۳') + .replaceAll('5', '۵'), + ), + ); + await tester.pumpAndSettle(); + expect(((current['root'] as Map)['layout'] as Map)['grid_mm'], grid); + } + }); + + testWidgets('anchor can be removed from settings and persisted document', ( + tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1600, 1000)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + var current = _designWithExistingAnchor(); + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (context, setState) => Scaffold( + body: ReportTemplateStudioV3Builder( + design: current, + blockCatalog: const [ + { + 'type': 'custom_text', + 'label_fa': 'متن دلخواه', + 'allowed_regions': ['header', 'body', 'footer'], + 'default_props': {'text': 'متن'}, + }, + ], + onDesignChanged: (value) => setState(() => current = value), + previewPane: const ColoredBox(color: Colors.white), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tapAt( + tester.getCenter(find.byKey(const ValueKey('freeform-block-text-two'))), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('قطع اتصال')); + await tester.pumpAndSettle(); + final node = _findNode( + (current['root'] as Map).cast(), + 'text-two', + )!; + expect(((node['constraints'] as Map)['links'] as List), isEmpty); + }); + + testWidgets('anchor UI rejects cycles and a second direct follower', ( + tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1600, 1000)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + var current = _designWithThirdBlock(); + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (context, setState) => Scaffold( + body: ReportTemplateStudioV3Builder( + design: current, + blockCatalog: const [ + { + 'type': 'custom_text', + 'label_fa': 'متن دلخواه', + 'allowed_regions': ['header', 'body', 'footer'], + 'default_props': {'text': 'متن'}, + }, + ], + onDesignChanged: (value) => setState(() => current = value), + previewPane: const ColoredBox(color: Colors.white), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tapAt( + tester.getCenter(find.byKey(const ValueKey('freeform-block-text-one'))), + ); + await tester.pump(); + await tester.tap(find.byKey(const ValueKey('anchor-handle-text-one-top'))); + await tester.pump(); + await tester.tap( + find.byKey(const ValueKey('anchor-handle-text-two-bottom')), + ); + await tester.pump(); + expect(find.text('این اتصال یک چرخه ایجاد می‌کند.'), findsOneWidget); + await tester.pumpAndSettle(); + + await tester.tapAt( + tester.getCenter(find.byKey(const ValueKey('freeform-block-text-three'))), + ); + await tester.pump(); + await tester.tap( + find.byKey(const ValueKey('anchor-handle-text-three-top')), + ); + await tester.pump(); + await tester.tap( + find.byKey(const ValueKey('anchor-handle-text-one-bottom')), + ); + await tester.pump(); + final third = _findNode( + (current['root'] as Map).cast(), + 'text-three', + )!; + final constraints = (third['constraints'] as Map?) ?? const {}; + expect((constraints['links'] as List?) ?? const [], isEmpty); + expect(find.byType(SnackBar), findsOneWidget); + }); + + testWidgets('zoom is clamped, resets, and never changes the design', ( + tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1600, 1000)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + var changes = 0; + final design = _design(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ReportTemplateStudioV3Builder( + design: design, + blockCatalog: const [ + { + 'type': 'custom_text', + 'label_fa': 'متن دلخواه', + 'allowed_regions': ['header', 'body', 'footer'], + 'default_props': {'text': 'متن'}, + }, + ], + onDesignChanged: (_) => changes++, + previewPane: const ColoredBox(color: Colors.white), + ), + ), + ), + ); + await tester.pumpAndSettle(); + for (var index = 0; index < 20; index++) { + await tester.tap(find.byKey(const ValueKey('studio-zoom-in'))); + await tester.pump(); + } + expect(find.text('250٪'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('studio-zoom-in'))); + await tester.pump(); + expect(find.text('250٪'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('studio-zoom-reset'))); + await tester.pump(); + expect(find.text('100٪'), findsOneWidget); + for (var index = 0; index < 20; index++) { + await tester.tap(find.byKey(const ValueKey('studio-zoom-out'))); + await tester.pump(); + } + expect(find.text('50٪'), findsOneWidget); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendEventToBinding( + PointerScrollEvent( + position: tester.getCenter( + find.byKey(const ValueKey('freeform-block-text-one')), + ), + scrollDelta: const Offset(0, 30), + ), + ); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pump(); + expect(find.text('50٪'), findsOneWidget); + expect(changes, 0); + expect(design.toString(), isNot(contains('zoom'))); + }); + + testWidgets('viewport resize does not change the print media profile', ( + tester, + ) async { + var changes = 0; + final design = _design(); + await tester.binding.setSurfaceSize(const Size(1600, 1000)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ReportTemplateStudioV3Builder( + design: design, + blockCatalog: const [ + { + 'type': 'custom_text', + 'label_fa': 'متن دلخواه', + 'allowed_regions': ['header', 'body', 'footer'], + 'default_props': {'text': 'متن'}, + }, + ], + onDesignChanged: (_) => changes++, + previewPane: const ColoredBox(color: Colors.white), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(reportTemplateV4ProfileKey(design), 'a4_portrait'); + await tester.binding.setSurfaceSize(const Size(700, 900)); + await tester.pumpAndSettle(); + expect(reportTemplateV4ProfileKey(design), 'a4_portrait'); + expect(changes, 0); + }); } -- 2.43.0