import type { ErrorProbeHost } from '../../common/error-probe-registry';
import { nextTick } from 'vue';
import { Prop, toNative } from 'vue-facing-decorator';
import { globalState } from '../../app/global-state';
import PowerduckState from '../../app/powerduck-state';
import TsxComponent, { Component } from '../../app/vuetsx';
import ErrorProbeRegistry from '../../common/error-probe-registry';
import ScrollUtils from '../../common/scroll-utils';
import Tabs, { TabsRenderMode } from '../tabs/tabs';
import { ModalSectionMode, ModalSectionPillScrollMode } from './../../common/enums/modal';
import './css/modal-section-wrapper.css';
interface ModalSectionWrapperArgs {
wrapInCard?: boolean;
}
/**
* Field-level validation indicators (Bootstrap + vuelidate output) that {@link navigateToFirstError}
* looks for:
* - `.has-danger` on the `.form-group` wrapper of an invalid field.
* - `.invalid-feedback` on the message `
` that vuelidate renders.
* - `.modalsection-has-error` applied to a section root by consumers that opt in.
* `.is-invalid` / `.has-error` / `.form-group-error` are kept as fallbacks for other consumers using
* stock Bootstrap or jQuery validation conventions.
*/
const ERROR_INDICATOR_SELECTOR = '.has-danger, .invalid-feedback, .modalsection-has-error, .is-invalid, .has-error, .form-group-error';
@Component
class ModalSectionWrapperComponent extends TsxComponent
implements ModalSectionWrapperArgs, ErrorProbeHost {
@Prop() wrapInCard!: boolean;
/**
* Validation probes currently open (see {@link beginErrorProbe}). In navPills mode only the active
* section is mounted; while this is above zero every section is, the inactive ones hidden.
*/
errorProbeDepth: number = 0;
// Scroll offset (per side-pill section index) remembered while the pill scroll
// mode is `rememberPosition`, so returning to a section restores where we were.
private _sectionScrollPositions: { [index: number]: number } = {};
// Index of the side-pill section currently displayed. Tracked so we can save
// the scroll offset of the section we are leaving before it is swapped out.
private _activeSectionIndex: number = 0;
mounted() {
// Only the side-pill layout mounts sections lazily; a fieldSet page shows them all, so a
// validation scan has nothing to probe there.
if (PowerduckState.getModalSectionMode() != ModalSectionMode.fieldSet) {
ErrorProbeRegistry.register(this);
}
}
beforeUnmount() {
ErrorProbeRegistry.unregister(this);
}
getErrorProbeRoot(): Element | null {
return this.$el instanceof Element ? this.$el : null;
}
/**
* Mounts every section for a validation scan — only the active one is mounted otherwise — keeping
* the inactive ones hidden. Takes effect on the next render; pair each call with
* {@link endErrorProbe}.
*/
beginErrorProbe(): void {
this.errorProbeDepth++;
}
/** Ends one {@link beginErrorProbe}; once none is open, only the active section stays mounted. */
endErrorProbe(): void {
if (this.errorProbeDepth > 0) {
this.errorProbeDepth--;
}
}
resetValidationErrors() {
const root = this.$el as HTMLElement;
root.querySelectorAll('.modalsection-has-error').forEach(el => el.classList.remove('modalsection-has-error'));
root.querySelectorAll('.fieldset-contains-error').forEach(el => el.classList.remove('fieldset-contains-error'));
}
displayValidationErrors() {
this.resetValidationErrors();
this.$nextTick(() => {
this.$nextTick(() => {
ScrollUtils.scrollToFirstPossibleError(this.$el as Element);
});
});
}
/**
* Switch the inner side-pill Tabs to the first section that contains a validation error. Useful
* right after the consumer runs vuelidate's `$validate()` so the user lands on the section with the
* highlighted field instead of staying on whichever pill was active when they pressed Save.
*
* Only the active section is mounted, so this mounts them all for one render
* ({@link beginErrorProbe}), takes the first section — in pill order — whose pane holds an error
* indicator ({@link ERROR_INDICATOR_SELECTOR}), switches to it and lets the others unmount again.
*
* No-op in `fieldSet` mode (single flat page — nothing to navigate). Resolves to false when no
* section holds an error.
*/
async navigateToFirstError(): Promise {
if (PowerduckState.getModalSectionMode() == ModalSectionMode.fieldSet) {
return false;
}
const innerTabs = this.$refs.innerTabs as typeof Tabs.prototype | undefined;
if (innerTabs?.setActivePageIndex == null) {
return false;
}
this.beginErrorProbe();
try {
await nextTick();
const index = this.findFirstErroringSectionIndex();
if (index == null) {
return false;
}
if (innerTabs.getActivePageIndex() != index) {
innerTabs.setActivePageIndex(index);
}
return true;
} finally {
this.endErrorProbe();
}
}
/**
* Index of the first section whose pane holds an error indicator, among the panes mounted right
* now. Only this wrapper's own panes are looked at — not its pills, which keep the
* `.modalsection-has-error` paint of an earlier scan, nor the panes of Tabs nested in a section.
*/
private findFirstErroringSectionIndex(): number | null {
const root = this.$el as HTMLElement | null;
const content = Array.from(root?.children ?? []).find(child => child.classList.contains('tab-content'));
const panes = Array.from(content?.children ?? []).filter(child => child.classList.contains('inv-tab-wrap'));
const erroringPane = panes.find(pane => pane.querySelector(ERROR_INDICATOR_SELECTOR) != null);
const index = erroringPane?.getAttribute('data-pane-index');
return index == null ? null : Number(index);
}
/**
* Reacts to a side-pill section change by scrolling the section content
* according to `PowerduckState.getModalSectionPillScrollMode()`:
* - `disabled` → leave the scroll position alone.
* - `scrollToTop` → always jump back to the top.
* - `rememberPosition` → save the offset of the section we are leaving and
* restore the target section's saved offset, falling
* back to the top when it has not been visited yet.
*
* The save has to happen synchronously (the section being left is still in the
* DOM here, before Vue re-renders); the restore is deferred until the newly
* selected section has rendered.
*/
private onSectionPillChange(newIndex: number): void {
const mode = PowerduckState.getModalSectionPillScrollMode();
const previousIndex = this._activeSectionIndex;
this._activeSectionIndex = newIndex;
if (mode == ModalSectionPillScrollMode.disabled) {
return;
}
if (mode == ModalSectionPillScrollMode.rememberPosition) {
this._sectionScrollPositions[previousIndex] = this.readScrollTop(this.getScrollContainer());
}
this.$nextTick(() => {
const apply = () => this.applySectionScroll(newIndex, mode);
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(apply);
} else {
apply();
}
});
}
private applySectionScroll(index: number, mode: ModalSectionPillScrollMode): void {
const remembered = this._sectionScrollPositions[index];
const target = (mode == ModalSectionPillScrollMode.rememberPosition && remembered != null) ? remembered : 0;
ScrollUtils.scrollToPos(
target,
this.getScrollContainer(),
false,
true,
);
}
/**
* Nearest scrollable ancestor of the section content. Resolves to the `.modal`
* element on desktop and to `.modal-body` in the mobile bottom-sheet layout;
* returns null when nothing scrolls (page-level usage → window).
*/
private getScrollContainer(): HTMLElement | null {
let parent = (this.$el as HTMLElement | null)?.parentElement ?? null;
while (parent != null) {
const overflowY = getComputedStyle(parent).overflowY;
if (overflowY === 'auto' || overflowY === 'scroll') {
return parent;
}
parent = parent.parentElement;
}
return null;
}
private readScrollTop(container: HTMLElement | null): number {
if (container != null) {
return container.scrollTop;
}
return globalState.scrollY ?? globalState.pageYOffset ?? 0;
}
render(h) {
if (PowerduckState.getModalSectionMode() == ModalSectionMode.fieldSet) {
return {this.$slots.default?.()}
;
} else {
// Only the active section is mounted: picking another pill unmounts it and mounts the next
// one. A validation probe mounts the rest for a moment (see beginErrorProbe).
return (
0}
onTabChange={(index: number) => this.onSectionPillChange(index)}
>
{this.$slots.default?.()}
);
}
}
}
const ModalSectionWrapper = toNative(ModalSectionWrapperComponent);
export default ModalSectionWrapper;