File size: 9,252 Bytes
2740e39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Groups work like functions in Unreal Engine Blueprints: a group node collapses a set
// of nodes into one card; double-click opens it and shows only its contents.
// Membership is stored on each node as data.groupId (null = top level of the board).

import { MarkerType } from '@xyflow/react';
import { getNodeSize } from './layout';
import { isDoneQuest, isQuest, questXp } from './quests';

export const PORTAL_IN_ID = '__portal_in__';
export const PORTAL_OUT_ID = '__portal_out__';

export const groupOf = (node) => node?.data?.groupId || null;

export const isVirtualNode = (id) => id === PORTAL_IN_ID || id === PORTAL_OUT_ID;
export const isVirtualEdge = (edge) => Boolean(edge?.data?.virtual);

/** Group nodes from the top level down to `groupId` (inclusive). */
export const getGroupPath = (nodes, groupId) => {
  const byId = new Map(nodes.map((n) => [n.id, n]));
  const path = [];
  const seen = new Set();
  let current = groupId ? byId.get(groupId) : null;
  while (current && !seen.has(current.id)) {
    seen.add(current.id);
    path.unshift(current);
    current = groupOf(current) ? byId.get(groupOf(current)) : null;
  }
  return path;
};

/** Every node inside the group, at any depth. */
export const getDescendants = (nodes, groupId) => {
  const result = [];
  const queue = [groupId];
  const seen = new Set(queue);
  while (queue.length) {
    const g = queue.shift();
    nodes.forEach((n) => {
      if (groupOf(n) === g && !seen.has(n.id)) {
        seen.add(n.id);
        result.push(n);
        if (n.type === 'cluster') queue.push(n.id);
      }
    });
  }
  return result;
};

/** Is `candidateId` the group itself or nested inside it? (used to forbid cycles) */
export const isInsideGroup = (nodes, candidateId, groupId) =>
  candidateId === groupId || getDescendants(nodes, groupId).some((n) => n.id === candidateId);

export const groupStats = (nodes, groupId) => {
  const inside = getDescendants(nodes, groupId);
  const quests = inside.filter(isQuest);
  const done = quests.filter(isDoneQuest);
  return {
    total: quests.length,
    done: done.length,
    xpEarned: done.reduce((s, n) => s + questXp(n), 0),
    xpTotal: quests.reduce((s, n) => s + questXp(n), 0),
    groups: inside.filter((n) => n.type === 'cluster').length,
    preview: quests
      .slice()
      .sort((a, b) => (a.data?.status === 'Done') - (b.data?.status === 'Done'))
      .slice(0, 4)
      .map((n) => ({ id: n.id, label: n.data?.label || '', done: n.data?.status === 'Done' })),
  };
};

/**
 * Builds what React Flow should show for the current view:
 * - nodes outside the current group are hidden (they stay in state, so saving keeps them),
 * - with `hideDone`, finished quests disappear (after their leave animation),
 * - edges into a collapsed group are drawn to the group card (proxy edges),
 * - inside a group, links to the outside world end at "entry"/"exit" portal cards.
 */
export const buildCanvasView = ({ nodes, edges, currentGroupId, hideDone, leavingIds, appearIds, onPortalJump, virtualSizes = {} }) => {
  const byId = new Map(nodes.map((n) => [n.id, n]));

  // The node that represents `id` in the current view (itself or its collapsed group)
  const repCache = new Map();
  const rep = (id) => {
    if (repCache.has(id)) return repCache.get(id);
    let node = byId.get(id);
    const seen = new Set();
    while (node && groupOf(node) !== currentGroupId && !seen.has(node.id)) {
      seen.add(node.id);
      node = groupOf(node) ? byId.get(groupOf(node)) : null;
    }
    const result = node && groupOf(node) === currentGroupId ? node.id : null;
    repCache.set(id, result);
    return result;
  };

  const statsCache = new Map();
  const displayNodes = nodes.map((n) => {
    const inView = groupOf(n) === currentGroupId && n.type !== 'habit';
    // A quest finished a moment ago stays briefly (the reward is showing), then fades out
    const justDone = hideDone && isDoneQuest(n) && n.data?.completedAt && Date.now() - Date.parse(n.data.completedAt) < 1400;
    const leaving = leavingIds.has(n.id) || justDone;
    const doneHidden = hideDone && isDoneQuest(n) && !leaving;
    const hidden = !inView || doneHidden;
    const className = leaving ? (justDone ? 'tf-node-leaving tf-late' : 'tf-node-leaving') : appearIds.has(n.id) ? 'tf-node-appear' : undefined;

    let next = n;
    if (n.type === 'cluster' && inView) {
      const stats = groupStats(nodes, n.id);
      statsCache.set(n.id, stats);
      next = { ...n, data: { ...n.data, groupStats: stats } };
    }
    if (next.hidden !== hidden || next.className !== className) {
      next = { ...next, hidden, className };
    }
    return next;
  });

  // Stickers, images and texts that only hang on hidden finished quests go away with them
  if (hideDone) {
    const shownById = new Map(displayNodes.map((n) => [n.id, n]));
    const doneHidden = (id) => {
      const n = shownById.get(id);
      return n && isDoneQuest(n) && (n.hidden || leavingIds.has(n.id) || (n.className || '').includes('tf-node-leaving'));
    };
    displayNodes.forEach((n, i) => {
      if (n.hidden || !['comment', 'image', 'text'].includes(n.type)) return;
      const linked = edges.filter((e) => e.source === n.id || e.target === n.id).map((e) => (e.source === n.id ? e.target : e.source));
      if (!linked.length || !linked.every(doneHidden)) return;
      const leavingNow = linked.some((id) => !shownById.get(id).hidden);
      displayNodes[i] = leavingNow
        ? { ...n, className: shownById.get(linked[0]).className || 'tf-node-leaving' }
        : { ...n, hidden: true, className: undefined };
    });
  }

  const displayEdges = [];
  const proxyKeys = new Set();
  const incoming = new Map(); // inside target -> outside sources
  const outgoing = new Map(); // inside source -> outside targets

  edges.forEach((e) => {
    const s = rep(e.source);
    const t = rep(e.target);
    if (s === e.source && t === e.target) {
      displayEdges.push(e);
      return;
    }
    if (s && t) {
      if (s === t) return; // both ends inside the same collapsed group
      const key = `${s}->${t}`;
      if (proxyKeys.has(key)) return;
      proxyKeys.add(key);
      displayEdges.push({
        id: `proxy-${e.id}`,
        source: s,
        target: t,
        sourceHandle: s === e.source ? e.sourceHandle : 'main-source',
        targetHandle: t === e.target ? e.targetHandle : 'main-target',
        type: e.type === 'sticker' ? 'sticker' : undefined,
        selectable: false,
        deletable: false,
        focusable: false,
        data: { virtual: true, proxy: true },
        style: { stroke: '#a855f7', strokeWidth: 2.5, strokeDasharray: '2 6' },
        markerEnd: { type: MarkerType.ArrowClosed, color: '#a855f7' },
      });
      return;
    }
    if (!currentGroupId) return;
    // One end is outside the open group
    if (t && !s) {
      if (!incoming.has(t)) incoming.set(t, []);
      incoming.get(t).push(e.source);
    } else if (s && !t) {
      if (!outgoing.has(s)) outgoing.set(s, []);
      outgoing.get(s).push(e.target);
    }
  });

  // Portal cards for links that leave the open group
  if (currentGroupId && (incoming.size || outgoing.size)) {
    const visible = displayNodes.filter((n) => !n.hidden);
    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
    visible.forEach((n) => {
      const { width, height } = getNodeSize(n);
      minX = Math.min(minX, n.position.x);
      minY = Math.min(minY, n.position.y);
      maxX = Math.max(maxX, n.position.x + width);
      maxY = Math.max(maxY, n.position.y + height);
    });
    if (!visible.length) {
      minX = 0; minY = 0; maxX = 400; maxY = 200;
    }
    const midY = (minY + maxY) / 2;
    const label = (id) => byId.get(id)?.data?.label || '';
    const portal = (id, direction, map, x) => {
      const items = [...new Set([...map.values()].flat())].map((nid) => ({ id: nid, label: label(nid) }));
      displayNodes.push({
        id,
        type: 'portal',
        position: { x, y: midY - 60 },
        draggable: false,
        selectable: false,
        deletable: false,
        connectable: false,
        data: { direction, items, onJump: onPortalJump },
        // Virtual nodes are not in state, so their measured size is kept by the page
        ...(virtualSizes[id] ? { measured: virtualSizes[id] } : {}),
      });
      map.forEach((_, insideId) => {
        displayEdges.push({
          id: `${id}-${insideId}`,
          source: direction === 'in' ? id : insideId,
          target: direction === 'in' ? insideId : id,
          sourceHandle: direction === 'in' ? 'portal-source' : 'main-source',
          targetHandle: direction === 'in' ? 'main-target' : 'portal-target',
          selectable: false,
          deletable: false,
          focusable: false,
          data: { virtual: true },
          style: { stroke: '#a855f7', strokeWidth: 2, strokeDasharray: '2 6', opacity: 0.8 },
          markerEnd: { type: MarkerType.ArrowClosed, color: '#a855f7' },
        });
      });
    };
    if (incoming.size) portal(PORTAL_IN_ID, 'in', incoming, minX - 340);
    if (outgoing.size) portal(PORTAL_OUT_ID, 'out', outgoing, maxX + 140);
  }

  return { displayNodes, displayEdges };
};