Add page editing and publish
This commit is contained in:
@@ -0,0 +1,142 @@
|
||||
"""Операции над деревом блоков в «сыром» front matter (dict): добавить, переместить, удалить.
|
||||
|
||||
Работаем с исходной структурой, а не с dataclass-ами: так сохраняются неизвестные ключи и
|
||||
порядок. Блоки адресуются по `id`, не по индексу (принцип 4 ТЗ, ADR-004).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
import string
|
||||
from typing import Iterator
|
||||
|
||||
_ALPHABET = string.ascii_lowercase + string.digits
|
||||
|
||||
|
||||
def _blocks_of(container: dict) -> Iterator[dict]:
|
||||
"""Блоки одного списка региона/слота вместе с вложенными."""
|
||||
yield container
|
||||
for slot in (container.get("slots") or {}).values():
|
||||
if isinstance(slot, list):
|
||||
for child in slot:
|
||||
if isinstance(child, dict):
|
||||
yield from _blocks_of(child)
|
||||
|
||||
|
||||
def all_blocks(meta: dict) -> Iterator[dict]:
|
||||
for items in (meta.get("regions") or {}).values():
|
||||
if isinstance(items, list):
|
||||
for block in items:
|
||||
if isinstance(block, dict):
|
||||
yield from _blocks_of(block)
|
||||
|
||||
|
||||
def all_ids(meta: dict) -> set[str]:
|
||||
return {b["id"] for b in all_blocks(meta) if isinstance(b.get("id"), str)}
|
||||
|
||||
|
||||
def _sibling_lists(meta: dict) -> Iterator[list]:
|
||||
def walk(items: list) -> Iterator[list]:
|
||||
yield items
|
||||
for block in items:
|
||||
if isinstance(block, dict):
|
||||
for slot in (block.get("slots") or {}).values():
|
||||
if isinstance(slot, list):
|
||||
yield from walk(slot)
|
||||
|
||||
for items in (meta.get("regions") or {}).values():
|
||||
if isinstance(items, list):
|
||||
yield from walk(items)
|
||||
|
||||
|
||||
def find_block(meta: dict, block_id: str) -> tuple[list, int, dict] | None:
|
||||
for siblings in _sibling_lists(meta):
|
||||
for index, block in enumerate(siblings):
|
||||
if isinstance(block, dict) and block.get("id") == block_id:
|
||||
return siblings, index, block
|
||||
return None
|
||||
|
||||
|
||||
def new_block_id(meta: dict) -> str:
|
||||
taken = all_ids(meta)
|
||||
while True:
|
||||
candidate = "b_" + "".join(secrets.choice(_ALPHABET) for _ in range(5))
|
||||
if candidate not in taken:
|
||||
return candidate
|
||||
|
||||
|
||||
def add_block(meta: dict, fragment_id: str, *, region: str | None = None,
|
||||
parent: str | None = None, slot: str | None = None) -> str:
|
||||
"""Добавляет пустой блок в конец региона или слота родителя. Возвращает id нового блока."""
|
||||
block = {"id": new_block_id(meta), "fragment": fragment_id}
|
||||
if parent:
|
||||
found = find_block(meta, parent)
|
||||
if found is None or not slot:
|
||||
raise KeyError(f"нет блока «{parent}» или не указан слот")
|
||||
slots = found[2].setdefault("slots", {})
|
||||
slots.setdefault(slot, []).append(block)
|
||||
elif region:
|
||||
regions = meta.setdefault("regions", {})
|
||||
if not isinstance(regions.get(region), list):
|
||||
regions[region] = []
|
||||
regions[region].append(block)
|
||||
else:
|
||||
raise KeyError("нужен region или parent+slot")
|
||||
return block["id"]
|
||||
|
||||
|
||||
def move_block(meta: dict, block_id: str, direction: str) -> bool:
|
||||
"""`up`/`down` в пределах своего списка. False, если двигаться некуда."""
|
||||
found = find_block(meta, block_id)
|
||||
if found is None:
|
||||
raise KeyError(block_id)
|
||||
siblings, index, _ = found
|
||||
target = index - 1 if direction == "up" else index + 1
|
||||
if direction not in ("up", "down") or not 0 <= target < len(siblings):
|
||||
return False
|
||||
siblings[index], siblings[target] = siblings[target], siblings[index]
|
||||
return True
|
||||
|
||||
|
||||
def delete_block(meta: dict, block_id: str) -> None:
|
||||
found = find_block(meta, block_id)
|
||||
if found is None:
|
||||
raise KeyError(block_id)
|
||||
siblings, index, _ = found
|
||||
del siblings[index]
|
||||
|
||||
|
||||
def set_hidden(meta: dict, block_id: str, hidden: bool) -> None:
|
||||
found = find_block(meta, block_id)
|
||||
if found is None:
|
||||
raise KeyError(block_id)
|
||||
block = found[2]
|
||||
if hidden:
|
||||
block["hidden"] = True
|
||||
else:
|
||||
block.pop("hidden", None)
|
||||
|
||||
|
||||
def replace_block_fields(block: dict, *, props: dict, manifest_keys: set[str], hidden: bool,
|
||||
anchor: str | None, note: str | None, requires: list[str]) -> None:
|
||||
"""Обновляет props и настройки блока. Ключи props, которых нет в манифесте, сохраняются
|
||||
как есть (их пометит валидация), чтобы правка формы ничего не теряла молча."""
|
||||
old = block.get("props") if isinstance(block.get("props"), dict) else {}
|
||||
merged = dict(props)
|
||||
for key, value in old.items():
|
||||
if key not in manifest_keys and key not in merged:
|
||||
merged[key] = value
|
||||
if merged:
|
||||
block["props"] = merged
|
||||
else:
|
||||
block.pop("props", None)
|
||||
for key, value in (("hidden", True if hidden else None), ("anchor", anchor or None),
|
||||
("note", note or None), ("requires", requires or None)):
|
||||
if value is None:
|
||||
block.pop(key, None)
|
||||
else:
|
||||
block[key] = value
|
||||
|
||||
|
||||
def region_names(meta: dict) -> list[str]:
|
||||
return list((meta.get("regions") or {}).keys())
|
||||
Reference in New Issue
Block a user