|
| 1 | +/** |
| 2 | + * ObjectUI |
| 3 | + * Copyright (c) 2024-present ObjectStack Inc. |
| 4 | + * |
| 5 | + * This source code is licensed under the MIT license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * objectstack#27056 — the record page's related column loads counts first, |
| 11 | + * then the first rows of only the cards in view, and never blocks the details. |
| 12 | + * |
| 13 | + * The REAL page, at a desktop width (the column tiers), over a data source |
| 14 | + * that holds every related read until the test answers it. The record has six |
| 15 | + * related lists. Measured: |
| 16 | + * |
| 17 | + * - the details draw from the record read alone, while every related read is |
| 18 | + * still out, and the related column shows one placeholder per card; |
| 19 | + * - the six counts go out as ONE request set, before any of them answers; |
| 20 | + * - once they answer, rows are read for the two counted cards in view only, |
| 21 | + * three rows each — never for a card counted at 0 (in view too), never for |
| 22 | + * the cards below the fold. |
| 23 | + */ |
| 24 | +import * as React from 'react'; |
| 25 | +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; |
| 26 | +import { render, cleanup, act } from '@testing-library/react'; |
| 27 | +import { MemoryRouter } from 'react-router-dom'; |
| 28 | +import { MetadataCtx } from '@object-ui/react'; |
| 29 | +import { RelatedCountStore } from '@object-ui/components'; |
| 30 | + |
| 31 | +vi.mock('@object-ui/auth', async (importOriginal) => ({ |
| 32 | + ...(await importOriginal<Record<string, unknown>>()), |
| 33 | + useAuth: () => ({ user: { id: 'u1', name: 'Ada', image: null }, activeOrganization: null }), |
| 34 | + createAuthenticatedFetch: () => vi.fn(), |
| 35 | +})); |
| 36 | +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ |
| 37 | + ...(await importOriginal<Record<string, unknown>>()), |
| 38 | + useRecordPresence: () => [], |
| 39 | + PresenceAvatars: () => null, |
| 40 | +})); |
| 41 | +vi.mock('sonner', () => ({ |
| 42 | + toast: Object.assign(vi.fn(), { |
| 43 | + success: vi.fn(), error: vi.fn(), info: vi.fn(), |
| 44 | + warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(), |
| 45 | + }), |
| 46 | +})); |
| 47 | +// Orthogonal chrome — stubbed so the only asynchrony here is the page's own. |
| 48 | +vi.mock('./ActionConfirmDialog', () => ({ ActionConfirmDialog: () => null })); |
| 49 | +vi.mock('./ActionParamDialog', () => ({ ActionParamDialog: () => null })); |
| 50 | +vi.mock('./ActionResultDialog', () => ({ ActionResultDialog: () => null })); |
| 51 | +vi.mock('./FlowRunner', () => ({ FlowRunner: () => null })); |
| 52 | +vi.mock('./MetadataInspector', () => ({ |
| 53 | + MetadataPanel: () => null, |
| 54 | + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), |
| 55 | +})); |
| 56 | + |
| 57 | +import { RecordDetailView } from './RecordDetailView'; |
| 58 | + |
| 59 | +const PARENT = 'os_27056_account'; |
| 60 | +const RECORD_ID = 'acc-1'; |
| 61 | +const CHILDREN = ['c1', 'c2', 'c3', 'c4', 'c5', 'c6'].map((n) => `os_27056_${n}`); |
| 62 | +const [C1, C2, C3] = CHILDREN; |
| 63 | +/** What each child's count answers: the second is empty. */ |
| 64 | +const TOTALS: Record<string, number> = Object.fromEntries(CHILDREN.map((c, i) => [c, [5, 0, 2, 4, 4, 4][i]])); |
| 65 | +/** The cards on screen at open: the first three; the rest are below the fold. */ |
| 66 | +const IN_VIEW = new Set([C1, C2, C3].map((c) => `${c}.account`)); |
| 67 | + |
| 68 | +const OBJECTS = [ |
| 69 | + { |
| 70 | + name: PARENT, |
| 71 | + label: 'Account', |
| 72 | + pluralLabel: 'Accounts', |
| 73 | + managedBy: 'platform', |
| 74 | + fields: { |
| 75 | + id: { type: 'text', label: 'Id' }, |
| 76 | + name: { type: 'text', label: 'Name' }, |
| 77 | + industry: { type: 'text', label: 'Industry' }, |
| 78 | + }, |
| 79 | + }, |
| 80 | + ...CHILDREN.map((name, i) => ({ |
| 81 | + name, |
| 82 | + label: `Child ${i + 1}`, |
| 83 | + pluralLabel: `Children ${i + 1}`, |
| 84 | + managedBy: 'platform', |
| 85 | + fields: { |
| 86 | + id: { type: 'text', label: 'Id' }, |
| 87 | + name: { type: 'text', label: 'Name' }, |
| 88 | + status: { type: 'select', label: 'Status', options: [{ value: 'open', label: 'Open' }] }, |
| 89 | + account: { type: 'lookup', reference: PARENT, label: 'Account' }, |
| 90 | + }, |
| 91 | + })), |
| 92 | +]; |
| 93 | + |
| 94 | +interface HeldRead { |
| 95 | + object: string; |
| 96 | + query: Record<string, any>; |
| 97 | + answered: boolean; |
| 98 | + answer: () => void; |
| 99 | +} |
| 100 | + |
| 101 | +let reads: HeldRead[] = []; |
| 102 | +let dataSource: Record<string, any>; |
| 103 | + |
| 104 | +function makeDataSource() { |
| 105 | + return { |
| 106 | + find: vi.fn((object: string, query: Record<string, any> = {}) => { |
| 107 | + if (!CHILDREN.includes(object)) return Promise.resolve({ data: [], total: 0 }); |
| 108 | + return new Promise((resolve) => { |
| 109 | + const read: HeldRead = { |
| 110 | + object, |
| 111 | + query, |
| 112 | + answered: false, |
| 113 | + answer: () => { |
| 114 | + read.answered = true; |
| 115 | + const total = TOTALS[object]; |
| 116 | + const top = typeof query.$top === 'number' ? query.$top : total; |
| 117 | + const rows = Array.from({ length: Math.min(top, total) }, (_, i) => ({ |
| 118 | + id: `${object}-${i}`, |
| 119 | + name: `${object} row ${i}`, |
| 120 | + status: 'open', |
| 121 | + })); |
| 122 | + resolve({ data: rows, total }); |
| 123 | + }, |
| 124 | + }; |
| 125 | + reads.push(read); |
| 126 | + }); |
| 127 | + }), |
| 128 | + findOne: vi.fn(async (_o: string, id: string) => ({ id, name: 'Acme', industry: 'Retail' })), |
| 129 | + getObjectSchema: vi.fn(async (name: string) => OBJECTS.find((o) => o.name === name) ?? null), |
| 130 | + create: vi.fn(async (_o: string, row: unknown) => row), |
| 131 | + update: vi.fn(async () => ({})), |
| 132 | + delete: vi.fn(async () => ({})), |
| 133 | + }; |
| 134 | +} |
| 135 | + |
| 136 | +/** The viewport: a card's root intersects when its relationship is on screen. */ |
| 137 | +class ViewportObserver { |
| 138 | + constructor(private readonly cb: (entries: Array<{ isIntersecting: boolean }>) => void) {} |
| 139 | + observe(el: Element) { |
| 140 | + const id = el.getAttribute('data-related-card-id'); |
| 141 | + if (id && IN_VIEW.has(id)) queueMicrotask(() => this.cb([{ isIntersecting: true }])); |
| 142 | + } |
| 143 | + unobserve() {} |
| 144 | + disconnect() {} |
| 145 | +} |
| 146 | + |
| 147 | +function renderPage() { |
| 148 | + dataSource = makeDataSource(); |
| 149 | + const metadata = { |
| 150 | + objects: OBJECTS, |
| 151 | + pages: [], |
| 152 | + loading: false, |
| 153 | + error: null, |
| 154 | + refresh: async () => {}, |
| 155 | + invalidate: () => {}, |
| 156 | + ensureType: async () => [], |
| 157 | + getItem: async () => null, |
| 158 | + getItemsByType: () => [], |
| 159 | + } as never; |
| 160 | + return render( |
| 161 | + <MemoryRouter initialEntries={[`/app/demo/${PARENT}/${RECORD_ID}`]}> |
| 162 | + <MetadataCtx.Provider value={metadata}> |
| 163 | + <RecordDetailView |
| 164 | + dataSource={dataSource as never} |
| 165 | + objects={OBJECTS} |
| 166 | + onEdit={() => {}} |
| 167 | + objectNameOverride={PARENT} |
| 168 | + recordIdOverride={RECORD_ID} |
| 169 | + /> |
| 170 | + </MetadataCtx.Provider> |
| 171 | + </MemoryRouter>, |
| 172 | + ); |
| 173 | +} |
| 174 | + |
| 175 | +async function idle() { |
| 176 | + await act(async () => { |
| 177 | + for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0)); |
| 178 | + }); |
| 179 | +} |
| 180 | + |
| 181 | +const isCount = (r: HeldRead) => r.query.$count === true && r.query.$skip === undefined; |
| 182 | +const isRows = (r: HeldRead) => r.query.$skip !== undefined; |
| 183 | +const column = (container: HTMLElement, name: string) => |
| 184 | + container.querySelector(`[data-record-column="${name}"]`) as HTMLElement | null; |
| 185 | + |
| 186 | +beforeEach(() => { |
| 187 | + cleanup(); |
| 188 | + reads = []; |
| 189 | + RelatedCountStore._reset(); |
| 190 | + window.localStorage.clear(); |
| 191 | + vi.stubGlobal('IntersectionObserver', ViewportObserver); |
| 192 | + vi.stubGlobal( |
| 193 | + 'fetch', |
| 194 | + vi.fn(async () => |
| 195 | + new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } }), |
| 196 | + ), |
| 197 | + ); |
| 198 | + const measure = HTMLElement.prototype.getBoundingClientRect; |
| 199 | + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) { |
| 200 | + if (!this.hasAttribute('data-record-page-root')) return measure.call(this); |
| 201 | + return { x: 0, y: 0, top: 0, left: 0, right: 1440, bottom: 900, width: 1440, height: 900, toJSON: () => ({}) } as DOMRect; |
| 202 | + }); |
| 203 | +}); |
| 204 | + |
| 205 | +afterEach(() => { |
| 206 | + vi.unstubAllGlobals(); |
| 207 | + vi.restoreAllMocks(); |
| 208 | +}); |
| 209 | + |
| 210 | +describe('RecordDetailView — the related column loads counts first (objectstack#27056)', () => { |
| 211 | + it('draws the details before any related read answers, with one placeholder per card', async () => { |
| 212 | + const { container } = renderPage(); |
| 213 | + await idle(); |
| 214 | + expect(reads.length).toBeGreaterThan(0); |
| 215 | + expect(reads.every((r) => !r.answered)).toBe(true); |
| 216 | + // The record's own values — its name, its highlight, its details — are on |
| 217 | + // screen from the record read alone. |
| 218 | + expect(container.textContent).toContain('Acme'); |
| 219 | + expect(container.textContent).toContain('Retail'); |
| 220 | + expect(column(container, 'details')?.textContent).toContain(RECORD_ID); |
| 221 | + const related = column(container, 'related')!; |
| 222 | + expect(related.querySelectorAll('[data-related-card-pending]')).toHaveLength(CHILDREN.length); |
| 223 | + expect(related.querySelector('[data-related-card-row]')).toBeNull(); |
| 224 | + }); |
| 225 | + |
| 226 | + it('asks the six counts as one request set, then the rows of the two counted cards in view only', async () => { |
| 227 | + const { container } = renderPage(); |
| 228 | + await idle(); |
| 229 | + // One request set: every list's count, all out before any answered, and |
| 230 | + // nothing else of theirs. |
| 231 | + expect(reads.filter(isCount).map((r) => r.object).sort()).toEqual([...CHILDREN].sort()); |
| 232 | + expect(reads.filter(isRows)).toEqual([]); |
| 233 | + expect(reads.filter(isCount).every((r) => r.query.$top === 1)).toBe(true); |
| 234 | + |
| 235 | + await act(async () => { |
| 236 | + for (const r of reads.filter((read) => !read.answered)) r.answer(); |
| 237 | + }); |
| 238 | + await idle(); |
| 239 | + const rowReads = reads.filter(isRows); |
| 240 | + // The counted cards in view: the first and the third. The second is in |
| 241 | + // view but counted at 0; the last three are below the fold. |
| 242 | + expect(rowReads.map((r) => r.object).sort()).toEqual([C1, C3].sort()); |
| 243 | + for (const r of rowReads) { |
| 244 | + expect(r.query.$top).toBe(3); |
| 245 | + expect(r.query.$select).toEqual(['id', 'name', 'status']); |
| 246 | + } |
| 247 | + // Two round trips in all: the counts, then the rows. |
| 248 | + expect(reads).toHaveLength(CHILDREN.length + 2); |
| 249 | + |
| 250 | + await act(async () => { |
| 251 | + for (const r of reads.filter((read) => !read.answered)) r.answer(); |
| 252 | + }); |
| 253 | + await idle(); |
| 254 | + const related = column(container, 'related')!; |
| 255 | + expect(related.querySelector(`[data-related-card-id="${C1}.account"]`)?.querySelectorAll('[data-related-card-row]')).toHaveLength(3); |
| 256 | + expect(related.querySelector(`[data-related-card-id="${C3}.account"]`)?.querySelectorAll('[data-related-card-row]')).toHaveLength(2); |
| 257 | + expect(related.querySelector('[data-related-card-pending]')).toBeNull(); |
| 258 | + // Still nothing for the empty card, nor for the cards out of view. |
| 259 | + expect(reads.filter(isRows).map((r) => r.object).sort()).toEqual([C1, C3].sort()); |
| 260 | + expect(reads.some((r) => r.object === C2 && isRows(r))).toBe(false); |
| 261 | + }); |
| 262 | +}); |
0 commit comments