outwest.dev

VueComponentTeleportExperiment

Building a Tiling Window Manager in Vue 3 with Teleport

· 12 min read

A while back I wrote about recursive components while I was working on a window manager in Vue 3. That project is now a small library called vue-tiler. It splits the screen into panes, side by side or stacked, and lets you drag your own components into those panes and resize them.

The vue-tiler demo: a sidebar of draggable widgets next to four panes in two columns, showing a line chart, a stopwatch with laps, a notes editor and a photo.

Splitting a box into smaller boxes isn't the hard part. The requirement that shaped everything else was this one: a component must keep its state when it moves. If you've typed half a note, started a stopwatch or scrolled a table, then dragging that widget to another pane, splitting its pane or closing the pane entirely shouldn't throw any of that away.

This post walks through how it works, and the one mistake I made along the way that's worth knowing about if you use <Teleport> yourself.

Why Moving a Component Loses Its State

In Vue, a component instance belongs to the spot in the template that rendered it. Say every pane renders whichever widget it's showing:

<ThePane v-for="pane in panes" :key="pane.id">
  <component :is="widgetFor(pane)" />
</ThePane>

When you move the notes widget from pane 1 to pane 2, Vue sees one <component> that no longer renders and another that now does. It unmounts the first instance and mounts a brand-new one in pane 2. The new instance starts from scratch, and everything in its refs is gone.

<KeepAlive> doesn't help here either. It caches instances that are switched in and out of one spot. It can't move an instance to a different parent.

What we need is a component that's mounted exactly once and stays put in the component tree, while its DOM shows up wherever we want. That's what <Teleport> does. (If you've used portal-vue in Vue 2, it's the same idea, built in.)

Mount Once, Change the Target

<Teleport> renders its content into a different DOM element, given by its to prop. The key detail is that changing to moves the existing DOM nodes; it doesn't re-create the component. The instance, its state and its watchers all stay exactly where they were in the component tree. Only its elements move.

So instead of each pane rendering a widget, the tiler renders every widget once, each inside its own <Teleport>, and points each one at the pane showing it. The first working version looked roughly like this:

<template>
  <TheTiler :panes="panes" @pane:dropped="handlePaneDropped" />

  <Teleport
    v-for="widget in widgets"
    :key="widget.id"
    :to="widget.target || '#hidden'"
  >
    <component :is="widget.component" />
  </Teleport>
</template>

Each pane had an element with an id like dropzone-2. Dropping a widget on pane 2 set that widget's target to '#dropzone-2', and Vue moved it there. A widget that wasn't in any pane went to #hidden, a hidden element, so it stayed mounted while you couldn't see it. That's also how a widget survives its pane being closed: it goes back to the hidden element until you drop it somewhere else.

This worked, and it's still the core of the library. But it only supported panes side by side in one row, and growing it into nested splits is where things got interesting.

The Layout Is a Tree

To split panes both side by side and stacked, at any depth, the layout becomes the binary tree from the recursive component post. It's actually slightly more general than that: a split can have any number of children. There are two kinds of nodes:

interface PaneNode {
  type: 'pane';
  id: PaneId;
  order: number;              // creation order, more on this below
  widgetId: WidgetId | null;  // the widget it's showing, if any
}

interface SplitNode {
  type: 'split';
  id: string;
  direction: 'row' | 'column';  // side by side, or stacked
  children: LayoutNode[];       // at least two
  sizes: number[];              // each child's share, in percent
}

type LayoutNode = PaneNode | SplitNode;

Notice that panes store which widget they show, and widgets store nothing. The layout is plain data. You can JSON.stringify it into local storage and pass it back in later to restore someone's workspace, and the component uses it with v-model:layout.

The functions that change the tree (splitPane, removePane, addPane and placeWidget) are plain TypeScript with no Vue in them. Each one keeps two rules true: every split has at least two children and its sizes add up to 100, and a split never directly contains another split in the same direction. If you split a pane side by side and it's already inside a row, the new pane joins that row instead of nesting a new one. Keeping the tree in that shape means there's only one way to describe any given layout, which made the rest of the code a lot easier to reason about.

Don't Render the Tree Recursively

In the recursive component post, I guessed that the window manager would render this tree with a recursive component: a split renders a flex container, and each child renders another split or a pane. That was the plan, and it's the mistake I mentioned at the start.

Here's what happens when you split pane 2 side by side, in a layout where pane 2 sits inside a stacked split:

before                          after
split (column)                  split (column)
├─ pane 1                       ├─ pane 1
└─ pane 2                       └─ split (row)      ← new
                                   ├─ pane 2        ← same pane, new parent
                                   └─ pane 3

Pane 2 is the same pane, but it now has a new parent. In a recursive render, that means a new parent component, and Vue can't move a component instance to a new parent any more than it could move our widgets. So it unmounts pane 2 and mounts a fresh one. Pane 2's content element is destroyed, and that element was the teleport target of whatever widget pane 2 was showing.

Teleport gets the widget out alive: its instance never lived inside the pane, so when the target changes Vue moves its DOM into the new element. But the panes themselves get torn down and rebuilt on every split, and any DOM moves around more than it needs to. As we'll see, moving DOM isn't free either.

The fix is to not render the tree as a tree. layoutToRects walks it once and turns it into a flat list, where each pane gets its distance from each edge of the tiler, in percent:

const layoutToRects = (root) => {
  const panes = [];
  const dividers = [];

  const visit = (node, insets) => {
    if (node.type === 'pane') {
      panes.push({ pane: node, insets });
      return;
    }

    // 'row' splits divide left to right, 'column' splits top to bottom.
    const [startEdge, endEdge] = node.direction === 'row'
      ? ['left', 'right']
      : ['top', 'bottom'];
    const start = insets[startEdge];
    const span = 100 - insets[startEdge] - insets[endEdge];
    let offset = 0;

    node.children.forEach((child, index) => {
      const childStart = start + (span * offset) / 100;
      offset += node.sizes[index];
      const childEnd = start + (span * offset) / 100;

      visit(child, { ...insets, [startEdge]: childStart, [endEdge]: 100 - childEnd });

      if (index < node.children.length - 1) {
        dividers.push({ id: `${node.id}:${index}`, split: node, index, insets, position: childEnd });
      }
    });
  };

  if (root) {
    visit(root, { top: 0, right: 0, bottom: 0, left: 0 });
  }

  panes.sort((a, b) => a.pane.order - b.pane.order);

  return { panes, dividers };
};

The recursion is still there, but it's in a plain function rather than in the component tree. Every pane then renders as a direct child of the tiler, absolutely positioned from its insets:

<TilerPane
  v-for="{ pane, insets } in rects.panes"
  :key="pane.id"
  :pane="pane"
  :insets="insets"
/>

Now splitting pane 2 only changes its insets. Same parent, same key, so Vue patches four style values and leaves the element alone.

That sort at the end is there for the same reason. A keyed v-for keeps each element, but if the order of existing items changes, Vue reorders the DOM to match, and reordering means moving elements. Vue's diff is good at keeping moves to a minimum, but sorting by creation order guarantees there are none: new panes are always added at the end, and the order of existing panes can never change, whatever the layout helpers do to the tree.

Why Moving DOM Matters

The browser treats a moved element as removed and re-inserted. For most elements you can't tell, but an <iframe> reloads, and a playing <video> or <audio> pauses. Vue's state survives the move, but the browser's state inside those elements doesn't.

Moving a widget to another pane still has to move its DOM, so widgets built around an iframe will reload when you move them. That's a limit of the platform, and it's in the README. What the flat render guarantees is that nothing else moves: splitting, resizing and closing a neighbor leave a widget's DOM exactly where it is.

Teleport to an Element, Not a Selector

The first version teleported to selectors like '#dropzone-2'. That has two problems. Ids are global, so two tilers on one page would fight over #dropzone-1. And a selector is just a string, so nothing tells Vue when the element it points to appears or goes away.

to also accepts an element, so each pane hands its content element up to the tiler when it mounts and takes it back when it unmounts:

// TilerPane.vue
onMounted(() => emit('content-element', contentElement.value));
onBeforeUnmount(() => emit('content-element', null));

The tiler keeps those in a reactive Map, and works out each widget's target from the layout:

const paneContentElements = shallowReactive(new Map());

// Widgets not shown in any pane stay mounted here, out of sight.
const parkingElement = document.createElement('div');
parkingElement.hidden = true;

onBeforeMount(() => document.body.appendChild(parkingElement));
onUnmounted(() => parkingElement.remove());

const getTeleportTarget = (widget) => {
  const paneId = placements.value.get(widget.id);

  return (paneId !== undefined && paneContentElements.get(paneId)) || parkingElement;
};
<Teleport
  v-for="widget in widgets"
  :key="widget.id"
  :to="getTeleportTarget(widget)"
>
  <component :is="toRaw(widget.component)" v-bind="widget.props" />
</Teleport>

Because the map is reactive, a widget's target updates as soon as its pane's element exists, and falls back to the parking element when it doesn't. Each tiler creates its own parking element, so several tilers on a page don't interfere. And since placements is computed from the layout, there's one source of truth: which pane shows a widget is decided entirely by the layout tree.

The toRaw is there because the widget list is often reactive, and Vue warns when a component definition is made reactive. The first version used markRaw on each component for the same reason, but that relied on the user remembering to do it.

Resizing

Each divider sits between two children of a split and resizes only those two. While you drag, it works out where the pointer is as a percentage of the split, then gives each side its share:

sizes[before] = position - start;
sizes[after] = end - position;

position is clamped so both panes keep a minimum size. If the two panes are already too small for that minimum, each can shrink to a quarter of their combined space instead, so the divider never locks in place.

The divider also calls setPointerCapture when you press on it. Without capture, pointermove events go to whatever is under the pointer. Drag quickly over a widget with an iframe in it and the iframe swallows the events, so the divider stops moving. With capture, every pointer event goes to the divider until you let go, even outside the browser window.

Drag and Drop

Widgets are dragged with the native HTML Drag and Drop API, and there are two details worth copying.

First, widget drags carry their own data type, application/x-tiler-widget. During dragover you can't read a drag's data yet, but you can see its types. So panes can tell a widget apart from a file or a link dragged in from somewhere else, and ignore everything that isn't a widget.

Second, dragenter and dragleave fire every time the pointer crosses into or out of a child element, not just the pane itself. Toggling a highlight class on each event makes it flicker as you move over the widget's contents. Counting instead fixes it:

const dragDepth = ref(0);
const isDropTarget = computed(() => dragDepth.value > 0);

const handleDragEnter = (event) => {
  if (!isWidgetDrag(event)) return;
  event.preventDefault();
  dragDepth.value++;
};

const handleDragLeave = (event) => {
  if (isWidgetDrag(event)) {
    dragDepth.value = Math.max(0, dragDepth.value - 1);
  }
};

Every enter has a matching leave, so the count is above zero exactly while the pointer is somewhere inside the pane. A drop resets it to zero.

The Trade-offs

Mounting every widget up front is what makes state survival simple, but it has costs worth knowing about:

  • Every widget runs all the time. A widget sitting in the parking element still mounts, fetches its data and runs its timers. That's the point for a stopwatch, but a list of fifty heavy widgets would all mount when the page loads.
  • It's client-side only. The tiler creates its parking element with document.createElement during setup, which fails on the server, and the pane elements widgets teleport into only exist once the panes mount in the browser. In Nuxt, wrap it in <ClientOnly>.

What I'd Change Next

The biggest gap is keyboard and assistive technology support. The dividers have role="separator", but they can't take focus and don't report their position, so you can only resize with a pointer. The ARIA window splitter pattern describes what's missing: tabindex="0", aria-valuenow, and arrow keys to move the divider. Placing a widget has the same problem, since native drag and drop has no keyboard equivalent. A "Move to pane" menu in each widget's header would cover that without changing the drag and drop code at all.

Those both fit nicely into the existing design, because everything goes through the layout helpers. A keyboard-driven divider only needs to change sizes, and a menu only needs to call placeWidget. The rendering doesn't change.

Conclusion

The library has more pieces than this, but the core idea is small. Mount every component once, and use <Teleport> to decide where its DOM appears. Then make sure the elements you teleport into are as stable as the components themselves, which is why the layout tree is rendered flat.

View Repo With Source