boxframe 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. {boxframe-0.2.0 → boxframe-0.3.0}/.gitignore +2 -1
  2. boxframe-0.3.0/.qwen/commands/bump.md +5 -0
  3. {boxframe-0.2.0 → boxframe-0.3.0}/AGENTS.md +11 -0
  4. boxframe-0.3.0/LICENSE.txt +21 -0
  5. {boxframe-0.2.0 → boxframe-0.3.0}/PKG-INFO +5 -1
  6. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/api/layouts.py +107 -37
  7. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/services/layout_service.py +140 -0
  8. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/services/renderer.py +160 -64
  9. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/static/css/editor.css +105 -41
  10. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/static/editor/index.html +54 -47
  11. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/static/js/core/history.js +46 -3
  12. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/static/js/core/renderer.js +164 -81
  13. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/static/js/core/store.js +104 -2
  14. boxframe-0.3.0/boxframe/static/js/editor.js +1851 -0
  15. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/templates/pages/editor.html +54 -47
  16. {boxframe-0.2.0 → boxframe-0.3.0}/pyproject.toml +6 -1
  17. boxframe-0.3.0/scripts/bump.sh +66 -0
  18. boxframe-0.3.0/tasks/0031-0040/0032-actions-in-panel.md +188 -0
  19. boxframe-0.3.0/tasks/0031-0040/0033-multi-selection.md +198 -0
  20. boxframe-0.3.0/tasks/0031-0040/0034-marquee-full-containment.md +91 -0
  21. boxframe-0.3.0/tasks/0031-0040/0035-box-container.md +232 -0
  22. boxframe-0.3.0/tasks/0031-0040/0036-drag-resize-no-selection.md +113 -0
  23. boxframe-0.3.0/tasks/0031-0040/0037-copy-selection-clipboard.md +133 -0
  24. {boxframe-0.2.0 → boxframe-0.3.0}/tests/api/test_layouts.py +343 -0
  25. {boxframe-0.2.0 → boxframe-0.3.0}/tests/e2e/test_editor.py +547 -12
  26. boxframe-0.3.0/tests/js/test_editor.js +447 -0
  27. {boxframe-0.2.0 → boxframe-0.3.0}/tests/js/test_history.js +170 -0
  28. {boxframe-0.2.0 → boxframe-0.3.0}/tests/js/test_renderer.js +106 -0
  29. boxframe-0.3.0/tests/js/test_store.js +342 -0
  30. {boxframe-0.2.0 → boxframe-0.3.0}/tests/test_js_renderer_parity.py +73 -0
  31. {boxframe-0.2.0 → boxframe-0.3.0}/tests/test_renderer.py +92 -0
  32. boxframe-0.2.0/boxframe/static/js/editor.js +0 -1172
  33. boxframe-0.2.0/tests/js/test_store.js +0 -156
  34. {boxframe-0.2.0 → boxframe-0.3.0}/.github/workflows/publish.yml +0 -0
  35. {boxframe-0.2.0 → boxframe-0.3.0}/.github/workflows/static.yml +0 -0
  36. {boxframe-0.2.0 → boxframe-0.3.0}/README.md +0 -0
  37. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/__init__.py +0 -0
  38. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/api/__init__.py +0 -0
  39. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/api/projects.py +0 -0
  40. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/api/test_cleanup.py +0 -0
  41. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/config.py +0 -0
  42. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/database.py +0 -0
  43. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/main.py +0 -0
  44. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/models/__init__.py +0 -0
  45. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/models/block.py +0 -0
  46. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/models/layout.py +0 -0
  47. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/models/project.py +0 -0
  48. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/services/__init__.py +0 -0
  49. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/static/css/style.css +0 -0
  50. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/static/index.html +0 -0
  51. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/static/js/alpine.min.js +0 -0
  52. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/static/js/core/import.js +0 -0
  53. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/templates/pages/404.html +0 -0
  54. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/templates/pages/base.html +0 -0
  55. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/templates/pages/project.html +0 -0
  56. {boxframe-0.2.0 → boxframe-0.3.0}/boxframe/templates/pages/projects.html +0 -0
  57. {boxframe-0.2.0 → boxframe-0.3.0}/index.html +0 -0
  58. {boxframe-0.2.0 → boxframe-0.3.0}/requirements.txt +0 -0
  59. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0000-template.md +0 -0
  60. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0001-0010/0001-fix-startup-and-add-testing.md +0 -0
  61. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0001-0010/0002-e2e-tests-cleanup.md +0 -0
  62. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0001-0010/0003-fix-new-layout-button.md +0 -0
  63. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0001-0010/0004-e2e-test-data-cleanup.md +0 -0
  64. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0001-0010/0005-add-server-logging.md +0 -0
  65. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0001-0010/0006-drag-drop-and-project-page-fix.md +0 -0
  66. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0001-0010/0007-add-block-resize-by-corner.md +0 -0
  67. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0001-0010/0008-add-block-z-order.md +0 -0
  68. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0001-0010/0009-auto-order-assignment.md +0 -0
  69. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0001-0010/0010-boxframe-layout.md +0 -0
  70. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0011-0020/0011-delete-layout-from-project.md +0 -0
  71. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0011-0020/0012-edit-block-content-inline.md +0 -0
  72. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0011-0020/0013-word-wrap-in-pseudo-graphics.md +0 -0
  73. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0011-0020/0014-line-blocks-and-border-styles.md +0 -0
  74. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0011-0020/0015-show-frame-for-none-border.md +0 -0
  75. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0011-0020/0016-single-click-block-selection.md +0 -0
  76. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0011-0020/0017-block-properties-panel.md +0 -0
  77. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0011-0020/0018-static-editor.md +0 -0
  78. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0011-0020/0019-unrestricted-block-placement.md +0 -0
  79. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0011-0020/0020-canvas-art-overlay-alignment.md +0 -0
  80. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0021-0030/0021-word-wrap-preserve-spaces.md +0 -0
  81. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0021-0030/0022-button.md +0 -0
  82. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0021-0030/0023-editor-canvas-ux.md +0 -0
  83. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0021-0030/0024-optional-layout-dimensions.md +0 -0
  84. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0021-0030/0025-static-editor-persistence.md +0 -0
  85. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0021-0030/0026-web-editor-clear-layout.md +0 -0
  86. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0021-0030/0027-editor-undo-redo.md +0 -0
  87. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0021-0030/0028-persistent-undo-buffer.md +0 -0
  88. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0021-0030/0029-pypi-publishing.md +0 -0
  89. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0021-0030/0030-import-layout-json.md +0 -0
  90. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/0031-0040/0031-remove-docker.md +0 -0
  91. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/README.md +0 -0
  92. {boxframe-0.2.0 → boxframe-0.3.0}/tasks/backlog/todo-0001-component-variants-completion.md +0 -0
  93. {boxframe-0.2.0 → boxframe-0.3.0}/tests/__init__.py +0 -0
  94. {boxframe-0.2.0 → boxframe-0.3.0}/tests/api/__init__.py +0 -0
  95. {boxframe-0.2.0 → boxframe-0.3.0}/tests/api/test_projects.py +0 -0
  96. {boxframe-0.2.0 → boxframe-0.3.0}/tests/conftest.py +0 -0
  97. {boxframe-0.2.0 → boxframe-0.3.0}/tests/e2e/__init__.py +0 -0
  98. {boxframe-0.2.0 → boxframe-0.3.0}/tests/e2e/conftest.py +0 -0
  99. {boxframe-0.2.0 → boxframe-0.3.0}/tests/e2e/test_drag_drop.py +0 -0
  100. {boxframe-0.2.0 → boxframe-0.3.0}/tests/e2e/test_projects.py +0 -0
  101. {boxframe-0.2.0 → boxframe-0.3.0}/tests/js/test_import.js +0 -0
@@ -12,6 +12,7 @@ venv/
12
12
  .mypy_cache/
13
13
  /log/
14
14
  /tmp/
15
- /.qwen/
15
+ /.qwen/*
16
+ !/.qwen/commands/
16
17
  /.idea/
17
18
  /.venv/
@@ -0,0 +1,5 @@
1
+ ---
2
+ description: Поднять минорную версию, закоммитить, нарезать тег vX.Y.Z, запушить ветку и тег (scripts/bump.sh)
3
+ ---
4
+
5
+ Выполни `bash scripts/bump.sh` и отчитайся о результате: новая версия, хэш коммита, тег, статус пуша. Если скрипт завершился ошибкой — покажи его вывод и не предпринимай никаких дальнейших действий (без force-push и ручных исправлений).
@@ -55,6 +55,8 @@ boxframe/
55
55
  │ ├── conftest.py # API-файстуры (async engine + TestClient)
56
56
  │ ├── test_js_renderer_parity.py # Parity Python↔JS рендереры
57
57
  │ └── test_renderer.py # Тесты рендерера (ASCII + HTML-оверлей)
58
+ ├── scripts/
59
+ │ └── bump.sh # Релиз: bump минора, тег vX.Y.Z, push
58
60
  ├── pyproject.toml
59
61
  ├── requirements.txt
60
62
  └── README.md
@@ -181,6 +183,15 @@ boxframe/
181
183
  2. Добавить route в `main.py`
182
184
  3. Добавить ссылки в существующие шаблоны
183
185
 
186
+ ### Релиз (bump минорной версии)
187
+
188
+ - Команда агента `/bump` (`.qwen/commands/bump.md`) — обёртка над `scripts/bump.sh`
189
+ - `bash scripts/bump.sh` — bump минора в `pyproject.toml`, commit
190
+ `chore(release): bump version to X.Y.0`, тег `vX.Y.0`, push ветки и тега
191
+ - `bash scripts/bump.sh --dry-run` — предпросмотр без изменений
192
+ - Версия живёт только в `pyproject.toml` (`boxframe/__init__.py` читает её
193
+ через `importlib.metadata`)
194
+
184
195
  ## Запуск
185
196
 
186
197
  ```bash
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sergey Shmakov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,7 +1,11 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: boxframe
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Pseudo-graphic UI mockup editor for AI agents
5
+ Project-URL: Online editor, https://sshmakov.github.io/boxframe/editor/
6
+ Project-URL: Repository, https://github.com/sshmakov/boxframe.git
7
+ Project-URL: Issues, https://github.com/sshmakov/boxframe/issues
8
+ License-File: LICENSE.txt
5
9
  Requires-Python: >=3.11
6
10
  Requires-Dist: aiosqlite>=0.20.0
7
11
  Requires-Dist: fastapi>=0.115.0
@@ -115,6 +115,45 @@ class BlocksReplace(BaseModel):
115
115
  blocks: list[BlockIn]
116
116
 
117
117
 
118
+ class BatchBlockCreate(BaseModel):
119
+ block_type: str = "box"
120
+ x: int = 0
121
+ y: int = 0
122
+ width: int = 20
123
+ height: int = 3
124
+ content: str = ""
125
+ border_style: str = "solid"
126
+ parent_id: str | None = None
127
+ meta: dict = {}
128
+ order: int = 0
129
+
130
+
131
+ class BatchBlockUpdate(BaseModel):
132
+ id: str
133
+ block_type: str | None = None
134
+ x: int | None = None
135
+ y: int | None = None
136
+ width: int | None = None
137
+ height: int | None = None
138
+ content: str | None = None
139
+ border_style: str | None = None
140
+ parent_id: str | None = None
141
+ meta: dict | None = None
142
+ order: int | None = None
143
+
144
+
145
+ class BlocksBatch(BaseModel):
146
+ create: list[BatchBlockCreate] = []
147
+ update: list[BatchBlockUpdate] = []
148
+ delete: list[str] = []
149
+
150
+
151
+ class BlocksBatchOut(BaseModel):
152
+ created: list[BlockOut] = []
153
+ updated: list[BlockOut] = []
154
+ deleted: list[str] = []
155
+
156
+
118
157
  class RenderOut(BaseModel):
119
158
  ascii: str
120
159
  html: str | None = None
@@ -159,19 +198,22 @@ async def delete_layout(layout_id: str, db: AsyncSession = Depends(get_db)):
159
198
  @router.post("/{layout_id}/blocks", response_model=BlockOut)
160
199
  async def create_block(layout_id: str, data: BlockCreate, db: AsyncSession = Depends(get_db)):
161
200
  service = LayoutService(db)
162
- block = await service.create_block(
163
- layout_id=layout_id,
164
- block_type=data.block_type,
165
- x=data.x,
166
- y=data.y,
167
- width=data.width,
168
- height=data.height,
169
- content=data.content,
170
- border_style=data.border_style,
171
- parent_id=data.parent_id,
172
- meta=data.meta,
173
- order=data.order,
174
- )
201
+ try:
202
+ block = await service.create_block(
203
+ layout_id=layout_id,
204
+ block_type=data.block_type,
205
+ x=data.x,
206
+ y=data.y,
207
+ width=data.width,
208
+ height=data.height,
209
+ content=data.content,
210
+ border_style=data.border_style,
211
+ parent_id=data.parent_id,
212
+ meta=data.meta,
213
+ order=data.order,
214
+ )
215
+ except ValueError as e:
216
+ raise HTTPException(status_code=400, detail=str(e))
175
217
  return block
176
218
 
177
219
 
@@ -183,10 +225,17 @@ async def update_block(layout_id: str, block_id: str, data: BlockUpdate, db: Asy
183
225
  raise HTTPException(status_code=404, detail="Block not found")
184
226
 
185
227
  update_data = data.model_dump(exclude_none=True)
228
+ # parent_id may be explicitly null (drag a block out of its container) —
229
+ # exclude_none would drop it, so restore it when the client set the field.
230
+ if "parent_id" in data.model_fields_set:
231
+ update_data["parent_id"] = data.parent_id
186
232
  if not update_data:
187
233
  return block
188
234
 
189
- updated = await service.update_block(block_id, **update_data)
235
+ try:
236
+ updated = await service.update_block(block_id, **update_data)
237
+ except ValueError as e:
238
+ raise HTTPException(status_code=400, detail=str(e))
190
239
  return updated
191
240
 
192
241
 
@@ -226,6 +275,38 @@ async def replace_layout_blocks(layout_id: str, data: BlocksReplace, db: AsyncSe
226
275
  return updated
227
276
 
228
277
 
278
+ @router.post("/{layout_id}/blocks/batch", response_model=BlocksBatchOut)
279
+ async def batch_blocks(layout_id: str, data: BlocksBatch, db: AsyncSession = Depends(get_db)):
280
+ """Apply a batch of block operations in a single request.
281
+
282
+ Backs the editor's multi-selection operations: group move, group
283
+ property edit, group delete, group duplicate. One request instead of
284
+ N, so the client records a single undo step.
285
+ """
286
+ service = LayoutService(db)
287
+ # parent_id may be explicitly null (drag out of a container) — restore it
288
+ # after exclude_none so the service can un-parent the block.
289
+ updates = []
290
+ for b in data.update:
291
+ d = b.model_dump(exclude_none=True)
292
+ if "parent_id" in b.model_fields_set:
293
+ d["parent_id"] = b.parent_id
294
+ updates.append(d)
295
+ try:
296
+ _, created, updated, deleted = await service.batch_blocks(
297
+ layout_id,
298
+ create=[b.model_dump() for b in data.create],
299
+ update=updates,
300
+ delete=data.delete,
301
+ )
302
+ except ValueError as e:
303
+ raise HTTPException(status_code=400, detail=str(e))
304
+ layout = await service.get_layout(layout_id)
305
+ if not layout:
306
+ raise HTTPException(status_code=404, detail="Layout not found")
307
+ return BlocksBatchOut(created=created, updated=updated, deleted=deleted)
308
+
309
+
229
310
  # ── Rendering ─────────────────────────────────────────────
230
311
 
231
312
  @router.get("/{layout_id}/render", response_model=RenderOut)
@@ -301,13 +382,16 @@ async def render_layout(
301
382
 
302
383
 
303
384
  def _serialize_blocks_for_html(blocks: list) -> list[dict]:
304
- """Serialize ORM blocks to dicts for HTML preview generation."""
385
+ """Serialize ORM blocks to nested dicts for HTML preview generation.
386
+
387
+ Children are nested recursively (arbitrary depth) so the Python HTML
388
+ preview matches the JS renderer, which builds the full tree from the
389
+ flat list. A block whose parent is missing from the set is a root.
390
+ """
305
391
  by_id = {b.id: b for b in blocks}
306
- result = []
307
- for block in blocks:
308
- if block.parent_id and block.parent_id in by_id:
309
- continue
310
- bd = {
392
+
393
+ def to_dict(block) -> dict:
394
+ return {
311
395
  "id": block.id,
312
396
  "x": block.x,
313
397
  "y": block.y,
@@ -317,24 +401,10 @@ def _serialize_blocks_for_html(blocks: list) -> list[dict]:
317
401
  "content": block.content,
318
402
  "border_style": block.border_style,
319
403
  "order": block.order,
320
- "children": [
321
- {
322
- "id": c.id,
323
- "x": c.x,
324
- "y": c.y,
325
- "width": c.width,
326
- "height": c.height,
327
- "block_type": c.block_type,
328
- "content": c.content,
329
- "border_style": c.border_style,
330
- "order": c.order,
331
- }
332
- for c in blocks
333
- if c.parent_id == block.id
334
- ],
404
+ "children": [to_dict(c) for c in blocks if c.parent_id == block.id],
335
405
  }
336
- result.append(bd)
337
- return result
406
+
407
+ return [to_dict(b) for b in blocks if not (b.parent_id and b.parent_id in by_id)]
338
408
 
339
409
 
340
410
  @router.get("/{layout_id}/export", response_model=ExportOut)
@@ -129,6 +129,11 @@ class LayoutService:
129
129
  max_order = result.scalar() or 0
130
130
  order = max_order + 1
131
131
 
132
+ # Validate a parent (exists, same layout, no cycle) before inserting
133
+ block_id = str(uuid.uuid4())
134
+ if parent_id:
135
+ await self._validate_reparent(block_id, parent_id, layout_id)
136
+
132
137
  # Lines are always 1 cell thick — the thin dimension is fixed
133
138
  if block_type == "hline":
134
139
  height = 1
@@ -136,6 +141,7 @@ class LayoutService:
136
141
  width = 1
137
142
 
138
143
  block = Block(
144
+ id=block_id,
139
145
  layout_id=layout_id,
140
146
  block_type=block_type,
141
147
  x=x,
@@ -156,6 +162,10 @@ class LayoutService:
156
162
  async def update_block(self, block_id: str, **kwargs) -> Block | None:
157
163
  block = await self.db.get(Block, block_id)
158
164
  if block:
165
+ # Validate a re-parenting before applying it (parent exists,
166
+ # same layout, no cycle)
167
+ if "parent_id" in kwargs:
168
+ await self._validate_reparent(block_id, kwargs["parent_id"], block.layout_id)
159
169
  for key, value in kwargs.items():
160
170
  if hasattr(block, key):
161
171
  setattr(block, key, value)
@@ -240,6 +250,136 @@ class LayoutService:
240
250
  async def get_block(self, block_id: str) -> Block | None:
241
251
  return await self.db.get(Block, block_id)
242
252
 
253
+ async def _validate_reparent(
254
+ self, block_id: str, parent_id: str | None, layout_id: str
255
+ ) -> None:
256
+ """Validate a re-parenting (or a create with a parent).
257
+
258
+ Raises ValueError when the parent is missing, belongs to another
259
+ layout, or the change would create a cycle (a block becoming its own
260
+ descendant — e.g. dropping a box onto one of its own children).
261
+ """
262
+ if parent_id is None:
263
+ return
264
+ if parent_id == block_id:
265
+ raise ValueError("A block cannot be its own parent")
266
+ parent = await self.db.get(Block, parent_id)
267
+ if parent is None or parent.layout_id != layout_id:
268
+ raise ValueError("Parent block not found in this layout")
269
+ # Walk up from the proposed parent; reaching the block means a cycle.
270
+ cursor_id = parent.parent_id
271
+ seen = {parent_id}
272
+ while cursor_id is not None:
273
+ if cursor_id == block_id:
274
+ raise ValueError("Cannot move a block into its own descendant")
275
+ if cursor_id in seen:
276
+ break # pre-existing cycle in the data — stop
277
+ seen.add(cursor_id)
278
+ cursor = await self.db.get(Block, cursor_id)
279
+ if cursor is None:
280
+ break
281
+ cursor_id = cursor.parent_id
282
+
283
+ async def batch_blocks(
284
+ self,
285
+ layout_id: str,
286
+ create: list[dict[str, Any]] | None = None,
287
+ update: list[dict[str, Any]] | None = None,
288
+ delete: list[str] | None = None,
289
+ ) -> tuple[Layout | None, list[Block], list[Block], list[str]]:
290
+ """Apply a batch of block operations in a single transaction.
291
+
292
+ Backs the editor's multi-selection operations (group move, group
293
+ property edit, group delete, group duplicate): one request instead
294
+ of N, and a single undo step on the client. Returns the layout
295
+ (None when not found), created blocks, updated blocks, and the
296
+ ids actually deleted.
297
+ """
298
+ layout = await self.get_layout(layout_id)
299
+ if not layout:
300
+ return None, [], [], []
301
+
302
+ created: list[Block] = []
303
+ updated: list[Block] = []
304
+ deleted: list[str] = []
305
+
306
+ for block_id in delete or []:
307
+ block = await self.db.get(Block, block_id)
308
+ if block and block.layout_id == layout_id:
309
+ await self.db.delete(block)
310
+ deleted.append(block_id)
311
+
312
+ if create:
313
+ result = await self.db.execute(
314
+ select(func.coalesce(func.max(Block.order), 0)).where(
315
+ Block.layout_id == layout_id
316
+ )
317
+ )
318
+ next_order = (result.scalar() or 0) + 1
319
+ for data in create:
320
+ block_type = data.get("block_type", "box")
321
+ width = data.get("width", 20)
322
+ height = data.get("height", 3)
323
+ # Lines are always 1 cell thick — the thin dimension is fixed
324
+ if block_type == "hline":
325
+ height = 1
326
+ elif block_type == "vline":
327
+ width = 1
328
+ order = data.get("order") or 0
329
+ if order == 0:
330
+ order = next_order
331
+ next_order += 1
332
+ parent_id = data.get("parent_id")
333
+ if parent_id:
334
+ await self._validate_reparent(
335
+ str(uuid.uuid4()), parent_id, layout_id
336
+ )
337
+ block = Block(
338
+ layout_id=layout_id,
339
+ parent_id=parent_id,
340
+ block_type=block_type,
341
+ x=data.get("x", 0),
342
+ y=data.get("y", 0),
343
+ width=width,
344
+ height=height,
345
+ content=data.get("content", ""),
346
+ border_style=data.get("border_style", "solid"),
347
+ meta=data.get("meta") or {},
348
+ order=order,
349
+ )
350
+ self.db.add(block)
351
+ created.append(block)
352
+
353
+ for data in update or []:
354
+ block = await self.db.get(Block, data.get("id"))
355
+ if not block or block.layout_id != layout_id:
356
+ continue
357
+ # Validate a re-parenting (parent_id may be None — un-parent)
358
+ if "parent_id" in data:
359
+ await self._validate_reparent(block.id, data["parent_id"], layout_id)
360
+ for key, value in data.items():
361
+ if key == "id":
362
+ continue
363
+ # parent_id may be explicitly None (drag out of a container);
364
+ # other None values are "not provided" and are skipped.
365
+ if value is None and key != "parent_id":
366
+ continue
367
+ if hasattr(block, key):
368
+ setattr(block, key, value)
369
+ # Lines are always 1 cell thick (also when block_type changes)
370
+ if block.block_type == "hline":
371
+ block.height = 1
372
+ elif block.block_type == "vline":
373
+ block.width = 1
374
+ updated.append(block)
375
+
376
+ await self.db.commit()
377
+ for block in created + updated:
378
+ await self.db.refresh(block)
379
+ self.db.expire_all()
380
+ layout = await self.get_layout(layout_id)
381
+ return layout, created, updated, deleted
382
+
243
383
  # ── Rendering ─────────────────────────────────────────────
244
384
 
245
385
  async def render_layout(self, layout_id: str) -> str | None: