svg.py

clew/wiki/svg.py

A derived flow drawn as a UML sequence diagram, in SVG with no dependency.

_fold_inside

_fold_inside(
    steps: tuple[Step, ...], runs: list[tuple[int, int]], marks: dict[int, str]
)

clew/wiki/svg.py:172

Show on the map →

Called by flow_svg

Calls none

Source · 32 lines
def _fold_inside(
    steps: tuple[Step, ...], runs: list[tuple[int, int]], marks: dict[int, str]
) -> tuple[list[tuple[int, int]], set[int]]:
    """UX review A-2 (owner Q/A 2026-11-22): measured on clew's flows with block lanes, 85-95% of
    arrows were self-calls, each its own row. A RUN INSIDE ONE LANE is two or more consecutive
    drawn arrows whose call stays in the same lane, with the same mark, none shallower than the
    first (a shallower call has left the first one's subtree, so it starts a new row). A loop fold
    (`_runs`) inside it is absorbed; a lone loop fold keeps its `loop ×N` frame.

    @brief Fold internal runs.
    @return Runs and internal starts.
    """

    def inside(i: int, head: int) -> bool:
        s, h = steps[i], steps[head]
        return (
            s.from_lane == s.to_lane == h.to_lane
            and not s.not_run
            and marks.get(i, "") == marks.get(head, "")
            and s.depth >= h.depth
        )

    out: list[tuple[int, int]] = []
    merged: set[int] = set()
    for start, n in runs:
        if out and inside(start, out[-1][0]) and inside(out[-1][0], out[-1][0]):
            head, count = out[-1]
            out[-1] = (head, count + n)
            merged.add(head)
        else:
            out.append((start, n))
    return out, merged
Activity · 11 steps
lines 185–192def inside(i: int, head: int) -> bool: s, h = steps[i], steps[head] return ( s.from_lane == s.to_lane == h.to_lane and not s.not_run and marks.get(i, "") == marks.get(head, "") and s.depth >= h.depth )lines 194–194out: list[tuple[int, int]] = []lines 195–195merged: set[int] = set()lines 196–196◇ for start, n in runslines 197–197◇ if out and inside(start, out[-1][0]) and inside(out[-1][0], out[-1][0])lines 198–198head, count = out[-1]lines 199–199out[-1] = (head, count + n)lines 200–200merged.add(head)lines 201–201elselines 202–202out.append((start, n))lines 203–203return out, merged

Flows

_runs

_runs(steps: tuple[Step, ...], marks: dict[int, str] | None = None)

clew/wiki/svg.py:220

Show on the map →

Called by flow_svg

Calls none

Source · 31 lines
def _runs(steps: tuple[Step, ...], marks: dict[int, str] | None = None) -> list[tuple[int, int]]:
    """A RUN IS THE SAME CALL REPEATED WITH NOTHING UNDER IT: same caller, callee, lanes, depth and
    frames, and no deeper step after any member (a call with a subtree is never folded — its
    subtree would be hidden).

    @brief Fold runs.
    @return Runs.
    """

    def key(i: int) -> tuple:
        step = steps[i]
        return (
            (marks or {}).get(i, ""),
            step.caller_qualified or step.caller,
            step.callee_qualified or step.callee,
            step.from_lane,
            step.to_lane,
            step.depth,
            step.frames,
        )

    def leaf(i: int) -> bool:
        return i + 1 >= len(steps) or steps[i + 1].depth <= steps[i].depth

    runs: list[tuple[int, int]] = []
    for i in range(len(steps)):
        if runs and leaf(i) and key(runs[-1][0]) == key(i) and leaf(i - 1):
            runs[-1] = (runs[-1][0], runs[-1][1] + 1)
        else:
            runs.append((i, 1))
    return runs
Activity · 9 steps
lines 229–239def key(i: int) -> tuple: step = steps[i] return ( (marks or {}).get(i, ""), step.caller_qualified or step.caller, step.callee_qualified or step.callee, step.from_lane, step.to_lane, step.depth, step.frames, )lines 241–242def leaf(i: int) -> bool: return i + 1 >= len(steps) or steps[i + 1].depth <= steps[i].depthlines 244–244runs: list[tuple[int, int]] = []lines 245–245◇ for i in range(len(steps))lines 246–246◇ if runs and leaf(i) and key(runs[-1][0]) == key(i) and leaf(i - 1)lines 247–247runs[-1] = (runs[-1][0], runs[-1][1] + 1)lines 248–248elselines 249–249runs.append((i, 1))lines 250–250return runs

Flows

_step_group

_step_group(
    index: int, step: Step, shape: str, animate: bool, drawn: tuple[int, int, str] = (-1, 1, "")
)

clew/wiki/svg.py:681

Show on the map →

Called by flow_svg

Calls none

Source · 17 lines
def _step_group(
    index: int, step: Step, shape: str, animate: bool, drawn: tuple[int, int, str] = (-1, 1, "")
) -> str:
    """@brief Wrap a step. @return SVG text."""
    slot, times, mark = drawn if drawn[0] >= 0 else (index, 1, "")
    kind = " ".join(c for c in ("st", "nr" if step.not_run else "", mark) if c)
    numbers = f"{index + 1}–{index + times}" if times > 1 else f"{index + 1}"
    title = f"<title>{numbers}. {escape(step.caller)} → {escape(step.callee)}</title>"
    steps = f' data-steps="{" ".join(str(index + k) for k in range(times))}"' if times > 1 else ""
    if not animate:
        return f'<g class="{kind}" data-step="{index}"{steps}>{title}{shape}</g>'
    delay = f"{slot * STEP_SECONDS:.2f}s"
    return (
        f'<g class="{kind.replace("st", "cs")}" data-step="{index}"{steps} '
        f'style="animation-delay:{delay}">'
        f"{title}{shape}</g>"
    )
Activity · 9 steps
lines 685–685slot, times, mark = drawn if drawn[0] >= 0 else (index, 1, "")lines 686–686kind = " ".join(c for c in ("st", "nr" if step.not_run else "", mark) if c)lines 687–687numbers = f"{index + 1}–{index + times}" if times > 1 else f"{index + 1}"lines 688–688title = f"<title>{numbers}. {escape(step.caller)} → {escape(step.callee)}</title>"lines 689–689steps = f' data-steps="{" ".join(str(index + k) for k in range(times))}"' if times > 1 else ""lines 690–690◇ if not animatelines 691–691return f'<g class="{kind}" data-step="{index}"{steps}>{title}{shape}</g>'lines 692–692delay = f"{slot * STEP_SECONDS:.2f}s"lines 693–697return ( f'<g class="{kind.replace("st", "cs")}" data-step="{index}"{steps} ' f'style="animation-delay:{delay}">' f"{title}{shape}</g>" )

Flows

flow_svg

flow_svg(
    flow: Flow,
    animate: bool = False,
    marks: dict[int, str] | None = None,
    first: int = 0,
    segments: dict[int, str] | None = None,
)

clew/wiki/svg.py:114

Show on the map →

Called by _block, _flow, slice_svg, test_a_flow_svg_draws_scenario_bands, test_a_fold_never_spans_marks_or_climbs_out_of_its_subtree, test_a_run_of_calls_inside_one_lane_draws_as_one_row, test_a_step_badge_number_is_at_least_eleven_pixels, test_a_tall_diagram_repeats_its_lane_names, test_band_labels_sit_on_top_with_a_backing

Tested by

4 teststest_a_not_run_stub_is_drawn_as_a_dim_note_not_a_call, test_an_animated_diagram_plays_the_steps_in_order_with_no_script, test_repeated_calls_fold_into_one_loop_frame, test_the_actor_lane_is_drawn_first_with_an_arrow_into_the_entry

Calls _fold_inside, _runs, _step_group

Source · 49 lines
def flow_svg(
    flow: Flow,
    animate: bool = False,
    marks: dict[int, str] | None = None,
    first: int = 0,
    segments: dict[int, str] | None = None,
) -> str:
    """X-1 (owner 2026-11-22): `segments` (step index → a scenario line) draws the scenario IN the
    diagram — a labelled band from that step to the next band — rather than as a separate list.

    @brief Lay out and draw the diagram.
    @return SVG text.
    """
    marks = marks or {}
    ## UX review A-2 (owner Q/A 2026-11-22): runs of calls inside one lane fold to one row.
    runs, inside = _fold_inside(flow.steps, _runs(flow.steps, marks), marks)
    ## A segment starting inside a folded run starts at the run.
    drawn = {
        d: text
        for d, (s, n) in enumerate(runs)
        for i, text in (segments or {}).items()
        if s <= i < s + n
    }
    layout = _Layout(replace(flow, steps=tuple(flow.steps[start] for start, _n in runs)), drawn)
    parts = [
        f'<svg class="seq" xmlns="http://www.w3.org/2000/svg" width="{layout.width}" '
        f'height="{layout.height}" viewBox="0 0 {layout.width} {layout.height}" role="img" '
        f'aria-label="Sequence from {escape(flow.entry)}">',
        _STYLE,
    ]
    if animate:
        parts.append(_ANIMATION)
    parts += layout.bands_markup()
    parts += layout.lanes_markup()
    parts += layout.frames_markup()
    parts += [
        layout.repeat_frame(d, n) for d, (s, n) in enumerate(runs) if n > 1 and s not in inside
    ]
    parts += layout.activations_markup()
    for d, (start, n) in enumerate(runs):
        mark = marks.get(start, "")
        shape = layout.step_markup(d, first + start + 1, n, start in inside)
        if "entry" in mark:
            shape += layout.entry_marker(d)
        group = _step_group(first + start, flow.steps[start], shape, animate, (d, n, mark))
        parts.append(group)
    parts += layout.band_labels_markup()
    parts.append("</svg>")
    return "".join(parts)
Activity · 22 steps
lines 127–127marks = marks or {}lines 129–129runs, inside = _fold_inside(flow.steps, _runs(flow.steps, marks), marks)lines 131–136drawn = { d: text for d, (s, n) in enumerate(runs) for i, text in (segments or {}).items() if s <= i < s + n }lines 137–137layout = _Layout(replace(flow, steps=tuple(flow.steps[start] for start, _n in runs)), drawn)lines 138–143parts = [ f'<svg class="seq" xmlns="http://www.w3.org/2000/svg" width="{layout.width}" ' f'height="{layout.height}" viewBox="0 0 {layout.width} {layout.height}" role="img" ' f'aria-label="Sequence from {escape(flow.entry)}">', _STYLE, ]lines 144–144◇ if animatelines 145–145parts.append(_ANIMATION)lines 146–146parts += layout.bands_markup()lines 147–147parts += layout.lanes_markup()lines 148–148parts += layout.frames_markup()lines 149–151parts += [ layout.repeat_frame(d, n) for d, (s, n) in enumerate(runs) if n > 1 and s not in inside ]lines 152–152parts += layout.activations_markup()lines 153–153◇ for d, (start, n) in enumerate(runs)lines 154–154mark = marks.get(start, "")lines 155–155shape = layout.step_markup(d, first + start + 1, n, start in inside)lines 156–156◇ if "entry" in marklines 157–157shape += layout.entry_marker(d)lines 158–158group = _step_group(first + start, flow.steps[start], shape, animate, (d, n, mark))lines 159–159parts.append(group)lines 160–160parts += layout.band_labels_markup()lines 161–161parts.append("</svg>")lines 162–162return "".join(parts)

Flows