ui-steps-model.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /**
  2. * The Steps view's model, without a browser: rows by the server's depth, the
  3. * words in a box by kind, one edge per pair with the Screens view's label
  4. * rule, and the panel's two lists.
  5. */
  6. import { describe, it, expect } from 'vitest';
  7. import { armWords, buildStepsModel, countWords, kindWord, kindWords, stepEdgeVisible, stepLabel, stepNeighbourhood, stepSub, stepViaText, triggerWords } from '../ui/src/lib/steps-model';
  8. import { placeLabels } from '../ui/src/lib/screens-model';
  9. import type { WireNodeRef, WireStep, WireStepLink, WireStepSite, WireStepsPayload } from '../ui/src/lib/wire';
  10. function ref(name: string, file = 'src/a.tsx', language: WireNodeRef['language'] = 'tsx'): WireNodeRef {
  11. return { id: `function:${name}`, kind: 'function', name, qualifiedName: name, file, line: 1, endLine: 9, language, test: false };
  12. }
  13. function step(label: string, kind: WireStep['kind'], depth: number, extra: Partial<WireStep> = {}): WireStep {
  14. const node = kind === 'effect' ? null : ref(label, extra.node?.file ?? 'src/a.tsx');
  15. return { id: node?.id ?? `effect:fn:${label}`, kind, anchor: depth === 0, node, label, sub: 'src/a.tsx', depth, cut: null, ...extra };
  16. }
  17. function link(from: WireStep, to: WireStep, extra: Partial<WireStepLink> = {}): WireStepLink {
  18. return { id: `${from.id} ${to.id}`, from: from.id, to: to.id, kind: 'calls', via: [], when: '', label: '', synthesized: false, uncertain: false, sites: [], ...extra };
  19. }
  20. function payload(steps: WireStep[], links: WireStepLink[]): WireStepsPayload {
  21. return {
  22. anchor: steps[0]!.node!,
  23. ambiguous: [],
  24. project: 'app',
  25. steps,
  26. links,
  27. depth: 8,
  28. limit: 120,
  29. through: false,
  30. truncated: { steps: 0, hubs: 0, chrome: 0 },
  31. index: { lastIndexedAt: null, edges: 0, files: 0 },
  32. timing: { elapsedMs: 1 },
  33. };
  34. }
  35. describe('steps model', () => {
  36. const screen = step('/capture/review', 'screen', 0, { screen: { path: '/capture/review', component: ref('ReviewScreen') } });
  37. const handler = step('handleApprove', 'trigger', 1);
  38. const bridge = step('finalizeCaptureSession', 'bridge', 2, { node: ref('finalizeCaptureSession', 'ios/CaptureView.swift', 'swift') });
  39. const event = step('handleZipComplete', 'event', 3, { event: 'onZipComplete' });
  40. const effect = step('client.post', 'effect', 4, { sub: 'network · uploadARCapture', effect: { api: 'client.post', apis: ['client.post'], category: 'network', by: ref('uploadARCapture'), line: 3 } });
  41. const store = step('setZipUri', 'store', 4, { node: ref('setZipUri', 'src/storage/capture.storage.ts') });
  42. const home = step('/', 'screen', 4, { screen: { path: '/', component: null } });
  43. const links = [
  44. link(screen, handler, { kind: 'handler', trigger: { kind: 'prop', name: 'onPress', of: 'Button', in: 'ReviewScreen' } }),
  45. link(handler, bridge, { kind: 'bridge', when: '!busy' }),
  46. link(bridge, event, { kind: 'event', synthesized: true, via: [ref('emitZipComplete', 'ios/CaptureEvents.swift', 'swift')], when: 'result', label: 'via rn-event-channel · event onZipComplete' }),
  47. link(event, effect, { kind: 'effect', via: [ref('uploadARCapture')] }),
  48. link(event, store, { kind: 'store' }),
  49. link(event, home, { kind: 'navigates', when: 'unlimited' }),
  50. // A second way from the event to the store, unconditional: the pair is one edge saying "2 ways".
  51. { ...link(event, store, { kind: 'store', when: 'retry' }), id: 'second' },
  52. ];
  53. const model = buildStepsModel(payload([screen, handler, bridge, event, effect, store, home], links));
  54. it('puts the anchor on top and each row one step further away', () => {
  55. const y = (id: string) => model.layout.nodes.find((n) => n.id === id)!.y;
  56. expect(y(screen.id)).toBeLessThan(y(handler.id));
  57. expect(y(handler.id)).toBeLessThan(y(bridge.id));
  58. expect(y(bridge.id)).toBeLessThan(y(event.id));
  59. expect(y(event.id)).toBeLessThan(y(effect.id));
  60. expect(y(effect.id)).toBe(y(store.id));
  61. expect(y(effect.id)).toBe(y(home.id));
  62. });
  63. it('one edge per pair, labelled with the innermost condition or a count', () => {
  64. const edges = [...model.edges.values()];
  65. expect(edges).toHaveLength(6);
  66. // A link into a handler says the event, not the conditions.
  67. const toHandler = edges.find((e) => e.to === handler.id)!;
  68. expect(toHandler.label).toBe('onPress · <Button>');
  69. const toBridge = edges.find((e) => e.to === bridge.id)!;
  70. expect(toBridge.label).toBe('NOT busy');
  71. expect(toBridge.kind).toBe('bridge');
  72. const toEvent = edges.find((e) => e.to === event.id)!;
  73. expect(toEvent.synthesized).toBe(true);
  74. expect(toEvent.label).toBe('result');
  75. const toStore = edges.find((e) => e.to === store.id)!;
  76. expect(toStore.links).toHaveLength(2);
  77. expect(toStore.label).toBe('2 ways · 1 conditional');
  78. expect(toStore.kind).toBe('store');
  79. });
  80. it('counts steps per kind', () => {
  81. expect(model.counts).toEqual({ anchor: 0, screen: 2, trigger: 1, bridge: 1, event: 1, store: 1, effect: 1 });
  82. });
  83. it('words a box by its kind', () => {
  84. expect(stepLabel(bridge)).toBe('⇢ finalizeCaptureSession');
  85. expect(stepLabel(event)).toBe('⇠ onZipComplete');
  86. expect(stepLabel({ ...event, events: ['onZipComplete', 'onZipError', 'onCameraReady'] })).toBe('⇠ onZipComplete +2');
  87. expect(stepLabel(screen)).toBe('/capture/review');
  88. expect(stepSub(event)).toBe('handleZipComplete · a.tsx');
  89. expect(stepSub(bridge)).toBe('native · CaptureView.swift');
  90. expect(stepSub(store)).toBe('store · capture.storage.ts');
  91. expect(stepSub(effect)).toBe('network · uploadARCapture');
  92. expect(kindWord('effect')).toBe('outside the index');
  93. expect(triggerWords({ kind: 'option', name: 'onSubmit', of: 'useFormik', in: 'LoginButton' })).toBe('onSubmit · useFormik(…)');
  94. expect(triggerWords({ kind: 'callback', name: 'addListener', of: "'onZipComplete'", in: 'X' })).toBe("addListener('onZipComplete')");
  95. expect(triggerWords({ kind: 'callback', name: 'useEffect', of: null, in: 'X' })).toBe('useEffect');
  96. expect(stepSub({ ...handler, trigger: { kind: 'prop', name: 'onPress', of: 'Button', in: 'ReviewScreen' } })).toBe('onPress · <Button> · a.tsx');
  97. expect(stepViaText(links[2]!)).toBe('emitZipComplete');
  98. });
  99. it('labels a selected step at the far end of each line, and lists its links', () => {
  100. const pills = placeLabels(model, event.id);
  101. expect(pills.hidden).toBe(0);
  102. const words = [...pills.pills.values()].map((p) => p.text).sort();
  103. expect(words).toEqual(['← result', '→ 2 ways · 1 conditional', '→ unlimited']);
  104. const lists = stepNeighbourhood(payload([screen, handler, bridge, event, effect, store, home], links), event.id);
  105. expect(lists.arrivesFrom.map((l) => l.from)).toEqual([bridge.id]);
  106. expect(lists.leadsTo.map((l) => l.to)).toEqual([effect.id, store.id, home.id, store.id]);
  107. });
  108. });
  109. describe('a decision drawn where it is made', () => {
  110. // The real shape this exists for: `return (await hasSeenWelcome(id)) ?
  111. // '/home/' : '/welcome/'` inside a store action, whose two returned routes
  112. // are two `navigates` edges out of ONE box. Each carried the whole
  113. // predicate — one of them the other's negation — and at rest the tree drew
  114. // both with no label at all, so nothing said it was a choice.
  115. const ON = 'await hasSeenWelcome(welcomeUserId())';
  116. const BRANCH = '140:9';
  117. const site = (when: string, not?: true): WireStepSite => ({
  118. file: 'src/org-user.storage.ts',
  119. line: 140,
  120. text: `push ${when}`,
  121. when,
  122. decision: { branch: BRANCH, on: ON, arm: when, form: 'ternary', ...(not ? { not: true as const } : {}) },
  123. });
  124. const anchor = step('/terms-of-service', 'screen', 0, { anchor: true });
  125. const resolve = step('resolvePostLoginRoute', 'store', 1, { node: ref('resolvePostLoginRoute', 'src/org-user.storage.ts') });
  126. const home = step('/home', 'screen', 2, { screen: { path: '/home', component: null } });
  127. const welcome = step('/welcome', 'screen', 2, { screen: { path: '/welcome', component: null } });
  128. const links = [
  129. link(anchor, resolve, { kind: 'store' }),
  130. link(resolve, home, { kind: 'navigates', when: ON, sites: [site(ON)] }),
  131. link(resolve, welcome, { kind: 'navigates', when: `!(${ON})`, sites: [site(`!(${ON})`, true)] }),
  132. ];
  133. const model = buildStepsModel(payload([anchor, resolve, home, welcome], links));
  134. const edgeTo = (id: string) => [...model.edges.values()].find((e) => e.to === id)!;
  135. it('says the condition once, under the box that decides it', () => {
  136. expect(model.decisions).toHaveLength(1);
  137. const d = model.decisions[0]!;
  138. expect(d.label).toBe('await hasSeenWelcome(welcomeUserId())?');
  139. // Under the deciding box and centred on it — not under the arms. The
  140. // condition may take more room than the box, since reading it is the
  141. // whole point of the caption.
  142. const box = model.layout.nodes.find((n) => n.id === resolve.id)!;
  143. expect(d.x + d.width / 2).toBeCloseTo(box.x + box.width / 2, 5);
  144. expect(d.width).toBeGreaterThanOrEqual(box.width);
  145. expect(d.y).toBeGreaterThan(box.y + box.height - 1);
  146. });
  147. it('each line out answers, instead of carrying the whole predicate', () => {
  148. expect(edgeTo(home.id).arm).toBe('yes');
  149. expect(edgeTo(home.id).label).toBe('yes');
  150. expect(edgeTo(welcome.id).arm).toBe('no');
  151. expect(edgeTo(welcome.id).label).toBe('no');
  152. // The line into the deciding box is not an arm of anything.
  153. expect(edgeTo(resolve.id).arm).toBeUndefined();
  154. });
  155. it('labels the arms at rest — and only the arms', () => {
  156. const arms = new Set([...model.edges.values()].filter((e) => e.arm !== undefined).map((e) => e.id));
  157. const pills = placeLabels(model, null, arms);
  158. expect([...pills.pills.values()].map((p) => p.text).sort()).toEqual(['→ no', '→ yes']);
  159. // With nothing asked for, the tree stays unlabelled as it always was.
  160. expect(placeLabels(model, null, false).pills.size).toBe(0);
  161. });
  162. it('keeps a lone arm, and a step reached either way, on a plain line', () => {
  163. // One drawn arm is a guard clause, not a choice.
  164. const only = buildStepsModel(
  165. payload([anchor, resolve, home], [link(anchor, resolve, { kind: 'store' }), link(resolve, home, { kind: 'navigates', when: ON, sites: [site(ON)] })])
  166. );
  167. expect(only.decisions).toEqual([]);
  168. expect([...only.edges.values()].every((e) => e.arm === undefined)).toBe(true);
  169. // A connector with a site that runs under NO condition is not exclusively
  170. // an arm — the step happens either way — so it never claims a side.
  171. const both = buildStepsModel(
  172. payload(
  173. [anchor, resolve, home, welcome],
  174. [
  175. link(anchor, resolve, { kind: 'store' }),
  176. link(resolve, home, { kind: 'navigates', when: ON, sites: [site(ON), { file: 'x.ts', line: 9, text: 'push', when: '' }] }),
  177. link(resolve, welcome, { kind: 'navigates', when: `!(${ON})`, sites: [site(`!(${ON})`, true)] }),
  178. ]
  179. )
  180. );
  181. expect(both.decisions).toEqual([]);
  182. });
  183. it('words a switch arm by its own value, and the default by else', () => {
  184. expect(armWords({ on: 'status', arm: "status === 'expired'", form: 'switch' })).toBe("'expired'");
  185. expect(armWords({ on: 'status', arm: 'anything', form: 'switch', not: true })).toBe('else');
  186. expect(armWords({ on: 'ready', arm: 'ready', form: 'if' })).toBe('yes');
  187. expect(armWords({ on: 'ready', arm: '!ready', form: 'if', not: true })).toBe('no');
  188. });
  189. });
  190. describe('words per project', () => {
  191. it('names the same box for an app, an API and a web app', () => {
  192. expect(kindWord('screen', 'app')).toBe('screen');
  193. expect(kindWord('screen', 'api')).toBe('endpoint');
  194. expect(kindWord('screen', 'web')).toBe('page');
  195. // A route that leads with a verb is an endpoint wherever it is.
  196. const endpoint = { id: 'r', kind: 'screen', anchor: false, node: null, label: 'POST /users', sub: 'createUser', depth: 1, cut: null, screen: { path: 'POST /users', component: null, endpoint: true, inline: false } } as const;
  197. expect(kindWord('screen', 'web', endpoint)).toBe('endpoint');
  198. expect(kindWords('store', 'api')).toEqual(['data call', 'data calls']);
  199. expect(kindWords('bridge', 'app')).toEqual(['native call', 'native calls']);
  200. expect(countWords(11, 'effect', 'api')).toBe('11 outside the index');
  201. expect(countWords(1, 'trigger')).toBe('1 handler');
  202. expect(countWords(3, 'trigger')).toBe('3 handlers');
  203. });
  204. it('says what fires a server-side step', () => {
  205. expect(triggerWords({ kind: 'request', name: 'POST', of: '/users', in: 'users.routes.ts', after: ['authenticate', 'validate(…)'] })).toBe('POST /users · after authenticate, validate(…)');
  206. expect(triggerWords({ kind: 'decorator', name: 'Process', of: "'email'", in: 'x.ts' })).toBe("@Process('email')");
  207. expect(triggerWords({ kind: 'load', name: 'GET', of: '/blog/[slug]', in: 'page.tsx' })).toBe('page load · /blog/[slug]');
  208. });
  209. });
  210. describe('row order', () => {
  211. it('lays a row out in the order the server gave, not by id', () => {
  212. const anchor = step('/login', 'screen', 0, { anchor: true });
  213. const a = step('User.findOne', 'effect', 1, { order: 0 });
  214. const b = step('jwt.sign', 'effect', 1, { order: 1 });
  215. const c = step('200', 'effect', 1, { order: 2 });
  216. const d = step('401', 'effect', 1, { order: 3 });
  217. const model = buildStepsModel(payload([anchor, d, c, b, a], [link(anchor, a), link(anchor, b), link(anchor, c), link(anchor, d)]));
  218. const row = model.layout.nodes.filter((n) => n.id !== anchor.id).sort((x, y) => x.x - y.x).map((n) => n.id);
  219. expect(row).toEqual([a.id, b.id, c.id, d.id]);
  220. });
  221. });
  222. describe('a screen laid out by region', () => {
  223. const A = { id: 'component:PanelA', label: 'PanelA' };
  224. const B = { id: 'component:PanelB', label: 'PanelB' };
  225. const anchor = step('/', 'screen', 0, { anchor: true });
  226. const a1 = step('tapSave', 'trigger', 1, { order: 0, region: A });
  227. const a2 = step('tapUndo', 'trigger', 1, { order: 1, region: A });
  228. const a3 = step('saveThing', 'store', 2, { order: 0, region: A, node: ref('saveThing', 'src/things.storage.ts') });
  229. const b1 = step('tapShare', 'trigger', 1, { order: 2, region: B, node: ref('tapShare', 'src/b.tsx') });
  230. const links = [
  231. link(anchor, a1),
  232. link(anchor, a2),
  233. link(anchor, b1),
  234. link(a1, a3, { kind: 'store' }),
  235. link(a1, b1),
  236. // Another region's way into a shared store — a lead-to line like any other.
  237. link(b1, a3, { kind: 'store' }),
  238. ];
  239. const model = buildStepsModel(payload([anchor, a1, a2, b1, a3], links));
  240. const at = (id: string) => model.layout.nodes.find((n) => n.id === id)!;
  241. const between = (id: string, zone: { x: number; width: number }) => {
  242. const n = at(id);
  243. return n.x >= zone.x && n.x + n.width <= zone.x + zone.width;
  244. };
  245. const edge = (from: string, to: string) => model.layout.edges.find((e) => e.source === from && e.target === to)!;
  246. it('names the regions in the order the walk met them, each holding its own boxes', () => {
  247. expect(model.regions!.map((z) => z.label)).toEqual(['PanelA', 'PanelB']);
  248. const [zoneA, zoneB] = model.regions!;
  249. expect(between(a1.id, zoneA!)).toBe(true);
  250. expect(between(a2.id, zoneA!)).toBe(true);
  251. expect(between(a3.id, zoneA!)).toBe(true);
  252. expect(between(b1.id, zoneB!)).toBe(true);
  253. // Side by side, not overlapping: the second region starts past the first.
  254. expect(zoneB!.x).toBeGreaterThanOrEqual(zoneA!.x + zoneA!.width);
  255. });
  256. it('keeps a step above what it sets in motion, inside its region', () => {
  257. expect(at(anchor.id).y).toBeLessThan(at(a1.id).y);
  258. expect(at(a1.id).y).toBe(at(a2.id).y);
  259. expect(at(a3.id).y).toBeGreaterThan(at(a1.id).y);
  260. });
  261. it('at rest hides only the screen’s own fan and what points back up; every other lead-to draws', () => {
  262. expect(model.regionEntries).toEqual(new Set([a1.id, b1.id]));
  263. // One line from the screen into each region stands in for its whole fan.
  264. expect(stepEdgeVisible(model, edge(anchor.id, a1.id), null)).toBe(true);
  265. expect(stepEdgeVisible(model, edge(anchor.id, a2.id), null)).toBe(false);
  266. expect(stepEdgeVisible(model, edge(anchor.id, b1.id), null)).toBe(true);
  267. // A region's internal line, and another region's way into a shared step.
  268. expect(stepEdgeVisible(model, edge(a1.id, a3.id), null)).toBe(true);
  269. expect(stepEdgeVisible(model, edge(b1.id, a3.id), null)).toBe(true);
  270. // Two boxes on one row point sideways — back-ish, a click away as everywhere.
  271. expect(stepEdgeVisible(model, edge(a1.id, b1.id), null)).toBe(false);
  272. // Selecting a step brings out everything that touches it, and only that.
  273. expect(stepEdgeVisible(model, edge(a1.id, b1.id), a1.id)).toBe(true);
  274. expect(stepEdgeVisible(model, edge(anchor.id, a2.id), a1.id)).toBe(false);
  275. });
  276. it('stacks a handler above the store it calls, even when both are one hop from the screen', () => {
  277. // Anchor distance is flat inside a region: both of these are depth 1, and
  278. // side by side their link was a level arch, hidden at rest — the store
  279. // floated. The region's own links order its rows instead.
  280. const C = { id: 'component:PanelC', label: 'PanelC' };
  281. const root = step('/', 'screen', 0, { anchor: true });
  282. const h = step('tapCopy', 'trigger', 1, { order: 0, region: C });
  283. const s = step('copyThing', 'store', 1, { order: 1, region: C, node: ref('copyThing', 'src/c.storage.ts') });
  284. const m = buildStepsModel(payload([root, h, s], [link(root, h), link(root, s), link(h, s, { kind: 'store' })]));
  285. const y = (id: string) => m.layout.nodes.find((n) => n.id === id)!.y;
  286. expect(y(s.id)).toBeGreaterThan(y(h.id));
  287. const e = m.layout.edges.find((x) => x.source === h.id && x.target === s.id)!;
  288. expect(e.route).toBe('down');
  289. expect(stepEdgeVisible(m, e, null)).toBe(true);
  290. });
  291. it('a payload without regions keeps the rows, and the Map’s at-rest rule', () => {
  292. const plain = buildStepsModel(payload([step('/x', 'screen', 0, { anchor: true }), step('go', 'trigger', 1)], [link(step('/x', 'screen', 0, { anchor: true }), step('go', 'trigger', 1))]));
  293. expect(plain.regions).toBeNull();
  294. expect(plain.regionEntries).toBeNull();
  295. });
  296. });