Refactor #5612 - OverlayPanel / Popover

pull/5677/head
tugcekucukoglu 2024-04-18 17:16:37 +03:00
parent f240b953b4
commit def5d060c0
16 changed files with 649 additions and 510 deletions

188
components/lib/overlaypanel/OverlayPanel.d.ts vendored Executable file → Normal file
View File

@ -2,224 +2,66 @@
* *
* OverlayPanel is a container component positioned as connected to its target. * OverlayPanel is a container component positioned as connected to its target.
* *
* [Live Demo](https://primevue.org/overlaypanel) * [Live Demo](https://primevue.org/popover)
* *
* @module overlaypanel * @module overlaypanel
* *
*/ */
import { TransitionProps, VNode } from 'vue'; import 'vue';
import { ComponentHooks } from '../basecomponent'; import * as Popover from '../popover';
import { PassThroughOptions } from '../passthrough'; import { ClassComponent, GlobalComponentConstructor } from '../ts-helpers';
import { ClassComponent, DesignToken, GlobalComponentConstructor, HintedString, PassThrough } from '../ts-helpers';
export declare type OverlayPanelPassThroughOptionType = OverlayPanelPassThroughAttributes | ((options: OverlayPanelPassThroughMethodOptions) => OverlayPanelPassThroughAttributes | string) | string | null | undefined;
export declare type OverlayPanelPassThroughTransitionType = TransitionProps | ((options: OverlayPanelPassThroughMethodOptions) => TransitionProps) | undefined;
/** /**
* Custom passthrough(pt) option method. * Custom passthrough(pt) option method.
*/ */
export interface OverlayPanelPassThroughMethodOptions { export interface OverlayPanelPassThroughMethodOptions extends Popover.PopoverPassThroughMethodOptions {}
/**
* Defines instance.
*/
instance: any;
/**
* Defines valid properties.
*/
props: OverlayPanelProps;
/**
* Defines current inline state.
*/
state: OverlayPanelState;
/**
* Defines valid attributes.
*/
attrs: any;
/**
* Defines parent options.
*/
parent: any;
/**
* Defines passthrough(pt) options in global config.
*/
global: object | undefined;
}
/** /**
* Custom passthrough(pt) options. * Custom passthrough(pt) options.
* @see {@link OverlayPanelProps.pt} * @see {@link OverlayPanelProps.pt}
*/ */
export interface OverlayPanelPassThroughOptions { export interface OverlayPanelPassThroughOptions extends Popover.PopoverPassThroughOptions {}
/**
* Used to pass attributes to the root's DOM element.
*/
root?: OverlayPanelPassThroughOptionType;
/**
* Used to pass attributes to the content's DOM element.
*/
content?: OverlayPanelPassThroughOptionType;
/**
* Used to manage all lifecycle hooks.
* @see {@link BaseComponent.ComponentHooks}
*/
hooks?: ComponentHooks;
/**
* Used to control Vue Transition API.
*/
transition?: OverlayPanelPassThroughTransitionType;
}
/** /**
* Custom passthrough attributes for each DOM elements * Custom passthrough attributes for each DOM elements
*/ */
export interface OverlayPanelPassThroughAttributes { export interface OverlayPanelPassThroughAttributes extends Popover.PopoverPassThroughAttributes {
[key: string]: any; [key: string]: any;
} }
/** /**
* Defines current inline state in OverlayPanel component. * Defines current inline state in OverlayPanel component.
*/ */
export interface OverlayPanelState { export interface OverlayPanelState extends Popover.PopoverState {}
/**
* Current visible state as a boolean.
* @defaultValue false
*/
visible: boolean;
}
/** /**
* OverlayPanel breakpoint metadata. * OverlayPanel breakpoint metadata.
*/ */
export interface OverlayPanelBreakpoints { export interface OverlayPanelBreakpoints extends Popover.PopoverBreakpoints {}
/**
* Breakpoint for responsive mode.
*
* Example:
*
* <OverlayPanel :breakpoints="{'960px': '75vw', '640px': '100vw'}" ... />
*
* Result:
*
* @media screen and (max-width: ${breakpoint[key]}) {
* .p-overlaypanel[attributeSelector] {
* width: ${breakpoint[value]} !important;
* }
* }
*/
[key: string]: string;
}
/** /**
* Defines valid properties in OverlayPanel component. * Defines valid properties in OverlayPanel component.
*/ */
export interface OverlayPanelProps { export interface OverlayPanelProps extends Popover.PopoverProps {}
/**
* Enables to hide the overlay when outside is clicked.
* @defaultValue true
*/
dismissable?: boolean;
/**
* A valid query selector or an HTMLElement to specify where the overlay gets attached.
* @defaultValue body
*/
appendTo?: HintedString<'body' | 'self'> | undefined | HTMLElement;
/**
* Base zIndex value to use in layering.
* @defaultValue 0
*/
baseZIndex?: number;
/**
* Whether to automatically manage layering.
* @defaultValue true
*/
autoZIndex?: boolean;
/**
* Object literal to define widths per screen size.
*/
breakpoints?: OverlayPanelBreakpoints;
/**
* It generates scoped CSS variables using design tokens for the component.
*/
dt?: DesignToken<any>;
/**
* Used to pass attributes to DOM elements inside the component.
* @type {OverlayPanelPassThroughOptions}
*/
pt?: PassThrough<OverlayPanelPassThroughOptions>;
/**
* Used to configure passthrough(pt) options of the component.
* @type {PassThroughOptions}
*/
ptOptions?: PassThroughOptions;
/**
* When enabled, it removes component related styles in the core.
* @defaultValue false
*/
unstyled?: boolean;
/**
* Specifies if pressing escape key should hide the dialog.
* @defaultValue true
*/
closeOnEscape?: boolean | undefined;
}
/** /**
* Defines valid slots in OverlayPanel component. * Defines valid slots in OverlayPanel component.
*/ */
export interface OverlayPanelSlots { export interface OverlayPanelSlots extends Popover.PopoverSlots {}
/**
* Custom content template.
*/
default(): VNode[];
/**
* Custom container slot.
* @param {Object} scope - container slot's params.
*/
container(scope: {
/**
* Close overlay panel function.
* @deprecated since v3.39.0. Use 'closeCallback' property instead.
*/
onClose: () => void;
/**
* Close button keydown function.
* @param {Event} event - Browser event
* @deprecated since v3.39.0. Use 'keydownCallback' property instead.
*/
onKeydown: (event: Event) => void;
/**
* Close overlay panel function.
*/
closeCallback: () => void;
/**
* Close button keydown function.
* @param {Event} event - Browser event
*/
keydownCallback: (event: Event) => void;
}): VNode[];
}
/** /**
* Defines valid emits in OverlayPanel component. * Defines valid emits in OverlayPanel component.
*/ */
export interface OverlayPanelEmits { export interface OverlayPanelEmits extends Popover.PopoverEmits {}
/**
* Callback to invoke when the overlay is shown.
*/
show(): void;
/**
* Callback to invoke when the overlay is hidden.
*/
hide(): void;
}
/** /**
* @deprecated Deprecated since v4. Use Popover component instead.
*
* **PrimeVue - OverlayPanel** * **PrimeVue - OverlayPanel**
* *
* _OverlayPanel, also known as Popover, is a container component that can overlay other components on page._ * _OverlayPanel, also known as Popover, is a container component that can overlay other components on page._
* *
* [Live Demo](https://www.primevue.org/overlaypanel/) * [Live Demo](https://www.primevue.org/popover/)
* --- --- * --- ---
* ![PrimeVue](https://primefaces.org/cdn/primevue/images/logo-100.png) * ![PrimeVue](https://primefaces.org/cdn/primevue/images/logo-100.png)
* *

309
components/lib/overlaypanel/OverlayPanel.vue Executable file → Normal file
View File

@ -1,314 +1,11 @@
<template>
<Portal :appendTo="appendTo">
<transition name="p-popover" @enter="onEnter" @leave="onLeave" @after-leave="onAfterLeave" v-bind="ptm('transition')">
<div v-if="visible" :ref="containerRef" v-focustrap role="dialog" :aria-modal="visible" @click="onOverlayClick" :class="cx('root')" v-bind="ptmi('root')">
<slot v-if="$slots.container" name="container" :onClose="hide" :onKeydown="(event) => onButtonKeydown(event)" :closeCallback="hide" :keydownCallback="(event) => onButtonKeydown(event)"></slot>
<template v-else>
<div :class="cx('content')" @click="onContentClick" @mousedown="onContentClick" @keydown="onContentKeydown" v-bind="ptm('content')">
<slot></slot>
</div>
</template>
</div>
</transition>
</Portal>
</template>
<script> <script>
import FocusTrap from 'primevue/focustrap'; import Popover from 'primevue/popover';
import OverlayEventBus from 'primevue/overlayeventbus';
import Portal from 'primevue/portal';
import Ripple from 'primevue/ripple';
import { $dt } from 'primevue/themes';
import { ConnectedOverlayScrollHandler, DomHandler, UniqueComponentId, ZIndexUtils } from 'primevue/utils';
import BaseOverlayPanel from './BaseOverlayPanel.vue';
export default { export default {
name: 'OverlayPanel', name: 'OverlayPanel',
extends: BaseOverlayPanel, extends: Popover,
inheritAttrs: false,
emits: ['show', 'hide'],
data() {
return {
visible: false
};
},
watch: {
dismissable: {
immediate: true,
handler(newValue) {
if (newValue) {
this.bindOutsideClickListener();
} else {
this.unbindOutsideClickListener();
}
}
}
},
selfClick: false,
target: null,
eventTarget: null,
outsideClickListener: null,
scrollHandler: null,
resizeListener: null,
container: null,
styleElement: null,
overlayEventListener: null,
documentKeydownListener: null,
beforeUnmount() {
if (this.dismissable) {
this.unbindOutsideClickListener();
}
if (this.scrollHandler) {
this.scrollHandler.destroy();
this.scrollHandler = null;
}
this.destroyStyle();
this.unbindResizeListener();
this.target = null;
if (this.container && this.autoZIndex) {
ZIndexUtils.clear(this.container);
}
if (this.overlayEventListener) {
OverlayEventBus.off('overlay-click', this.overlayEventListener);
this.overlayEventListener = null;
}
this.container = null;
},
mounted() { mounted() {
if (this.breakpoints) { console.warn('Deprecated since v4. Use Popover component instead.');
this.createStyle();
}
},
methods: {
toggle(event, target) {
if (this.visible) this.hide();
else this.show(event, target);
},
show(event, target) {
this.visible = true;
this.eventTarget = event.currentTarget;
this.target = target || event.currentTarget;
},
hide() {
this.visible = false;
},
onContentClick() {
this.selfClick = true;
},
onEnter(el) {
this.container.setAttribute(this.attributeSelector, '');
DomHandler.addStyles(el, { position: 'absolute', top: '0', left: '0' });
this.alignOverlay();
if (this.dismissable) {
this.bindOutsideClickListener();
}
this.bindScrollListener();
this.bindResizeListener();
if (this.autoZIndex) {
ZIndexUtils.set('overlay', el, this.baseZIndex + this.$primevue.config.zIndex.overlay);
}
this.overlayEventListener = (e) => {
if (this.container.contains(e.target)) {
this.selfClick = true;
}
};
this.focus();
OverlayEventBus.on('overlay-click', this.overlayEventListener);
this.$emit('show');
if (this.closeOnEscape) {
this.bindDocumentKeyDownListener();
}
},
onLeave() {
this.unbindOutsideClickListener();
this.unbindScrollListener();
this.unbindResizeListener();
this.unbindDocumentKeyDownListener();
OverlayEventBus.off('overlay-click', this.overlayEventListener);
this.overlayEventListener = null;
this.$emit('hide');
},
onAfterLeave(el) {
if (this.autoZIndex) {
ZIndexUtils.clear(el);
}
},
alignOverlay() {
DomHandler.absolutePosition(this.container, this.target, false);
const containerOffset = DomHandler.getOffset(this.container);
const targetOffset = DomHandler.getOffset(this.target);
let arrowLeft = 0;
if (containerOffset.left < targetOffset.left) {
arrowLeft = targetOffset.left - containerOffset.left;
}
this.container.style.setProperty($dt('overlay.arrow.left').name, `${arrowLeft}px`);
if (containerOffset.top < targetOffset.top) {
this.container.setAttribute('data-p-overlaypanel-flipped', 'true');
!this.isUnstyled && DomHandler.addClass(this.container, 'p-overlaypanel-flipped');
}
},
onContentKeydown(event) {
if (event.code === 'Escape' && this.closeOnEscape) {
this.hide();
DomHandler.focus(this.target);
}
},
onButtonKeydown(event) {
switch (event.code) {
case 'ArrowDown':
case 'ArrowUp':
case 'ArrowLeft':
case 'ArrowRight':
event.preventDefault();
default:
break;
}
},
focus() {
let focusTarget = this.container.querySelector('[autofocus]');
if (focusTarget) {
focusTarget.focus();
}
},
onKeyDown(event) {
if (event.code === 'Escape' && this.closeOnEscape) {
this.visible = false;
}
},
bindDocumentKeyDownListener() {
if (!this.documentKeydownListener) {
this.documentKeydownListener = this.onKeyDown.bind(this);
window.document.addEventListener('keydown', this.documentKeydownListener);
}
},
unbindDocumentKeyDownListener() {
if (this.documentKeydownListener) {
window.document.removeEventListener('keydown', this.documentKeydownListener);
this.documentKeydownListener = null;
}
},
bindOutsideClickListener() {
if (!this.outsideClickListener && DomHandler.isClient()) {
this.outsideClickListener = (event) => {
if (this.visible && !this.selfClick && !this.isTargetClicked(event)) {
this.visible = false;
}
this.selfClick = false;
};
document.addEventListener('click', this.outsideClickListener);
}
},
unbindOutsideClickListener() {
if (this.outsideClickListener) {
document.removeEventListener('click', this.outsideClickListener);
this.outsideClickListener = null;
this.selfClick = false;
}
},
bindScrollListener() {
if (!this.scrollHandler) {
this.scrollHandler = new ConnectedOverlayScrollHandler(this.target, () => {
if (this.visible) {
this.visible = false;
}
});
}
this.scrollHandler.bindScrollListener();
},
unbindScrollListener() {
if (this.scrollHandler) {
this.scrollHandler.unbindScrollListener();
}
},
bindResizeListener() {
if (!this.resizeListener) {
this.resizeListener = () => {
if (this.visible && !DomHandler.isTouchDevice()) {
this.visible = false;
}
};
window.addEventListener('resize', this.resizeListener);
}
},
unbindResizeListener() {
if (this.resizeListener) {
window.removeEventListener('resize', this.resizeListener);
this.resizeListener = null;
}
},
isTargetClicked(event) {
return this.eventTarget && (this.eventTarget === event.target || this.eventTarget.contains(event.target));
},
containerRef(el) {
this.container = el;
},
createStyle() {
if (!this.styleElement && !this.isUnstyled) {
this.styleElement = document.createElement('style');
this.styleElement.type = 'text/css';
DomHandler.setAttribute(this.styleElement, 'nonce', this.$primevue?.config?.csp?.nonce);
document.head.appendChild(this.styleElement);
let innerHTML = '';
for (let breakpoint in this.breakpoints) {
innerHTML += `
@media screen and (max-width: ${breakpoint}) {
.p-overlaypanel[${this.attributeSelector}] {
width: ${this.breakpoints[breakpoint]} !important;
}
}
`;
}
this.styleElement.innerHTML = innerHTML;
}
},
destroyStyle() {
if (this.styleElement) {
document.head.removeChild(this.styleElement);
this.styleElement = null;
}
},
onOverlayClick(event) {
OverlayEventBus.emit('overlay-click', {
originalEvent: event,
target: this.target
});
}
},
computed: {
attributeSelector() {
return UniqueComponentId();
}
},
directives: {
focustrap: FocusTrap,
ripple: Ripple
},
components: {
Portal
} }
}; };
</script> </script>

View File

@ -1,3 +1,3 @@
import { BaseStyle } from '../../base/style'; import { PopoverStyle } from '../../popover/style/PopoverStyle';
export interface OverlayPanelStyle extends BaseStyle {} export interface OverlayPanelStyle extends PopoverStyle {}

View File

@ -1,16 +1,5 @@
import BaseStyle from 'primevue/base/style'; import BaseStyle from 'primevue/base/style';
const classes = {
root: ({ instance }) => [
'p-popover p-component',
{
'p-ripple-disabled': instance.$primevue.config.ripple === false
}
],
content: 'p-popover-content'
};
export default BaseStyle.extend({ export default BaseStyle.extend({
name: 'overlaypanel', name: 'overlaypanel'
classes
}); });

View File

@ -1,9 +1,9 @@
<script> <script>
import BaseComponent from 'primevue/basecomponent'; import BaseComponent from 'primevue/basecomponent';
import OverlayPanelStyle from 'primevue/overlaypanel/style'; import PopoverStyle from 'primevue/popover/style';
export default { export default {
name: 'BaseOverlayPanel', name: 'BasePopover',
extends: BaseComponent, extends: BaseComponent,
props: { props: {
dismissable: { dismissable: {
@ -31,7 +31,7 @@ export default {
default: true default: true
} }
}, },
style: OverlayPanelStyle, style: PopoverStyle,
provide() { provide() {
return { return {
$parentInstance: this $parentInstance: this

263
components/lib/popover/Popover.d.ts vendored Executable file
View File

@ -0,0 +1,263 @@
/**
*
* Popover is a container component positioned as connected to its target.
*
* [Live Demo](https://primevue.org/popover)
*
* @module popover
*
*/
import { TransitionProps, VNode } from 'vue';
import { ComponentHooks } from '../basecomponent/BaseComponent';
import { PassThroughOptions } from '../passthrough';
import { ClassComponent, DesignToken, GlobalComponentConstructor, HintedString, PassThrough } from '../ts-helpers';
export declare type PopoverPassThroughOptionType = PopoverPassThroughAttributes | ((options: PopoverPassThroughMethodOptions) => PopoverPassThroughAttributes | string) | string | null | undefined;
export declare type PopoverPassThroughTransitionType = TransitionProps | ((options: PopoverPassThroughMethodOptions) => TransitionProps) | undefined;
/**
* Custom passthrough(pt) option method.
*/
export interface PopoverPassThroughMethodOptions {
/**
* Defines instance.
*/
instance: any;
/**
* Defines valid properties.
*/
props: PopoverProps;
/**
* Defines current inline state.
*/
state: PopoverState;
/**
* Defines valid attributes.
*/
attrs: any;
/**
* Defines parent options.
*/
parent: any;
/**
* Defines passthrough(pt) options in global config.
*/
global: object | undefined;
}
/**
* Custom passthrough(pt) options.
* @see {@link PopoverProps.pt}
*/
export interface PopoverPassThroughOptions {
/**
* Used to pass attributes to the root's DOM element.
*/
root?: PopoverPassThroughOptionType;
/**
* Used to pass attributes to the content's DOM element.
*/
content?: PopoverPassThroughOptionType;
/**
* Used to manage all lifecycle hooks.
* @see {@link BaseComponent.ComponentHooks}
*/
hooks?: ComponentHooks;
/**
* Used to control Vue Transition API.
*/
transition?: PopoverPassThroughTransitionType;
}
/**
* Custom passthrough attributes for each DOM elements
*/
export interface PopoverPassThroughAttributes {
[key: string]: any;
}
/**
* Defines current inline state in Popover component.
*/
export interface PopoverState {
/**
* Current visible state as a boolean.
* @defaultValue false
*/
visible: boolean;
}
/**
* Popover breakpoint metadata.
*/
export interface PopoverBreakpoints {
/**
* Breakpoint for responsive mode.
*
* Example:
*
* <Popover :breakpoints="{'960px': '75vw', '640px': '100vw'}" ... />
*
* Result:
*
* @media screen and (max-width: ${breakpoint[key]}) {
* .p-popover[attributeSelector] {
* width: ${breakpoint[value]} !important;
* }
* }
*/
[key: string]: string;
}
/**
* Defines valid properties in Popover component.
*/
export interface PopoverProps {
/**
* Enables to hide the overlay when outside is clicked.
* @defaultValue true
*/
dismissable?: boolean;
/**
* A valid query selector or an HTMLElement to specify where the overlay gets attached.
* @defaultValue body
*/
appendTo?: HintedString<'body' | 'self'> | undefined | HTMLElement;
/**
* Base zIndex value to use in layering.
* @defaultValue 0
*/
baseZIndex?: number;
/**
* Whether to automatically manage layering.
* @defaultValue true
*/
autoZIndex?: boolean;
/**
* Object literal to define widths per screen size.
*/
breakpoints?: PopoverBreakpoints;
/**
* It generates scoped CSS variables using design tokens for the component.
*/
dt?: DesignToken<any>;
/**
* Used to pass attributes to DOM elements inside the component.
* @type {PopoverPassThroughOptions}
*/
pt?: PassThrough<PopoverPassThroughOptions>;
/**
* Used to configure passthrough(pt) options of the component.
* @type {PassThroughOptions}
*/
ptOptions?: PassThroughOptions;
/**
* When enabled, it removes component related styles in the core.
* @defaultValue false
*/
unstyled?: boolean;
/**
* Specifies if pressing escape key should hide the dialog.
* @defaultValue true
*/
closeOnEscape?: boolean | undefined;
}
/**
* Defines valid slots in Popover component.
*/
export interface PopoverSlots {
/**
* Custom content template.
*/
default(): VNode[];
/**
* Custom container slot.
* @param {Object} scope - container slot's params.
*/
container(scope: {
/**
* Close overlay panel function.
* @deprecated since v3.39.0. Use 'closeCallback' property instead.
*/
onClose: () => void;
/**
* Close button keydown function.
* @param {Event} event - Browser event
* @deprecated since v3.39.0. Use 'keydownCallback' property instead.
*/
onKeydown: (event: Event) => void;
/**
* Close overlay panel function.
*/
closeCallback: () => void;
/**
* Close button keydown function.
* @param {Event} event - Browser event
*/
keydownCallback: (event: Event) => void;
}): VNode[];
}
/**
* Defines valid emits in Popover component.
*/
export interface PopoverEmits {
/**
* Callback to invoke when the overlay is shown.
*/
show(): void;
/**
* Callback to invoke when the overlay is hidden.
*/
hide(): void;
}
/**
* **PrimeVue - Popover**
*
* _Popover, also known as Popover, is a container component that can overlay other components on page._
*
* [Live Demo](https://www.primevue.org/popover/)
* --- ---
* ![PrimeVue](https://primefaces.org/cdn/primevue/images/logo-100.png)
*
* @group Component
*/
declare class Popover extends ClassComponent<PopoverProps, PopoverSlots, PopoverEmits> {
/**
* Aligns overlay panel based on the current position of the container.
*/
alignOverlay(): void;
/**
* Toggles the visibility of the overlay.
* @param {Event} event - Browser event.
* @param {*} [target] - Optional target if event.currentTarget should not be used.
*
* @memberof Popover
*/
toggle(event: Event, target?: any): void;
/**
* Shows the overlay.
* @param {Event} event - Browser event.
* @param {*} [target] - Optional target if event.currentTarget should not be used.
*
* @memberof Popover
*/
show(event: Event, target?: any): void;
/**
* Hides the overlay.
*
* @memberof Popover
*/
hide(): void;
}
declare module 'vue' {
export interface GlobalComponents {
Popover: GlobalComponentConstructor<Popover>;
}
}
export default Popover;

View File

@ -1,12 +1,12 @@
import { mount } from '@vue/test-utils'; import { mount } from '@vue/test-utils';
import PrimeVue from 'primevue/config'; import PrimeVue from 'primevue/config';
import OverlayPanel from './OverlayPanel.vue'; import Popover from './Popover.vue';
describe('OverlayPanel.vue', () => { describe('Popover.vue', () => {
let wrapper; let wrapper;
beforeEach(async () => { beforeEach(async () => {
wrapper = mount(OverlayPanel, { wrapper = mount(Popover, {
global: { global: {
plugins: [PrimeVue], plugins: [PrimeVue],
stubs: { stubs: {
@ -25,9 +25,9 @@ describe('OverlayPanel.vue', () => {
}); });
it('should exist', () => { it('should exist', () => {
expect(wrapper.find('.p-overlaypanel.p-component').exists()).toBe(true); expect(wrapper.find('.p-popover.p-component').exists()).toBe(true);
expect(wrapper.find('.p-overlaypanel-content').exists()).toBe(true); expect(wrapper.find('.p-popover-content').exists()).toBe(true);
expect(wrapper.find('.p-overlaypanel-content').text()).toBe('PrimeVue'); expect(wrapper.find('.p-popover-content').text()).toBe('PrimeVue');
expect(wrapper.find('.p-overlaypanel-close').exists()).toBe(true); expect(wrapper.find('.p-popover-close').exists()).toBe(true);
}); });
}); });

View File

@ -0,0 +1,314 @@
<template>
<Portal :appendTo="appendTo">
<transition name="p-popover" @enter="onEnter" @leave="onLeave" @after-leave="onAfterLeave" v-bind="ptm('transition')">
<div v-if="visible" :ref="containerRef" v-focustrap role="dialog" :aria-modal="visible" @click="onOverlayClick" :class="cx('root')" v-bind="ptmi('root')">
<slot v-if="$slots.container" name="container" :onClose="hide" :onKeydown="(event) => onButtonKeydown(event)" :closeCallback="hide" :keydownCallback="(event) => onButtonKeydown(event)"></slot>
<template v-else>
<div :class="cx('content')" @click="onContentClick" @mousedown="onContentClick" @keydown="onContentKeydown" v-bind="ptm('content')">
<slot></slot>
</div>
</template>
</div>
</transition>
</Portal>
</template>
<script>
import FocusTrap from 'primevue/focustrap';
import OverlayEventBus from 'primevue/overlayeventbus';
import Portal from 'primevue/portal';
import Ripple from 'primevue/ripple';
import { $dt } from 'primevue/themes';
import { ConnectedOverlayScrollHandler, DomHandler, UniqueComponentId, ZIndexUtils } from 'primevue/utils';
import BasePopover from './BasePopover.vue';
export default {
name: 'Popover',
extends: BasePopover,
inheritAttrs: false,
emits: ['show', 'hide'],
data() {
return {
visible: false
};
},
watch: {
dismissable: {
immediate: true,
handler(newValue) {
if (newValue) {
this.bindOutsideClickListener();
} else {
this.unbindOutsideClickListener();
}
}
}
},
selfClick: false,
target: null,
eventTarget: null,
outsideClickListener: null,
scrollHandler: null,
resizeListener: null,
container: null,
styleElement: null,
overlayEventListener: null,
documentKeydownListener: null,
beforeUnmount() {
if (this.dismissable) {
this.unbindOutsideClickListener();
}
if (this.scrollHandler) {
this.scrollHandler.destroy();
this.scrollHandler = null;
}
this.destroyStyle();
this.unbindResizeListener();
this.target = null;
if (this.container && this.autoZIndex) {
ZIndexUtils.clear(this.container);
}
if (this.overlayEventListener) {
OverlayEventBus.off('overlay-click', this.overlayEventListener);
this.overlayEventListener = null;
}
this.container = null;
},
mounted() {
if (this.breakpoints) {
this.createStyle();
}
},
methods: {
toggle(event, target) {
if (this.visible) this.hide();
else this.show(event, target);
},
show(event, target) {
this.visible = true;
this.eventTarget = event.currentTarget;
this.target = target || event.currentTarget;
},
hide() {
this.visible = false;
},
onContentClick() {
this.selfClick = true;
},
onEnter(el) {
this.container.setAttribute(this.attributeSelector, '');
DomHandler.addStyles(el, { position: 'absolute', top: '0', left: '0' });
this.alignOverlay();
if (this.dismissable) {
this.bindOutsideClickListener();
}
this.bindScrollListener();
this.bindResizeListener();
if (this.autoZIndex) {
ZIndexUtils.set('overlay', el, this.baseZIndex + this.$primevue.config.zIndex.overlay);
}
this.overlayEventListener = (e) => {
if (this.container.contains(e.target)) {
this.selfClick = true;
}
};
this.focus();
OverlayEventBus.on('overlay-click', this.overlayEventListener);
this.$emit('show');
if (this.closeOnEscape) {
this.bindDocumentKeyDownListener();
}
},
onLeave() {
this.unbindOutsideClickListener();
this.unbindScrollListener();
this.unbindResizeListener();
this.unbindDocumentKeyDownListener();
OverlayEventBus.off('overlay-click', this.overlayEventListener);
this.overlayEventListener = null;
this.$emit('hide');
},
onAfterLeave(el) {
if (this.autoZIndex) {
ZIndexUtils.clear(el);
}
},
alignOverlay() {
DomHandler.absolutePosition(this.container, this.target, false);
const containerOffset = DomHandler.getOffset(this.container);
const targetOffset = DomHandler.getOffset(this.target);
let arrowLeft = 0;
if (containerOffset.left < targetOffset.left) {
arrowLeft = targetOffset.left - containerOffset.left;
}
this.container.style.setProperty($dt('overlay.arrow.left').name, `${arrowLeft}px`);
if (containerOffset.top < targetOffset.top) {
this.container.setAttribute('data-p-popover-flipped', 'true');
!this.isUnstyled && DomHandler.addClass(this.container, 'p-popover-flipped');
}
},
onContentKeydown(event) {
if (event.code === 'Escape' && this.closeOnEscape) {
this.hide();
DomHandler.focus(this.target);
}
},
onButtonKeydown(event) {
switch (event.code) {
case 'ArrowDown':
case 'ArrowUp':
case 'ArrowLeft':
case 'ArrowRight':
event.preventDefault();
default:
break;
}
},
focus() {
let focusTarget = this.container.querySelector('[autofocus]');
if (focusTarget) {
focusTarget.focus();
}
},
onKeyDown(event) {
if (event.code === 'Escape' && this.closeOnEscape) {
this.visible = false;
}
},
bindDocumentKeyDownListener() {
if (!this.documentKeydownListener) {
this.documentKeydownListener = this.onKeyDown.bind(this);
window.document.addEventListener('keydown', this.documentKeydownListener);
}
},
unbindDocumentKeyDownListener() {
if (this.documentKeydownListener) {
window.document.removeEventListener('keydown', this.documentKeydownListener);
this.documentKeydownListener = null;
}
},
bindOutsideClickListener() {
if (!this.outsideClickListener && DomHandler.isClient()) {
this.outsideClickListener = (event) => {
if (this.visible && !this.selfClick && !this.isTargetClicked(event)) {
this.visible = false;
}
this.selfClick = false;
};
document.addEventListener('click', this.outsideClickListener);
}
},
unbindOutsideClickListener() {
if (this.outsideClickListener) {
document.removeEventListener('click', this.outsideClickListener);
this.outsideClickListener = null;
this.selfClick = false;
}
},
bindScrollListener() {
if (!this.scrollHandler) {
this.scrollHandler = new ConnectedOverlayScrollHandler(this.target, () => {
if (this.visible) {
this.visible = false;
}
});
}
this.scrollHandler.bindScrollListener();
},
unbindScrollListener() {
if (this.scrollHandler) {
this.scrollHandler.unbindScrollListener();
}
},
bindResizeListener() {
if (!this.resizeListener) {
this.resizeListener = () => {
if (this.visible && !DomHandler.isTouchDevice()) {
this.visible = false;
}
};
window.addEventListener('resize', this.resizeListener);
}
},
unbindResizeListener() {
if (this.resizeListener) {
window.removeEventListener('resize', this.resizeListener);
this.resizeListener = null;
}
},
isTargetClicked(event) {
return this.eventTarget && (this.eventTarget === event.target || this.eventTarget.contains(event.target));
},
containerRef(el) {
this.container = el;
},
createStyle() {
if (!this.styleElement && !this.isUnstyled) {
this.styleElement = document.createElement('style');
this.styleElement.type = 'text/css';
DomHandler.setAttribute(this.styleElement, 'nonce', this.$primevue?.config?.csp?.nonce);
document.head.appendChild(this.styleElement);
let innerHTML = '';
for (let breakpoint in this.breakpoints) {
innerHTML += `
@media screen and (max-width: ${breakpoint}) {
.p-popover[${this.attributeSelector}] {
width: ${this.breakpoints[breakpoint]} !important;
}
}
`;
}
this.styleElement.innerHTML = innerHTML;
}
},
destroyStyle() {
if (this.styleElement) {
document.head.removeChild(this.styleElement);
this.styleElement = null;
}
},
onOverlayClick(event) {
OverlayEventBus.emit('overlay-click', {
originalEvent: event,
target: this.target
});
}
},
computed: {
attributeSelector() {
return UniqueComponentId();
}
},
directives: {
focustrap: FocusTrap,
ripple: Ripple
},
components: {
Portal
}
};
</script>

View File

@ -0,0 +1,9 @@
{
"main": "./popover.cjs.js",
"module": "./popover.esm.js",
"unpkg": "./popover.min.js",
"types": "./Popover.d.ts",
"browser": {
"./sfc": "./Popover.vue"
}
}

View File

@ -0,0 +1,3 @@
import { BaseStyle } from '../../base/style/BaseStyle';
export interface PopoverStyle extends BaseStyle {}

View File

@ -0,0 +1,16 @@
import BaseStyle from 'primevue/base/style';
const classes = {
root: ({ instance }) => [
'p-popover p-component',
{
'p-ripple-disabled': instance.$primevue.config.ripple === false
}
],
content: 'p-popover-content'
};
export default BaseStyle.extend({
name: 'popover',
classes
});

View File

@ -0,0 +1,6 @@
{
"main": "./popoverstyle.cjs.js",
"module": "./popoverstyle.esm.js",
"unpkg": "./popoverstyle.min.js",
"types": "./PopoverStyle.d.ts"
}

View File

@ -2,9 +2,9 @@ export default {
css: ({ dt }) => ` css: ({ dt }) => `
.p-popover { .p-popover {
margin-top: 10px; margin-top: 10px;
background: ${dt('overlaypanel.background')}; background: ${dt('popover.background')};
color: ${dt('overlaypanel.color')}; color: ${dt('popover.color')};
border: 1px solid ${dt('overlaypanel.border.color')}; border: 1px solid ${dt('popover.border.color')};
border-radius: ${dt('rounded.base')}; border-radius: ${dt('rounded.base')};
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1); box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
} }
@ -51,7 +51,7 @@ export default {
margin-left: -8px; margin-left: -8px;
border-style: solid; border-style: solid;
border-color: transparent; border-color: transparent;
border-bottom-color: ${dt('overlaypanel.background')}; border-bottom-color: ${dt('popover.background')};
} }
.p-popover:before { .p-popover:before {
@ -59,7 +59,7 @@ export default {
margin-left: -10px; margin-left: -10px;
border-style: solid; border-style: solid;
border-color: transparent; border-color: transparent;
border-bottom-color: ${dt('overlaypanel.border.color')}; border-bottom-color: ${dt('popover.border.color')};
} }
.p-popover-flipped:after, .p-popover-flipped:after,
@ -70,12 +70,12 @@ export default {
.p-popover.p-popover-flipped:after { .p-popover.p-popover-flipped:after {
border-bottom-color: transparent; border-bottom-color: transparent;
border-top-color: ${dt('overlaypanel.background')}; border-top-color: ${dt('popover.background')};
} }
.p-popover.p-popover-flipped:before { .p-popover.p-popover-flipped:before {
border-bottom-color: transparent; border-bottom-color: transparent;
border-top-color: ${dt('overlaypanel.border.color')}; border-top-color: ${dt('popover.border.color')};
} }
` `
}; };