Repository navigation
Expand file tree
/
Copy path_diff_presenter.txt
More file actions
401 lines (393 loc) · 22.4 KB
/
Copy path_diff_presenter.txt
File metadata and controls
401 lines (393 loc) · 22.4 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
diff --git a/dashboard/site/src/presenter.js b/dashboard/site/src/presenter.js
index f9d0973..ab95854 100644
--- a/dashboard/site/src/presenter.js
+++ b/dashboard/site/src/presenter.js
@@ -3,6 +3,7 @@
*/
import { h } from './dom.js';
+import { batch, effect, state } from './reactive.js';
import { getPrimerStyles } from './styles.js';
import { octicon } from './octicons.js';
import { renderDataStateMetrics } from './components/data-state.js';
@@ -99,7 +100,7 @@ import {
*/
/**
- * @typedef {((pageId: string, options: PageSourceLoadOptions) => Promise<Record<string, LogicalSourceInput>>) & { prepare?: (pageId: string) => Promise<void>, subscribeBackgroundSources?: (sourceNames: string[], options: PageSourceLoadOptions) => Promise<Record<string, LogicalSourceInput>> }} PageSourceLoader
+ * @typedef {((pageId: string, options: PageSourceLoadOptions) => Promise<Record<string, LogicalSourceInput>>) & { prepare?: (pageId: string) => Promise<void>, subscribeBackgroundSources?: (sourceNames: string[], options: PageSourceLoadOptions) => Promise<Record<string, LogicalSourceInput>>, subscribeViewSources?: (pageId: string, viewId: string, sourceNames: string[], options: PageSourceLoadOptions) => Promise<Record<string, LogicalSourceInput>> }} PageSourceLoader
*/
/**
@@ -190,8 +191,6 @@ export function renderDashboard(input) {
const cardTemplates = Object.fromEntries((document.dashboard['card-templates'] ?? []).map((template) => [template.id, template]));
const reusableViews = document.dashboard.views ?? [];
const horizonRange = resolveDashboardHorizon(document.dashboard);
- const hasData = Object.values(rawSources).some((source) => Array.isArray(source?.rows) && source.rows.length > 0);
- const showInitialLoadingSkeleton = input.loading === true && !hasData;
const dataHorizon = resolveDataHorizon(rawSources);
const githubUrlBase = typeof document.dashboard['github-url-base'] === 'string' && document.dashboard['github-url-base'].length > 0
? document.dashboard['github-url-base']
@@ -277,6 +276,8 @@ export function renderDashboard(input) {
const effectiveQueryContext = options.queryContext ?? (initialViewMode ? { viewMode: initialViewMode } : undefined);
options.queryContext = effectiveQueryContext;
const rendersBeforePageSources = dashboardPageSourcesAreIndependentlyBound(resolvedPage(), reusableViews);
+ const liveSources = state(sources);
+ const loading = state((input.loading === true || Boolean(input.loadPageSources)) && !rendersBeforePageSources);
/** @param {Record<string, LogicalSourceInput>} pageSources */
const updateHorizon = (pageSources) => {
if (options.signal?.aborted !== true) {
@@ -294,13 +295,11 @@ export function renderDashboard(input) {
const page = resolvedPage();
if (!page) throw new Error(`Dashboard page "${pageId}" is not available.`);
updateHorizon(pageSources);
- const pageHasData = Object.values(pageSources).some(
- (source) => Array.isArray(source?.rows) && source.rows.length > 0
- );
- const rendered = showInitialLoadingSkeleton
- && (page.id === 'overview' || !pageHasData)
- ? renderPageLoadingSkeleton(page)
- : renderPage(page, pageSources, isPlainObject(document.dashboard.units) ? document.dashboard.units : {}, dashboardDefaults, cardTemplates, reusableViews, effectiveQueryContext, document.dashboard.queries ?? []);
+ const rendered = renderPage(page, pageSources, isPlainObject(document.dashboard.units) ? document.dashboard.units : {}, dashboardDefaults, cardTemplates, reusableViews, effectiveQueryContext, document.dashboard.queries ?? [], {
+ sources: liveSources,
+ loading,
+ signal: options.signal
+ });
debugPerformance('page render', {
pageId,
phase: renderCount++ === 0 ? 'initial' : 'update',
@@ -314,8 +313,60 @@ export function renderDashboard(input) {
if (rendersBeforePageSources) {
return render(sources);
}
- options.onUpdate = (pageSources) => options.renderUpdate(render(pageSources));
- return input.loadPageSources(pageId, options).then(render);
+ /** @param {Record<string, LogicalSourceInput>} pageSources @param {boolean} [replace] @param {string[][]} [aliases] */
+ const publish = (pageSources, replace = false, aliases = []) => {
+ if (options.signal.aborted) return;
+ const merged = replace ? pageSources : { ...liveSources.get(), ...pageSources };
+ for (const [alias, authored] of aliases) {
+ if (pageSources[authored] && !pageSources[alias]) delete merged[alias];
+ }
+ updateHorizon(merged);
+ batch(() => {
+ liveSources.set(merged);
+ });
+ };
+ const rendered = render(sources);
+ if (input.loadPageSources.subscribeViewSources) {
+ const payload = getBuiltInPagePayload(resolvedPage(), reusableViews);
+ const bindings = (payload.views ?? []).flatMap((view, index) => {
+ if (!isPlainObject(view) || (typeof view.element === 'string' && elementLoadsSourcesAsync(view.element))) return [];
+ const names = getViewSources(view);
+ return names.length ? [{
+ id: typeof view.id === 'string' ? view.id : `view-${index + 1}`,
+ names,
+ aliases: names.map((name, sourceIndex) => [dashboardViewAliasName(pageId, view, index, name, sourceIndex), name])
+ }] : [];
+ });
+ const remaining = collectDashboardPageSourceNames(document, pageId, effectiveQueryContext?.viewMode)
+ .filter((name) => !bindings.some((binding) => binding.names.includes(name)));
+ if (remaining.length) bindings.push({ id: 'page-chrome', names: remaining, aliases: [] });
+ const subscribeViewSources = input.loadPageSources.subscribeViewSources;
+ const subscriptions = bindings.map(({ id, names, aliases }) => subscribeViewSources(
+ pageId, id, names, { ...options, onUpdate: (next) => publish(next, false, aliases) }
+ ).then((next) => publish(next, false, aliases)));
+ void Promise.allSettled(subscriptions).then((results) => {
+ if (options.signal.aborted) return;
+ for (const result of results) {
+ if (result.status === 'rejected') debugRender('view source binding failed', {
+ pageId,
+ message: result.reason instanceof Error ? result.reason.message : String(result.reason)
+ });
+ }
+ if (!input.loading) loading.set(false);
+ });
+ } else {
+ options.onUpdate = (pageSources) => publish(pageSources, true);
+ void input.loadPageSources(pageId, options).then(options.onUpdate).catch((error) => {
+ if (options.signal.aborted) return;
+ debugRender('page source binding failed', {
+ pageId,
+ message: error instanceof Error ? error.message : String(error)
+ });
+ }).finally(() => {
+ if (!options.signal.aborted && !input.loading) loading.set(false);
+ });
+ }
+ return rendered;
}
const renderedPage = render(sources);
/** @param {HTMLElement} rendered */
@@ -665,31 +716,6 @@ function renderPagePlaceholder(page) {
});
}
-/**
- * @param {PresentableBuiltInPage | PresentableCustomPage} page
- * @returns {HTMLElement}
- */
-function renderPageLoadingSkeleton(page) {
- const placeholder = renderPagePlaceholder(page);
- const payload = page.kind === 'built-in' ? getBuiltInPagePayload(page) : page;
- const routeParameter = typeof payload.route?.['hash-query-parameter'] === 'string'
- ? payload.route['hash-query-parameter']
- : undefined;
- const routeTabs = routeParameter ? declaredRouteTabs(payload.route) : null;
- placeholder.removeAttribute('data-page-pending');
- placeholder.setAttribute('aria-busy', 'true');
- if (routeTabs && routeParameter) {
- placeholder.append(renderDeclaredRouteTabs({
- routeParameter,
- currentTab: routeTabs.currentTab,
- tabs: routeTabs.tabs,
- className: routeTabs.className
- }));
- }
- placeholder.append(renderPageSkeleton());
- return placeholder;
-}
-
/**
* @returns {HTMLElement}
*/
@@ -706,12 +732,13 @@ function renderPageSkeleton() {
* @param {Array<Record<string, unknown>>} reusableViews
* @param {PageSourceLoadOptions['queryContext']} [queryContext]
* @param {Array<Record<string, unknown>>} [queries]
+ * @param {{ sources: import('./reactive.js').State<Record<string, LogicalSourceInput>>, loading: import('./reactive.js').State<boolean>, signal: AbortSignal }} [binding]
* @returns {HTMLElement}
*/
-function renderPage(page, sources, units, dashboardDefaults, cardTemplates, reusableViews, queryContext, queries = []) {
+function renderPage(page, sources, units, dashboardDefaults, cardTemplates, reusableViews, queryContext, queries = [], binding = undefined) {
const title = getPageTitle(page);
const payload = getBuiltInPagePayload(page, reusableViews);
- return renderCustomPage(payload, title, sources, units, dashboardDefaults, cardTemplates, true, queryContext, queries);
+ return renderCustomPage(payload, title, sources, units, dashboardDefaults, cardTemplates, true, queryContext, queries, binding);
}
/**
@@ -724,9 +751,10 @@ function renderPage(page, sources, units, dashboardDefaults, cardTemplates, reus
* @param {boolean} [withFilterBar]
* @param {PageSourceLoadOptions['queryContext']} [queryContext]
* @param {Array<Record<string, unknown>>} [queries]
+ * @param {{ sources: import('./reactive.js').State<Record<string, LogicalSourceInput>>, loading: import('./reactive.js').State<boolean>, signal: AbortSignal }} [binding]
* @returns {HTMLElement}
*/
-function renderCustomPage(page, title, sources, units, dashboardDefaults, cardTemplates, withFilterBar = true, queryContext, queries = []) {
+function renderCustomPage(page, title, sources, units, dashboardDefaults, cardTemplates, withFilterBar = true, queryContext, queries = [], binding = undefined) {
const effectiveDashboardDefaults = inventoryPage(page.id)
? { ...dashboardDefaults, time: undefined }
: dashboardDefaults;
@@ -763,6 +791,14 @@ function renderCustomPage(page, title, sources, units, dashboardDefaults, cardTe
}
}
const renderedViews = views.map((view, index) => {
+ const viewSourceNames = getViewSources(view);
+ const isSelfBound = isPlainObject(view) && typeof view.element === 'string' && elementLoadsSourcesAsync(view.element);
+ /** @param {Record<string, LogicalSourceInput>} current */
+ const viewIsPending = (current) => binding?.loading.get() === true
+ && viewSourceNames.some((name, sourceIndex) => (
+ !current[resolveViewSourceName(current, page.id, view, index, name, sourceIndex)]
+ || current[resolveViewSourceName(current, page.id, view, index, name, sourceIndex)]?.metadata?.availability === 'unavailable'
+ ));
const viewId = isPlainObject(view) && typeof view.id === 'string' ? view.id : '';
const headingTag = sections.length > 0 && !standaloneCalloutViewIds.has(viewId) ? 'h4' : 'h3';
const layout = isPlainObject(view) && typeof view.layout === 'string' ? view.layout : 'full';
@@ -777,14 +813,23 @@ function renderCustomPage(page, title, sources, units, dashboardDefaults, cardTe
)
);
const isNavigationCompositeView = isPlainObject(view) && view.mark === 'element';
- const render = () => {
- let rendered = renderCustomView(page.id, view, index, sources, units, cardTemplates, headingTag, routeParameter, queryContext);
+ const render = (viewSources = sources, pending = false) => {
+ const readySources = isSelfBound && binding?.loading.get()
+ ? Object.fromEntries(Object.entries(viewSources).filter(([, source]) => source.metadata?.availability !== 'unavailable'))
+ : viewSources;
+ let rendered = pending && viewSourceNames.length > 0 && !isSelfBound
+ ? renderPageSection(page.id, getViewTitle(view, index), [
+ renderDashboardViewSkeleton(),
+ h('span', { className: 'sr-only' }, `Loading ${getViewTitle(view, index)}`)
+ ], headingTag)
+ : renderCustomView(page.id, view, index, readySources, units, cardTemplates, headingTag, routeParameter, queryContext);
+ if (pending && !isSelfBound) rendered.setAttribute('aria-busy', 'true');
if (isPlainObject(view)) {
const semantics = effectiveViewSemantics(view, queries);
if (view.prompt === 'always' || (view.prompt !== 'none'
&& semantics.subject && semantics.objective && semantics.acceptance)) {
const selectedSources = Object.fromEntries(getViewSources(view).flatMap((sourceName, sourceIndex) => {
- const source = sources[resolveViewSourceName(sources, page.id, view, index, sourceName, sourceIndex)];
+ const source = viewSources[resolveViewSourceName(viewSources, page.id, view, index, sourceName, sourceIndex)];
return source ? [[sourceName, source]] : [];
}));
const prompt = renderPromptPreviewAction(
@@ -846,18 +891,64 @@ function renderCustomPage(page, title, sources, units, dashboardDefaults, cardTe
if (!isNavigationCompositeView && disclosure === 'essential') rendered.dataset.viewModeContent = viewModeForView(view);
return rendered;
};
- const rendered = isRouteView
+ let rendered = isRouteView
+ || (binding && viewIsPending(binding.sources.get()))
|| index === 0
|| (isPlainObject(view) && (view.mark === 'callout' || (
typeof view.element === 'string' && elementLoadsSourcesAsync(view.element)
)))
- ? render()
+ ? render(binding?.sources.get() ?? sources, viewIsPending(binding?.sources.get() ?? sources))
: renderLazyView({
label: getViewTitle(view, index),
headingLevel: headingTag,
minHeight: layout === 'half' || layout === 'third' ? 180 : 280,
- render
+ render: () => {
+ const current = binding?.sources.get() ?? sources;
+ const next = render(current, viewIsPending(current));
+ if (disclosure !== 'supplemental') rendered = next;
+ return next;
+ }
});
+ if (binding && viewSourceNames.length > 0 && !isSelfBound) {
+ let initial = true;
+ let previousSources = binding.sources.get();
+ let previousPending = viewIsPending(previousSources);
+ effect(() => {
+ const current = binding.sources.get();
+ const pending = viewIsPending(current);
+ if (initial) {
+ initial = false;
+ return;
+ }
+ const changed = previousPending !== pending || viewSourceNames.some((name, sourceIndex) => {
+ const resolved = resolveViewSourceName(current, page.id, view, index, name, sourceIndex);
+ return current[resolved] !== previousSources[resolved];
+ });
+ previousSources = current;
+ previousPending = pending;
+ const target = disclosure === 'supplemental'
+ ? rendered.querySelector(':scope > :not(summary)')
+ : rendered;
+ if (!(target instanceof HTMLElement) || !changed || target.hasAttribute('data-lazy-view')) return;
+ const replacement = render(current, pending);
+ for (const attribute of ['data-view-id', 'data-view-layout', 'data-disclosure', 'data-view-mode-content', 'data-view-lazy-list']) {
+ if (target.hasAttribute(attribute)) replacement.setAttribute(attribute, target.getAttribute(attribute) ?? '');
+ }
+ if (target.classList.contains('custom-view')) replacement.classList.add('custom-view');
+ const active = target.ownerDocument.activeElement;
+ const focusedId = active instanceof HTMLElement && target.contains(active) ? active.id : '';
+ if (target.parentNode) target.replaceWith(replacement);
+ if (disclosure !== 'supplemental') rendered = replacement;
+ if (focusedId) {
+ const focusTarget = [...replacement.querySelectorAll('[id]')].find((node) => node.id === focusedId);
+ if (focusTarget instanceof HTMLElement) focusTarget.focus({ preventScroll: true });
+ }
+ const owningPage = replacement.closest('.dashboard-page');
+ if (isRouteView && owningPage instanceof HTMLElement && routeParameter) {
+ dispatchPageRoute(replacement, routeParameter, owningPage.dataset.routeValue ?? '');
+ }
+ }, { signal: binding.signal });
+ }
rendered.classList.add('custom-view');
rendered.setAttribute('data-view-id', viewId || `view-${index + 1}`);
rendered.setAttribute('data-view-layout', layout);
@@ -872,7 +963,8 @@ function renderCustomPage(page, title, sources, units, dashboardDefaults, cardTe
rendered.classList.remove('custom-view');
rendered.removeAttribute('data-view-layout');
- return renderViewDisclosure(rendered, layout, disclosure, getViewTitle(view, index));
+ rendered = renderViewDisclosure(rendered, layout, disclosure, getViewTitle(view, index));
+ return rendered;
});
const renderedViewsById = new Map(views.map((view, index) => [
isPlainObject(view) && typeof view.id === 'string' ? view.id : `view-${index + 1}`,
@@ -885,6 +977,21 @@ function renderCustomPage(page, title, sources, units, dashboardDefaults, cardTe
...sections.map((section) => renderLayoutSection(page.id, section, renderedViewsById, sources))
)
: h('div', { className: 'custom-view-grid' }, ...renderedViews);
+ if (binding) {
+ for (const section of sections) {
+ if (!section['count-source'] && !section['count-sources']?.length) continue;
+ const sectionRoot = [...renderedContent.querySelectorAll('[data-section-id]')]
+ .find((element) => element.getAttribute('data-section-id') === section.id);
+ if (!(sectionRoot instanceof HTMLElement) || !sectionRoot.classList.contains('layout-section')) continue;
+ let initial = true;
+ effect(() => {
+ const current = binding.sources.get();
+ if (initial) { initial = false; return; }
+ const oldChrome = sectionRoot.querySelector(':scope > :first-child');
+ if (oldChrome) oldChrome.replaceWith(renderLayoutSectionChrome(page.id, section, layoutSectionCount(section, current)));
+ }, { signal: binding.signal });
+ }
+ }
const routeTabs = routeParameter ? declaredRouteTabs(page.route) : null;
const renderedRouteTabs = routeTabs && routeParameter
? renderDeclaredRouteTabs({
@@ -1066,23 +1173,7 @@ function renderHiddenDataStateMetrics(effectiveState) {
*/
function renderLayoutSection(pageId, section, renderedViews, sources) {
const headingId = `${pageId}-${section.id}-layout-heading`;
- const countSourceNames = Array.isArray(section['count-sources'])
- ? section['count-sources']
- : section['count-source'] ? [section['count-source']] : [];
- const countField = typeof section['count-field'] === 'string' ? section['count-field'] : null;
- const countSources = countSourceNames.map((sourceName) => sources[sourceName]).filter(Boolean);
- const countValues = countField
- ? countSources.flatMap((source) => {
- if (source.metadata?.availability === 'unavailable') return [];
- const value = Number(source.rows?.[0]?.[countField]);
- return Number.isFinite(value) ? [value] : [];
- })
- : [];
- const count = countField
- ? countValues.length > 0 ? countValues.reduce((total, value) => total + value, 0) : null
- : countSources.length === 1 && Array.isArray(countSources[0]?.rows)
- ? countSources[0].rows.length
- : null;
+ const count = layoutSectionCount(section, sources);
const sectionViews = section.views.map((viewId) => renderedViews.get(viewId)
?? renderEmptyMessage(`View unavailable: ${viewId}`, { 'data-missing-view-id': viewId }));
if (sectionViews.length === 1 && sectionViews[0].classList.contains('dashboard-callout')) {
@@ -1108,6 +1199,27 @@ function renderLayoutSection(pageId, section, renderedViews, sources) {
);
}
+/** @param {PresentablePageSection} section @param {Record<string, LogicalSourceInput>} sources */
+function layoutSectionCount(section, sources) {
+ const countSourceNames = Array.isArray(section['count-sources'])
+ ? section['count-sources']
+ : section['count-source'] ? [section['count-source']] : [];
+ const countField = typeof section['count-field'] === 'string' ? section['count-field'] : null;
+ const countSources = countSourceNames.map((sourceName) => sources[sourceName]).filter(Boolean);
+ const countValues = countField
+ ? countSources.flatMap((source) => {
+ if (source.metadata?.availability === 'unavailable') return [];
+ const value = Number(source.rows?.[0]?.[countField]);
+ return Number.isFinite(value) ? [value] : [];
+ })
+ : [];
+ return countField
+ ? countValues.length > 0 ? countValues.reduce((total, value) => total + value, 0) : null
+ : countSources.length === 1 && Array.isArray(countSources[0]?.rows)
+ ? countSources[0].rows.length
+ : null;
+}
+
/**
* Shows a single dashboard page and keeps sidebar state synchronized with the URL hash.
* @param {HTMLElement} root
@@ -2176,6 +2288,16 @@ function renderElementView(pageId, title, view, viewIndex, sources, contextDetai
? [[sourceName, source]]
: [];
}));
+ const hashParameters = new URLSearchParams(globalThis.location?.hash.split('?')[1] ?? '');
+ const declaredParameters = [
+ routeParameter,
+ ...(Array.isArray(viewData?.arguments) ? viewData.arguments.flatMap((argument) => (
+ isPlainObject(argument) && typeof argument.name === 'string' ? [argument.name] : []
+ )) : [])
+ ].filter((parameter) => typeof parameter === 'string');
+ const routeParameters = Object.fromEntries(declaredParameters.flatMap((parameter) => (
+ hashParameters.has(parameter) ? [[parameter, hashParameters.get(parameter) ?? '']] : []
+ )));
if (sourceNames.length === 1) {
const sourceName = sourceNames[0];
@@ -2208,6 +2330,7 @@ function renderElementView(pageId, title, view, viewIndex, sources, contextDetai
time: isPlainObject(viewData?.time) ? viewData.time : undefined,
titleLink: isPlainObject(view['title-link']) ? view['title-link'] : undefined,
routeParameter,
+ routeParameters,
queryContext,
viewId: typeof view.id === 'string' ? view.id : undefined,
viewIndex,