repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
YaroShkvorets/ant-design-vue
|
components/vc-trigger/utils/alignUtil.ts
|
<reponame>YaroShkvorets/ant-design-vue
import type { AlignType, BuildInPlacements, AlignPoint } from '../interface';
function isPointsEq(a1: AlignPoint[], a2: AlignPoint[], isAlignPoint: boolean): boolean {
if (isAlignPoint) {
return a1[0] === a2[0];
}
return a1[0] === a2[0] && a1[1] === a2[1];
}
export function getAlignFromPlacement(
builtinPlacements: BuildInPlacements,
placementStr: string,
align: AlignType,
): AlignType {
const baseAlign = builtinPlacements[placementStr] || {};
return {
...baseAlign,
...align,
};
}
export function getAlignPopupClassName(
builtinPlacements: BuildInPlacements,
prefixCls: string,
align: AlignType,
isAlignPoint: boolean,
): string {
const { points } = align;
const placements = Object.keys(builtinPlacements);
for (let i = 0; i < placements.length; i += 1) {
const placement = placements[i];
if (isPointsEq(builtinPlacements[placement].points, points, isAlignPoint)) {
return `${prefixCls}-placement-${placement}`;
}
}
return '';
}
|
YaroShkvorets/ant-design-vue
|
components/locale/nb_NO.tsx
|
<gh_stars>1000+
/* eslint-disable no-template-curly-in-string */
import Pagination from '../vc-pagination/locale/nb_NO';
import DatePicker from '../date-picker/locale/nb_NO';
import TimePicker from '../time-picker/locale/nb_NO';
import Calendar from '../calendar/locale/nb_NO';
import type { Locale } from '../locale-provider';
const typeTemplate = '${label} er ikke et gyldig ${type}';
const localeValues: Locale = {
locale: 'nb',
Pagination,
DatePicker,
TimePicker,
Calendar,
global: {
placeholder: 'Vennligst velg',
},
Table: {
filterTitle: 'Filtermeny',
filterConfirm: 'OK',
filterReset: 'Nullstill',
filterEmptyText: 'Ingen filtre',
selectAll: 'Velg alle',
selectInvert: 'Inverter gjeldende side',
selectionAll: 'Velg all data',
sortTitle: 'Sorter',
expand: 'Utvid rad',
collapse: 'Skjul rad',
triggerDesc: 'Sorter data i synkende rekkefølge',
triggerAsc: 'Sorterer data i stigende rekkefølge',
cancelSort: 'Klikk for å avbryte sorteringen',
},
Modal: {
okText: 'OK',
cancelText: 'Avbryt',
justOkText: 'OK',
},
Popconfirm: {
okText: 'OK',
cancelText: 'Avbryt',
},
Transfer: {
titles: ['', ''],
searchPlaceholder: 'Søk her',
itemUnit: 'element',
itemsUnit: 'elementer',
remove: 'Fjern',
selectCurrent: 'Velg gjeldende side',
removeCurrent: 'Fjern gjeldende side',
selectAll: 'Velg all data',
removeAll: 'Fjern all data',
selectInvert: 'Inverter gjeldende side',
},
Upload: {
uploading: 'Laster opp...',
removeFile: 'Fjern fil',
uploadError: 'Feil ved opplastning',
previewFile: 'Forhåndsvisning',
downloadFile: '<NAME>',
},
Empty: {
description: 'Ingen data',
},
Icon: {
icon: 'ikon',
},
Text: {
edit: 'Rediger',
copy: 'Kopier',
copied: 'Kopiert',
expand: 'Utvid',
},
PageHeader: {
back: 'Tilbake',
},
Form: {
defaultValidateMessages: {
default: 'Feltvalideringsfeil ${label}',
required: 'Vennligst skriv inn ${label}',
enum: '${label} må være en av [${enum}]',
whitespace: '${label} kan ikke være et blankt tegn',
date: {
format: '${label} datoformatet er ugyldig',
parse: '${label} kan ikke konverteres til en dato',
invalid: '${label} er en ugyldig dato',
},
types: {
string: typeTemplate,
method: typeTemplate,
array: typeTemplate,
object: typeTemplate,
number: typeTemplate,
date: typeTemplate,
boolean: typeTemplate,
integer: typeTemplate,
float: typeTemplate,
regexp: typeTemplate,
email: typeTemplate,
url: typeTemplate,
hex: typeTemplate,
},
string: {
len: '${label} må være ${len} tegn',
min: '${label} må minst ha ${min} tegn',
max: '${label} opp til ${max} tegn',
range: '${label} må være mellom ${min}-${max} tegn',
},
number: {
len: '${label} må være lik ${len}',
min: '${label} minimumsverdien er ${min}',
max: '${label} maksimumsverdien er ${max}',
range: '${label} må være mellom ${min}-${max}',
},
array: {
len: 'Må være ${len} ${label}',
min: 'Må være minst ${min} ${label}',
max: 'På det meste ${max} ${label}',
range: 'Totalt av ${label} må være mellom ${min}-${max}',
},
pattern: {
mismatch: '${label} stemmer ikke overens med mønsteret ${pattern}',
},
},
},
};
export default localeValues;
|
YaroShkvorets/ant-design-vue
|
components/vc-picker/PickerPanel.tsx
|
<reponame>YaroShkvorets/ant-design-vue
/**
* Logic:
* When `mode` === `picker`,
* click will trigger `onSelect` (if value changed trigger `onChange` also).
* Panel change will not trigger `onSelect` but trigger `onPanelChange`
*/
import type { SharedTimeProps } from './panels/TimePanel';
import TimePanel from './panels/TimePanel';
import DatetimePanel from './panels/DatetimePanel';
import DatePanel from './panels/DatePanel';
import WeekPanel from './panels/WeekPanel';
import MonthPanel from './panels/MonthPanel';
import QuarterPanel from './panels/QuarterPanel';
import YearPanel from './panels/YearPanel';
import DecadePanel from './panels/DecadePanel';
import type { GenerateConfig } from './generate';
import type {
Locale,
PanelMode,
PanelRefProps,
PickerMode,
DisabledTime,
OnPanelChange,
Components,
} from './interface';
import { isEqual } from './utils/dateUtil';
import { useInjectPanel, useProvidePanel } from './PanelContext';
import type { DateRender } from './panels/DatePanel/DateBody';
import { PickerModeMap } from './utils/uiUtil';
import type { MonthCellRender } from './panels/MonthPanel/MonthBody';
import { useInjectRange } from './RangeContext';
import getExtraFooter from './utils/getExtraFooter';
import getRanges from './utils/getRanges';
import { getLowerBoundTime, setDateTime, setTime } from './utils/timeUtil';
import type { VueNode } from '../_util/type';
import { computed, createVNode, defineComponent, ref, toRef, watch, watchEffect } from 'vue';
import useMergedState from '../_util/hooks/useMergedState';
import { warning } from '../vc-util/warning';
import KeyCode from '../_util/KeyCode';
import classNames from '../_util/classNames';
export type PickerPanelSharedProps<DateType> = {
prefixCls?: string;
// className?: string;
// style?: React.CSSProperties;
/** @deprecated Will be removed in next big version. Please use `mode` instead */
mode?: PanelMode;
tabindex?: number;
// Locale
locale: Locale;
generateConfig: GenerateConfig<DateType>;
// Value
value?: DateType | null;
defaultValue?: DateType;
/** [Legacy] Set default display picker view date */
pickerValue?: DateType;
/** [Legacy] Set default display picker view date */
defaultPickerValue?: DateType;
// Date
disabledDate?: (date: DateType) => boolean;
// Render
dateRender?: DateRender<DateType>;
monthCellRender?: MonthCellRender<DateType>;
renderExtraFooter?: (mode: PanelMode) => VueNode;
// Event
onSelect?: (value: DateType) => void;
onChange?: (value: DateType) => void;
onPanelChange?: OnPanelChange<DateType>;
onMousedown?: (e: MouseEvent) => void;
onOk?: (date: DateType) => void;
direction?: 'ltr' | 'rtl';
/** @private This is internal usage. Do not use in your production env */
hideHeader?: boolean;
/** @private This is internal usage. Do not use in your production env */
onPickerValueChange?: (date: DateType) => void;
/** @private Internal usage. Do not use in your production env */
components?: Components;
};
export type PickerPanelBaseProps<DateType> = {
picker: Exclude<PickerMode, 'date' | 'time'>;
} & PickerPanelSharedProps<DateType>;
export type PickerPanelDateProps<DateType> = {
picker?: 'date';
showToday?: boolean;
showNow?: boolean;
// Time
showTime?: boolean | SharedTimeProps<DateType>;
disabledTime?: DisabledTime<DateType>;
} & PickerPanelSharedProps<DateType>;
export type PickerPanelTimeProps<DateType> = {
picker: 'time';
} & PickerPanelSharedProps<DateType> &
SharedTimeProps<DateType>;
export type PickerPanelProps<DateType> =
| PickerPanelBaseProps<DateType>
| PickerPanelDateProps<DateType>
| PickerPanelTimeProps<DateType>;
// TMP type to fit for ts 3.9.2
type OmitType<DateType> = Omit<PickerPanelBaseProps<DateType>, 'picker'> &
Omit<PickerPanelDateProps<DateType>, 'picker'> &
Omit<PickerPanelTimeProps<DateType>, 'picker'>;
type MergedPickerPanelProps<DateType> = {
picker?: PickerMode;
} & OmitType<DateType>;
function PickerPanel<DateType>() {
return defineComponent<MergedPickerPanelProps<DateType>>({
name: 'PickerPanel',
inheritAttrs: false,
props: {
prefixCls: String,
locale: Object,
generateConfig: Object,
value: Object,
defaultValue: Object,
pickerValue: Object,
defaultPickerValue: Object,
disabledDate: Function,
mode: String,
picker: { type: String, default: 'date' },
tabindex: { type: [Number, String], default: 0 },
showNow: { type: Boolean, default: undefined },
showTime: [Boolean, Object],
showToday: Boolean,
renderExtraFooter: Function,
dateRender: Function,
hideHeader: { type: Boolean, default: undefined },
onSelect: Function,
onChange: Function,
onPanelChange: Function,
onMousedown: Function,
onPickerValueChange: Function,
onOk: Function,
components: Object,
direction: String,
hourStep: { type: Number, default: 1 },
minuteStep: { type: Number, default: 1 },
secondStep: { type: Number, default: 1 },
} as any,
setup(props, { attrs }) {
const needConfirmButton = computed(
() => (props.picker === 'date' && !!props.showTime) || props.picker === 'time',
);
const isHourStepValid = computed(() => 24 % props.hourStep === 0);
const isMinuteStepValid = computed(() => 60 % props.minuteStep === 0);
const isSecondStepValid = computed(() => 60 % props.secondStep === 0);
if (process.env.NODE_ENV !== 'production') {
watchEffect(() => {
const { generateConfig, value, hourStep = 1, minuteStep = 1, secondStep = 1 } = props;
warning(!value || generateConfig.isValidate(value), 'Invalidate date pass to `value`.');
warning(
!value || generateConfig.isValidate(value),
'Invalidate date pass to `defaultValue`.',
);
warning(
isHourStepValid.value,
`\`hourStep\` ${hourStep} is invalid. It should be a factor of 24.`,
);
warning(
isMinuteStepValid.value,
`\`minuteStep\` ${minuteStep} is invalid. It should be a factor of 60.`,
);
warning(
isSecondStepValid.value,
`\`secondStep\` ${secondStep} is invalid. It should be a factor of 60.`,
);
});
}
const panelContext = useInjectPanel();
const {
operationRef,
panelRef: panelDivRef,
onSelect: onContextSelect,
hideRanges,
defaultOpenValue,
} = panelContext;
const { inRange, panelPosition, rangedValue, hoverRangedValue } = useInjectRange();
const panelRef = ref<PanelRefProps>({});
// Value
const [mergedValue, setInnerValue] = useMergedState<DateType | null>(null, {
value: toRef(props, 'value'),
defaultValue: props.defaultValue,
postState: val => {
if (!val && defaultOpenValue?.value && props.picker === 'time') {
return defaultOpenValue.value;
}
return val;
},
});
// View date control
const [viewDate, setInnerViewDate] = useMergedState<DateType | null>(null, {
value: toRef(props, 'pickerValue'),
defaultValue: props.defaultPickerValue || mergedValue.value,
postState: date => {
const { generateConfig, showTime, defaultValue } = props;
const now = generateConfig.getNow();
if (!date) return now;
// When value is null and set showTime
if (!mergedValue.value && props.showTime) {
if (typeof showTime === 'object') {
return setDateTime(generateConfig, date, showTime.defaultValue || now);
}
if (defaultValue) {
return setDateTime(generateConfig, date, defaultValue);
}
return setDateTime(generateConfig, date, now);
}
return date;
},
});
const setViewDate = (date: DateType) => {
setInnerViewDate(date);
if (props.onPickerValueChange) {
props.onPickerValueChange(date);
}
};
// Panel control
const getInternalNextMode = (nextMode: PanelMode): PanelMode => {
const getNextMode = PickerModeMap[props.picker!];
if (getNextMode) {
return getNextMode(nextMode);
}
return nextMode;
};
// Save panel is changed from which panel
const [mergedMode, setInnerMode] = useMergedState(
() => {
if (props.picker === 'time') {
return 'time';
}
return getInternalNextMode('date');
},
{
value: toRef(props, 'mode'),
},
);
watch(
() => props.picker,
() => {
setInnerMode(props.picker);
},
);
const sourceMode = ref(mergedMode.value);
const setSourceMode = (val: PanelMode) => {
sourceMode.value = val;
};
const onInternalPanelChange = (newMode: PanelMode | null, viewValue: DateType) => {
const { onPanelChange, generateConfig } = props;
const nextMode = getInternalNextMode(newMode || mergedMode.value);
setSourceMode(mergedMode.value);
setInnerMode(nextMode);
if (
onPanelChange &&
(mergedMode.value !== nextMode || isEqual(generateConfig, viewDate.value, viewDate.value))
) {
onPanelChange(viewValue, nextMode);
}
};
const triggerSelect = (
date: DateType,
type: 'key' | 'mouse' | 'submit',
forceTriggerSelect = false,
) => {
const { picker, generateConfig, onSelect, onChange, disabledDate } = props;
if (mergedMode.value === picker || forceTriggerSelect) {
setInnerValue(date);
if (onSelect) {
onSelect(date);
}
if (onContextSelect) {
onContextSelect(date, type);
}
if (
onChange &&
!isEqual(generateConfig, date, mergedValue.value) &&
!disabledDate?.(date)
) {
onChange(date);
}
}
};
// ========================= Interactive ==========================
const onInternalKeydown = (e: KeyboardEvent) => {
if (panelRef.value && panelRef.value.onKeydown) {
if (
[
KeyCode.LEFT,
KeyCode.RIGHT,
KeyCode.UP,
KeyCode.DOWN,
KeyCode.PAGE_UP,
KeyCode.PAGE_DOWN,
KeyCode.ENTER,
].includes(e.which)
) {
e.preventDefault();
}
return panelRef.value.onKeydown(e);
}
/* istanbul ignore next */
/* eslint-disable no-lone-blocks */
{
warning(
false,
'Panel not correct handle keyDown event. Please help to fire issue about this.',
);
return false;
}
/* eslint-enable no-lone-blocks */
};
const onInternalBlur = (e: FocusEvent) => {
if (panelRef.value && panelRef.value.onBlur) {
panelRef.value.onBlur(e);
}
};
const onNow = () => {
const { generateConfig, hourStep, minuteStep, secondStep } = props;
const now = generateConfig.getNow();
const lowerBoundTime = getLowerBoundTime(
generateConfig.getHour(now),
generateConfig.getMinute(now),
generateConfig.getSecond(now),
isHourStepValid.value ? hourStep : 1,
isMinuteStepValid.value ? minuteStep : 1,
isSecondStepValid.value ? secondStep : 1,
);
const adjustedNow = setTime(
generateConfig,
now,
lowerBoundTime[0], // hour
lowerBoundTime[1], // minute
lowerBoundTime[2], // second
);
triggerSelect(adjustedNow, 'submit');
};
const classString = computed(() => {
const { prefixCls, direction } = props;
return classNames(`${prefixCls}-panel`, {
[`${prefixCls}-panel-has-range`]:
rangedValue && rangedValue.value && rangedValue.value[0] && rangedValue.value[1],
[`${prefixCls}-panel-has-range-hover`]:
hoverRangedValue &&
hoverRangedValue.value &&
hoverRangedValue.value[0] &&
hoverRangedValue.value[1],
[`${prefixCls}-panel-rtl`]: direction === 'rtl',
});
});
useProvidePanel({
...panelContext,
mode: mergedMode,
hideHeader: computed(() =>
props.hideHeader !== undefined ? props.hideHeader : panelContext.hideHeader?.value,
),
hidePrevBtn: computed(() => inRange.value && panelPosition.value === 'right'),
hideNextBtn: computed(() => inRange.value && panelPosition.value === 'left'),
});
watch(
() => props.value,
() => {
if (props.value) {
setInnerViewDate(props.value);
}
},
);
return () => {
const {
prefixCls = 'ant-picker',
locale,
generateConfig,
disabledDate,
picker = 'date',
tabindex = 0,
showNow,
showTime,
showToday,
renderExtraFooter,
onMousedown,
onOk,
components,
} = props;
if (operationRef && panelPosition.value !== 'right') {
operationRef.value = {
onKeydown: onInternalKeydown,
onClose: () => {
if (panelRef.value && panelRef.value.onClose) {
panelRef.value.onClose();
}
},
};
}
// ============================ Panels ============================
let panelNode: VueNode;
const pickerProps = {
...attrs,
...(props as MergedPickerPanelProps<DateType>),
operationRef: panelRef,
prefixCls,
viewDate: viewDate.value,
value: mergedValue.value,
onViewDateChange: setViewDate,
sourceMode: sourceMode.value,
onPanelChange: onInternalPanelChange,
disabledDate,
};
delete pickerProps.onChange;
delete pickerProps.onSelect;
switch (mergedMode.value) {
case 'decade':
panelNode = (
<DecadePanel<DateType>
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
break;
case 'year':
panelNode = (
<YearPanel<DateType>
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
break;
case 'month':
panelNode = (
<MonthPanel<DateType>
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
break;
case 'quarter':
panelNode = (
<QuarterPanel<DateType>
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
break;
case 'week':
panelNode = (
<WeekPanel
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
break;
case 'time':
delete pickerProps.showTime;
panelNode = (
<TimePanel<DateType>
{...pickerProps}
{...(typeof showTime === 'object' ? showTime : null)}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
break;
default:
if (showTime) {
panelNode = (
<DatetimePanel
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
} else {
panelNode = (
<DatePanel<DateType>
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
}
}
// ============================ Footer ============================
let extraFooter: VueNode;
let rangesNode: VueNode;
if (!hideRanges?.value) {
extraFooter = getExtraFooter(prefixCls, mergedMode.value, renderExtraFooter);
rangesNode = getRanges({
prefixCls,
components,
needConfirmButton: needConfirmButton.value,
okDisabled: !mergedValue.value || (disabledDate && disabledDate(mergedValue.value)),
locale,
showNow,
onNow: needConfirmButton.value && onNow,
onOk: () => {
if (mergedValue.value) {
triggerSelect(mergedValue.value, 'submit', true);
if (onOk) {
onOk(mergedValue.value);
}
}
},
});
}
let todayNode: VueNode;
if (showToday && mergedMode.value === 'date' && picker === 'date' && !showTime) {
const now = generateConfig.getNow();
const todayCls = `${prefixCls}-today-btn`;
const disabled = disabledDate && disabledDate(now);
todayNode = (
<a
class={classNames(todayCls, disabled && `${todayCls}-disabled`)}
aria-disabled={disabled}
onClick={() => {
if (!disabled) {
triggerSelect(now, 'mouse', true);
}
}}
>
{locale.today}
</a>
);
}
return (
<div
tabindex={tabindex}
class={classNames(classString.value, attrs.class)}
style={attrs.style}
onKeydown={onInternalKeydown}
onBlur={onInternalBlur}
onMousedown={onMousedown}
ref={panelDivRef}
>
{panelNode}
{extraFooter || rangesNode || todayNode ? (
<div class={`${prefixCls}-footer`}>
{extraFooter}
{rangesNode}
{todayNode}
</div>
) : null}
</div>
);
};
},
});
}
const InterPickerPanel = PickerPanel<any>();
export default <DateType extends any>(props: MergedPickerPanelProps<DateType>): JSX.Element =>
createVNode(InterPickerPanel, props);
|
YaroShkvorets/ant-design-vue
|
components/descriptions/index.tsx
|
<filename>components/descriptions/index.tsx<gh_stars>1000+
import type {
Ref,
App,
PropType,
VNode,
HTMLAttributes,
ExtractPropTypes,
Plugin,
CSSProperties,
InjectionKey,
} from 'vue';
import { ref, defineComponent, onMounted, onBeforeUnmount, provide, toRef, computed } from 'vue';
import warning from '../_util/warning';
import type { Breakpoint, ScreenMap } from '../_util/responsiveObserve';
import ResponsiveObserve, { responsiveArray } from '../_util/responsiveObserve';
import Row from './Row';
import PropTypes from '../_util/vue-types';
import { tuple } from '../_util/type';
import { cloneElement } from '../_util/vnode';
import { flattenChildren } from '../_util/props-util';
import useConfigInject from '../_util/hooks/useConfigInject';
export const DescriptionsItemProps = {
prefixCls: PropTypes.string,
label: PropTypes.any,
span: PropTypes.number,
};
const descriptionsItemProp = {
prefixCls: PropTypes.string,
label: PropTypes.VNodeChild,
labelStyle: PropTypes.style,
contentStyle: PropTypes.style,
span: PropTypes.number.def(1),
};
export type DescriptionsItemProp = Partial<ExtractPropTypes<typeof descriptionsItemProp>>;
export const DescriptionsItem = defineComponent({
name: 'ADescriptionsItem',
props: descriptionsItemProp,
slots: ['label'],
setup(_, { slots }) {
return () => slots.default?.();
},
});
const DEFAULT_COLUMN_MAP: Partial<Record<Breakpoint, number>> = {
xxl: 3,
xl: 3,
lg: 3,
md: 3,
sm: 2,
xs: 1,
};
function getColumn(column: DescriptionsProps['column'], screens: ScreenMap): number {
if (typeof column === 'number') {
return column;
}
if (typeof column === 'object') {
for (let i = 0; i < responsiveArray.length; i++) {
const breakpoint: Breakpoint = responsiveArray[i];
if (screens[breakpoint] && column[breakpoint] !== undefined) {
return column[breakpoint] || DEFAULT_COLUMN_MAP[breakpoint];
}
}
}
return 3;
}
function getFilledItem(node: VNode, span: number | undefined, rowRestCol: number): VNode {
let clone = node;
if (span === undefined || span > rowRestCol) {
clone = cloneElement(node, {
span: rowRestCol,
});
warning(
span === undefined,
'Descriptions',
'Sum of column `span` in a line not match `column` of Descriptions.',
);
}
return clone;
}
function getRows(children: VNode[], column: number) {
const childNodes = flattenChildren(children);
const rows: VNode[][] = [];
let tmpRow: VNode[] = [];
let rowRestCol = column;
childNodes.forEach((node, index) => {
const span: number | undefined = node.props?.span;
const mergedSpan = span || 1;
// Additional handle last one
if (index === childNodes.length - 1) {
tmpRow.push(getFilledItem(node, span, rowRestCol));
rows.push(tmpRow);
return;
}
if (mergedSpan < rowRestCol) {
rowRestCol -= mergedSpan;
tmpRow.push(node);
} else {
tmpRow.push(getFilledItem(node, mergedSpan, rowRestCol));
rows.push(tmpRow);
rowRestCol = column;
tmpRow = [];
}
});
return rows;
}
const descriptionsProps = {
prefixCls: PropTypes.string,
bordered: PropTypes.looseBool,
size: PropTypes.oneOf(tuple('default', 'middle', 'small')).def('default'),
title: PropTypes.VNodeChild,
extra: PropTypes.VNodeChild,
column: {
type: [Number, Object] as PropType<number | Partial<Record<Breakpoint, number>>>,
default: (): number | Partial<Record<Breakpoint, number>> => DEFAULT_COLUMN_MAP,
},
layout: PropTypes.oneOf(tuple('horizontal', 'vertical')),
colon: PropTypes.looseBool,
labelStyle: PropTypes.style,
contentStyle: PropTypes.style,
};
export type DescriptionsProps = HTMLAttributes &
Partial<ExtractPropTypes<typeof descriptionsProps>>;
export interface DescriptionsContextProp {
labelStyle?: Ref<CSSProperties>;
contentStyle?: Ref<CSSProperties>;
}
export const descriptionsContext: InjectionKey<DescriptionsContextProp> =
Symbol('descriptionsContext');
const Descriptions = defineComponent({
name: 'ADescriptions',
props: descriptionsProps,
slots: ['title', 'extra'],
Item: DescriptionsItem,
setup(props, { slots }) {
const { prefixCls, direction } = useConfigInject('descriptions', props);
let token: number;
const screens = ref<ScreenMap>({});
onMounted(() => {
token = ResponsiveObserve.subscribe(screen => {
if (typeof props.column !== 'object') {
return;
}
screens.value = screen;
});
});
onBeforeUnmount(() => {
ResponsiveObserve.unsubscribe(token);
});
provide(descriptionsContext, {
labelStyle: toRef(props, 'labelStyle'),
contentStyle: toRef(props, 'contentStyle'),
});
const mergeColumn = computed(() => getColumn(props.column, screens.value));
return () => {
const {
size,
bordered = false,
layout = 'horizontal',
colon = true,
title = slots.title?.(),
extra = slots.extra?.(),
} = props;
const children = slots.default?.();
const rows = getRows(children, mergeColumn.value);
return (
<div
class={[
prefixCls.value,
{
[`${prefixCls.value}-${size}`]: size !== 'default',
[`${prefixCls.value}-bordered`]: !!bordered,
[`${prefixCls.value}-rtl`]: direction.value === 'rtl',
},
]}
>
{(title || extra) && (
<div class={`${prefixCls.value}-header`}>
{title && <div class={`${prefixCls.value}-title`}>{title}</div>}
{extra && <div class={`${prefixCls.value}-extra`}>{extra}</div>}
</div>
)}
<div class={`${prefixCls.value}-view`}>
<table>
<tbody>
{rows.map((row, index) => (
<Row
key={index}
index={index}
colon={colon}
prefixCls={prefixCls.value}
vertical={layout === 'vertical'}
bordered={bordered}
row={row}
/>
))}
</tbody>
</table>
</div>
</div>
);
};
},
});
Descriptions.install = function (app: App) {
app.component(Descriptions.name, Descriptions);
app.component(Descriptions.Item.name, Descriptions.Item);
return app;
};
export default Descriptions as typeof Descriptions &
Plugin & {
readonly Item: typeof DescriptionsItem;
};
|
YaroShkvorets/ant-design-vue
|
components/transfer/search.tsx
|
import PropTypes from '../_util/vue-types';
import initDefaultProps from '../_util/props-util/initDefaultProps';
import CloseCircleFilled from '@ant-design/icons-vue/CloseCircleFilled';
import SearchOutlined from '@ant-design/icons-vue/SearchOutlined';
import Input from '../input';
import type { ExtractPropTypes } from 'vue';
import { defineComponent } from 'vue';
export const transferSearchProps = {
prefixCls: PropTypes.string,
placeholder: PropTypes.string,
value: PropTypes.string,
handleClear: PropTypes.func,
disabled: PropTypes.looseBool,
onChange: PropTypes.func,
};
export type TransferSearchProps = Partial<ExtractPropTypes<typeof transferSearchProps>>;
export default defineComponent({
name: 'Search',
inheritAttrs: false,
props: initDefaultProps(transferSearchProps, {
placeholder: '',
}),
emits: ['change'],
setup(props, { emit }) {
const handleChange = (e: Event) => {
emit('change', e);
};
const handleClearFn = (e: Event) => {
const { handleClear, disabled } = props;
if (!disabled && handleClear) {
handleClear(e);
}
};
return () => {
const { placeholder, value, prefixCls, disabled } = props;
const icon =
value && value.length > 0 ? (
<a class={`${prefixCls}-action`} onClick={handleClearFn}>
<CloseCircleFilled />
</a>
) : (
<span class={`${prefixCls}-action`}>
<SearchOutlined />
</span>
);
return (
<>
<Input
placeholder={placeholder}
class={prefixCls}
value={value}
onChange={handleChange}
disabled={disabled}
/>
{icon}
</>
);
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/date-picker/generatePicker/index.tsx
|
<filename>components/date-picker/generatePicker/index.tsx
import type { GenerateConfig } from '../../vc-picker/generate';
import type { SharedTimeProps } from '../../vc-picker/panels/TimePanel';
import type { PickerMode } from '../../vc-picker/interface';
import PickerButton from '../PickerButton';
import PickerTag from '../PickerTag';
import generateSinglePicker from './generateSinglePicker';
import generateRangePicker from './generateRangePicker';
export * from './interface';
export const Components = { button: PickerButton, rangeItem: PickerTag };
function toArray<T>(list: T | T[]): T[] {
if (!list) {
return [];
}
return Array.isArray(list) ? list : [list];
}
export function getTimeProps<DateType>(
props: { format?: string; picker?: PickerMode } & SharedTimeProps<DateType>,
) {
const { format, picker, showHour, showMinute, showSecond, use12Hours } = props;
const firstFormat = toArray(format)[0];
const showTimeObj: SharedTimeProps<DateType> = { ...props };
if (firstFormat && typeof firstFormat === 'string') {
if (!firstFormat.includes('s') && showSecond === undefined) {
showTimeObj.showSecond = false;
}
if (!firstFormat.includes('m') && showMinute === undefined) {
showTimeObj.showMinute = false;
}
if (!firstFormat.includes('H') && !firstFormat.includes('h') && showHour === undefined) {
showTimeObj.showHour = false;
}
if ((firstFormat.includes('a') || firstFormat.includes('A')) && use12Hours === undefined) {
showTimeObj.use12Hours = true;
}
}
if (picker === 'time') {
return showTimeObj;
}
if (typeof firstFormat === 'function') {
// format of showTime should use default when format is custom format function
delete showTimeObj.format;
}
return {
showTime: showTimeObj,
};
}
function generatePicker<DateType, ExtraProps extends {} = {}>(
generateConfig: GenerateConfig<DateType>,
extraProps?: ExtraProps,
) {
// =========================== Picker ===========================
const { DatePicker, WeekPicker, MonthPicker, YearPicker, TimePicker, QuarterPicker } =
generateSinglePicker<DateType, ExtraProps>(generateConfig, extraProps);
// ======================== Range Picker ========================
const RangePicker = generateRangePicker<DateType, ExtraProps>(generateConfig, extraProps);
return {
DatePicker,
WeekPicker,
MonthPicker,
YearPicker,
TimePicker,
QuarterPicker,
RangePicker,
};
}
export default generatePicker;
|
YaroShkvorets/ant-design-vue
|
components/slider/SliderTooltip.tsx
|
<filename>components/slider/SliderTooltip.tsx
import { onBeforeUnmount, watch, onActivated, defineComponent, ref } from 'vue';
import Tooltip, { tooltipProps } from '../tooltip';
import raf from '../_util/raf';
export default defineComponent({
name: 'SliderTooltip',
inheritAttrs: false,
props: tooltipProps(),
setup(props, { attrs, slots }) {
const innerRef = ref<any>(null);
const rafRef = ref<number | null>(null);
function cancelKeepAlign() {
raf.cancel(rafRef.value!);
rafRef.value = null;
}
function keepAlign() {
rafRef.value = raf(() => {
innerRef.value?.forcePopupAlign();
rafRef.value = null;
});
}
const align = () => {
cancelKeepAlign();
if (props.visible) {
keepAlign();
}
};
watch(
[() => props.visible, () => props.title],
() => {
align();
},
{ flush: 'post', immediate: true },
);
onActivated(() => {
align();
});
onBeforeUnmount(() => {
cancelKeepAlign();
});
return () => {
return <Tooltip ref={innerRef} {...props} {...attrs} v-slots={slots} />;
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/_util/reactivePick.ts
|
<filename>components/_util/reactivePick.ts<gh_stars>1000+
import type { UnwrapRef } from 'vue';
import { reactive, toRef } from 'vue';
/**
* Reactively pick fields from a reactive object
*
* @see https://vueuse.js.org/reactivePick
*/
export function reactivePick<T extends object, K extends keyof T>(
obj: T,
...keys: K[]
): { [S in K]: UnwrapRef<T[S]> } {
return reactive(Object.fromEntries(keys.map(k => [k, toRef(obj, k)]))) as any;
}
|
YaroShkvorets/ant-design-vue
|
components/tabs/src/hooks/useSyncState.ts
|
<gh_stars>1000+
import type { Ref } from 'vue';
import { ref } from 'vue';
type Updater<T> = (prev: T) => T;
export default function useSyncState<T>(
defaultState: T,
onChange: (newValue: T, prevValue: T) => void,
): [Ref<T>, (updater: T | Updater<T>) => void] {
const stateRef = ref(defaultState);
function setState(updater: any) {
const newValue = typeof updater === 'function' ? updater(stateRef.value) : updater;
if (newValue !== stateRef.value) {
onChange(newValue, stateRef.value as T);
}
stateRef.value = newValue;
}
return [stateRef as Ref<T>, setState];
}
|
YaroShkvorets/ant-design-vue
|
components/rate/util.ts
|
function getScroll(w: Window) {
let ret = w.pageXOffset;
const method = 'scrollLeft';
if (typeof ret !== 'number') {
const d = w.document;
// ie6,7,8 standard mode
ret = d.documentElement[method];
if (typeof ret !== 'number') {
// quirks mode
ret = d.body[method];
}
}
return ret;
}
function getClientPosition(elem: HTMLElement) {
let x: number;
let y: number;
const doc = elem.ownerDocument;
const { body } = doc;
const docElem = doc && doc.documentElement;
const box = elem.getBoundingClientRect();
x = box.left;
y = box.top;
x -= docElem.clientLeft || body.clientLeft || 0;
y -= docElem.clientTop || body.clientTop || 0;
return {
left: x,
top: y,
};
}
export function getOffsetLeft(el: HTMLElement) {
const pos = getClientPosition(el);
const doc = el.ownerDocument;
// Only IE use `parentWindow`
const w: Window = doc.defaultView || (doc as any).parentWindow;
pos.left += getScroll(w);
return pos.left;
}
|
YaroShkvorets/ant-design-vue
|
components/_util/__mocks__/Portal.tsx
|
import { defineComponent } from 'vue';
export default defineComponent({
name: 'Portal',
inheritAttrs: false,
props: ['getContainer'],
setup(_props, { slots }) {
return () => {
return slots.default?.();
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/vc-drawer/src/DrawerChild.tsx
|
import {
defineComponent,
reactive,
onMounted,
computed,
onUnmounted,
nextTick,
watch,
ref,
} from 'vue';
import classnames from '../../_util/classNames';
import getScrollBarSize from '../../_util/getScrollBarSize';
import KeyCode from '../../_util/KeyCode';
import omit from '../../_util/omit';
import supportsPassive from '../../_util/supportsPassive';
import { drawerChildProps } from './IDrawerPropTypes';
import {
addEventListener,
dataToArray,
getTouchParentScroll,
isNumeric,
removeEventListener,
transformArguments,
transitionEndFun,
windowIsUndefined,
} from './utils';
const currentDrawer: Record<string, boolean> = {};
export interface scrollLockOptions {
container: HTMLElement;
}
const DrawerChild = defineComponent({
inheritAttrs: false,
props: drawerChildProps(),
emits: ['close', 'handleClick', 'change'],
setup(props, { emit, slots }) {
const state = reactive({
startPos: {
x: null,
y: null,
},
});
let timeout;
const contentWrapper = ref<HTMLElement>();
const dom = ref<HTMLElement>();
const maskDom = ref<HTMLElement>();
const handlerDom = ref<HTMLElement>();
const contentDom = ref<HTMLElement>();
let levelDom = [];
const drawerId = `drawer_id_${Number(
(Date.now() + Math.random())
.toString()
.replace('.', Math.round(Math.random() * 9).toString()),
).toString(16)}`;
const passive = !windowIsUndefined && supportsPassive ? { passive: false } : false;
onMounted(() => {
nextTick(() => {
const { open, getContainer, showMask, autofocus } = props;
const container = getContainer?.();
getLevelDom(props);
if (open) {
if (container && container.parentNode === document.body) {
currentDrawer[drawerId] = open;
}
// 默认打开状态时推出 level;
openLevelTransition();
nextTick(() => {
if (autofocus) {
domFocus();
}
});
if (showMask) {
props.scrollLocker?.lock();
}
}
});
});
watch(
() => props.level,
() => {
getLevelDom(props);
},
{ flush: 'post' },
);
watch(
() => props.open,
() => {
const { open, getContainer, scrollLocker, showMask, autofocus } = props;
const container = getContainer?.();
if (container && container.parentNode === document.body) {
currentDrawer[drawerId] = !!open;
}
openLevelTransition();
if (open) {
if (autofocus) {
domFocus();
}
if (showMask) {
scrollLocker?.lock();
}
} else {
scrollLocker?.unLock();
}
},
{ flush: 'post' },
);
onUnmounted(() => {
const { open } = props;
delete currentDrawer[drawerId];
if (open) {
setLevelTransform(false);
document.body.style.touchAction = '';
}
props.scrollLocker?.unLock();
});
watch(
() => props.placement,
val => {
if (val) {
// test 的 bug, 有动画过场,删除 dom
contentDom.value = null;
}
},
);
const domFocus = () => {
dom.value?.focus?.();
};
const removeStartHandler = (e: TouchEvent) => {
if (e.touches.length > 1) {
return;
}
state.startPos = {
x: e.touches[0].clientX,
y: e.touches[0].clientY,
};
};
const removeMoveHandler = (e: TouchEvent) => {
if (e.changedTouches.length > 1) {
return;
}
const currentTarget = e.currentTarget as HTMLElement;
const differX = e.changedTouches[0].clientX - state.startPos.x;
const differY = e.changedTouches[0].clientY - state.startPos.y;
if (
(currentTarget === maskDom.value ||
currentTarget === handlerDom.value ||
(currentTarget === contentDom.value &&
getTouchParentScroll(currentTarget, e.target as HTMLElement, differX, differY))) &&
e.cancelable
) {
e.preventDefault();
}
};
const transitionEnd = (e: TransitionEvent) => {
const dom: HTMLElement = e.target as HTMLElement;
removeEventListener(dom, transitionEndFun, transitionEnd);
dom.style.transition = '';
};
const onClose = (e: Event) => {
emit('close', e);
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.keyCode === KeyCode.ESC) {
e.stopPropagation();
onClose(e);
}
};
const onWrapperTransitionEnd = (e: TransitionEvent) => {
const { open, afterVisibleChange } = props;
if (e.target === contentWrapper.value && e.propertyName.match(/transform$/)) {
dom.value.style.transition = '';
if (!open && getCurrentDrawerSome()) {
document.body.style.overflowX = '';
if (maskDom.value) {
maskDom.value.style.left = '';
maskDom.value.style.width = '';
}
}
if (afterVisibleChange) {
afterVisibleChange(!!open);
}
}
};
const horizontalBoolAndPlacementName = computed(() => {
const { placement } = props;
const isHorizontal = placement === 'left' || placement === 'right';
const placementName = `translate${isHorizontal ? 'X' : 'Y'}`;
return {
isHorizontal,
placementName,
};
});
const openLevelTransition = () => {
const { open, width, height } = props;
const { isHorizontal, placementName } = horizontalBoolAndPlacementName.value;
const contentValue = contentDom.value
? contentDom.value.getBoundingClientRect()[isHorizontal ? 'width' : 'height']
: 0;
const value = (isHorizontal ? width : height) || contentValue;
setLevelAndScrolling(open, placementName, value);
};
const setLevelTransform = (
open?: boolean,
placementName?: string,
value?: string | number,
right?: number,
) => {
const { placement, levelMove, duration, ease, showMask } = props;
// router 切换时可能会导至页面失去滚动条,所以需要时时获取。
levelDom.forEach(dom => {
dom.style.transition = `transform ${duration} ${ease}`;
addEventListener(dom, transitionEndFun, transitionEnd);
let levelValue = open ? value : 0;
if (levelMove) {
const $levelMove = transformArguments(levelMove, { target: dom, open });
levelValue = open ? $levelMove[0] : $levelMove[1] || 0;
}
const $value = typeof levelValue === 'number' ? `${levelValue}px` : levelValue;
let placementPos = placement === 'left' || placement === 'top' ? $value : `-${$value}`;
placementPos =
showMask && placement === 'right' && right
? `calc(${placementPos} + ${right}px)`
: placementPos;
dom.style.transform = levelValue ? `${placementName}(${placementPos})` : '';
});
};
const setLevelAndScrolling = (
open?: boolean,
placementName?: string,
value?: string | number,
) => {
if (!windowIsUndefined) {
const right =
document.body.scrollHeight >
(window.innerHeight || document.documentElement.clientHeight) &&
window.innerWidth > document.body.offsetWidth
? getScrollBarSize(true)
: 0;
setLevelTransform(open, placementName, value, right);
toggleScrollingToDrawerAndBody(right);
}
emit('change', open);
};
const toggleScrollingToDrawerAndBody = (right: number) => {
const { getContainer, showMask, open } = props;
const container = getContainer?.();
// 处理 body 滚动
if (container && container.parentNode === document.body && showMask) {
const eventArray = ['touchstart'];
const domArray = [document.body, maskDom.value, handlerDom.value, contentDom.value];
if (open && document.body.style.overflow !== 'hidden') {
if (right) {
addScrollingEffect(right);
}
document.body.style.touchAction = 'none';
// 手机禁滚
domArray.forEach((item, i) => {
if (!item) {
return;
}
addEventListener(
item,
eventArray[i] || 'touchmove',
i ? removeMoveHandler : removeStartHandler,
passive,
);
});
} else if (getCurrentDrawerSome()) {
document.body.style.touchAction = '';
if (right) {
remScrollingEffect(right);
}
// 恢复事件
domArray.forEach((item, i) => {
if (!item) {
return;
}
removeEventListener(
item,
eventArray[i] || 'touchmove',
i ? removeMoveHandler : removeStartHandler,
passive,
);
});
}
}
};
const addScrollingEffect = (right: number) => {
const { placement, duration, ease } = props;
const widthTransition = `width ${duration} ${ease}`;
const transformTransition = `transform ${duration} ${ease}`;
dom.value.style.transition = 'none';
switch (placement) {
case 'right':
dom.value.style.transform = `translateX(-${right}px)`;
break;
case 'top':
case 'bottom':
dom.value.style.width = `calc(100% - ${right}px)`;
dom.value.style.transform = 'translateZ(0)';
break;
default:
break;
}
clearTimeout(timeout);
timeout = setTimeout(() => {
if (dom.value) {
dom.value.style.transition = `${transformTransition},${widthTransition}`;
dom.value.style.width = '';
dom.value.style.transform = '';
}
});
};
const remScrollingEffect = (right: number) => {
const { placement, duration, ease } = props;
dom.value.style.transition = 'none';
let heightTransition: string;
let widthTransition = `width ${duration} ${ease}`;
const transformTransition = `transform ${duration} ${ease}`;
switch (placement) {
case 'left': {
dom.value.style.width = '100%';
widthTransition = `width 0s ${ease} ${duration}`;
break;
}
case 'right': {
dom.value.style.transform = `translateX(${right}px)`;
dom.value.style.width = '100%';
widthTransition = `width 0s ${ease} ${duration}`;
if (maskDom.value) {
maskDom.value.style.left = `-${right}px`;
maskDom.value.style.width = `calc(100% + ${right}px)`;
}
break;
}
case 'top':
case 'bottom': {
dom.value.style.width = `calc(100% + ${right}px)`;
dom.value.style.height = '100%';
dom.value.style.transform = 'translateZ(0)';
heightTransition = `height 0s ${ease} ${duration}`;
break;
}
default:
break;
}
clearTimeout(timeout);
timeout = setTimeout(() => {
if (dom.value) {
dom.value.style.transition = `${transformTransition},${
heightTransition ? `${heightTransition},` : ''
}${widthTransition}`;
dom.value.style.transform = '';
dom.value.style.width = '';
dom.value.style.height = '';
}
});
};
const getCurrentDrawerSome = () => !Object.keys(currentDrawer).some(key => currentDrawer[key]);
const getLevelDom = ({ level, getContainer }) => {
if (windowIsUndefined) {
return;
}
const container = getContainer?.();
const parent = container ? (container.parentNode as HTMLElement) : null;
levelDom = [];
if (level === 'all') {
const children: HTMLElement[] = parent ? Array.prototype.slice.call(parent.children) : [];
children.forEach((child: HTMLElement) => {
if (
child.nodeName !== 'SCRIPT' &&
child.nodeName !== 'STYLE' &&
child.nodeName !== 'LINK' &&
child !== container
) {
levelDom.push(child);
}
});
} else if (level) {
dataToArray(level).forEach(key => {
document.querySelectorAll(key).forEach(item => {
levelDom.push(item);
});
});
}
};
const onHandleClick = e => {
emit('handleClick', e);
};
const canOpen = ref(false);
watch(dom, () => {
nextTick(() => {
canOpen.value = true;
});
});
return () => {
const {
width,
height,
open: $open,
prefixCls,
placement,
level,
levelMove,
ease,
duration,
getContainer,
onChange,
afterVisibleChange,
showMask,
maskClosable,
maskStyle,
keyboard,
getOpenCount,
scrollLocker,
contentWrapperStyle,
style,
class: className,
...otherProps
} = props;
// 首次渲染都将是关闭状态。
const open = $open && canOpen.value;
const wrapperClassName = classnames(prefixCls, {
[`${prefixCls}-${placement}`]: true,
[`${prefixCls}-open`]: open,
[className]: !!className,
'no-mask': !showMask,
});
const { placementName } = horizontalBoolAndPlacementName.value;
// 百分比与像素动画不同步,第一次打用后全用像素动画。
// const defaultValue = !this.contentDom || !level ? '100%' : `${value}px`;
const placementPos = placement === 'left' || placement === 'top' ? '-100%' : '100%';
const transform = open ? '' : `${placementName}(${placementPos})`;
return (
<div
{...omit(otherProps, ['switchScrollingEffect', 'autofocus'])}
tabindex={-1}
class={wrapperClassName}
style={style}
ref={dom}
onKeydown={open && keyboard ? onKeyDown : undefined}
onTransitionend={onWrapperTransitionEnd}
>
{showMask && (
<div
class={`${prefixCls}-mask`}
onClick={maskClosable ? onClose : undefined}
style={maskStyle}
ref={maskDom}
/>
)}
<div
class={`${prefixCls}-content-wrapper`}
style={{
transform,
msTransform: transform,
width: isNumeric(width) ? `${width}px` : width,
height: isNumeric(height) ? `${height}px` : height,
...contentWrapperStyle,
}}
ref={contentWrapper}
>
<div class={`${prefixCls}-content`} ref={contentDom}>
{slots.default?.()}
</div>
{slots.handler ? (
<div onClick={onHandleClick} ref={handlerDom}>
{slots.handler?.()}
</div>
) : null}
</div>
</div>
);
};
},
});
export default DrawerChild;
|
YaroShkvorets/ant-design-vue
|
components/vc-tree-select/TreeNode.tsx
|
<filename>components/vc-tree-select/TreeNode.tsx
/* istanbul ignore file */
import type { FunctionalComponent } from 'vue';
import type { DataNode, Key } from './interface';
export interface TreeNodeProps extends Omit<DataNode, 'children'> {
value: Key;
}
/** This is a placeholder, not real render in dom */
const TreeNode: FunctionalComponent<TreeNodeProps> & { isTreeSelectNode: boolean } = () => null;
TreeNode.inheritAttrs = false;
TreeNode.displayName = 'ATreeSelectNode';
TreeNode.isTreeSelectNode = true;
export default TreeNode;
|
YaroShkvorets/ant-design-vue
|
components/vc-trigger/Popup/index.tsx
|
<filename>components/vc-trigger/Popup/index.tsx
import { defineComponent, ref, watch } from 'vue';
import { popupProps } from './interface';
import Mask from './Mask';
import MobilePopupInner from './MobilePopupInner';
import PopupInner from './PopupInner';
export default defineComponent({
name: 'Popup',
inheritAttrs: false,
props: popupProps,
setup(props, { attrs, slots, expose }) {
const innerVisible = ref(false);
const inMobile = ref(false);
const popupRef = ref();
watch(
[() => props.visible, () => props.mobile],
() => {
innerVisible.value = props.visible;
if (props.visible && props.mobile) {
inMobile.value = true;
}
},
{ immediate: true, flush: 'post' },
);
expose({
forceAlign: () => {
popupRef.value?.forceAlign();
},
getElement: () => {
return popupRef.value?.getElement();
},
});
return () => {
const cloneProps = { ...props, ...attrs, visible: innerVisible.value };
const popupNode = inMobile.value ? (
<MobilePopupInner
{...cloneProps}
mobile={props.mobile}
ref={popupRef}
v-slots={{ default: slots.default }}
></MobilePopupInner>
) : (
<PopupInner {...cloneProps} ref={popupRef} v-slots={{ default: slots.default }} />
);
return (
<div>
<Mask {...cloneProps} />
{popupNode}
</div>
);
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/transfer/operation.tsx
|
<filename>components/transfer/operation.tsx
import type { CSSProperties, FunctionalComponent } from 'vue';
import LeftOutlined from '@ant-design/icons-vue/LeftOutlined';
import RightOutlined from '@ant-design/icons-vue/RightOutlined';
import Button from '../button';
import type { Direction } from '../config-provider';
function noop() {}
export interface TransferOperationProps {
class?: string;
leftArrowText?: string;
rightArrowText?: string;
moveToLeft?: (e: MouseEvent) => void;
moveToRight?: (e: MouseEvent) => void;
leftActive?: boolean;
rightActive?: boolean;
style?: CSSProperties | string;
disabled?: boolean;
direction?: Direction;
oneWay?: boolean;
}
const Operation: FunctionalComponent<TransferOperationProps> = props => {
const {
disabled,
moveToLeft = noop,
moveToRight = noop,
leftArrowText = '',
rightArrowText = '',
leftActive,
rightActive,
class: className,
style,
direction,
oneWay,
} = props;
return (
<div class={className} style={style}>
<Button
type="primary"
size="small"
disabled={disabled || !rightActive}
onClick={moveToRight}
icon={direction !== 'rtl' ? <RightOutlined /> : <LeftOutlined />}
>
{rightArrowText}
</Button>
{!oneWay && (
<Button
type="primary"
size="small"
disabled={disabled || !leftActive}
onClick={moveToLeft}
icon={direction !== 'rtl' ? <LeftOutlined /> : <RightOutlined />}
>
{leftArrowText}
</Button>
)}
</div>
);
};
Operation.displayName = 'Operation';
Operation.inheritAttrs = false;
export default Operation;
|
YaroShkvorets/ant-design-vue
|
components/vc-picker/hooks/useMergeProps.ts
|
<filename>components/vc-picker/hooks/useMergeProps.ts
import type { HTMLAttributes } from 'vue';
import { useAttrs } from 'vue';
// 仅用在函数式组件中,不用考虑响应式问题
export default function useMergeProps<T>(props: T) {
const attrs: HTMLAttributes = useAttrs();
return { ...props, ...attrs };
}
|
YaroShkvorets/ant-design-vue
|
components/vc-trigger/index.ts
|
<filename>components/vc-trigger/index.ts
// based on rc-trigger 5.2.10
import Trigger from './Trigger';
export default Trigger;
|
YaroShkvorets/ant-design-vue
|
components/vc-mentions/index.ts
|
// base rc-mentions .6.2
import Mentions from './src/Mentions';
import Option from './src/Option';
Mentions.Option = Option;
export { Option };
export default Mentions;
|
YaroShkvorets/ant-design-vue
|
components/menu/src/placements.ts
|
<reponame>YaroShkvorets/ant-design-vue<filename>components/menu/src/placements.ts
const autoAdjustOverflow = {
adjustX: 1,
adjustY: 1,
};
export const placements = {
topLeft: {
points: ['bl', 'tl'],
overflow: autoAdjustOverflow,
offset: [0, -7],
},
bottomLeft: {
points: ['tl', 'bl'],
overflow: autoAdjustOverflow,
offset: [0, 7],
},
leftTop: {
points: ['tr', 'tl'],
overflow: autoAdjustOverflow,
offset: [-4, 0],
},
rightTop: {
points: ['tl', 'tr'],
overflow: autoAdjustOverflow,
offset: [4, 0],
},
};
export const placementsRtl = {
topLeft: {
points: ['bl', 'tl'],
overflow: autoAdjustOverflow,
offset: [0, -7],
},
bottomLeft: {
points: ['tl', 'bl'],
overflow: autoAdjustOverflow,
offset: [0, 7],
},
rightTop: {
points: ['tr', 'tl'],
overflow: autoAdjustOverflow,
offset: [-4, 0],
},
leftTop: {
points: ['tl', 'tr'],
overflow: autoAdjustOverflow,
offset: [4, 0],
},
};
export default placements;
|
YaroShkvorets/ant-design-vue
|
components/vc-picker/hooks/useValueTexts.ts
|
<reponame>YaroShkvorets/ant-design-vue
import type { ComputedRef, Ref } from 'vue';
import { computed } from 'vue';
import useMemo from '../../_util/hooks/useMemo';
import shallowequal from '../../_util/shallowequal';
import type { GenerateConfig } from '../generate';
import type { CustomFormat, Locale } from '../interface';
import { formatValue } from '../utils/dateUtil';
export type ValueTextConfig<DateType> = {
formatList: ComputedRef<(string | CustomFormat<DateType>)[]>;
generateConfig: Ref<GenerateConfig<DateType>>;
locale: Ref<Locale>;
};
export default function useValueTexts<DateType>(
value: Ref<DateType | null>,
{ formatList, generateConfig, locale }: ValueTextConfig<DateType>,
): [ComputedRef<string[]>, ComputedRef<string>] {
const texts = useMemo<[string[], string]>(
() => {
if (!value.value) {
return [[''], ''];
}
// We will convert data format back to first format
let firstValueText = '';
const fullValueTexts: string[] = [];
for (let i = 0; i < formatList.value.length; i += 1) {
const format = formatList.value[i];
const formatStr = formatValue(value.value, {
generateConfig: generateConfig.value,
locale: locale.value,
format,
});
fullValueTexts.push(formatStr);
if (i === 0) {
firstValueText = formatStr;
}
}
return [fullValueTexts, firstValueText];
},
[value, formatList],
(next, prev) => prev[0] !== next[0] || !shallowequal(prev[1], next[1]),
);
const fullValueTexts = computed(() => texts.value[0]);
const firstValueText = computed(() => texts.value[1]);
return [fullValueTexts, firstValueText];
}
|
YaroShkvorets/ant-design-vue
|
components/pagination/index.ts
|
import Pagination from './Pagination';
import { withInstall } from '../_util/type';
export { paginationProps, paginationConfig } from './Pagination';
export type { PaginationProps, PaginationConfig } from './Pagination';
export default withInstall(Pagination);
|
YaroShkvorets/ant-design-vue
|
components/vc-tree-select/hooks/useSelectValues.ts
|
<reponame>YaroShkvorets/ant-design-vue<gh_stars>1000+
import type { RawValueType, FlattenDataNode, Key, LabelValueType } from '../interface';
import type { SkipType } from './useKeyValueMapping';
import { getRawValueLabeled } from '../utils/valueUtil';
import type { CheckedStrategy } from '../utils/strategyUtil';
import { formatStrategyKeys } from '../utils/strategyUtil';
import type { DefaultValueType } from '../../vc-select/interface/generator';
import type { DataEntity } from '../../vc-tree/interface';
import type { Ref } from 'vue';
import { shallowRef, watchEffect } from 'vue';
interface Config {
treeConduction: Ref<boolean>;
/** Current `value` of TreeSelect */
value: Ref<DefaultValueType>;
showCheckedStrategy: Ref<CheckedStrategy>;
conductKeyEntities: Ref<Record<Key, DataEntity>>;
getEntityByKey: (key: Key, skipType?: SkipType, ignoreDisabledCheck?: boolean) => FlattenDataNode;
getEntityByValue: (
value: RawValueType,
skipType?: SkipType,
ignoreDisabledCheck?: boolean,
) => FlattenDataNode;
getLabelProp: (entity: FlattenDataNode) => any;
}
/** Return */
export default function useSelectValues(
rawValues: Ref<RawValueType[]>,
{
value,
getEntityByValue,
getEntityByKey,
treeConduction,
showCheckedStrategy,
conductKeyEntities,
getLabelProp,
}: Config,
): Ref<LabelValueType[]> {
const rawValueLabeled = shallowRef([]);
watchEffect(() => {
let mergedRawValues = rawValues.value;
if (treeConduction.value) {
const rawKeys = formatStrategyKeys(
rawValues.value.map(val => {
const entity = getEntityByValue(val);
return entity ? entity.key : val;
}),
showCheckedStrategy.value,
conductKeyEntities.value,
);
mergedRawValues = rawKeys.map(key => {
const entity = getEntityByKey(key);
return entity ? entity.data.value : key;
});
}
rawValueLabeled.value = getRawValueLabeled(
mergedRawValues,
value.value,
getEntityByValue,
getLabelProp,
);
});
return rawValueLabeled;
}
|
YaroShkvorets/ant-design-vue
|
components/vc-image/src/Preview.tsx
|
import { computed, defineComponent, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import RotateLeftOutlined from '@ant-design/icons-vue/RotateLeftOutlined';
import RotateRightOutlined from '@ant-design/icons-vue/RotateRightOutlined';
import ZoomInOutlined from '@ant-design/icons-vue/ZoomInOutlined';
import ZoomOutOutlined from '@ant-design/icons-vue/ZoomOutOutlined';
import CloseOutlined from '@ant-design/icons-vue/CloseOutlined';
import LeftOutlined from '@ant-design/icons-vue/LeftOutlined';
import RightOutlined from '@ant-design/icons-vue/RightOutlined';
import classnames from '../../_util/classNames';
import PropTypes from '../../_util/vue-types';
import Dialog from '../../vc-dialog';
import getIDialogPropTypes from '../../vc-dialog/IDialogPropTypes';
import { getOffset } from '../../vc-util/Dom/css';
import addEventListener from '../../vc-util/Dom/addEventListener';
import { warning } from '../../vc-util/warning';
import useFrameSetState from './hooks/useFrameSetState';
import getFixScaleEleTransPosition from './getFixScaleEleTransPosition';
import { context } from './PreviewGroup';
const IDialogPropTypes = getIDialogPropTypes();
export type MouseEventHandler = (payload: MouseEvent) => void;
export interface PreviewProps extends Omit<typeof IDialogPropTypes, 'onClose'> {
onClose?: (e: Element) => void;
src?: string;
alt?: string;
}
const initialPosition = {
x: 0,
y: 0,
};
const PreviewType = {
src: PropTypes.string,
alt: PropTypes.string,
...IDialogPropTypes,
};
const Preview = defineComponent({
name: 'Preview',
inheritAttrs: false,
props: PreviewType,
emits: ['close', 'afterClose'],
setup(props, { emit, attrs }) {
const scale = ref(1);
const rotate = ref(0);
const [position, setPosition] = useFrameSetState<{
x: number;
y: number;
}>(initialPosition);
const onClose = () => emit('close');
const imgRef = ref<HTMLImageElement>();
const originPositionRef = reactive<{
originX: number;
originY: number;
deltaX: number;
deltaY: number;
}>({
originX: 0,
originY: 0,
deltaX: 0,
deltaY: 0,
});
const isMoving = ref(false);
const groupContext = context.inject();
const { previewUrls, current, isPreviewGroup, setCurrent } = groupContext;
const previewGroupCount = computed(() => Object.keys(previewUrls).length);
const previewUrlsKeys = computed(() => Object.keys(previewUrls));
const currentPreviewIndex = computed(() =>
previewUrlsKeys.value.indexOf(String(current.value)),
);
const combinationSrc = computed(() =>
isPreviewGroup.value ? previewUrls[current.value] : props.src,
);
const showLeftOrRightSwitches = computed(
() => isPreviewGroup.value && previewGroupCount.value > 1,
);
const onAfterClose = () => {
scale.value = 1;
rotate.value = 0;
setPosition(initialPosition);
};
const onZoomIn = () => {
scale.value++;
setPosition(initialPosition);
};
const onZoomOut = () => {
if (scale.value > 1) {
scale.value--;
}
setPosition(initialPosition);
};
const onRotateRight = () => {
rotate.value += 90;
};
const onRotateLeft = () => {
rotate.value -= 90;
};
const onSwitchLeft: MouseEventHandler = event => {
event.preventDefault();
// Without this mask close will abnormal
event.stopPropagation();
if (currentPreviewIndex.value > 0) {
setCurrent(previewUrlsKeys.value[String(currentPreviewIndex.value - 1)]);
}
};
const onSwitchRight: MouseEventHandler = event => {
event.preventDefault();
// Without this mask close will abnormal
event.stopPropagation();
if (currentPreviewIndex.value < previewGroupCount.value - 1) {
setCurrent(previewUrlsKeys.value[String(currentPreviewIndex.value + 1)]);
}
};
const wrapClassName = classnames({
[`${props.prefixCls}-moving`]: isMoving.value,
});
const toolClassName = `${props.prefixCls}-operations-operation`;
const iconClassName = `${props.prefixCls}-operations-icon`;
const tools = [
{
icon: CloseOutlined,
onClick: onClose,
type: 'close',
},
{
icon: ZoomInOutlined,
onClick: onZoomIn,
type: 'zoomIn',
},
{
icon: ZoomOutOutlined,
onClick: onZoomOut,
type: 'zoomOut',
disabled: computed(() => scale.value === 1),
},
{
icon: RotateRightOutlined,
onClick: onRotateRight,
type: 'rotateRight',
},
{
icon: RotateLeftOutlined,
onClick: onRotateLeft,
type: 'rotateLeft',
},
];
const onMouseUp: MouseEventHandler = () => {
if (props.visible && isMoving.value) {
const width = imgRef.value.offsetWidth * scale.value;
const height = imgRef.value.offsetHeight * scale.value;
const { left, top } = getOffset(imgRef.value);
const isRotate = rotate.value % 180 !== 0;
isMoving.value = false;
const fixState = getFixScaleEleTransPosition(
isRotate ? height : width,
isRotate ? width : height,
left,
top,
);
if (fixState) {
setPosition({ ...fixState });
}
}
};
const onMouseDown: MouseEventHandler = event => {
event.preventDefault();
// Without this mask close will abnormal
event.stopPropagation();
originPositionRef.deltaX = event.pageX - position.x;
originPositionRef.deltaY = event.pageY - position.y;
originPositionRef.originX = position.x;
originPositionRef.originY = position.y;
isMoving.value = true;
};
const onMouseMove: MouseEventHandler = event => {
if (props.visible && isMoving.value) {
setPosition({
x: event.pageX - originPositionRef.deltaX,
y: event.pageY - originPositionRef.deltaY,
});
}
};
let removeListeners = () => {};
onMounted(() => {
watch(
[() => props.visible, isMoving],
() => {
removeListeners();
let onTopMouseUpListener: { remove: any };
let onTopMouseMoveListener: { remove: any };
const onMouseUpListener = addEventListener(window, 'mouseup', onMouseUp, false);
const onMouseMoveListener = addEventListener(window, 'mousemove', onMouseMove, false);
try {
// Resolve if in iframe lost event
/* istanbul ignore next */
if (window.top !== window.self) {
onTopMouseUpListener = addEventListener(window.top, 'mouseup', onMouseUp, false);
onTopMouseMoveListener = addEventListener(
window.top,
'mousemove',
onMouseMove,
false,
);
}
} catch (error) {
/* istanbul ignore next */
warning(false, `[vc-image] ${error}`);
}
removeListeners = () => {
onMouseUpListener.remove();
onMouseMoveListener.remove();
/* istanbul ignore next */
if (onTopMouseUpListener) onTopMouseUpListener.remove();
/* istanbul ignore next */
if (onTopMouseMoveListener) onTopMouseMoveListener.remove();
};
},
{ flush: 'post', immediate: true },
);
});
onUnmounted(() => {
removeListeners();
});
return () => (
<Dialog
{...attrs}
transitionName="zoom"
maskTransitionName="fade"
closable={false}
keyboard
prefixCls={props.prefixCls}
onClose={onClose}
afterClose={onAfterClose}
visible={props.visible}
wrapClassName={wrapClassName}
getContainer={props.getContainer}
>
<ul class={`${props.prefixCls}-operations`}>
{tools.map(({ icon: IconType, onClick, type, disabled }) => (
<li
class={classnames(toolClassName, {
[`${props.prefixCls}-operations-operation-disabled`]: disabled && disabled?.value,
})}
onClick={onClick}
key={type}
>
<IconType class={iconClassName} />
</li>
))}
</ul>
<div
class={`${props.prefixCls}-img-wrapper`}
style={{
transform: `translate3d(${position.x}px, ${position.y}px, 0)`,
}}
>
<img
onMousedown={onMouseDown}
ref={imgRef}
class={`${props.prefixCls}-img`}
src={combinationSrc.value}
alt={props.alt}
style={{
transform: `scale3d(${scale.value}, ${scale.value}, 1) rotate(${rotate.value}deg)`,
}}
/>
</div>
{showLeftOrRightSwitches.value && (
<div
class={classnames(`${props.prefixCls}-switch-left`, {
[`${props.prefixCls}-switch-left-disabled`]: currentPreviewIndex.value <= 0,
})}
onClick={onSwitchLeft}
>
<LeftOutlined />
</div>
)}
{showLeftOrRightSwitches.value && (
<div
class={classnames(`${props.prefixCls}-switch-right`, {
[`${props.prefixCls}-switch-right-disabled`]:
currentPreviewIndex.value >= previewGroupCount.value - 1,
})}
onClick={onSwitchRight}
>
<RightOutlined />
</div>
)}
</Dialog>
);
},
});
export default Preview;
|
YaroShkvorets/ant-design-vue
|
components/anchor/Anchor.tsx
|
import type { ExtractPropTypes } from 'vue';
import {
defineComponent,
nextTick,
onBeforeUnmount,
onMounted,
onUpdated,
reactive,
ref,
computed,
} from 'vue';
import PropTypes from '../_util/vue-types';
import classNames from '../_util/classNames';
import addEventListener from '../vc-util/Dom/addEventListener';
import Affix from '../affix';
import scrollTo from '../_util/scrollTo';
import getScroll from '../_util/getScroll';
import useConfigInject from '../_util/hooks/useConfigInject';
import useProvideAnchor from './context';
function getDefaultContainer() {
return window;
}
function getOffsetTop(element: HTMLElement, container: AnchorContainer): number {
if (!element.getClientRects().length) {
return 0;
}
const rect = element.getBoundingClientRect();
if (rect.width || rect.height) {
if (container === window) {
container = element.ownerDocument!.documentElement!;
return rect.top - container.clientTop;
}
return rect.top - (container as HTMLElement).getBoundingClientRect().top;
}
return rect.top;
}
const sharpMatcherRegx = /#(\S+)$/;
type Section = {
link: string;
top: number;
};
export type AnchorContainer = HTMLElement | Window;
const anchorProps = {
prefixCls: PropTypes.string,
offsetTop: PropTypes.number,
bounds: PropTypes.number,
affix: PropTypes.looseBool.def(true),
showInkInFixed: PropTypes.looseBool.def(false),
getContainer: PropTypes.func.def(getDefaultContainer),
wrapperClass: PropTypes.string,
wrapperStyle: PropTypes.style,
getCurrentAnchor: PropTypes.func,
targetOffset: PropTypes.number,
onChange: PropTypes.func,
onClick: PropTypes.func,
};
export type AnchorProps = Partial<ExtractPropTypes<typeof anchorProps>>;
export interface AnchorState {
scrollContainer: HTMLElement | Window;
links: string[];
scrollEvent: any;
animating: boolean;
}
export default defineComponent({
name: 'AAnchor',
inheritAttrs: false,
props: anchorProps,
emits: ['change', 'click'],
setup(props, { emit, attrs, slots, expose }) {
const { prefixCls, getTargetContainer, direction } = useConfigInject('anchor', props);
const inkNodeRef = ref();
const anchorRef = ref();
const state = reactive<AnchorState>({
links: [],
scrollContainer: null,
scrollEvent: null,
animating: false,
});
const activeLink = ref(null);
const getContainer = computed(() => {
const { getContainer } = props;
return getContainer || getTargetContainer.value || getDefaultContainer;
});
// func...
const getCurrentAnchor = (offsetTop = 0, bounds = 5) => {
const linkSections: Array<Section> = [];
const container = getContainer.value();
state.links.forEach(link => {
const sharpLinkMatch = sharpMatcherRegx.exec(link.toString());
if (!sharpLinkMatch) {
return;
}
const target = document.getElementById(sharpLinkMatch[1]);
if (target) {
const top = getOffsetTop(target, container);
if (top < offsetTop + bounds) {
linkSections.push({
link,
top,
});
}
}
});
if (linkSections.length) {
const maxSection = linkSections.reduce((prev, curr) => (curr.top > prev.top ? curr : prev));
return maxSection.link;
}
return '';
};
const setCurrentActiveLink = (link: string) => {
const { getCurrentAnchor } = props;
if (activeLink.value === link) {
return;
}
activeLink.value = typeof getCurrentAnchor === 'function' ? getCurrentAnchor() : link;
emit('change', link);
};
const handleScrollTo = (link: string) => {
const { offsetTop, getContainer, targetOffset } = props;
setCurrentActiveLink(link);
const container = getContainer();
const scrollTop = getScroll(container, true);
const sharpLinkMatch = sharpMatcherRegx.exec(link);
if (!sharpLinkMatch) {
return;
}
const targetElement = document.getElementById(sharpLinkMatch[1]);
if (!targetElement) {
return;
}
const eleOffsetTop = getOffsetTop(targetElement, container);
let y = scrollTop + eleOffsetTop;
y -= targetOffset !== undefined ? targetOffset : offsetTop || 0;
state.animating = true;
scrollTo(y, {
callback: () => {
state.animating = false;
},
getContainer,
});
};
expose({
scrollTo: handleScrollTo,
});
const handleScroll = () => {
if (state.animating) {
return;
}
const { offsetTop, bounds, targetOffset } = props;
const currentActiveLink = getCurrentAnchor(
targetOffset !== undefined ? targetOffset : offsetTop || 0,
bounds,
);
setCurrentActiveLink(currentActiveLink);
};
const updateInk = () => {
const linkNode = anchorRef.value.getElementsByClassName(
`${prefixCls.value}-link-title-active`,
)[0];
if (linkNode) {
(inkNodeRef.value as HTMLElement).style.top = `${
linkNode.offsetTop + linkNode.clientHeight / 2 - 4.5
}px`;
}
};
useProvideAnchor({
registerLink: (link: string) => {
if (!state.links.includes(link)) {
state.links.push(link);
}
},
unregisterLink: (link: string) => {
const index = state.links.indexOf(link);
if (index !== -1) {
state.links.splice(index, 1);
}
},
activeLink,
scrollTo: handleScrollTo,
handleClick: (e, info) => {
emit('click', e, info);
},
});
onMounted(() => {
nextTick(() => {
const container = getContainer.value();
state.scrollContainer = container;
state.scrollEvent = addEventListener(state.scrollContainer, 'scroll', handleScroll);
handleScroll();
});
});
onBeforeUnmount(() => {
if (state.scrollEvent) {
state.scrollEvent.remove();
}
});
onUpdated(() => {
if (state.scrollEvent) {
const currentContainer = getContainer.value();
if (state.scrollContainer !== currentContainer) {
state.scrollContainer = currentContainer;
state.scrollEvent.remove();
state.scrollEvent = addEventListener(state.scrollContainer, 'scroll', handleScroll);
handleScroll();
}
}
updateInk();
});
return () => {
const { offsetTop, affix, showInkInFixed } = props;
const pre = prefixCls.value;
const inkClass = classNames(`${pre}-ink-ball`, {
visible: activeLink.value,
});
const wrapperClass = classNames(props.wrapperClass, `${pre}-wrapper`, {
[`${pre}-rtl`]: direction.value === 'rtl',
});
const anchorClass = classNames(pre, {
fixed: !affix && !showInkInFixed,
});
const wrapperStyle = {
maxHeight: offsetTop ? `calc(100vh - ${offsetTop}px)` : '100vh',
...props.wrapperStyle,
};
const anchorContent = (
<div class={wrapperClass} style={wrapperStyle} ref={anchorRef}>
<div class={anchorClass}>
<div class={`${pre}-ink`}>
<span class={inkClass} ref={inkNodeRef} />
</div>
{slots.default?.()}
</div>
</div>
);
return !affix ? (
anchorContent
) : (
<Affix {...attrs} offsetTop={offsetTop} target={getContainer.value}>
{anchorContent}
</Affix>
);
};
},
});
|
YaroShkvorets/ant-design-vue
|
site/typings/shared.d.ts
|
<reponame>YaroShkvorets/ant-design-vue<filename>site/typings/shared.d.ts
// types shared between server and client
export interface LocaleConfig {
lang: string;
title?: string;
description?: string;
head?: HeadConfig[];
label?: string;
selectText?: string;
}
export interface SiteData<ThemeConfig = any> {
base: string;
lang: string;
title: string;
description: string;
head: HeadConfig[];
themeConfig: ThemeConfig;
locales: Record<string, LocaleConfig>;
}
export type HeadConfig =
| [string, Record<string, string>]
| [string, Record<string, string>, string];
export interface PageData {
relativePath: string;
title: string;
description: string;
headers: Header[];
frontmatter: Record<string, any>;
lastUpdated: number;
content?: string;
html?: string;
}
export interface Header {
level: number;
title: string;
slug: string;
content: string;
}
|
YaroShkvorets/ant-design-vue
|
components/_util/omit.ts
|
<reponame>YaroShkvorets/ant-design-vue
function omit<T extends object, K extends keyof T>(obj: T, fields: K[]): Omit<T, K> {
// eslint-disable-next-line prefer-object-spread
const shallowCopy = Object.assign({}, obj);
for (let i = 0; i < fields.length; i += 1) {
const key = fields[i];
delete shallowCopy[key];
}
return shallowCopy;
}
export default omit;
|
YaroShkvorets/ant-design-vue
|
components/vc-mentions/src/DropdownMenu.tsx
|
import Menu, { Item as MenuItem } from '../../menu';
import type { PropType } from 'vue';
import { defineComponent, inject, ref } from 'vue';
import type { OptionProps } from './Option';
import MentionsContextKey from './MentionsContext';
import Spin from '../../spin';
function noop() {}
export default defineComponent({
name: 'DropdownMenu',
props: {
prefixCls: String,
options: {
type: Array as PropType<OptionProps[]>,
default: () => [],
},
},
slots: ['notFoundContent', 'option'],
setup(props, { slots }) {
const {
activeIndex,
setActiveIndex,
selectOption,
onFocus = noop,
onBlur = noop,
loading,
} = inject(MentionsContextKey, {
activeIndex: ref(),
loading: ref(false),
});
return () => {
const { prefixCls, options } = props;
const activeOption = options[activeIndex.value] || {};
return (
<Menu
prefixCls={`${prefixCls}-menu`}
activeKey={activeOption.value}
onSelect={({ key }) => {
const option = options.find(({ value }) => value === key);
selectOption(option);
}}
onBlur={onBlur}
onFocus={onFocus}
>
{!loading.value &&
options.map((option, index) => {
const { value, disabled, label = option.value } = option;
return (
<MenuItem
key={value}
disabled={disabled}
onMouseenter={() => {
setActiveIndex(index);
}}
>
{slots.option?.(option) ??
(typeof label === 'function' ? label({ value, disabled }) : label)}
</MenuItem>
);
})}
{!loading.value && options.length === 0 ? (
<MenuItem key="notFoundContent" disabled>
{slots.notFoundContent?.()}
</MenuItem>
) : null}
{loading.value && (
<MenuItem key="loading" disabled>
<Spin size="small" />
</MenuItem>
)}
</Menu>
);
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/_util/getScrollBarSize.ts
|
<filename>components/_util/getScrollBarSize.ts
/* eslint-disable no-param-reassign */
let cached: number;
export default function getScrollBarSize(fresh?: boolean) {
if (typeof document === 'undefined') {
return 0;
}
if (fresh || cached === undefined) {
const inner = document.createElement('div');
inner.style.width = '100%';
inner.style.height = '200px';
const outer = document.createElement('div');
const outerStyle = outer.style;
outerStyle.position = 'absolute';
outerStyle.top = '0';
outerStyle.left = '0';
outerStyle.pointerEvents = 'none';
outerStyle.visibility = 'hidden';
outerStyle.width = '200px';
outerStyle.height = '150px';
outerStyle.overflow = 'hidden';
outer.appendChild(inner);
document.body.appendChild(outer);
const widthContained = inner.offsetWidth;
outer.style.overflow = 'scroll';
let widthScroll = inner.offsetWidth;
if (widthContained === widthScroll) {
widthScroll = outer.clientWidth;
}
document.body.removeChild(outer);
cached = widthContained - widthScroll;
}
return cached;
}
function ensureSize(str: string) {
const match = str.match(/^(.*)px$/);
const value = Number(match?.[1]);
return Number.isNaN(value) ? getScrollBarSize() : value;
}
export function getTargetScrollBarSize(target: HTMLElement) {
if (typeof document === 'undefined' || !target || !(target instanceof Element)) {
return { width: 0, height: 0 };
}
const { width, height } = getComputedStyle(target, '::-webkit-scrollbar');
return {
width: ensureSize(width),
height: ensureSize(height),
};
}
|
YaroShkvorets/ant-design-vue
|
components/vc-util/devWarning.ts
|
import devWarning, { resetWarned } from './warning';
export { resetWarned };
export default (valid: boolean, component: string, message: string): void => {
devWarning(valid, `[ant-design-vue: ${component}] ${message}`);
};
|
YaroShkvorets/ant-design-vue
|
components/transfer/index.tsx
|
<filename>components/transfer/index.tsx
import type { CSSProperties, ExtractPropTypes, PropType } from 'vue';
import { watchEffect, defineComponent, ref, watch, toRaw } from 'vue';
import PropTypes from '../_util/vue-types';
import { getPropsSlot } from '../_util/props-util';
import classNames from '../_util/classNames';
import List from './list';
import Operation from './operation';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale-provider/default';
import type { RenderEmptyHandler } from '../config-provider';
import type { VueNode } from '../_util/type';
import { withInstall } from '../_util/type';
import useConfigInject from '../_util/hooks/useConfigInject';
import type { TransferListBodyProps } from './ListBody';
import type { PaginationType } from './interface';
import { useInjectFormItemContext } from '../form/FormItemContext';
export type { TransferListProps } from './list';
export type { TransferOperationProps } from './operation';
export type { TransferSearchProps } from './search';
export type TransferDirection = 'left' | 'right';
export interface RenderResultObject {
label: VueNode;
value: string;
}
export type RenderResult = VueNode | RenderResultObject | string | null;
export interface TransferItem {
key?: string;
title?: string;
description?: string;
disabled?: boolean;
[name: string]: any;
}
export type KeyWise<T> = T & { key: string };
export type KeyWiseTransferItem = KeyWise<TransferItem>;
type TransferRender<RecordType> = (item: RecordType) => RenderResult;
export interface ListStyle {
direction: TransferDirection;
}
export type SelectAllLabel =
| VueNode
| ((info: { selectedCount: number; totalCount: number }) => VueNode);
export interface TransferLocale {
titles: VueNode[];
notFoundContent?: VueNode;
searchPlaceholder: string;
itemUnit: string;
itemsUnit: string;
remove: string;
selectAll: string;
selectCurrent: string;
selectInvert: string;
removeAll: string;
removeCurrent: string;
}
export const transferProps = {
id: String,
prefixCls: String,
dataSource: { type: Array as PropType<TransferItem[]>, default: [] },
disabled: { type: Boolean, default: undefined },
targetKeys: { type: Array as PropType<string[]>, default: undefined },
selectedKeys: { type: Array as PropType<string[]>, default: undefined },
render: { type: Function as PropType<TransferRender<TransferItem>> },
listStyle: {
type: [Function, Object] as PropType<((style: ListStyle) => CSSProperties) | CSSProperties>,
default: () => ({}),
},
operationStyle: PropTypes.style,
titles: { type: Array as PropType<string[]> },
operations: { type: Array as PropType<string[]> },
showSearch: { type: Boolean, default: false },
filterOption: { type: Function as PropType<(inputValue: string, item: TransferItem) => boolean> },
searchPlaceholder: String,
notFoundContent: PropTypes.any,
locale: { type: Object as PropType<Partial<TransferLocale>>, default: () => ({}) },
rowKey: { type: Function as PropType<(record: TransferItem) => string> },
showSelectAll: { type: Boolean, default: undefined },
selectAllLabels: { type: Array as PropType<SelectAllLabel[]> },
children: { type: Function as PropType<(props: TransferListBodyProps) => VueNode> },
oneWay: { type: Boolean, default: undefined },
pagination: { type: [Object, Boolean] as PropType<PaginationType>, default: undefined },
};
export type TransferProps = Partial<ExtractPropTypes<typeof transferProps>>;
const Transfer = defineComponent({
name: 'ATransfer',
inheritAttrs: false,
props: transferProps,
slots: [
'leftTitle',
'rightTitle',
'children',
'render',
'notFoundContent',
'leftSelectAllLabel',
'rightSelectAllLabel',
'footer',
],
emits: ['update:targetKeys', 'update:selectedKeys', 'change', 'search', 'scroll', 'selectChange'],
setup(props, { emit, attrs, slots, expose }) {
const { configProvider, prefixCls, direction } = useConfigInject('transfer', props);
const sourceSelectedKeys = ref([]);
const targetSelectedKeys = ref([]);
const formItemContext = useInjectFormItemContext();
watch(
() => props.selectedKeys,
() => {
sourceSelectedKeys.value =
props.selectedKeys?.filter(key => props.targetKeys.indexOf(key) === -1) || [];
targetSelectedKeys.value =
props.selectedKeys?.filter(key => props.targetKeys.indexOf(key) > -1) || [];
},
{ immediate: true },
);
const getLocale = (transferLocale: TransferLocale, renderEmpty: RenderEmptyHandler) => {
// Keep old locale props still working.
const oldLocale: { notFoundContent?: any; searchPlaceholder?: string } = {
notFoundContent: renderEmpty('Transfer'),
};
const notFoundContent = getPropsSlot(slots, props, 'notFoundContent');
if (notFoundContent) {
oldLocale.notFoundContent = notFoundContent;
}
if (props.searchPlaceholder !== undefined) {
oldLocale.searchPlaceholder = props.searchPlaceholder;
}
return { ...transferLocale, ...oldLocale, ...props.locale };
};
const moveTo = (direction: TransferDirection) => {
const { targetKeys = [], dataSource = [] } = props;
const moveKeys = direction === 'right' ? sourceSelectedKeys.value : targetSelectedKeys.value;
// filter the disabled options
const newMoveKeys = moveKeys.filter(
key => !dataSource.some(data => !!(key === data.key && data.disabled)),
);
// move items to target box
const newTargetKeys =
direction === 'right'
? newMoveKeys.concat(targetKeys)
: targetKeys.filter(targetKey => newMoveKeys.indexOf(targetKey) === -1);
// empty checked keys
const oppositeDirection = direction === 'right' ? 'left' : 'right';
direction === 'right' ? (sourceSelectedKeys.value = []) : (targetSelectedKeys.value = []);
emit('update:targetKeys', newTargetKeys);
handleSelectChange(oppositeDirection, []);
emit('change', newTargetKeys, direction, newMoveKeys);
formItemContext.onFieldChange();
};
const moveToLeft = () => {
moveTo('left');
};
const moveToRight = () => {
moveTo('right');
};
const onItemSelectAll = (direction: TransferDirection, selectedKeys: string[]) => {
handleSelectChange(direction, selectedKeys);
};
const onLeftItemSelectAll = (selectedKeys: string[]) => {
return onItemSelectAll('left', selectedKeys);
};
const onRightItemSelectAll = (selectedKeys: string[]) => {
return onItemSelectAll('right', selectedKeys);
};
const handleSelectChange = (direction: TransferDirection, holder: string[]) => {
if (direction === 'left') {
if (!props.selectedKeys) {
sourceSelectedKeys.value = holder;
}
emit('update:selectedKeys', [...holder, ...targetSelectedKeys.value]);
emit('selectChange', holder, toRaw(targetSelectedKeys.value));
} else {
if (!props.selectedKeys) {
targetSelectedKeys.value = holder;
}
emit('update:selectedKeys', [...holder, ...sourceSelectedKeys.value]);
emit('selectChange', toRaw(sourceSelectedKeys.value), holder);
}
};
const handleFilter = (direction: TransferDirection, e) => {
const value = e.target.value;
emit('search', direction, value);
};
const handleLeftFilter = (e: Event) => {
handleFilter('left', e);
};
const handleRightFilter = (e: Event) => {
handleFilter('right', e);
};
const handleClear = (direction: TransferDirection) => {
emit('search', direction, '');
};
const handleLeftClear = () => {
handleClear('left');
};
const handleRightClear = () => {
handleClear('right');
};
const onItemSelect = (direction: TransferDirection, selectedKey: string, checked: boolean) => {
const holder =
direction === 'left' ? [...sourceSelectedKeys.value] : [...targetSelectedKeys.value];
const index = holder.indexOf(selectedKey);
if (index > -1) {
holder.splice(index, 1);
}
if (checked) {
holder.push(selectedKey);
}
handleSelectChange(direction, holder);
};
const onLeftItemSelect = (selectedKey: string, checked: boolean) => {
return onItemSelect('left', selectedKey, checked);
};
const onRightItemSelect = (selectedKey: string, checked: boolean) => {
return onItemSelect('right', selectedKey, checked);
};
const onRightItemRemove = (targetedKeys: string[]) => {
const { targetKeys = [] } = props;
const newTargetKeys = targetKeys.filter(key => !targetedKeys.includes(key));
emit('update:targetKeys', newTargetKeys);
emit('change', newTargetKeys, 'left', [...targetedKeys]);
};
const handleScroll = (direction: TransferDirection, e: Event) => {
emit('scroll', direction, e);
};
const handleLeftScroll = (e: Event) => {
handleScroll('left', e);
};
const handleRightScroll = (e: Event) => {
handleScroll('right', e);
};
const handleListStyle = (
listStyle: ((style: ListStyle) => CSSProperties) | CSSProperties,
direction: TransferDirection,
) => {
if (typeof listStyle === 'function') {
return listStyle({ direction });
}
return listStyle;
};
const leftDataSource = ref([]);
const rightDataSource = ref([]);
watchEffect(() => {
const { dataSource, rowKey, targetKeys = [] } = props;
const ld = [];
const rd = new Array(targetKeys.length);
dataSource.forEach(record => {
if (rowKey) {
record.key = rowKey(record);
}
// rightDataSource should be ordered by targetKeys
// leftDataSource should be ordered by dataSource
const indexOfKey = targetKeys.indexOf(record.key);
if (indexOfKey !== -1) {
rd[indexOfKey] = record;
} else {
ld.push(record);
}
});
leftDataSource.value = ld;
rightDataSource.value = rd;
});
expose({ handleSelectChange });
const renderTransfer = (transferLocale: TransferLocale) => {
const {
disabled,
operations = [],
showSearch,
listStyle,
operationStyle,
filterOption,
showSelectAll,
selectAllLabels = [],
oneWay,
pagination,
id = formItemContext.id.value,
} = props;
const { class: className, style } = attrs;
const children = slots.children;
const mergedPagination = !children && pagination;
const renderEmpty = configProvider.renderEmpty;
const locale = getLocale(transferLocale, renderEmpty);
const { footer } = slots;
const renderItem = props.render || slots.render;
const leftActive = targetSelectedKeys.value.length > 0;
const rightActive = sourceSelectedKeys.value.length > 0;
const cls = classNames(prefixCls.value, className, {
[`${prefixCls.value}-disabled`]: disabled,
[`${prefixCls.value}-customize-list`]: !!children,
});
const titles = props.titles;
const leftTitle =
(titles && titles[0]) ?? slots.leftTitle?.() ?? (locale.titles || ['', ''])[0];
const rightTitle =
(titles && titles[1]) ?? slots.rightTitle?.() ?? (locale.titles || ['', ''])[1];
return (
<div class={cls} style={style} id={id}>
<List
key="leftList"
prefixCls={`${prefixCls.value}-list`}
dataSource={leftDataSource.value}
filterOption={filterOption}
style={handleListStyle(listStyle, 'left')}
checkedKeys={sourceSelectedKeys.value}
handleFilter={handleLeftFilter}
handleClear={handleLeftClear}
onItemSelect={onLeftItemSelect}
onItemSelectAll={onLeftItemSelectAll}
renderItem={renderItem}
showSearch={showSearch}
renderList={children}
onScroll={handleLeftScroll}
disabled={disabled}
direction="left"
showSelectAll={showSelectAll}
selectAllLabel={selectAllLabels[0] || slots.leftSelectAllLabel}
pagination={mergedPagination}
{...locale}
v-slots={{ titleText: () => leftTitle, footer }}
/>
<Operation
key="operation"
class={`${prefixCls.value}-operation`}
rightActive={rightActive}
rightArrowText={operations[0]}
moveToRight={moveToRight}
leftActive={leftActive}
leftArrowText={operations[1]}
moveToLeft={moveToLeft}
style={operationStyle}
disabled={disabled}
direction={direction.value}
oneWay={oneWay}
/>
<List
key="rightList"
prefixCls={`${prefixCls.value}-list`}
dataSource={rightDataSource.value}
filterOption={filterOption}
style={handleListStyle(listStyle, 'right')}
checkedKeys={targetSelectedKeys.value}
handleFilter={handleRightFilter}
handleClear={handleRightClear}
onItemSelect={onRightItemSelect}
onItemSelectAll={onRightItemSelectAll}
onItemRemove={onRightItemRemove}
renderItem={renderItem}
showSearch={showSearch}
renderList={children}
onScroll={handleRightScroll}
disabled={disabled}
direction="right"
showSelectAll={showSelectAll}
selectAllLabel={selectAllLabels[1] || slots.rightSelectAllLabel}
showRemove={oneWay}
pagination={mergedPagination}
{...locale}
v-slots={{ titleText: () => rightTitle, footer }}
/>
</div>
);
};
return () => (
<LocaleReceiver
componentName="Transfer"
defaultLocale={defaultLocale.Transfer}
children={renderTransfer}
/>
);
},
});
export default withInstall(Transfer);
|
YaroShkvorets/ant-design-vue
|
components/table/Column.tsx
|
import { defineComponent } from 'vue';
import type { ColumnType } from './interface';
export type ColumnProps<RecordType = unknown> = ColumnType<RecordType>;
export default defineComponent<ColumnProps>({
name: 'ATableColumn',
slots: ['title', 'filterIcon'],
render() {
return null;
},
});
|
YaroShkvorets/ant-design-vue
|
components/vc-trigger/utils/motionUtil.ts
|
import type { AnimationType, TransitionNameType } from '../interface';
interface GetMotionProps {
animation: AnimationType;
transitionName: TransitionNameType;
prefixCls: string;
}
export function getMotion({ prefixCls, animation, transitionName }: GetMotionProps) {
if (animation) {
return {
name: `${prefixCls}-${animation}`,
};
}
if (transitionName) {
return {
name: transitionName,
};
}
return {};
}
|
YaroShkvorets/ant-design-vue
|
components/vc-table/context/SummaryContext.tsx
|
<gh_stars>1000+
import type { InjectionKey } from 'vue';
import { inject, provide } from 'vue';
import type { ColumnType, StickyOffsets } from '../interface';
export type FlattenColumns<RecordType> = readonly (ColumnType<RecordType> & {
scrollbar?: boolean;
})[];
type SummaryContextProps = {
stickyOffsets?: StickyOffsets;
scrollColumnIndex?: number;
flattenColumns?: FlattenColumns<any>;
};
export const SummaryContextKey: InjectionKey<SummaryContextProps> = Symbol('SummaryContextProps');
export const useProvideSummary = (props: SummaryContextProps) => {
provide(SummaryContextKey, props);
};
export const useInjectSummary = () => {
return inject(SummaryContextKey, {} as SummaryContextProps);
};
|
YaroShkvorets/ant-design-vue
|
antd-tools/generator-types/src/type.ts
|
<reponame>YaroShkvorets/ant-design-vue<gh_stars>1000+
import type { PathLike } from 'fs';
export type VueSlot = {
name: string;
description: string;
};
export type VueEventArgument = {
name: string;
type: string;
};
export type VueEvent = {
name: string;
description?: string;
arguments?: VueEventArgument[];
};
export type VueAttribute = {
name: string;
default: string;
description: string;
value: {
kind: 'expression';
type: string;
};
};
export type VueTag = {
name: string;
slots?: VueSlot[];
events?: VueEvent[];
attributes?: VueAttribute[];
description?: string;
};
export type VeturTag = {
description?: string;
attributes: string[];
};
export type VeturTags = Record<string, VeturTag>;
export type VeturAttribute = {
type: string;
description: string;
};
export type VeturAttributes = Record<string, VeturAttribute>;
export type VeturResult = {
tags: VeturTags;
attributes: VeturAttributes;
};
export type Options = {
name: string;
path: PathLike;
test: RegExp;
version: string;
outputDir?: string;
tagPrefix?: string;
};
|
YaroShkvorets/ant-design-vue
|
components/input/Password.tsx
|
import classNames from '../_util/classNames';
import { getComponent, getOptionProps } from '../_util/props-util';
import { cloneElement } from '../_util/vnode';
import Input from './Input';
import EyeOutlined from '@ant-design/icons-vue/EyeOutlined';
import EyeInvisibleOutlined from '@ant-design/icons-vue/EyeInvisibleOutlined';
import inputProps from './inputProps';
import PropTypes from '../_util/vue-types';
import BaseMixin from '../_util/BaseMixin';
import { defineComponent, inject } from 'vue';
import { defaultConfigProvider } from '../config-provider';
const ActionMap = {
click: 'onClick',
hover: 'onMouseover',
};
export default defineComponent({
name: 'AInputPassword',
mixins: [BaseMixin],
inheritAttrs: false,
props: {
...inputProps,
prefixCls: PropTypes.string,
inputPrefixCls: PropTypes.string,
action: PropTypes.string.def('click'),
visibilityToggle: PropTypes.looseBool.def(true),
iconRender: PropTypes.func.def((visible: boolean) =>
visible ? <EyeOutlined /> : <EyeInvisibleOutlined />,
),
},
setup() {
return {
input: null,
configProvider: inject('configProvider', defaultConfigProvider),
};
},
data() {
return {
visible: false,
};
},
methods: {
saveInput(node: any) {
this.input = node;
},
focus() {
this.input.focus();
},
blur() {
this.input.blur();
},
onVisibleChange() {
if (this.disabled) {
return;
}
this.setState({
visible: !this.visible,
});
},
getIcon(prefixCls) {
const { action } = this.$props;
const iconTrigger = ActionMap[action] || '';
const iconRender = this.$slots.iconRender || this.$props.iconRender;
const icon = iconRender(this.visible);
const iconProps = {
[iconTrigger]: this.onVisibleChange,
onMousedown: (e: Event) => {
// Prevent focused state lost
// https://github.com/ant-design/ant-design/issues/15173
e.preventDefault();
},
onMouseup: (e: Event) => {
// Prevent focused state lost
// https://github.com/ant-design/ant-design/pull/23633/files
e.preventDefault();
},
class: `${prefixCls}-icon`,
key: 'passwordIcon',
};
return cloneElement(icon, iconProps);
},
},
render() {
const {
prefixCls: customizePrefixCls,
inputPrefixCls: customizeInputPrefixCls,
size,
suffix,
action,
visibilityToggle,
iconRender,
...restProps
} = getOptionProps(this);
const { class: className } = this.$attrs;
const getPrefixCls = this.configProvider.getPrefixCls;
const inputPrefixCls = getPrefixCls('input', customizeInputPrefixCls);
const prefixCls = getPrefixCls('input-password', customizePrefixCls);
const suffixIcon = visibilityToggle && this.getIcon(prefixCls);
const inputClassName = classNames(prefixCls, className, {
[`${prefixCls}-${size}`]: !!size,
});
const inputProps = {
...restProps,
prefixCls: inputPrefixCls,
size,
suffix: suffixIcon,
prefix: getComponent(this, 'prefix'),
addonAfter: getComponent(this, 'addonAfter'),
addonBefore: getComponent(this, 'addonBefore'),
...this.$attrs,
type: this.visible ? 'text' : 'password',
class: inputClassName,
ref: 'input',
};
return <Input {...inputProps} ref={this.saveInput} />;
},
});
|
YaroShkvorets/ant-design-vue
|
components/vc-table/utils/legacyUtil.ts
|
<gh_stars>1000+
import { warning } from '../../vc-util/warning';
import type { ExpandableConfig, LegacyExpandableProps } from '../interface';
export const INTERNAL_COL_DEFINE = 'RC_TABLE_INTERNAL_COL_DEFINE';
export function getExpandableProps<RecordType>(
props: LegacyExpandableProps<RecordType> & {
expandable?: ExpandableConfig<RecordType>;
},
): ExpandableConfig<RecordType> {
const { expandable, ...legacyExpandableConfig } = props;
if (props.expandable !== undefined) {
return {
...legacyExpandableConfig,
...expandable,
};
}
if (
process.env.NODE_ENV !== 'production' &&
[
'indentSize',
'expandedRowKeys',
'defaultExpandedRowKeys',
'defaultExpandAllRows',
'expandedRowRender',
'expandRowByClick',
'expandIcon',
'onExpand',
'onExpandedRowsChange',
'expandedRowClassName',
'expandIconColumnIndex',
].some(prop => prop in props)
) {
warning(false, 'expanded related props have been moved into `expandable`.');
}
return legacyExpandableConfig;
}
/**
* Returns only data- and aria- key/value pairs
* @param {object} props
*/
export function getDataAndAriaProps(props: object) {
/* eslint-disable no-param-reassign */
return Object.keys(props).reduce((memo, key) => {
if (key.substr(0, 5) === 'data-' || key.substr(0, 5) === 'aria-') {
memo[key] = props[key];
}
return memo;
}, {});
/* eslint-enable */
}
|
YaroShkvorets/ant-design-vue
|
components/result/index.tsx
|
<reponame>YaroShkvorets/ant-design-vue<gh_stars>1000+
import type { App, VNodeTypes, Plugin, ExtractPropTypes } from 'vue';
import { defineComponent, computed } from 'vue';
import PropTypes from '../_util/vue-types';
import { tuple } from '../_util/type';
import CheckCircleFilled from '@ant-design/icons-vue/CheckCircleFilled';
import CloseCircleFilled from '@ant-design/icons-vue/CloseCircleFilled';
import ExclamationCircleFilled from '@ant-design/icons-vue/ExclamationCircleFilled';
import WarningFilled from '@ant-design/icons-vue/WarningFilled';
import noFound from './noFound';
import serverError from './serverError';
import unauthorized from './unauthorized';
import useConfigInject from '../_util/hooks/useConfigInject';
import classNames from '../_util/classNames';
export const IconMap = {
success: CheckCircleFilled,
error: CloseCircleFilled,
info: ExclamationCircleFilled,
warning: WarningFilled,
};
export const ExceptionMap = {
'404': noFound,
'500': serverError,
'403': unauthorized,
};
// ExceptionImageMap keys
const ExceptionStatus = Object.keys(ExceptionMap);
export const resultProps = {
prefixCls: PropTypes.string,
icon: PropTypes.any,
status: PropTypes.oneOf(tuple('success', 'error', 'info', 'warning', '404', '403', '500')).def(
'info',
),
title: PropTypes.any,
subTitle: PropTypes.any,
extra: PropTypes.any,
};
export type ResultProps = Partial<ExtractPropTypes<typeof resultProps>>;
const renderIcon = (prefixCls: string, { status, icon }) => {
if (ExceptionStatus.includes(`${status}`)) {
const SVGComponent = ExceptionMap[status];
return (
<div class={`${prefixCls}-icon ${prefixCls}-image`}>
<SVGComponent />
</div>
);
}
const IconComponent = IconMap[status];
const iconNode = icon || <IconComponent />;
return <div class={`${prefixCls}-icon`}>{iconNode}</div>;
};
const renderExtra = (prefixCls: string, extra: VNodeTypes) =>
extra && <div class={`${prefixCls}-extra`}>{extra}</div>;
const Result = defineComponent({
name: 'AResult',
props: resultProps,
slots: ['title', 'subTitle', 'icon', 'extra'],
setup(props, { slots }) {
const { prefixCls, direction } = useConfigInject('result', props);
const className = computed(() =>
classNames(prefixCls.value, `${prefixCls.value}-${props.status}`, {
[`${prefixCls.value}-rtl`]: direction.value === 'rtl',
}),
);
return () => {
const title = props.title ?? slots.title?.();
const subTitle = props.subTitle ?? slots.subTitle?.();
const icon = props.icon ?? slots.icon?.();
const extra = props.extra ?? slots.extra?.();
const pre = prefixCls.value;
return (
<div class={className.value}>
{renderIcon(pre, { status: props.status, icon })}
<div class={`${pre}-title`}>{title}</div>
{subTitle && <div class={`${pre}-subtitle`}>{subTitle}</div>}
{renderExtra(pre, extra)}
{slots.default && <div class={`${pre}-content`}>{slots.default()}</div>}
</div>
);
};
},
});
/* add resource */
Result.PRESENTED_IMAGE_403 = ExceptionMap[403];
Result.PRESENTED_IMAGE_404 = ExceptionMap[404];
Result.PRESENTED_IMAGE_500 = ExceptionMap[500];
/* istanbul ignore next */
Result.install = function (app: App) {
app.component(Result.name, Result);
return app;
};
export default Result as typeof Result &
Plugin & {
readonly PRESENTED_IMAGE_403: typeof unauthorized;
readonly PRESENTED_IMAGE_404: typeof noFound;
readonly PRESENTED_IMAGE_500: typeof serverError;
};
|
YaroShkvorets/ant-design-vue
|
components/vc-mentions/src/Option.tsx
|
import type { ExtractPropTypes } from 'vue';
import { defineComponent } from 'vue';
export const optionProps = {
value: String,
disabled: Boolean,
label: [String, Number, Function],
};
export type OptionProps = Partial<ExtractPropTypes<typeof optionProps>>;
export default defineComponent({
name: 'Option',
props: optionProps,
render(_props: any, { slots }: any) {
return slots.default?.();
},
});
|
YaroShkvorets/ant-design-vue
|
components/vc-picker/panels/DecadePanel/DecadeHeader.tsx
|
<reponame>YaroShkvorets/ant-design-vue<filename>components/vc-picker/panels/DecadePanel/DecadeHeader.tsx
import Header from '../Header';
import type { GenerateConfig } from '../../generate';
import { DECADE_DISTANCE_COUNT } from '.';
import { useInjectPanel } from '../../PanelContext';
import useMergeProps from '../../hooks/useMergeProps';
export type YearHeaderProps<DateType> = {
prefixCls: string;
viewDate: DateType;
generateConfig: GenerateConfig<DateType>;
onPrevDecades: () => void;
onNextDecades: () => void;
};
function DecadeHeader<DateType>(_props: YearHeaderProps<DateType>) {
const props = useMergeProps(_props);
const { prefixCls, generateConfig, viewDate, onPrevDecades, onNextDecades } = props;
const { hideHeader } = useInjectPanel();
if (hideHeader) {
return null;
}
const headerPrefixCls = `${prefixCls}-header`;
const yearNumber = generateConfig.getYear(viewDate);
const startYear = Math.floor(yearNumber / DECADE_DISTANCE_COUNT) * DECADE_DISTANCE_COUNT;
const endYear = startYear + DECADE_DISTANCE_COUNT - 1;
return (
<Header
{...props}
prefixCls={headerPrefixCls}
onSuperPrev={onPrevDecades}
onSuperNext={onNextDecades}
>
{startYear}-{endYear}
</Header>
);
}
DecadeHeader.displayName = 'DecadeHeader';
DecadeHeader.inheritAttrs = false;
export default DecadeHeader;
|
YaroShkvorets/ant-design-vue
|
components/vc-picker/panels/TimePanel/TimeHeader.tsx
|
<reponame>YaroShkvorets/ant-design-vue
import Header from '../Header';
import type { Locale } from '../../interface';
import type { GenerateConfig } from '../../generate';
import { useInjectPanel } from '../../PanelContext';
import { formatValue } from '../../utils/dateUtil';
import useMergeProps from '../../hooks/useMergeProps';
export type TimeHeaderProps<DateType> = {
prefixCls: string;
value?: DateType | null;
locale: Locale;
generateConfig: GenerateConfig<DateType>;
format: string;
};
function TimeHeader<DateType>(_props: TimeHeaderProps<DateType>) {
const props = useMergeProps(_props);
const { hideHeader } = useInjectPanel();
if (hideHeader.value) {
return null;
}
const { prefixCls, generateConfig, locale, value, format } = props;
const headerPrefixCls = `${prefixCls}-header`;
return (
<Header prefixCls={headerPrefixCls}>
{value
? formatValue(value, {
locale,
format,
generateConfig,
})
: '\u00A0'}
</Header>
);
}
TimeHeader.displayName = 'TimeHeader';
TimeHeader.inheritAttrs = false;
export default TimeHeader;
|
YaroShkvorets/ant-design-vue
|
components/input-number/index.tsx
|
<gh_stars>1000+
import type { PropType, ExtractPropTypes } from 'vue';
import { defineComponent, inject, nextTick, onMounted, ref } from 'vue';
import PropTypes from '../_util/vue-types';
import { getOptionProps } from '../_util/props-util';
import classNames from '../_util/classNames';
import UpOutlined from '@ant-design/icons-vue/UpOutlined';
import DownOutlined from '@ant-design/icons-vue/DownOutlined';
import VcInputNumber from '../vc-input-number/src';
import { defaultConfigProvider } from '../config-provider';
import { tuple, withInstall } from '../_util/type';
import type { EventHandler } from '../_util/EventInterface';
import { useInjectFormItemContext } from '../form/FormItemContext';
const inputNumberProps = {
prefixCls: PropTypes.string,
min: PropTypes.number,
max: PropTypes.number,
value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
step: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).def(1),
defaultValue: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
tabindex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
disabled: PropTypes.looseBool,
size: PropTypes.oneOf(tuple('large', 'small', 'default')),
formatter: PropTypes.func,
parser: PropTypes.func,
decimalSeparator: PropTypes.string,
placeholder: PropTypes.string,
name: PropTypes.string,
id: PropTypes.string,
precision: PropTypes.number,
autofocus: PropTypes.looseBool,
onPressEnter: {
type: Function as PropType<EventHandler>,
},
onChange: Function as PropType<(num: number) => void>,
};
export type InputNumberProps = Partial<ExtractPropTypes<typeof inputNumberProps>>;
const InputNumber = defineComponent({
name: 'AInputNumber',
inheritAttrs: false,
props: inputNumberProps,
emits: ['input', 'change', 'blur', 'update:value'],
setup(props, { emit }) {
const formItemContext = useInjectFormItemContext();
const inputNumberRef = ref(null);
const focus = () => {
inputNumberRef.value.focus();
};
const blur = () => {
inputNumberRef.value.blur();
};
const handleChange = (val: number) => {
emit('update:value', val);
emit('change', val);
};
const handleBlur = () => {
emit('blur');
};
onMounted(() => {
nextTick(() => {
if (process.env.NODE_ENV === 'test') {
if (props.autofocus && !props.disabled) {
focus();
}
}
});
});
return {
configProvider: inject('configProvider', defaultConfigProvider),
inputNumberRef,
focus,
blur,
formItemContext,
handleBlur,
handleChange,
};
},
render() {
const {
prefixCls: customizePrefixCls,
size,
class: className,
id = this.formItemContext.id.value,
...others
} = {
...getOptionProps(this),
...this.$attrs,
} as any;
const { getPrefixCls } = this.configProvider;
const prefixCls = getPrefixCls('input-number', customizePrefixCls);
const inputNumberClass = classNames(
{
[`${prefixCls}-lg`]: size === 'large',
[`${prefixCls}-sm`]: size === 'small',
},
className,
);
const upIcon = <UpOutlined class={`${prefixCls}-handler-up-inner`} />;
const downIcon = <DownOutlined class={`${prefixCls}-handler-down-inner`} />;
const vcInputNumberProps = {
prefixCls,
upHandler: upIcon,
downHandler: downIcon,
...others,
class: inputNumberClass,
onChange: this.handleChange,
onBlur: this.handleBlur,
id,
};
return <VcInputNumber {...vcInputNumberProps} ref="inputNumberRef" />;
},
});
export default withInstall(InputNumber);
|
YaroShkvorets/ant-design-vue
|
components/tooltip/abstractTooltipProps.ts
|
<reponame>YaroShkvorets/ant-design-vue
import PropTypes from '../_util/vue-types';
import { tuple } from '../_util/type';
export const triggerTypes = tuple('hover', 'focus', 'click', 'contextmenu');
export const placementTypes = tuple(
'top',
'left',
'right',
'bottom',
'topLeft',
'topRight',
'bottomLeft',
'bottomRight',
'leftTop',
'leftBottom',
'rightTop',
'rightBottom',
);
export default () => ({
trigger: PropTypes.oneOfType([
PropTypes.oneOf(triggerTypes),
PropTypes.arrayOf(PropTypes.oneOf(triggerTypes)),
]),
visible: PropTypes.looseBool,
defaultVisible: PropTypes.looseBool,
placement: PropTypes.oneOf(placementTypes),
color: PropTypes.string,
transitionName: PropTypes.string,
overlayStyle: PropTypes.style,
overlayClassName: PropTypes.string,
openClassName: PropTypes.string,
prefixCls: PropTypes.string,
mouseEnterDelay: PropTypes.number,
mouseLeaveDelay: PropTypes.number,
getPopupContainer: PropTypes.func,
arrowPointAtCenter: PropTypes.looseBool,
autoAdjustOverflow: PropTypes.oneOfType([PropTypes.looseBool, PropTypes.object]),
destroyTooltipOnHide: PropTypes.looseBool,
align: PropTypes.object,
builtinPlacements: PropTypes.object,
children: PropTypes.array,
onVisibleChange: PropTypes.func,
'onUpdate:visible': PropTypes.func,
});
|
YaroShkvorets/ant-design-vue
|
components/vc-trigger/Popup/Mask.tsx
|
<gh_stars>1000+
import { Transition } from 'vue';
import type { TransitionNameType, AnimationType } from '../interface';
import { getMotion } from '../utils/motionUtil';
export interface MaskProps {
prefixCls: string;
visible?: boolean;
zIndex?: number;
mask?: boolean;
maskAnimation?: AnimationType;
maskTransitionName?: TransitionNameType;
}
export default function Mask(props: MaskProps) {
const { prefixCls, visible, zIndex, mask, maskAnimation, maskTransitionName } = props;
if (!mask) {
return null;
}
let motion = {};
if (maskTransitionName || maskAnimation) {
motion = getMotion({
prefixCls,
transitionName: maskTransitionName,
animation: maskAnimation,
});
}
return (
<Transition appear {...motion}>
<div v-if={visible} style={{ zIndex }} class={`${prefixCls}-mask`} />
</Transition>
);
}
Mask.displayName = 'Mask';
|
YaroShkvorets/ant-design-vue
|
components/input/ResizableTextArea.tsx
|
<filename>components/input/ResizableTextArea.tsx
import type { PropType, VNode } from 'vue';
import { nextTick, defineComponent, withDirectives } from 'vue';
import ResizeObserver from '../vc-resize-observer';
import classNames from '../_util/classNames';
import calculateNodeHeight from './calculateNodeHeight';
import raf from '../_util/raf';
import warning from '../_util/warning';
import BaseMixin from '../_util/BaseMixin';
import inputProps from './inputProps';
import PropTypes from '../_util/vue-types';
import { getOptionProps } from '../_util/props-util';
import antInput from '../_util/antInputDirective';
import omit from '../_util/omit';
const RESIZE_STATUS_NONE = 0;
const RESIZE_STATUS_RESIZING = 1;
const RESIZE_STATUS_RESIZED = 2;
export interface AutoSizeType {
minRows?: number;
maxRows?: number;
}
const TextAreaProps = {
...inputProps,
autosize: { type: [Boolean, Object] as PropType<AutoSizeType>, default: undefined },
autoSize: { type: [Boolean, Object] as PropType<AutoSizeType>, default: undefined },
onResize: PropTypes.func,
};
const ResizableTextArea = defineComponent({
name: 'ResizableTextArea',
mixins: [BaseMixin],
inheritAttrs: false,
props: TextAreaProps,
setup() {
return {
nextFrameActionId: undefined,
textArea: null,
resizeFrameId: undefined,
};
},
data() {
return {
textareaStyles: {},
resizeStatus: RESIZE_STATUS_NONE,
};
},
watch: {
value() {
nextTick(() => {
this.resizeTextarea();
});
},
},
mounted() {
this.resizeTextarea();
},
beforeUnmount() {
raf.cancel(this.nextFrameActionId);
raf.cancel(this.resizeFrameId);
},
methods: {
saveTextArea(textArea: HTMLTextAreaElement) {
this.textArea = textArea;
},
handleResize(size: { width: number; height: number }) {
const { resizeStatus } = this.$data;
if (resizeStatus !== RESIZE_STATUS_NONE) {
return;
}
this.$emit('resize', size);
},
resizeOnNextFrame() {
raf.cancel(this.nextFrameActionId);
this.nextFrameActionId = raf(this.resizeTextarea);
},
resizeTextarea() {
const autoSize = this.$props.autoSize || this.$props.autosize;
if (!autoSize || !this.textArea) {
return;
}
const { minRows, maxRows } = autoSize;
const textareaStyles = calculateNodeHeight(this.textArea, false, minRows, maxRows);
this.setState({ textareaStyles, resizeStatus: RESIZE_STATUS_RESIZING }, () => {
raf.cancel(this.resizeFrameId);
this.resizeFrameId = raf(() => {
this.setState({ resizeStatus: RESIZE_STATUS_RESIZED }, () => {
this.resizeFrameId = raf(() => {
this.setState({ resizeStatus: RESIZE_STATUS_NONE });
this.fixFirefoxAutoScroll();
});
});
});
});
},
// https://github.com/ant-design/ant-design/issues/21870
fixFirefoxAutoScroll() {
try {
if (document.activeElement === this.textArea) {
const currentStart = this.textArea.selectionStart;
const currentEnd = this.textArea.selectionEnd;
this.textArea.setSelectionRange(currentStart, currentEnd);
}
} catch (e) {
// Fix error in Chrome:
// Failed to read the 'selectionStart' property from 'HTMLInputElement'
// http://stackoverflow.com/q/21177489/3040605
}
},
renderTextArea() {
const props: any = { ...getOptionProps(this), ...this.$attrs };
const { prefixCls, autoSize, autosize, disabled, class: className } = props;
const { textareaStyles, resizeStatus } = this.$data;
warning(
autosize === undefined,
'Input.TextArea',
'autosize is deprecated, please use autoSize instead.',
);
const otherProps = omit(props, [
'prefixCls',
'onPressEnter',
'autoSize',
'autosize',
'defaultValue',
'allowClear',
'type',
'lazy',
]);
const cls = classNames(prefixCls, className, {
[`${prefixCls}-disabled`]: disabled,
});
// Fix https://github.com/ant-design/ant-design/issues/6776
// Make sure it could be reset when using form.getFieldDecorator
if ('value' in otherProps) {
otherProps.value = otherProps.value || '';
}
const style = {
...props.style,
...textareaStyles,
...(resizeStatus === RESIZE_STATUS_RESIZING
? { overflowX: 'hidden', overflowY: 'hidden' }
: null),
};
const textareaProps: any = {
...otherProps,
style,
class: cls,
};
if (!textareaProps.autofocus) {
delete textareaProps.autofocus;
}
return (
<ResizeObserver onResize={this.handleResize} disabled={!(autoSize || autosize)}>
{withDirectives((<textarea {...textareaProps} ref={this.saveTextArea} />) as VNode, [
[antInput],
])}
</ResizeObserver>
);
},
},
render() {
return this.renderTextArea();
},
});
export default ResizableTextArea;
|
YaroShkvorets/ant-design-vue
|
components/vc-drawer/index.ts
|
// base rc-drawer 4.4.2
import Drawer from './src/DrawerWrapper';
export default Drawer;
|
YaroShkvorets/ant-design-vue
|
components/vc-select/index.ts
|
import type { ExportedSelectProps } from './Select';
import Select, { selectProps } from './Select';
import Option from './Option';
import OptGroup from './OptGroup';
import { selectBaseProps } from './generate';
import type { ExtractPropTypes } from 'vue';
export type SelectProps<T = any> = Partial<ExtractPropTypes<ExportedSelectProps<T>>>;
export { Option, OptGroup, selectBaseProps, selectProps };
export default Select;
|
YaroShkvorets/ant-design-vue
|
components/list/contextKey.ts
|
<gh_stars>1000+
import type { InjectionKey, Ref } from 'vue';
export interface ListContext {
grid?: Ref<any>;
itemLayout?: Ref<string>;
}
export const ListContextKey: InjectionKey<ListContext> = Symbol('ListContextKey');
|
YaroShkvorets/ant-design-vue
|
components/_util/firstNotUndefined.ts
|
<reponame>YaroShkvorets/ant-design-vue<gh_stars>1000+
function firstNotUndefined<T>(arr: T[] = []): T {
for (let i = 0, len = arr.length; i < len; i++) {
if (arr[i] !== undefined) {
return arr[i];
}
}
return undefined;
}
export default firstNotUndefined;
|
YaroShkvorets/ant-design-vue
|
components/calendar/index.tsx
|
<filename>components/calendar/index.tsx
import Calendar from './dayjs';
export * from './dayjs';
export default Calendar;
|
YaroShkvorets/ant-design-vue
|
components/vc-slider/src/common/createSlider.tsx
|
<reponame>YaroShkvorets/ant-design-vue<filename>components/vc-slider/src/common/createSlider.tsx
import { defineComponent } from 'vue';
import classNames from '../../../_util/classNames';
import PropTypes from '../../../_util/vue-types';
import addEventListener from '../../../vc-util/Dom/addEventListener';
import warning from '../../../_util/warning';
import { initDefaultProps, getSlot } from '../../../_util/props-util';
import Steps from './Steps';
import Marks from './Marks';
import Handle from '../Handle';
import * as utils from '../utils';
import BaseMixin from '../../../_util/BaseMixin';
import supportsPassive from '../../../_util/supportsPassive';
function noop() {}
export default function createSlider(Component) {
// const displayName = `ComponentEnhancer(${Component.displayName})`
const propTypes = {
id: PropTypes.string,
min: PropTypes.number,
max: PropTypes.number,
step: PropTypes.number,
marks: PropTypes.object,
included: PropTypes.looseBool,
prefixCls: PropTypes.string,
disabled: PropTypes.looseBool,
handle: PropTypes.func,
dots: PropTypes.looseBool,
vertical: PropTypes.looseBool,
reverse: PropTypes.looseBool,
minimumTrackStyle: PropTypes.object, // just for compatibility, will be deperecate
maximumTrackStyle: PropTypes.object, // just for compatibility, will be deperecate
handleStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.arrayOf(PropTypes.object)]),
trackStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.arrayOf(PropTypes.object)]),
railStyle: PropTypes.object,
dotStyle: PropTypes.object,
activeDotStyle: PropTypes.object,
autofocus: PropTypes.looseBool,
draggableTrack: PropTypes.looseBool,
};
return defineComponent({
name: 'CreateSlider',
mixins: [BaseMixin, Component],
inheritAttrs: false,
slots: ['mark'],
props: initDefaultProps(propTypes, {
prefixCls: 'rc-slider',
min: 0,
max: 100,
step: 1,
marks: {},
included: true,
disabled: false,
dots: false,
vertical: false,
reverse: false,
trackStyle: [{}],
handleStyle: [{}],
railStyle: {},
dotStyle: {},
activeDotStyle: {},
}),
data() {
const { step, max, min } = this;
const isPointDiffEven = isFinite(max - min) ? (max - min) % step === 0 : true; // eslint-disable-line
warning(
step && Math.floor(step) === step ? isPointDiffEven : true,
`Slider[max] - Slider[min] (${max - min}) should be a multiple of Slider[step] (${step})`,
);
(this as any).handlesRefs = {};
return {};
},
mounted() {
this.$nextTick(() => {
// Snapshot testing cannot handle refs, so be sure to null-check this.
this.document = this.sliderRef && this.sliderRef.ownerDocument;
// this.setHandleRefs()
const { autofocus, disabled } = this;
if (autofocus && !disabled) {
this.focus();
}
});
},
beforeUnmount() {
this.$nextTick(() => {
// if (super.componentWillUnmount) super.componentWillUnmount()
this.removeDocumentEvents();
});
},
methods: {
defaultHandle({ index, directives, className, style, ...restProps }) {
delete restProps.dragging;
if (restProps.value === null) {
return null;
}
const handleProps = {
...restProps,
class: className,
style,
key: index,
};
return <Handle {...handleProps} />;
},
onDown(e, position) {
let p = position;
const { draggableTrack, vertical: isVertical } = this.$props;
const { bounds } = this.$data;
const value = draggableTrack && this.positionGetValue ? this.positionGetValue(p) || [] : [];
const inPoint = utils.isEventFromHandle(e, this.handlesRefs);
this.dragTrack =
draggableTrack &&
bounds.length >= 2 &&
!inPoint &&
!value
.map((n, i) => {
const v = !i ? n >= bounds[i] : true;
return i === value.length - 1 ? n <= bounds[i] : v;
})
.some(c => !c);
if (this.dragTrack) {
this.dragOffset = p;
this.startBounds = [...bounds];
} else {
if (!inPoint) {
this.dragOffset = 0;
} else {
const handlePosition = utils.getHandleCenterPosition(isVertical, e.target);
this.dragOffset = p - handlePosition;
p = handlePosition;
}
this.onStart(p);
}
},
onMouseDown(e) {
if (e.button !== 0) {
return;
}
this.removeDocumentEvents();
const isVertical = this.$props.vertical;
const position = utils.getMousePosition(isVertical, e);
this.onDown(e, position);
this.addDocumentMouseEvents();
},
onTouchStart(e) {
if (utils.isNotTouchEvent(e)) return;
const isVertical = this.vertical;
const position = utils.getTouchPosition(isVertical, e);
this.onDown(e, position);
this.addDocumentTouchEvents();
utils.pauseEvent(e);
},
onFocus(e) {
const { vertical } = this;
if (utils.isEventFromHandle(e, this.handlesRefs) && !this.dragTrack) {
const handlePosition = utils.getHandleCenterPosition(vertical, e.target);
this.dragOffset = 0;
this.onStart(handlePosition);
utils.pauseEvent(e);
this.__emit('focus', e);
}
},
onBlur(e) {
if (!this.dragTrack) {
this.onEnd();
}
this.__emit('blur', e);
},
onMouseUp() {
if (this.handlesRefs[this.prevMovedHandleIndex]) {
this.handlesRefs[this.prevMovedHandleIndex].clickFocus();
}
},
onMouseMove(e) {
if (!this.sliderRef) {
this.onEnd();
return;
}
const position = utils.getMousePosition(this.vertical, e);
this.onMove(e, position - this.dragOffset, this.dragTrack, this.startBounds);
},
onTouchMove(e) {
if (utils.isNotTouchEvent(e) || !this.sliderRef) {
this.onEnd();
return;
}
const position = utils.getTouchPosition(this.vertical, e);
this.onMove(e, position - this.dragOffset, this.dragTrack, this.startBounds);
},
onKeyDown(e) {
if (this.sliderRef && utils.isEventFromHandle(e, this.handlesRefs)) {
this.onKeyboard(e);
}
},
onClickMarkLabel(e, value) {
e.stopPropagation();
this.onChange({ sValue: value });
this.setState({ sValue: value }, () => this.onEnd(true));
},
getSliderStart() {
const slider = this.sliderRef;
const { vertical, reverse } = this;
const rect = slider.getBoundingClientRect();
if (vertical) {
return reverse ? rect.bottom : rect.top;
}
return window.pageXOffset + (reverse ? rect.right : rect.left);
},
getSliderLength() {
const slider = this.sliderRef;
if (!slider) {
return 0;
}
const coords = slider.getBoundingClientRect();
return this.vertical ? coords.height : coords.width;
},
addDocumentTouchEvents() {
// just work for Chrome iOS Safari and Android Browser
this.onTouchMoveListener = addEventListener(this.document, 'touchmove', this.onTouchMove);
this.onTouchUpListener = addEventListener(this.document, 'touchend', this.onEnd);
},
addDocumentMouseEvents() {
this.onMouseMoveListener = addEventListener(this.document, 'mousemove', this.onMouseMove);
this.onMouseUpListener = addEventListener(this.document, 'mouseup', this.onEnd);
},
removeDocumentEvents() {
/* eslint-disable no-unused-expressions */
this.onTouchMoveListener && this.onTouchMoveListener.remove();
this.onTouchUpListener && this.onTouchUpListener.remove();
this.onMouseMoveListener && this.onMouseMoveListener.remove();
this.onMouseUpListener && this.onMouseUpListener.remove();
/* eslint-enable no-unused-expressions */
},
focus() {
if (this.$props.disabled) {
return;
}
this.handlesRefs[0]?.focus();
},
blur() {
if (this.$props.disabled) {
return;
}
Object.keys(this.handlesRefs).forEach(key => {
this.handlesRefs[key]?.blur?.();
});
},
calcValue(offset) {
const { vertical, min, max } = this;
const ratio = Math.abs(Math.max(offset, 0) / this.getSliderLength());
const value = vertical ? (1 - ratio) * (max - min) + min : ratio * (max - min) + min;
return value;
},
calcValueByPos(position) {
const sign = this.reverse ? -1 : +1;
const pixelOffset = sign * (position - this.getSliderStart());
const nextValue = this.trimAlignValue(this.calcValue(pixelOffset));
return nextValue;
},
calcOffset(value) {
const { min, max } = this;
const ratio = (value - min) / (max - min);
return Math.max(0, ratio * 100);
},
saveSlider(slider) {
this.sliderRef = slider;
},
saveHandle(index, handle) {
this.handlesRefs[index] = handle;
},
},
render() {
const {
prefixCls,
marks,
dots,
step,
included,
disabled,
vertical,
reverse,
min,
max,
maximumTrackStyle,
railStyle,
dotStyle,
activeDotStyle,
id,
} = this;
const { class: className, style } = this.$attrs;
const { tracks, handles } = this.renderSlider();
const sliderClassName = classNames(prefixCls, className, {
[`${prefixCls}-with-marks`]: Object.keys(marks).length,
[`${prefixCls}-disabled`]: disabled,
[`${prefixCls}-vertical`]: vertical,
});
const markProps = {
vertical,
marks,
included,
lowerBound: this.getLowerBound(),
upperBound: this.getUpperBound(),
max,
min,
reverse,
class: `${prefixCls}-mark`,
onClickLabel: disabled ? noop : this.onClickMarkLabel,
};
const touchEvents = {
[supportsPassive ? 'onTouchstartPassive' : 'onTouchstart']: disabled
? noop
: this.onTouchStart,
};
return (
<div
id={id}
ref={this.saveSlider}
tabindex="-1"
class={sliderClassName}
{...touchEvents}
onMousedown={disabled ? noop : this.onMouseDown}
onMouseup={disabled ? noop : this.onMouseUp}
onKeydown={disabled ? noop : this.onKeyDown}
onFocus={disabled ? noop : this.onFocus}
onBlur={disabled ? noop : this.onBlur}
style={style}
>
<div
class={`${prefixCls}-rail`}
style={{
...maximumTrackStyle,
...railStyle,
}}
/>
{tracks}
<Steps
prefixCls={prefixCls}
vertical={vertical}
reverse={reverse}
marks={marks}
dots={dots}
step={step}
included={included}
lowerBound={this.getLowerBound()}
upperBound={this.getUpperBound()}
max={max}
min={min}
dotStyle={dotStyle}
activeDotStyle={activeDotStyle}
/>
{handles}
<Marks {...markProps} v-slots={{ mark: this.$slots.mark }} />
{getSlot(this)}
</div>
);
},
});
}
|
YaroShkvorets/ant-design-vue
|
components/_util/transButton.tsx
|
<reponame>YaroShkvorets/ant-design-vue<gh_stars>1000+
import type { CSSProperties } from 'vue';
import { defineComponent, ref, onMounted } from 'vue';
/**
* Wrap of sub component which need use as Button capacity (like Icon component).
* This helps accessibility reader to tread as a interactive button to operation.
*/
import KeyCode from './KeyCode';
import PropTypes from './vue-types';
const inlineStyle = {
border: 0,
background: 'transparent',
padding: 0,
lineHeight: 'inherit',
display: 'inline-block',
};
const TransButton = defineComponent({
name: 'TransButton',
inheritAttrs: false,
props: {
noStyle: PropTypes.looseBool,
onClick: PropTypes.func,
disabled: PropTypes.looseBool,
autofocus: PropTypes.looseBool,
},
setup(props, { slots, emit, attrs, expose }) {
const domRef = ref();
const onKeyDown = (event: KeyboardEvent) => {
const { keyCode } = event;
if (keyCode === KeyCode.ENTER) {
event.preventDefault();
}
};
const onKeyUp = (event: KeyboardEvent) => {
const { keyCode } = event;
if (keyCode === KeyCode.ENTER) {
emit('click', event);
}
};
const onClick = (e: Event) => {
emit('click', e);
};
const focus = () => {
if (domRef.value) {
domRef.value.focus();
}
};
const blur = () => {
if (domRef.value) {
domRef.value.blur();
}
};
onMounted(() => {
if (props.autofocus) {
focus();
}
});
expose({
focus,
blur,
});
return () => {
const { noStyle, disabled, ...restProps } = props;
let mergedStyle: CSSProperties = {};
if (!noStyle) {
mergedStyle = {
...inlineStyle,
};
}
if (disabled) {
mergedStyle.pointerEvents = 'none';
}
return (
<div
role="button"
tabindex={0}
ref={domRef}
{...restProps}
{...attrs}
onClick={onClick}
onKeydown={onKeyDown}
onKeyup={onKeyUp}
style={{
...mergedStyle,
...((attrs.style as object) || {}),
}}
>
{slots.default?.()}
</div>
);
};
},
});
export default TransButton;
|
YaroShkvorets/ant-design-vue
|
components/table/hooks/useColumns.tsx
|
import devWarning from '../../vc-util/devWarning';
import { renderSlot } from 'vue';
import type { Ref } from 'vue';
import type { ContextSlots } from '../context';
import type { TransformColumns, ColumnsType } from '../interface';
function fillSlots<RecordType>(columns: ColumnsType<RecordType>, contextSlots: Ref<ContextSlots>) {
const $slots = contextSlots.value;
return columns.map(column => {
const cloneColumn = { ...column };
const { slots = {} } = cloneColumn;
cloneColumn.__originColumn__ = column;
devWarning(
!('slots' in cloneColumn),
'Table',
'`column.slots` is deprecated. Please use `v-slot:headerCell` `v-slot:bodyCell` instead.',
);
Object.keys(slots).forEach(key => {
const name = slots[key];
if (cloneColumn[key] === undefined && $slots[name]) {
cloneColumn[key] = $slots[name];
}
});
if (contextSlots.value.headerCell && !column.slots?.title) {
cloneColumn.title = renderSlot(
contextSlots.value,
'headerCell',
{
title: column.title,
column,
},
() => [column.title as any],
);
}
if ('children' in cloneColumn) {
cloneColumn.children = fillSlots(cloneColumn.children, contextSlots);
}
return cloneColumn;
});
}
export default function useColumns<RecordType>(
contextSlots: Ref<ContextSlots>,
): [TransformColumns<RecordType>] {
const filledColumns = (columns: ColumnsType<RecordType>) => fillSlots(columns, contextSlots);
return [filledColumns];
}
|
YaroShkvorets/ant-design-vue
|
components/comment/index.tsx
|
import type { ExtractPropTypes } from 'vue';
import { defineComponent } from 'vue';
import PropsTypes from '../_util/vue-types';
import { flattenChildren } from '../_util/props-util';
import type { VueNode } from '../_util/type';
import { withInstall } from '../_util/type';
import useConfigInject from '../_util/hooks/useConfigInject';
export const commentProps = {
actions: PropsTypes.array,
/** The element to display as the comment author. */
author: PropsTypes.VNodeChild,
/** The element to display as the comment avatar - generally an antd Avatar */
avatar: PropsTypes.VNodeChild,
/** The main content of the comment */
content: PropsTypes.VNodeChild,
/** Comment prefix defaults to '.ant-comment' */
prefixCls: PropsTypes.string,
/** A datetime element containing the time to be displayed */
datetime: PropsTypes.VNodeChild,
};
export type CommentProps = Partial<ExtractPropTypes<typeof commentProps>>;
const Comment = defineComponent({
name: 'AComment',
props: commentProps,
slots: ['actions', 'author', 'avatar', 'content', 'datetime'],
setup(props, { slots }) {
const { prefixCls, direction } = useConfigInject('comment', props);
const renderNested = (prefixCls: string, children: VueNode) => {
return <div class={`${prefixCls}-nested`}>{children}</div>;
};
const getAction = (actions: VueNode[]) => {
if (!actions || !actions.length) {
return null;
}
const actionList = actions.map((action, index) => <li key={`action-${index}`}>{action}</li>);
return actionList;
};
return () => {
const pre = prefixCls.value;
const actions = props.actions ?? slots.actions?.();
const author = props.author ?? slots.author?.();
const avatar = props.avatar ?? slots.avatar?.();
const content = props.content ?? slots.content?.();
const datetime = props.datetime ?? slots.datetime?.();
const avatarDom = (
<div class={`${pre}-avatar`}>
{typeof avatar === 'string' ? <img src={avatar} alt="comment-avatar" /> : avatar}
</div>
);
const actionDom = actions ? (
<ul class={`${pre}-actions`}>{getAction(Array.isArray(actions) ? actions : [actions])}</ul>
) : null;
const authorContent = (
<div class={`${pre}-content-author`}>
{author && <span class={`${pre}-content-author-name`}>{author}</span>}
{datetime && <span class={`${pre}-content-author-time`}>{datetime}</span>}
</div>
);
const contentDom = (
<div class={`${pre}-content`}>
{authorContent}
<div class={`${pre}-content-detail`}>{content}</div>
{actionDom}
</div>
);
const comment = (
<div class={`${pre}-inner`}>
{avatarDom}
{contentDom}
</div>
);
const children = flattenChildren(slots.default?.());
return (
<div
class={[
pre,
{
[`${pre}-rtl`]: direction.value === 'rtl',
},
]}
>
{comment}
{children && children.length ? renderNested(pre, children) : null}
</div>
);
};
},
});
export default withInstall(Comment);
|
YaroShkvorets/ant-design-vue
|
components/vc-picker/panels/TimePanel/index.tsx
|
<reponame>YaroShkvorets/ant-design-vue<gh_stars>1000+
import TimeHeader from './TimeHeader';
import type { BodyOperationRef } from './TimeBody';
import TimeBody from './TimeBody';
import type { PanelSharedProps, DisabledTimes } from '../../interface';
import { createKeydownHandler } from '../../utils/uiUtil';
import classNames from '../../../_util/classNames';
import { ref } from 'vue';
import useMergeProps from '../../hooks/useMergeProps';
export type SharedTimeProps<DateType> = {
format?: string;
showNow?: boolean;
showHour?: boolean;
showMinute?: boolean;
showSecond?: boolean;
use12Hours?: boolean;
hourStep?: number;
minuteStep?: number;
secondStep?: number;
hideDisabledOptions?: boolean;
defaultValue?: DateType;
} & DisabledTimes;
export type TimePanelProps<DateType> = {
format?: string;
active?: boolean;
} & PanelSharedProps<DateType> &
SharedTimeProps<DateType>;
const countBoolean = (boolList: (boolean | undefined)[]) =>
boolList.filter(bool => bool !== false).length;
function TimePanel<DateType>(_props: TimePanelProps<DateType>) {
const props = useMergeProps(_props);
const {
generateConfig,
format = 'HH:mm:ss',
prefixCls,
active,
operationRef,
showHour,
showMinute,
showSecond,
use12Hours = false,
onSelect,
value,
} = props;
const panelPrefixCls = `${prefixCls}-time-panel`;
const bodyOperationRef = ref<BodyOperationRef>();
// ======================= Keyboard =======================
const activeColumnIndex = ref(-1);
const columnsCount = countBoolean([showHour, showMinute, showSecond, use12Hours]);
operationRef.value = {
onKeydown: (event: KeyboardEvent) =>
createKeydownHandler(event, {
onLeftRight: diff => {
activeColumnIndex.value = (activeColumnIndex.value + diff + columnsCount) % columnsCount;
},
onUpDown: diff => {
if (activeColumnIndex.value === -1) {
activeColumnIndex.value = 0;
} else if (bodyOperationRef.value) {
bodyOperationRef.value.onUpDown(diff);
}
},
onEnter: () => {
onSelect(value || generateConfig.getNow(), 'key');
activeColumnIndex.value = -1;
},
}),
onBlur: () => {
activeColumnIndex.value = -1;
},
};
return (
<div
class={classNames(panelPrefixCls, {
[`${panelPrefixCls}-active`]: active,
})}
>
<TimeHeader {...props} format={format} prefixCls={prefixCls} />
<TimeBody
{...props}
prefixCls={prefixCls}
activeColumnIndex={activeColumnIndex.value}
operationRef={bodyOperationRef}
/>
</div>
);
}
TimePanel.displayName = 'TimePanel';
TimePanel.inheritAttrs = false;
export default TimePanel;
|
YaroShkvorets/ant-design-vue
|
components/vc-select/OptionList.tsx
|
<filename>components/vc-select/OptionList.tsx
import TransBtn from './TransBtn';
import PropTypes from '../_util/vue-types';
import KeyCode from '../_util/KeyCode';
import classNames from '../_util/classNames';
import pickAttrs from '../_util/pickAttrs';
import { isValidElement } from '../_util/props-util';
import createRef from '../_util/createRef';
import type { PropType } from 'vue';
import { computed, defineComponent, nextTick, reactive, watch } from 'vue';
import List from '../vc-virtual-list/List';
import type {
OptionsType as SelectOptionsType,
OptionData,
RenderNode,
OnActiveValue,
} from './interface';
import type { RawValueType, FlattenOptionsType } from './interface/generator';
import useMemo from '../_util/hooks/useMemo';
export interface RefOptionListProps {
onKeydown: (e?: KeyboardEvent) => void;
onKeyup: (e?: KeyboardEvent) => void;
scrollTo?: (index: number) => void;
}
import type { EventHandler } from '../_util/EventInterface';
export interface OptionListProps<OptionType extends object> {
prefixCls: string;
id: string;
options: OptionType[];
flattenOptions: FlattenOptionsType<OptionType>;
height: number;
itemHeight: number;
values: Set<RawValueType>;
multiple: boolean;
open: boolean;
defaultActiveFirstOption?: boolean;
notFoundContent?: any;
menuItemSelectedIcon?: RenderNode;
childrenAsData: boolean;
searchValue: string;
virtual: boolean;
onSelect: (value: RawValueType, option: { selected: boolean }) => void;
onToggleOpen: (open?: boolean) => void;
/** Tell Select that some value is now active to make accessibility work */
onActiveValue: OnActiveValue;
onScroll: EventHandler;
/** Tell Select that mouse enter the popup to force re-render */
onMouseenter?: EventHandler;
}
const OptionListProps = {
prefixCls: PropTypes.string,
id: PropTypes.string,
options: PropTypes.array,
flattenOptions: PropTypes.array,
height: PropTypes.number,
itemHeight: PropTypes.number,
values: PropTypes.any,
multiple: PropTypes.looseBool,
open: PropTypes.looseBool,
defaultActiveFirstOption: PropTypes.looseBool,
notFoundContent: PropTypes.any,
menuItemSelectedIcon: PropTypes.any,
childrenAsData: PropTypes.looseBool,
searchValue: PropTypes.string,
virtual: PropTypes.looseBool,
onSelect: PropTypes.func,
onToggleOpen: { type: Function as PropType<(open?: boolean) => void> },
/** Tell Select that some value is now active to make accessibility work */
onActiveValue: PropTypes.func,
onScroll: PropTypes.func,
/** Tell Select that mouse enter the popup to force re-render */
onMouseenter: PropTypes.func,
};
/**
* Using virtual list of option display.
* Will fallback to dom if use customize render.
*/
const OptionList = defineComponent<OptionListProps<SelectOptionsType[number]>, { state?: any }>({
name: 'OptionList',
inheritAttrs: false,
slots: ['option'],
setup(props) {
const itemPrefixCls = computed(() => `${props.prefixCls}-item`);
const memoFlattenOptions = useMemo(
() => props.flattenOptions,
[() => props.open, () => props.flattenOptions],
next => next[0],
);
// =========================== List ===========================
const listRef = createRef();
const onListMouseDown: EventHandler = event => {
event.preventDefault();
};
const scrollIntoView = (index: number) => {
if (listRef.current) {
listRef.current.scrollTo({ index });
}
};
// ========================== Active ==========================
const getEnabledActiveIndex = (index: number, offset = 1) => {
const len = memoFlattenOptions.value.length;
for (let i = 0; i < len; i += 1) {
const current = (index + i * offset + len) % len;
const { group, data } = memoFlattenOptions.value[current];
if (!group && !(data as OptionData).disabled) {
return current;
}
}
return -1;
};
const state = reactive({
activeIndex: getEnabledActiveIndex(0),
});
const setActive = (index: number, fromKeyboard = false) => {
state.activeIndex = index;
const info = { source: fromKeyboard ? ('keyboard' as const) : ('mouse' as const) };
// Trigger active event
const flattenItem = memoFlattenOptions.value[index];
if (!flattenItem) {
props.onActiveValue(null, -1, info);
return;
}
props.onActiveValue(flattenItem.data.value, index, info);
};
// Auto active first item when list length or searchValue changed
watch(
[() => memoFlattenOptions.value.length, () => props.searchValue],
() => {
setActive(props.defaultActiveFirstOption !== false ? getEnabledActiveIndex(0) : -1);
},
{ immediate: true },
);
// Auto scroll to item position in single mode
watch(
() => props.open,
() => {
if (!props.multiple && props.open && props.values.size === 1) {
const value = Array.from(props.values)[0];
const index = memoFlattenOptions.value.findIndex(({ data }) => data.value === value);
setActive(index);
nextTick(() => {
scrollIntoView(index);
});
}
// Force trigger scrollbar visible when open
if (props.open) {
nextTick(() => {
listRef.current?.scrollTo(undefined);
});
}
},
{ immediate: true, flush: 'post' },
);
// ========================== Values ==========================
const onSelectValue = (value?: RawValueType) => {
if (value !== undefined) {
props.onSelect(value, { selected: !props.values.has(value) });
}
// Single mode should always close by select
if (!props.multiple) {
props.onToggleOpen(false);
}
};
function renderItem(index: number) {
const item = memoFlattenOptions.value[index];
if (!item) return null;
const itemData = (item.data || {}) as OptionData;
const { value, label, children } = itemData;
const attrs = pickAttrs(itemData, true);
const mergedLabel = props.childrenAsData ? children : label;
return item ? (
<div
aria-label={typeof mergedLabel === 'string' ? mergedLabel : undefined}
{...attrs}
key={index}
role="option"
id={`${props.id}_list_${index}`}
aria-selected={props.values.has(value)}
>
{value}
</div>
) : null;
}
return {
memoFlattenOptions,
renderItem,
listRef,
state,
onListMouseDown,
itemPrefixCls,
setActive,
onSelectValue,
onKeydown: (event: KeyboardEvent) => {
const { which } = event;
switch (which) {
// >>> Arrow keys
case KeyCode.UP:
case KeyCode.DOWN: {
let offset = 0;
if (which === KeyCode.UP) {
offset = -1;
} else if (which === KeyCode.DOWN) {
offset = 1;
}
if (offset !== 0) {
const nextActiveIndex = getEnabledActiveIndex(state.activeIndex + offset, offset);
scrollIntoView(nextActiveIndex);
setActive(nextActiveIndex, true);
}
break;
}
// >>> Select
case KeyCode.ENTER: {
// value
const item = memoFlattenOptions.value[state.activeIndex];
if (item && !item.data.disabled) {
onSelectValue(item.data.value);
} else {
onSelectValue(undefined);
}
if (props.open) {
event.preventDefault();
}
break;
}
// >>> Close
case KeyCode.ESC: {
props.onToggleOpen(false);
if (props.open) {
event.stopPropagation();
}
}
}
},
onKeyup: () => {},
scrollTo: (index: number) => {
scrollIntoView(index);
},
};
},
render() {
const {
renderItem,
listRef,
onListMouseDown,
itemPrefixCls,
setActive,
onSelectValue,
memoFlattenOptions,
$slots,
} = this as any;
const {
id,
childrenAsData,
values,
height,
itemHeight,
menuItemSelectedIcon,
notFoundContent,
virtual,
onScroll,
onMouseenter,
} = this.$props;
const renderOption = $slots.option;
const { activeIndex } = this.state;
// ========================== Render ==========================
if (memoFlattenOptions.length === 0) {
return (
<div
role="listbox"
id={`${id}_list`}
class={`${itemPrefixCls}-empty`}
onMousedown={onListMouseDown}
>
{notFoundContent}
</div>
);
}
return (
<>
<div role="listbox" id={`${id}_list`} style={{ height: 0, width: 0, overflow: 'hidden' }}>
{renderItem(activeIndex - 1)}
{renderItem(activeIndex)}
{renderItem(activeIndex + 1)}
</div>
<List
itemKey="key"
ref={listRef}
data={memoFlattenOptions}
height={height}
itemHeight={itemHeight}
fullHeight={false}
onMousedown={onListMouseDown}
onScroll={onScroll}
virtual={virtual}
onMouseenter={onMouseenter}
children={({ group, groupOption, data }, itemIndex) => {
const { label, key } = data;
// Group
if (group) {
return (
<div class={classNames(itemPrefixCls, `${itemPrefixCls}-group`)}>
{renderOption ? renderOption(data) : label !== undefined ? label : key}
</div>
);
}
const {
disabled,
value,
title,
children,
style,
class: cls,
className,
...otherProps
} = data;
// Option
const selected = values.has(value);
const optionPrefixCls = `${itemPrefixCls}-option`;
const optionClassName = classNames(itemPrefixCls, optionPrefixCls, cls, className, {
[`${optionPrefixCls}-grouped`]: groupOption,
[`${optionPrefixCls}-active`]: activeIndex === itemIndex && !disabled,
[`${optionPrefixCls}-disabled`]: disabled,
[`${optionPrefixCls}-selected`]: selected,
});
const mergedLabel = childrenAsData ? children : label;
const iconVisible =
!menuItemSelectedIcon || typeof menuItemSelectedIcon === 'function' || selected;
const content = mergedLabel || value;
// https://github.com/ant-design/ant-design/issues/26717
let optionTitle =
typeof content === 'string' || typeof content === 'number'
? content.toString()
: undefined;
if (title !== undefined) {
optionTitle = title;
}
return (
<div
{...otherProps}
aria-selected={selected}
class={optionClassName}
title={optionTitle}
onMousemove={e => {
if (otherProps.onMousemove) {
otherProps.onMousemove(e);
}
if (activeIndex === itemIndex || disabled) {
return;
}
setActive(itemIndex);
}}
onClick={e => {
if (!disabled) {
onSelectValue(value);
}
if (otherProps.onClick) {
otherProps.onClick(e);
}
}}
style={style}
>
<div class={`${optionPrefixCls}-content`}>
{renderOption ? renderOption(data) : content}
</div>
{isValidElement(menuItemSelectedIcon) || selected}
{iconVisible && (
<TransBtn
class={`${itemPrefixCls}-option-state`}
customizeIcon={menuItemSelectedIcon}
customizeIconProps={{ isSelected: selected }}
>
{selected ? '✓' : null}
</TransBtn>
)}
</div>
);
}}
></List>
</>
);
},
});
OptionList.props = OptionListProps;
export default OptionList;
|
YaroShkvorets/ant-design-vue
|
components/table/hooks/useTitleColumns.tsx
|
import type { Ref } from 'vue';
import type { TransformColumns, ColumnTitleProps, ColumnsType } from '../interface';
import { renderColumnTitle } from '../util';
function fillTitle<RecordType>(
columns: ColumnsType<RecordType>,
columnTitleProps: ColumnTitleProps<RecordType>,
) {
return columns.map(column => {
const cloneColumn = { ...column };
cloneColumn.title = renderColumnTitle(cloneColumn.title, columnTitleProps);
if ('children' in cloneColumn) {
cloneColumn.children = fillTitle(cloneColumn.children, columnTitleProps);
}
return cloneColumn;
});
}
export default function useTitleColumns<RecordType>(
columnTitleProps: Ref<ColumnTitleProps<RecordType>>,
): [TransformColumns<RecordType>] {
const filledColumns = (columns: ColumnsType<RecordType>) =>
fillTitle(columns, columnTitleProps.value);
return [filledColumns];
}
|
YaroShkvorets/ant-design-vue
|
components/vc-tree/DropIndicator.tsx
|
import type { CSSProperties } from 'vue';
export default function DropIndicator({
dropPosition,
dropLevelOffset,
indent,
}: {
dropPosition: -1 | 0 | 1;
dropLevelOffset: number;
indent: number;
}) {
const style: CSSProperties = {
pointerEvents: 'none',
position: 'absolute',
right: 0,
backgroundColor: 'red',
height: `${2}px`,
};
switch (dropPosition) {
case -1:
style.top = 0;
style.left = `${-dropLevelOffset * indent}px`;
break;
case 1:
style.bottom = 0;
style.left = `${-dropLevelOffset * indent}px`;
break;
case 0:
style.bottom = 0;
style.left = `${indent}`;
break;
}
return <div style={style} />;
}
|
YaroShkvorets/ant-design-vue
|
components/vc-table/Footer/Row.tsx
|
<filename>components/vc-table/Footer/Row.tsx
import { defineComponent } from 'vue';
export default defineComponent({
name: 'FooterRow',
setup(_props, { slots }) {
return () => <tr>{slots.default?.()}</tr>;
},
});
|
YaroShkvorets/ant-design-vue
|
components/vc-table/index.ts
|
<gh_stars>1000+
// base rc-table@7.17.2
import Table from './Table';
import { FooterComponents as Summary, SummaryCell, SummaryRow } from './Footer';
import Column from './sugar/Column';
import ColumnGroup from './sugar/ColumnGroup';
import { INTERNAL_COL_DEFINE } from './utils/legacyUtil';
export { Summary, Column, ColumnGroup, SummaryCell, SummaryRow, INTERNAL_COL_DEFINE };
export default Table;
|
YaroShkvorets/ant-design-vue
|
components/skeleton/Paragraph.tsx
|
<reponame>YaroShkvorets/ant-design-vue<filename>components/skeleton/Paragraph.tsx
import type { ExtractPropTypes, PropType } from 'vue';
import { defineComponent } from 'vue';
type widthUnit = number | string;
export const skeletonParagraphProps = {
prefixCls: String,
width: { type: [Number, String, Array] as PropType<widthUnit[] | widthUnit> },
rows: Number,
};
export type SkeletonParagraphProps = Partial<ExtractPropTypes<typeof skeletonParagraphProps>>;
const SkeletonParagraph = defineComponent({
name: 'SkeletonParagraph',
props: skeletonParagraphProps,
setup(props) {
const getWidth = (index: number) => {
const { width, rows = 2 } = props;
if (Array.isArray(width)) {
return width[index];
}
// last paragraph
if (rows - 1 === index) {
return width;
}
return undefined;
};
return () => {
const { prefixCls, rows } = props;
const rowList = [...Array(rows)].map((_, index) => {
const width = getWidth(index);
return (
<li key={index} style={{ width: typeof width === 'number' ? `${width}px` : width }} />
);
});
return <ul class={prefixCls}>{rowList}</ul>;
};
},
});
export default SkeletonParagraph;
|
YaroShkvorets/ant-design-vue
|
components/vc-picker/panels/WeekPanel/index.tsx
|
import DatePanel from '../DatePanel';
import type { PanelSharedProps } from '../../interface';
import { isSameWeek } from '../../utils/dateUtil';
import classNames from '../../../_util/classNames';
import useMergeProps from '../../hooks/useMergeProps';
export type WeekPanelProps<DateType> = PanelSharedProps<DateType>;
function WeekPanel<DateType>(_props: WeekPanelProps<DateType>) {
const props = useMergeProps(_props);
const { prefixCls, generateConfig, locale, value } = props;
// Render additional column
const cellPrefixCls = `${prefixCls}-cell`;
const prefixColumn = (date: DateType) => (
<td key="week" class={classNames(cellPrefixCls, `${cellPrefixCls}-week`)}>
{generateConfig.locale.getWeek(locale.locale, date)}
</td>
);
// Add row className
const rowPrefixCls = `${prefixCls}-week-panel-row`;
const rowClassName = (date: DateType) =>
classNames(rowPrefixCls, {
[`${rowPrefixCls}-selected`]: isSameWeek(generateConfig, locale.locale, value, date),
});
return (
<DatePanel
{...props}
panelName="week"
prefixColumn={prefixColumn}
rowClassName={rowClassName}
keyboardConfig={{
onLeftRight: null,
}}
/>
);
}
WeekPanel.displayName = 'WeekPanel';
WeekPanel.inheritAttrs = false;
export default WeekPanel;
|
YaroShkvorets/ant-design-vue
|
plugin/md/markdown/plugins/preWrapper.ts
|
// markdown-it plugin for wrapping <pre> ... </pre>.
//
// If your plugin was chained before preWrapper, you can add additional element directly.
// If your plugin was chained after preWrapper, you can use these slots:
// 1. <!--beforebegin-->
// 2. <!--afterbegin-->
// 3. <!--beforeend-->
// 4. <!--afterend-->
import type MarkdownIt from 'markdown-it';
import type { MarkdownParsedData } from '../markdown';
export const preWrapperPlugin = (md: MarkdownIt) => {
const fence = md.renderer.rules.fence!;
md.renderer.rules.fence = (...args) => {
const [tokens, idx] = args;
const token = tokens[idx];
const data = (md as any).__data as MarkdownParsedData;
if (token.info.trim() === 'vue') {
data.vueCode = token.content;
}
const rawCode = fence(...args).replace(/<pre /g, `<pre class="language-${token.info.trim()}" `);
return rawCode; //`<div class="language-${token.info.trim()}">${rawCode}</div>`;
};
};
|
YaroShkvorets/ant-design-vue
|
components/collapse/commonProps.ts
|
import type { PropType } from 'vue';
import { tuple } from '../_util/type';
import PropTypes from '../_util/vue-types';
export type CollapsibleType = 'header' | 'disabled';
export type ActiveKeyType = Array<string | number> | string | number;
const collapseProps = () => ({
prefixCls: PropTypes.string,
activeKey: { type: [Array, Number, String] as PropType<ActiveKeyType> },
defaultActiveKey: { type: [Array, Number, String] as PropType<ActiveKeyType> },
accordion: PropTypes.looseBool,
destroyInactivePanel: PropTypes.looseBool,
bordered: PropTypes.looseBool,
expandIcon: PropTypes.func,
openAnimation: PropTypes.object,
expandIconPosition: PropTypes.oneOf(tuple('left', 'right')),
collapsible: { type: String as PropType<CollapsibleType> },
ghost: PropTypes.looseBool,
});
const collapsePanelProps = () => ({
openAnimation: PropTypes.object,
prefixCls: PropTypes.string,
header: PropTypes.any,
headerClass: PropTypes.string,
showArrow: PropTypes.looseBool,
isActive: PropTypes.looseBool,
destroyInactivePanel: PropTypes.looseBool,
/** @deprecated Use `collapsible="disabled"` instead */
disabled: PropTypes.looseBool,
accordion: PropTypes.looseBool,
forceRender: PropTypes.looseBool,
expandIcon: PropTypes.func,
extra: PropTypes.any,
panelKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
collapsible: { type: String as PropType<CollapsibleType> },
role: String,
onItemClick: { type: Function as PropType<(panelKey: string | number) => void> },
});
export { collapseProps, collapsePanelProps };
|
YaroShkvorets/ant-design-vue
|
components/pagination/MiniSelect.tsx
|
import { defineComponent } from 'vue';
import VcSelect, { selectProps } from '../select';
export default defineComponent({
inheritAttrs: false,
props: selectProps(),
Option: VcSelect.Option,
setup(props, { attrs, slots }) {
return () => {
const selelctProps: any = {
...props,
size: 'small',
...attrs,
};
return <VcSelect {...selelctProps} v-slots={slots}></VcSelect>;
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/vc-table/Footer/index.tsx
|
import Summary from './Summary';
import SummaryRow from './Row';
import SummaryCell from './Cell';
import type { DefaultRecordType, StickyOffsets } from '../interface';
import { computed, defineComponent, reactive, toRef } from 'vue';
import type { FlattenColumns } from '../context/SummaryContext';
import { useProvideSummary } from '../context/SummaryContext';
import { useInjectTable } from '../context/TableContext';
export interface FooterProps<RecordType = DefaultRecordType> {
stickyOffsets: StickyOffsets;
flattenColumns: FlattenColumns<RecordType>;
}
export default defineComponent({
name: 'Footer',
inheritAttrs: false,
props: ['stickyOffsets', 'flattenColumns'],
setup(props, { slots }) {
const tableContext = useInjectTable();
useProvideSummary(
reactive({
stickyOffsets: toRef(props, 'stickyOffsets'),
flattenColumns: toRef(props, 'flattenColumns'),
scrollColumnIndex: computed(() => {
const lastColumnIndex = props.flattenColumns.length - 1;
const scrollColumn = props.flattenColumns[lastColumnIndex];
return scrollColumn?.scrollbar ? lastColumnIndex : null;
}),
}),
);
return () => {
const { prefixCls } = tableContext;
return <tfoot class={`${prefixCls}-summary`}>{slots.default?.()}</tfoot>;
};
},
});
export { SummaryRow, SummaryCell };
export const FooterComponents = Summary;
|
YaroShkvorets/ant-design-vue
|
components/vc-virtual-list/interface.ts
|
import type { CSSProperties, VNodeTypes } from 'vue';
import type { Key } from '../_util/type';
export type RenderFunc<T> = (
item: T,
index: number,
props: { style?: CSSProperties },
) => VNodeTypes;
export interface SharedConfig<T> {
getKey: (item: T) => Key;
}
export type GetKey<T = object> = (item: T) => Key;
|
YaroShkvorets/ant-design-vue
|
components/vc-progress/index.ts
|
<filename>components/vc-progress/index.ts
// based on rc-progress 3.1.4
import Progress, { Line, Circle } from './src';
import type { ProgressProps } from './src';
export { Line, Circle };
export type { ProgressProps };
export default Progress;
|
YaroShkvorets/ant-design-vue
|
components/_util/hooks/useMergedState.ts
|
import type { Ref, UnwrapRef } from 'vue';
import { toRaw, watchEffect, unref, watch, ref } from 'vue';
export default function useMergedState<T, R = Ref<T>>(
defaultStateValue: T | (() => T),
option?: {
defaultValue?: T | (() => T);
value?: Ref<T> | Ref<UnwrapRef<T>>;
onChange?: (val: T, prevValue: T) => void;
postState?: (val: T) => T;
},
): [R, (val: T) => void] {
const { defaultValue, value = ref() } = option || {};
let initValue: T =
typeof defaultStateValue === 'function' ? (defaultStateValue as any)() : defaultStateValue;
if (value.value !== undefined) {
initValue = unref(value as any) as T;
}
if (defaultValue !== undefined) {
initValue = typeof defaultValue === 'function' ? (defaultValue as any)() : defaultValue;
}
const innerValue = ref(initValue) as Ref<T>;
const mergedValue = ref(initValue) as Ref<T>;
watchEffect(() => {
let val = value.value !== undefined ? value.value : innerValue.value;
if (option.postState) {
val = option.postState(val as T);
}
mergedValue.value = val as T;
});
function triggerChange(newValue: T) {
const preVal = mergedValue.value;
innerValue.value = newValue;
if (toRaw(mergedValue.value) !== newValue && option.onChange) {
option.onChange(newValue, preVal);
}
}
// Effect of reset value to `undefined`
watch(value, () => {
innerValue.value = value.value as T;
});
return [mergedValue as unknown as R, triggerChange];
}
|
YaroShkvorets/ant-design-vue
|
components/input/ClearableLabeledInput.tsx
|
import classNames from '../_util/classNames';
import CloseCircleFilled from '@ant-design/icons-vue/CloseCircleFilled';
import { getInputClassName } from './Input';
import PropTypes from '../_util/vue-types';
import { cloneElement } from '../_util/vnode';
import { getComponent } from '../_util/props-util';
import type { VNode } from 'vue';
import { defineComponent } from 'vue';
import { tuple } from '../_util/type';
export function hasPrefixSuffix(instance: any) {
return !!(
getComponent(instance, 'prefix') ||
getComponent(instance, 'suffix') ||
instance.$props.allowClear
);
}
const ClearableInputType = ['text', 'input'];
const ClearableLabeledInput = defineComponent({
name: 'ClearableLabeledInput',
inheritAttrs: false,
props: {
prefixCls: PropTypes.string,
inputType: PropTypes.oneOf(tuple('text', 'input')),
value: PropTypes.any,
defaultValue: PropTypes.any,
allowClear: PropTypes.looseBool,
element: PropTypes.VNodeChild,
handleReset: PropTypes.func,
disabled: PropTypes.looseBool,
size: PropTypes.oneOf(tuple('small', 'large', 'default')),
suffix: PropTypes.VNodeChild,
prefix: PropTypes.VNodeChild,
addonBefore: PropTypes.VNodeChild,
addonAfter: PropTypes.VNodeChild,
readonly: PropTypes.looseBool,
isFocused: PropTypes.looseBool,
},
methods: {
renderClearIcon(prefixCls: string) {
const { allowClear, value, disabled, readonly, inputType, handleReset } = this.$props;
if (!allowClear) {
return null;
}
const showClearIcon =
!disabled && !readonly && value !== undefined && value !== null && value !== '';
const className =
inputType === ClearableInputType[0]
? `${prefixCls}-textarea-clear-icon`
: `${prefixCls}-clear-icon`;
return (
<CloseCircleFilled
onClick={handleReset}
class={classNames(className, {
[`${className}-hidden`]: !showClearIcon,
})}
role="button"
/>
);
},
renderSuffix(prefixCls: string) {
const { suffix, allowClear } = this.$props;
if (suffix || allowClear) {
return (
<span class={`${prefixCls}-suffix`}>
{this.renderClearIcon(prefixCls)}
{suffix}
</span>
);
}
return null;
},
renderLabeledIcon(prefixCls: string, element: VNode): VNode {
const props = this.$props;
const { style } = this.$attrs;
const suffix = this.renderSuffix(prefixCls);
if (!hasPrefixSuffix(this)) {
return cloneElement(element, {
value: props.value,
});
}
const prefix = props.prefix ? (
<span class={`${prefixCls}-prefix`}>{props.prefix}</span>
) : null;
const affixWrapperCls = classNames(this.$attrs?.class, `${prefixCls}-affix-wrapper`, {
[`${prefixCls}-affix-wrapper-focused`]: props.isFocused,
[`${prefixCls}-affix-wrapper-disabled`]: props.disabled,
[`${prefixCls}-affix-wrapper-sm`]: props.size === 'small',
[`${prefixCls}-affix-wrapper-lg`]: props.size === 'large',
[`${prefixCls}-affix-wrapper-input-with-clear-btn`]:
props.suffix && props.allowClear && this.$props.value,
});
return (
<span class={affixWrapperCls} style={style}>
{prefix}
{cloneElement(element, {
style: null,
value: props.value,
class: getInputClassName(prefixCls, props.size, props.disabled),
})}
{suffix}
</span>
) as VNode;
},
renderInputWithLabel(prefixCls: string, labeledElement: VNode) {
const { addonBefore, addonAfter, size } = this.$props;
const { style, class: className } = this.$attrs;
// Not wrap when there is not addons
if (!addonBefore && !addonAfter) {
return labeledElement;
}
const wrapperClassName = `${prefixCls}-group`;
const addonClassName = `${wrapperClassName}-addon`;
const addonBeforeNode = addonBefore ? (
<span class={addonClassName}>{addonBefore}</span>
) : null;
const addonAfterNode = addonAfter ? <span class={addonClassName}>{addonAfter}</span> : null;
const mergedWrapperClassName = classNames(`${prefixCls}-wrapper`, {
[wrapperClassName]: addonBefore || addonAfter,
});
const mergedGroupClassName = classNames(className, `${prefixCls}-group-wrapper`, {
[`${prefixCls}-group-wrapper-sm`]: size === 'small',
[`${prefixCls}-group-wrapper-lg`]: size === 'large',
});
// Need another wrapper for changing display:table to display:inline-block
// and put style prop in wrapper
return (
<span class={mergedGroupClassName} style={style}>
<span class={mergedWrapperClassName}>
{addonBeforeNode}
{cloneElement(labeledElement, { style: null })}
{addonAfterNode}
</span>
</span>
);
},
renderTextAreaWithClearIcon(prefixCls: string, element: VNode) {
const { value, allowClear } = this.$props;
const { style, class: className } = this.$attrs;
if (!allowClear) {
return cloneElement(element, { value });
}
const affixWrapperCls = classNames(
className,
`${prefixCls}-affix-wrapper`,
`${prefixCls}-affix-wrapper-textarea-with-clear-btn`,
);
return (
<span class={affixWrapperCls} style={style}>
{cloneElement(element, {
style: null,
value,
})}
{this.renderClearIcon(prefixCls)}
</span>
);
},
renderClearableLabeledInput() {
const { prefixCls, inputType, element } = this.$props as any;
if (inputType === ClearableInputType[0]) {
return this.renderTextAreaWithClearIcon(prefixCls, element);
}
return this.renderInputWithLabel(prefixCls, this.renderLabeledIcon(prefixCls, element));
},
},
render() {
return this.renderClearableLabeledInput();
},
});
export default ClearableLabeledInput;
|
YaroShkvorets/ant-design-vue
|
components/button/button-group.tsx
|
import { computed, defineComponent } from 'vue';
import { flattenChildren } from '../_util/props-util';
import PropTypes from '../_util/vue-types';
import useConfigInject from '../_util/hooks/useConfigInject';
import type { ExtractPropTypes, PropType } from 'vue';
import type { SizeType } from '../config-provider';
const buttonGroupProps = {
prefixCls: PropTypes.string,
size: {
type: String as PropType<SizeType>,
},
};
export { buttonGroupProps };
export type ButtonGroupProps = Partial<ExtractPropTypes<typeof buttonGroupProps>>;
export default defineComponent({
name: 'AButtonGroup',
props: buttonGroupProps,
setup(props, { slots }) {
const { prefixCls, direction } = useConfigInject('btn-group', props);
const classes = computed(() => {
const { size } = props;
// large => lg
// small => sm
let sizeCls = '';
switch (size) {
case 'large':
sizeCls = 'lg';
break;
case 'small':
sizeCls = 'sm';
break;
default:
break;
}
return {
[`${prefixCls.value}`]: true,
[`${prefixCls.value}-${sizeCls}`]: sizeCls,
[`${prefixCls.value}-rtl`]: direction.value === 'rtl',
};
});
return () => {
return <div class={classes.value}>{flattenChildren(slots.default?.())}</div>;
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/vc-pagination/locale/lt_LT.ts
|
export default {
// Options.jsx
items_per_page: '/ psl.',
jump_to: 'Pereiti',
jump_to_confirm: 'patvirtinti',
page: '',
// Pagination.jsx
prev_page: 'Atgal',
next_page: 'Pirmyn',
prev_5: 'Grįžti 5 pls.',
next_5: 'Peršokti 5 pls.',
prev_3: 'Grįžti 3 pls.',
next_3: 'Peršokti 3 pls.',
};
|
YaroShkvorets/ant-design-vue
|
components/statistic/index.ts
|
<filename>components/statistic/index.ts
import type { App, Plugin } from 'vue';
import Statistic from './Statistic';
import Countdown from './Countdown';
export type { StatisticProps } from './Statistic';
Statistic.Countdown = Countdown;
/* istanbul ignore next */
Statistic.install = function (app: App) {
app.component(Statistic.name, Statistic);
app.component(Statistic.Countdown.name, Statistic.Countdown);
return app;
};
export const StatisticCountdown = Statistic.Countdown;
export default Statistic as typeof Statistic &
Plugin & {
readonly Countdown: typeof Countdown;
};
|
YaroShkvorets/ant-design-vue
|
components/vc-picker/hooks/useRangeViewDates.ts
|
<reponame>YaroShkvorets/ant-design-vue<filename>components/vc-picker/hooks/useRangeViewDates.ts
import type { RangeValue, PickerMode } from '../interface';
import type { GenerateConfig } from '../generate';
import { getValue, updateValues } from '../utils/miscUtil';
import { getClosingViewDate, isSameYear, isSameMonth, isSameDecade } from '../utils/dateUtil';
import type { Ref } from 'vue';
import { watch, computed, ref } from 'vue';
function getStartEndDistance<DateType>(
startDate: DateType,
endDate: DateType,
picker: PickerMode,
generateConfig: GenerateConfig<DateType>,
): 'same' | 'closing' | 'far' {
const startNext = getClosingViewDate(startDate, picker, generateConfig, 1);
function getDistance(compareFunc: (start: DateType | null, end: DateType | null) => boolean) {
if (compareFunc(startDate, endDate)) {
return 'same';
}
if (compareFunc(startNext, endDate)) {
return 'closing';
}
return 'far';
}
switch (picker) {
case 'year':
return getDistance((start, end) => isSameDecade(generateConfig, start, end));
case 'quarter':
case 'month':
return getDistance((start, end) => isSameYear(generateConfig, start, end));
default:
return getDistance((start, end) => isSameMonth(generateConfig, start, end));
}
}
function getRangeViewDate<DateType>(
values: RangeValue<DateType>,
index: 0 | 1,
picker: PickerMode,
generateConfig: GenerateConfig<DateType>,
): DateType | null {
const startDate = getValue(values, 0);
const endDate = getValue(values, 1);
if (index === 0) {
return startDate;
}
if (startDate && endDate) {
const distance = getStartEndDistance(startDate, endDate, picker, generateConfig);
switch (distance) {
case 'same':
return startDate;
case 'closing':
return startDate;
default:
return getClosingViewDate(endDate, picker, generateConfig, -1);
}
}
return startDate;
}
export default function useRangeViewDates<DateType>({
values,
picker,
defaultDates,
generateConfig,
}: {
values: Ref<RangeValue<DateType>>;
picker: Ref<PickerMode>;
defaultDates: RangeValue<DateType> | undefined;
generateConfig: Ref<GenerateConfig<DateType>>;
}): [Ref<DateType>, Ref<DateType>, (viewDate: DateType | null, index: 0 | 1) => void] {
const defaultViewDates = ref<[DateType | null, DateType | null]>([
getValue(defaultDates, 0),
getValue(defaultDates, 1),
]);
const viewDates = ref<RangeValue<DateType>>(null);
const startDate = computed(() => getValue(values.value, 0));
const endDate = computed(() => getValue(values.value, 1));
const getViewDate = (index: 0 | 1): DateType => {
// If set default view date, use it
if (defaultViewDates.value[index]) {
return defaultViewDates.value[index]! as DateType;
}
return (
(getValue(viewDates.value, index) as any) ||
getRangeViewDate(values.value, index, picker.value, generateConfig.value) ||
startDate.value ||
endDate.value ||
generateConfig.value.getNow()
);
};
const startViewDate = ref(null);
const endViewDate = ref(null);
watch(
viewDates,
() => {
startViewDate.value = getViewDate(0);
endViewDate.value = getViewDate(1);
},
{ immediate: true },
);
function setViewDate(viewDate: DateType | null, index: 0 | 1) {
if (viewDate) {
let newViewDates = updateValues(viewDates.value, viewDate as any, index);
// Set view date will clean up default one
// Should always be an array
defaultViewDates.value = updateValues(defaultViewDates.value, null, index) || [null, null];
// Reset another one when not have value
const anotherIndex = (index + 1) % 2;
if (!getValue(values.value, anotherIndex)) {
newViewDates = updateValues(newViewDates, viewDate, anotherIndex);
}
viewDates.value = newViewDates;
} else if (startDate.value || endDate.value) {
// Reset all when has values when `viewDate` is `null` which means from open trigger
viewDates.value = null;
}
}
return [startViewDate, endViewDate, setViewDate];
}
|
YaroShkvorets/ant-design-vue
|
components/vc-trigger/Popup/MobilePopupInner.tsx
|
import type { CSSProperties } from 'vue';
import { defineComponent, ref, Transition } from 'vue';
import { flattenChildren } from '../../_util/props-util';
import classNames from '../../_util/classNames';
import type { MobilePopupProps } from './interface';
import { mobileProps } from './interface';
export default defineComponent({
name: 'MobilePopupInner',
inheritAttrs: false,
props: mobileProps,
emits: ['mouseenter', 'mouseleave', 'mousedown', 'touchstart', 'align'],
setup(props, { expose, slots }) {
const elementRef = ref<HTMLDivElement>();
expose({
forceAlign: () => {},
getElement: () => elementRef.value,
});
return () => {
const {
zIndex,
visible,
prefixCls,
mobile: { popupClassName, popupStyle, popupMotion = {}, popupRender } = {},
} = props as MobilePopupProps;
// ======================== Render ========================
const mergedStyle: CSSProperties = {
zIndex,
...popupStyle,
};
let childNode: any = flattenChildren(slots.default?.());
// Wrapper when multiple children
if (childNode.length > 1) {
childNode = <div class={`${prefixCls}-content`}>{childNode}</div>;
}
// Mobile support additional render
if (popupRender) {
childNode = popupRender(childNode);
}
const mergedClassName = classNames(prefixCls, popupClassName);
return (
<Transition ref={elementRef} {...popupMotion}>
{visible ? (
<div class={mergedClassName} style={mergedStyle}>
{childNode}
</div>
) : null}
</Transition>
);
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/table/hooks/useFilter/FilterDropdown.tsx
|
import isEqual from 'lodash-es/isEqual';
import FilterFilled from '@ant-design/icons-vue/FilterFilled';
import Button from '../../../button';
import Menu from '../../../menu';
import Checkbox from '../../../checkbox';
import Radio from '../../../radio';
import Dropdown from '../../../dropdown';
import Empty from '../../../empty';
import type {
ColumnType,
ColumnFilterItem,
Key,
TableLocale,
GetPopupContainer,
} from '../../interface';
import FilterDropdownMenuWrapper from './FilterWrapper';
import type { FilterState } from '.';
import { computed, defineComponent, onBeforeUnmount, ref, shallowRef, watch } from 'vue';
import classNames from '../../../_util/classNames';
import useConfigInject from '../../../_util/hooks/useConfigInject';
import { useInjectSlots } from '../../context';
const { SubMenu, Item: MenuItem } = Menu;
function hasSubMenu(filters: ColumnFilterItem[]) {
return filters.some(({ children }) => children && children.length > 0);
}
function renderFilterItems({
filters,
prefixCls,
filteredKeys,
filterMultiple,
locale,
}: {
filters: ColumnFilterItem[];
prefixCls: string;
filteredKeys: Key[];
filterMultiple: boolean;
locale: TableLocale;
}) {
if (filters.length === 0) {
// wrapped with <div /> to avoid react warning
// https://github.com/ant-design/ant-design/issues/25979
return (
<MenuItem key="empty">
<div
style={{
margin: '16px 0',
}}
>
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={locale.filterEmptyText}
imageStyle={{
height: 24,
}}
/>
</div>
</MenuItem>
);
}
return filters.map((filter, index) => {
const key = String(filter.value);
if (filter.children) {
return (
<SubMenu
key={key || index}
title={filter.text}
popupClassName={`${prefixCls}-dropdown-submenu`}
>
{renderFilterItems({
filters: filter.children,
prefixCls,
filteredKeys,
filterMultiple,
locale,
})}
</SubMenu>
);
}
const Component = filterMultiple ? Checkbox : Radio;
return (
<MenuItem key={filter.value !== undefined ? key : index}>
<Component checked={filteredKeys.includes(key)} />
<span>{filter.text}</span>
</MenuItem>
);
});
}
export interface FilterDropdownProps<RecordType> {
tablePrefixCls: string;
prefixCls: string;
dropdownPrefixCls: string;
column: ColumnType<RecordType>;
filterState?: FilterState<RecordType>;
filterMultiple: boolean;
columnKey: Key;
triggerFilter: (filterState: FilterState<RecordType>) => void;
locale: TableLocale;
getPopupContainer?: GetPopupContainer;
}
export default defineComponent<FilterDropdownProps<any>>({
name: 'FilterDropdown',
props: [
'tablePrefixCls',
'prefixCls',
'dropdownPrefixCls',
'column',
'filterState',
'filterMultiple',
'columnKey',
'triggerFilter',
'locale',
'getPopupContainer',
] as any,
setup(props, { slots }) {
const contextSlots = useInjectSlots();
const filterDropdownVisible = computed(() => props.column.filterDropdownVisible);
const visible = ref(false);
const filtered = computed(
() =>
!!(
props.filterState &&
(props.filterState.filteredKeys?.length || props.filterState.forceFiltered)
),
);
const filterDropdownRef = computed(() => {
const { filterDropdown, slots = {}, customFilterDropdown } = props.column;
return (
filterDropdown ||
(slots.filterDropdown && contextSlots.value[slots.filterDropdown]) ||
(customFilterDropdown && contextSlots.value.customFilterDropdown)
);
});
const filterIconRef = computed(() => {
const { filterIcon, slots = {} } = props.column;
return (
filterIcon ||
(slots.filterIcon && contextSlots.value[slots.filterIcon]) ||
contextSlots.value.customFilterIcon
);
});
const triggerVisible = (newVisible: boolean) => {
visible.value = newVisible;
props.column.onFilterDropdownVisibleChange?.(newVisible);
};
const mergedVisible = computed(() =>
typeof filterDropdownVisible.value === 'boolean'
? filterDropdownVisible.value
: visible.value,
);
const propFilteredKeys = computed(() => props.filterState?.filteredKeys);
const filteredKeys = shallowRef([]);
const onSelectKeys = ({ selectedKeys }: { selectedKeys?: Key[] }) => {
filteredKeys.value = selectedKeys;
};
watch(
propFilteredKeys,
() => {
onSelectKeys({ selectedKeys: propFilteredKeys.value || [] });
},
{ immediate: true },
);
const openKeys = shallowRef([]);
const openRef = ref();
const onOpenChange = (keys: string[]) => {
openRef.value = window.setTimeout(() => {
openKeys.value = keys;
});
};
const onMenuClick = () => {
window.clearTimeout(openRef.value);
};
onBeforeUnmount(() => {
window.clearTimeout(openRef.value);
});
// ======================= Submit ========================
const internalTriggerFilter = (keys: Key[] | undefined | null) => {
const { column, columnKey, filterState } = props;
const mergedKeys = keys && keys.length ? keys : null;
if (mergedKeys === null && (!filterState || !filterState.filteredKeys)) {
return null;
}
if (isEqual(mergedKeys, filterState?.filteredKeys)) {
return null;
}
props.triggerFilter({
column,
key: columnKey,
filteredKeys: mergedKeys,
});
};
const onConfirm = () => {
triggerVisible(false);
internalTriggerFilter(filteredKeys.value);
};
const onReset = () => {
filteredKeys.value = [];
triggerVisible(false);
internalTriggerFilter([]);
};
const doFilter = ({ closeDropdown } = { closeDropdown: true }) => {
if (closeDropdown) {
triggerVisible(false);
}
internalTriggerFilter(filteredKeys.value);
};
const onVisibleChange = (newVisible: boolean) => {
if (newVisible && propFilteredKeys.value !== undefined) {
// Sync filteredKeys on appear in controlled mode (propFilteredKeys.value !== undefiend)
filteredKeys.value = propFilteredKeys.value || [];
}
triggerVisible(newVisible);
// Default will filter when closed
if (!newVisible && !filterDropdownRef.value) {
onConfirm();
}
};
const { direction } = useConfigInject('', props);
return () => {
const {
tablePrefixCls,
prefixCls,
column,
dropdownPrefixCls,
filterMultiple,
locale,
getPopupContainer,
} = props;
// ======================== Style ========================
const dropdownMenuClass = classNames({
[`${dropdownPrefixCls}-menu-without-submenu`]: !hasSubMenu(column.filters || []),
});
let dropdownContent;
if (typeof filterDropdownRef.value === 'function') {
dropdownContent = filterDropdownRef.value({
prefixCls: `${dropdownPrefixCls}-custom`,
setSelectedKeys: (selectedKeys: Key[]) => onSelectKeys({ selectedKeys }),
selectedKeys: filteredKeys.value,
confirm: doFilter,
clearFilters: onReset,
filters: column.filters,
visible: mergedVisible.value,
column: column.__originColumn__,
});
} else if (filterDropdownRef.value) {
dropdownContent = filterDropdownRef.value;
} else {
const selectedKeys = filteredKeys.value as any;
dropdownContent = (
<>
<Menu
multiple={filterMultiple}
prefixCls={`${dropdownPrefixCls}-menu`}
class={dropdownMenuClass}
onClick={onMenuClick}
onSelect={onSelectKeys}
onDeselect={onSelectKeys}
selectedKeys={selectedKeys}
getPopupContainer={getPopupContainer}
openKeys={openKeys.value}
onOpenChange={onOpenChange}
v-slots={{
default: () =>
renderFilterItems({
filters: column.filters || [],
prefixCls,
filteredKeys: filteredKeys.value,
filterMultiple,
locale,
}),
}}
></Menu>
<div class={`${prefixCls}-dropdown-btns`}>
<Button
type="link"
size="small"
disabled={selectedKeys.length === 0}
onClick={onReset}
>
{locale.filterReset}
</Button>
<Button type="primary" size="small" onClick={onConfirm}>
{locale.filterConfirm}
</Button>
</div>
</>
);
}
const menu = (
<FilterDropdownMenuWrapper class={`${prefixCls}-dropdown`}>
{dropdownContent}
</FilterDropdownMenuWrapper>
);
let filterIcon;
if (typeof filterIconRef.value === 'function') {
filterIcon = filterIconRef.value({
filtered: filtered.value,
column: column.__originColumn__,
});
} else if (filterIconRef.value) {
filterIcon = filterIconRef.value;
} else {
filterIcon = <FilterFilled />;
}
return (
<div class={`${prefixCls}-column`}>
<span class={`${tablePrefixCls}-column-title`}>{slots.default?.()}</span>
<Dropdown
overlay={menu}
trigger={['click']}
visible={mergedVisible.value}
onVisibleChange={onVisibleChange}
getPopupContainer={getPopupContainer}
placement={direction.value === 'rtl' ? 'bottomLeft' : 'bottomRight'}
>
<span
role="button"
tabindex={-1}
class={classNames(`${prefixCls}-trigger`, {
active: filtered.value,
})}
onClick={e => {
e.stopPropagation();
}}
>
{filterIcon}
</span>
</Dropdown>
</div>
);
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/_util/debouncedWatch.ts
|
<reponame>YaroShkvorets/ant-design-vue
// copy from https://github.dev/vueuse/vueuse
import type { Ref, WatchOptions, WatchStopHandle } from 'vue';
import { unref, watch } from 'vue';
type MaybeRef<T> = T | Ref<T>;
type Fn = () => void;
export type FunctionArgs<Args extends any[] = any[], Return = void> = (...args: Args) => Return;
export interface FunctionWrapperOptions<Args extends any[] = any[], This = any> {
fn: FunctionArgs<Args, This>;
args: Args;
thisArg: This;
}
export type EventFilter<Args extends any[] = any[], This = any> = (
invoke: Fn,
options: FunctionWrapperOptions<Args, This>,
) => void;
const bypassFilter: EventFilter = invoke => {
return invoke();
};
/**
* Create an EventFilter that debounce the events
*
* @param ms
*/
export function debounceFilter(ms: MaybeRef<number>) {
let timer: ReturnType<typeof setTimeout> | undefined;
const filter: EventFilter = invoke => {
const duration = unref(ms);
if (timer) clearTimeout(timer);
if (duration <= 0) return invoke();
timer = setTimeout(invoke, duration);
};
return filter;
}
export interface DebouncedWatchOptions<Immediate> extends WatchOptions<Immediate> {
debounce?: MaybeRef<number>;
}
interface ConfigurableEventFilter {
eventFilter?: EventFilter;
}
/**
* @internal
*/
function createFilterWrapper<T extends FunctionArgs>(filter: EventFilter, fn: T) {
function wrapper(this: any, ...args: any[]) {
filter(() => fn.apply(this, args), { fn, thisArg: this, args });
}
return wrapper as any as T;
}
export interface WatchWithFilterOptions<Immediate>
extends WatchOptions<Immediate>,
ConfigurableEventFilter {}
// implementation
export function watchWithFilter<Immediate extends Readonly<boolean> = false>(
source: any,
cb: any,
options: WatchWithFilterOptions<Immediate> = {},
): WatchStopHandle {
const { eventFilter = bypassFilter, ...watchOptions } = options;
return watch(source, createFilterWrapper(eventFilter, cb), watchOptions);
}
// implementation
export default function debouncedWatch<Immediate extends Readonly<boolean> = false>(
source: any,
cb: any,
options: DebouncedWatchOptions<Immediate> = {},
): WatchStopHandle {
const { debounce = 0, ...watchOptions } = options;
return watchWithFilter(source, cb, {
...watchOptions,
eventFilter: debounceFilter(debounce),
});
}
|
YaroShkvorets/ant-design-vue
|
components/vc-table/Footer/Summary.tsx
|
import { computed, defineComponent, onBeforeUnmount, watchEffect } from 'vue';
import { useInjectTable } from '../context/TableContext';
export interface SummaryProps {
fixed?: boolean | 'top' | 'bottom';
}
let indexGuid = 0;
const Summary = defineComponent<SummaryProps>({
name: 'Summary',
props: ['fixed'] as any,
setup(props, { slots }) {
const tableContext = useInjectTable();
const uniKey = `table-summary-uni-key-${++indexGuid}`;
const fixed = computed(() => (props.fixed as string) === '' || props.fixed);
watchEffect(() => {
tableContext.summaryCollect(uniKey, fixed.value);
});
onBeforeUnmount(() => {
tableContext.summaryCollect(uniKey, false);
});
return () => slots.default?.();
},
});
export default Summary;
|
YaroShkvorets/ant-design-vue
|
components/collapse/index.ts
|
<gh_stars>1000+
import type { App, Plugin } from 'vue';
import Collapse, { collapseProps } from './Collapse';
import CollapsePanel, { collapsePanelProps } from './CollapsePanel';
export type { CollapseProps } from './Collapse';
export type { CollapsePanelProps } from './CollapsePanel';
Collapse.Panel = CollapsePanel;
/* istanbul ignore next */
Collapse.install = function (app: App) {
app.component(Collapse.name, Collapse);
app.component(CollapsePanel.name, CollapsePanel);
return app;
};
export { CollapsePanel, collapseProps, collapsePanelProps };
export default Collapse as typeof Collapse &
Plugin & {
readonly Panel: typeof CollapsePanel;
};
|
YaroShkvorets/ant-design-vue
|
plugin/md/utils/fetchCode.ts
|
<gh_stars>1000+
// import cheerio from 'cheerio';
const scriptRE = /<script[^>]*>([\s\S]*)<\/script>/;
const scriptContentRE = /(?<=<script[^>]*>)([\s\S]*)(?=<\/script>)/;
const templateRE = /<template[^>]*>([\s\S]*)<\/template>/;
const styleRE = /<style[^>]*>([\s\S]*)<\/style>/;
const docsRE = /(?<=<docs>)([\s\S]*)(?=<\/docs>)/;
const reObj = {
script: scriptRE,
style: styleRE,
docs: docsRE,
template: templateRE,
scriptContent: scriptContentRE,
};
export default function fetchCode(src: string, type: string): string {
if (type === 'template') {
// const $ = cheerio.load(src, {
// decodeEntities: false,
// xmlMode: false,
// recognizeSelfClosing: true,
// _useHtmlParser2: true,
// });
// return `<template>
// ${$(type).html().trim()}
// </template>`;
src = src.split('<script')[0];
}
const matches = src.match(reObj[type]);
return matches ? matches[0] : '';
}
|
YaroShkvorets/ant-design-vue
|
plugin/docs/index.ts
|
import { createVueToMarkdownRenderFn } from './vueToMarkdown';
import type { MarkdownOptions } from '../md/markdown/markdown';
import type { Plugin } from 'vite';
import { createMarkdownToVueRenderFn } from '../md/markdownToVue';
interface Options {
root?: string;
markdown?: MarkdownOptions;
}
export default (options: Options = {}): Plugin => {
const { root, markdown } = options;
const vueToMarkdown = createVueToMarkdownRenderFn(root);
const markdownToVue = createMarkdownToVueRenderFn(root, markdown);
return {
name: 'vueToMdToVue',
transform(code, id) {
if (
(id.endsWith('.vue') && id.indexOf('/demo/') > -1 && id.indexOf('index.vue') === -1) ||
id.indexOf('/examples/App.vue') > -1
) {
const res = vueToMarkdown(code, id);
// transform .md files into vueSrc so plugin-vue can handle it
return { code: res.ignore ? res.vueSrc : markdownToVue(res.vueSrc, id).vueSrc, map: null };
}
},
};
};
|
YaroShkvorets/ant-design-vue
|
components/vc-table/Panel/index.tsx
|
<gh_stars>1000+
function Panel(_, { slots }) {
return <div>{slots.default?.()}</div>;
}
Panel.displayName = 'Panel';
export default Panel;
|
YaroShkvorets/ant-design-vue
|
components/vc-overflow/examples/basic.tsx
|
<reponame>YaroShkvorets/ant-design-vue
import { defineComponent, ref } from 'vue';
import Overflow from '..';
import '../assets/index.less';
import './common.less';
interface ItemType {
value: string | number;
label: string;
}
function createData(count: number): ItemType[] {
const data: ItemType[] = new Array(count).fill(undefined).map((_, index) => ({
value: index,
label: `Label ${index}`,
}));
return data;
}
function renderItem(item: ItemType) {
return (
<div
style={{
margin: '0 16px 0 8px',
padding: '4px 8px',
background: 'rgba(255, 0, 0, 0.2)',
}}
>
{item.label}
</div>
);
}
function renderRest(items: ItemType[]) {
return (
<div
style={{
margin: '0 16px 0 8px',
padding: '4px 8px',
background: 'rgba(255, 0, 0, 0.2)',
}}
>
+{items.length}...
</div>
);
}
export default defineComponent({
setup() {
const responsive = ref(true);
const data = ref(createData(1));
return () => {
return (
<div style={{ padding: '32px' }}>
<button
type="button"
onClick={() => {
responsive.value = !responsive.value;
}}
>
{responsive.value ? 'Responsive' : 'MaxCount: 6'}
</button>
<select
style={{ width: '200px', height: '32px' }}
value={data.value.length}
onChange={(e: any) => {
data.value = createData(Number(e.target.value));
}}
>
<option value={0}>0</option>
<option value={1}>1</option>
<option value={2}>2</option>
<option value={3}>3</option>
<option value={5}>5</option>
<option value={10}>10</option>
<option value={20}>20</option>
<option value={200}>200</option>
</select>
<div
style={{
border: '5px solid green',
padding: '8px',
maxWidth: '300px',
marginTop: '32px',
}}
>
<Overflow
data={data.value}
renderItem={renderItem}
renderRest={renderRest}
maxCount={responsive.value ? 'responsive' : 6}
/>
</div>
</div>
);
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/menu/src/hooks/useDirectionStyle.ts
|
<filename>components/menu/src/hooks/useDirectionStyle.ts
import type { ComputedRef, CSSProperties } from 'vue';
import { computed } from 'vue';
import { useInjectMenu } from './useMenuContext';
export default function useDirectionStyle(level: ComputedRef<number>): ComputedRef<CSSProperties> {
const { mode, rtl, inlineIndent } = useInjectMenu();
return computed(() =>
mode.value !== 'inline'
? null
: rtl.value
? { paddingRight: `${level.value * inlineIndent.value}px` }
: { paddingLeft: `${level.value * inlineIndent.value}px` },
);
}
|
YaroShkvorets/ant-design-vue
|
components/vc-picker/utils/getExtraFooter.tsx
|
<reponame>YaroShkvorets/ant-design-vue
import type { PanelMode } from '../interface';
export default function getExtraFooter(
prefixCls: string,
mode: PanelMode,
renderExtraFooter?: (mode: PanelMode) => any,
) {
if (!renderExtraFooter) {
return null;
}
return <div class={`${prefixCls}-footer-extra`}>{renderExtraFooter(mode)}</div>;
}
|
YaroShkvorets/ant-design-vue
|
components/modal/locale.ts
|
<filename>components/modal/locale.ts
export interface ModalLocale {
okText: string;
cancelText: string;
justOkText: string;
}
|
YaroShkvorets/ant-design-vue
|
components/menu/index.tsx
|
import type { MenuProps } from './src/Menu';
import Menu from './src/Menu';
import type { MenuItemProps } from './src/MenuItem';
import MenuItem from './src/MenuItem';
import type { SubMenuProps } from './src/SubMenu';
import SubMenu from './src/SubMenu';
import type { MenuItemGroupProps } from './src/ItemGroup';
import ItemGroup from './src/ItemGroup';
import Divider from './src/Divider';
import type { App, Plugin } from 'vue';
import type { MenuTheme } from './src/interface';
/* istanbul ignore next */
Menu.install = function (app: App) {
app.component(Menu.name, Menu);
app.component(MenuItem.name, MenuItem);
app.component(SubMenu.name, SubMenu);
app.component(Divider.name, Divider);
app.component(ItemGroup.name, ItemGroup);
return app;
};
Menu.Item = MenuItem;
Menu.Divider = Divider;
Menu.SubMenu = SubMenu;
Menu.ItemGroup = ItemGroup;
export type { MenuProps, SubMenuProps, MenuItemProps, MenuItemGroupProps, MenuTheme };
export {
SubMenu,
MenuItem as Item,
MenuItem,
ItemGroup,
ItemGroup as MenuItemGroup,
Divider,
Divider as MenuDivider,
};
export default Menu as typeof Menu &
Plugin & {
readonly Item: typeof MenuItem;
readonly SubMenu: typeof SubMenu;
readonly Divider: typeof Divider;
readonly ItemGroup: typeof ItemGroup;
};
|
YaroShkvorets/ant-design-vue
|
components/collapse/PanelContent.tsx
|
<reponame>YaroShkvorets/ant-design-vue
import { defineComponent, ref, watchEffect } from 'vue';
import { collapsePanelProps } from './commonProps';
import classNames from '../_util/classNames';
export default defineComponent({
name: 'PanelContent',
props: collapsePanelProps(),
setup(props, { slots }) {
const rendered = ref(false);
watchEffect(() => {
if (props.isActive || props.forceRender) {
rendered.value = true;
}
});
return () => {
if (!rendered.value) return null;
const { prefixCls, isActive, role } = props;
return (
<div
ref={ref}
class={classNames(`${prefixCls}-content`, {
[`${prefixCls}-content-active`]: isActive,
[`${prefixCls}-content-inactive`]: !isActive,
})}
role={role}
>
<div class={`${prefixCls}-content-box`}>{slots.default?.()}</div>
</div>
);
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/vc-slider/src/common/Track.tsx
|
<reponame>YaroShkvorets/ant-design-vue<filename>components/vc-slider/src/common/Track.tsx
/* eslint-disable */
const Track = (_, { attrs }) => {
const { included, vertical, style, class: className } = attrs;
let { length, offset, reverse } = attrs;
if (length < 0) {
reverse = !reverse;
length = Math.abs(length);
offset = 100 - offset;
}
const positonStyle = vertical
? {
[reverse ? 'top' : 'bottom']: `${offset}%`,
[reverse ? 'bottom' : 'top']: 'auto',
height: `${length}%`,
}
: {
[reverse ? 'right' : 'left']: `${offset}%`,
[reverse ? 'left' : 'right']: 'auto',
width: `${length}%`,
};
const elStyle = {
...style,
...positonStyle,
};
return included ? <div class={className} style={elStyle} /> : null;
};
Track.inheritAttrs = false;
export default Track;
|
YaroShkvorets/ant-design-vue
|
components/tabs/src/TabContext.ts
|
<reponame>YaroShkvorets/ant-design-vue
import type { Tab } from './interface';
import type { PropType, InjectionKey, Ref } from 'vue';
import { provide, inject, defineComponent, toRefs, ref } from 'vue';
export interface TabContextProps {
tabs: Ref<Tab[]>;
prefixCls: Ref<string>;
}
const TabsContextKey: InjectionKey<TabContextProps> = Symbol('tabsContextKey');
export const useProvideTabs = (props: TabContextProps) => {
provide(TabsContextKey, props);
};
export const useInjectTabs = () => {
return inject(TabsContextKey, { tabs: ref([]), prefixCls: ref() });
};
const TabsContextProvider = defineComponent({
name: 'TabsContextProvider',
inheritAttrs: false,
props: {
tabs: { type: Object as PropType<TabContextProps['tabs']>, default: undefined },
prefixCls: { type: String, default: undefined },
},
setup(props, { slots }) {
useProvideTabs(toRefs(props));
return () => slots.default?.();
},
});
export default TabsContextProvider;
|
YaroShkvorets/ant-design-vue
|
components/vc-slider/src/common/Marks.tsx
|
<reponame>YaroShkvorets/ant-design-vue
import supportsPassive from '../../../_util/supportsPassive';
import classNames from '../../../_util/classNames';
import { isValidElement } from '../../../_util/props-util';
const Marks = (_: any, { attrs, slots }: any) => {
const {
class: className,
vertical,
reverse,
marks,
included,
upperBound,
lowerBound,
max,
min,
onClickLabel,
} = attrs;
const marksKeys = Object.keys(marks);
const customMark = slots.mark;
const range = max - min;
const elements = marksKeys
.map(parseFloat)
.sort((a, b) => a - b)
.map(point => {
const markPoint = typeof marks[point] === 'function' ? marks[point]() : marks[point];
const markPointIsObject = typeof markPoint === 'object' && !isValidElement(markPoint);
let markLabel = markPointIsObject ? markPoint.label : markPoint;
if (!markLabel && markLabel !== 0) {
return null;
}
if (customMark) {
markLabel = customMark({ point, label: markLabel });
}
const isActive =
(!included && point === upperBound) ||
(included && point <= upperBound && point >= lowerBound);
const markClassName = classNames({
[`${className}-text`]: true,
[`${className}-text-active`]: isActive,
});
const bottomStyle = {
marginBottom: '-50%',
[reverse ? 'top' : 'bottom']: `${((point - min) / range) * 100}%`,
};
const leftStyle = {
transform: `translateX(${reverse ? `50%` : `-50%`})`,
msTransform: `translateX(${reverse ? `50%` : `-50%`})`,
[reverse ? 'right' : 'left']: `${((point - min) / range) * 100}%`,
};
const style = vertical ? bottomStyle : leftStyle;
const markStyle = markPointIsObject ? { ...style, ...markPoint.style } : style;
const touchEvents = {
[supportsPassive ? 'onTouchstartPassive' : 'onTouchstart']: e => onClickLabel(e, point),
};
return (
<span
class={markClassName}
style={markStyle}
key={point}
onMousedown={e => onClickLabel(e, point)}
{...touchEvents}
>
{markLabel}
</span>
);
});
return <div class={className}>{elements}</div>;
};
Marks.inheritAttrs = false;
export default Marks;
|
YaroShkvorets/ant-design-vue
|
components/vc-table/Body/ExpandedRow.tsx
|
import type { CustomizeComponent } from '../interface';
import Cell from '../Cell';
import { defineComponent } from 'vue';
import { useInjectTable } from '../context/TableContext';
export interface ExpandedRowProps {
prefixCls: string;
component: CustomizeComponent;
cellComponent: CustomizeComponent;
fixHeader: boolean;
fixColumn: boolean;
horizonScroll: boolean;
componentWidth: number;
expanded: boolean;
colSpan: number;
}
export default defineComponent<ExpandedRowProps>({
name: 'ExpandedRow',
inheritAttrs: false,
props: [
'prefixCls',
'component',
'cellComponent',
'fixHeader',
'fixColumn',
'horizonScroll',
'componentWidth',
'expanded',
'colSpan',
] as any,
setup(props, { slots, attrs }) {
const tableContext = useInjectTable();
return () => {
const {
prefixCls,
component: Component,
cellComponent,
fixHeader,
fixColumn,
expanded,
componentWidth,
colSpan,
} = props;
return (
<Component
class={attrs.class}
style={{
display: expanded ? null : 'none',
}}
>
<Cell
component={cellComponent}
prefixCls={prefixCls}
colSpan={colSpan}
v-slots={{
default: () => {
let contentNode: any = slots.default?.();
if (fixColumn) {
contentNode = (
<div
style={{
width: `${componentWidth - (fixHeader ? tableContext.scrollbarSize : 0)}px`,
position: 'sticky',
left: 0,
overflow: 'hidden',
}}
class={`${prefixCls}-expanded-row-fixed`}
>
{contentNode}
</div>
);
}
return contentNode;
},
}}
></Cell>
</Component>
);
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/vc-mentions/src/mentionsProps.ts
|
import type { PropType } from 'vue';
import PropTypes from '../../_util/vue-types';
import { initDefaultProps } from '../../_util/props-util';
import {
filterOption as defaultFilterOption,
validateSearch as defaultValidateSearch,
} from './util';
import { tuple } from '../../_util/type';
import type { OptionProps } from './Option';
export const PlaceMent = tuple('top', 'bottom');
export type Direction = 'ltr' | 'rtl';
export const mentionsProps = {
autofocus: PropTypes.looseBool,
prefix: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
prefixCls: PropTypes.string,
value: PropTypes.string,
disabled: PropTypes.looseBool,
split: PropTypes.string,
transitionName: PropTypes.string,
placement: PropTypes.oneOf(PlaceMent),
character: PropTypes.any,
characterRender: PropTypes.func,
filterOption: {
type: [Boolean, Function] as PropType<typeof defaultFilterOption | false>,
},
validateSearch: PropTypes.func,
getPopupContainer: {
type: Function as PropType<() => HTMLElement>,
},
options: {
type: Array as PropType<OptionProps>,
default: () => undefined,
},
loading: PropTypes.looseBool,
rows: [Number, String],
direction: { type: String as PropType<Direction> },
};
export const vcMentionsProps = {
...mentionsProps,
};
export const defaultProps = {
prefix: '@',
split: ' ',
rows: 1,
validateSearch: defaultValidateSearch,
filterOption: (() => defaultFilterOption) as any,
};
export default initDefaultProps(vcMentionsProps, defaultProps);
|
YaroShkvorets/ant-design-vue
|
components/vc-trigger/Popup/useStretchStyle.ts
|
<reponame>YaroShkvorets/ant-design-vue<filename>components/vc-trigger/Popup/useStretchStyle.ts
import type { ComputedRef, CSSProperties, Ref } from 'vue';
import { computed, ref } from 'vue';
import type { StretchType } from '../interface';
export default (
stretch?: Ref<StretchType>,
): [ComputedRef<CSSProperties>, (element: HTMLElement) => void] => {
const targetSize = ref({ width: 0, height: 0 });
function measureStretch(element: HTMLElement) {
targetSize.value = {
width: element.offsetWidth,
height: element.offsetHeight,
};
}
// Merge stretch style
const style = computed(() => {
const sizeStyle: CSSProperties = {};
if (stretch.value) {
const { width, height } = targetSize.value;
// Stretch with target
if (stretch.value.indexOf('height') !== -1 && height) {
sizeStyle.height = `${height}px`;
} else if (stretch.value.indexOf('minHeight') !== -1 && height) {
sizeStyle.minHeight = `${height}px`;
}
if (stretch.value.indexOf('width') !== -1 && width) {
sizeStyle.width = `${width}px`;
} else if (stretch.value.indexOf('minWidth') !== -1 && width) {
sizeStyle.minWidth = `${width}px`;
}
}
return sizeStyle;
});
return [style, measureStretch];
};
|
YaroShkvorets/ant-design-vue
|
components/tabs/index.ts
|
<filename>components/tabs/index.ts
import type { App, Plugin } from 'vue';
import Tabs, { TabPane } from './src';
export type { TabsProps, TabPaneProps } from './src';
Tabs.TabPane = { ...TabPane, name: 'ATabPane', __ANT_TAB_PANE: true };
/* istanbul ignore next */
Tabs.install = function (app: App) {
app.component(Tabs.name, Tabs);
app.component(Tabs.TabPane.name, Tabs.TabPane);
return app;
};
export default Tabs as typeof Tabs &
Plugin & {
readonly TabPane: typeof TabPane;
};
export { TabPane };
|
YaroShkvorets/ant-design-vue
|
components/vc-progress/src/types.ts
|
import type { PropType, ExtractPropTypes } from 'vue';
import PropTypes from '../../_util/vue-types';
export type StrokeColorType = string | string[] | object;
export type GapPositionType = 'top' | 'right' | 'bottom' | 'left';
export type StrokeLinecapType = 'round' | 'butt' | 'square';
export const propTypes = {
gapDegree: PropTypes.number,
gapPosition: {
type: String as PropType<GapPositionType>,
},
percent: {
type: [Array, Number] as PropType<number | number[]>,
},
prefixCls: PropTypes.string,
strokeColor: {
type: [Object, String, Array] as PropType<StrokeColorType>,
},
strokeLinecap: {
type: String as PropType<StrokeLinecapType>,
},
strokeWidth: PropTypes.number,
trailColor: PropTypes.string,
trailWidth: PropTypes.number,
transition: PropTypes.string,
};
export type ProgressProps = Partial<ExtractPropTypes<typeof propTypes>>;
|
YaroShkvorets/ant-design-vue
|
components/vc-tooltip/src/Content.tsx
|
import type { ExtractPropTypes } from 'vue';
import { defineComponent } from 'vue';
import PropTypes from '../../_util/vue-types';
const tooltipContentProps = {
prefixCls: PropTypes.string,
id: PropTypes.string,
overlayInnerStyle: PropTypes.any,
};
export type TooltipContentProps = Partial<ExtractPropTypes<typeof tooltipContentProps>>;
export default defineComponent({
name: 'Content',
props: tooltipContentProps,
slots: ['overlay'],
setup(props: TooltipContentProps, { slots }) {
return () => (
<div
class={`${props.prefixCls}-inner`}
id={props.id}
role="tooltip"
style={props.overlayInnerStyle}
>
{slots.overlay?.()}
</div>
);
},
});
|
YaroShkvorets/ant-design-vue
|
components/dropdown/index.ts
|
<reponame>YaroShkvorets/ant-design-vue
import type { App, Plugin } from 'vue';
import Dropdown from './dropdown';
import DropdownButton from './dropdown-button';
import { dropdownProps, dropdownButtonProps } from './props';
export type { DropdownProps } from './dropdown';
export type { DropdownButtonProps } from './dropdown-button';
Dropdown.Button = DropdownButton;
/* istanbul ignore next */
Dropdown.install = function (app: App) {
app.component(Dropdown.name, Dropdown);
app.component(DropdownButton.name, DropdownButton);
return app;
};
export { DropdownButton, dropdownProps, dropdownButtonProps };
export default Dropdown as typeof Dropdown &
Plugin & {
readonly Button: typeof DropdownButton;
};
|
YaroShkvorets/ant-design-vue
|
components/row/index.ts
|
<filename>components/row/index.ts
import { Row } from '../grid';
import { withInstall } from '../_util/type';
export type { RowProps } from '../grid';
export default withInstall(Row);
|
YaroShkvorets/ant-design-vue
|
components/time-picker/index.tsx
|
<reponame>YaroShkvorets/ant-design-vue
import TimePicker from './dayjs';
export * from './dayjs';
export interface TimePickerLocale {
placeholder?: string;
rangePlaceholder?: [string, string];
}
export default TimePicker;
|
YaroShkvorets/ant-design-vue
|
components/time-picker/locale/lt_LT.tsx
|
<filename>components/time-picker/locale/lt_LT.tsx
import type { TimePickerLocale } from '../index';
const locale: TimePickerLocale = {
placeholder: 'Pasirinkite laiką',
rangePlaceholder: ['Pradžios laikas', 'Pabaigos laikas'],
};
export default locale;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.