repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
senritsu/micro-color-sudoku
src/machines/appMachine.ts
import { Machine, assign } from 'xstate'; import randomize from '../randomize' import puzzles from '../puzzles' interface SudokuContext { size: number, cells: number[], fixedCells: number[] } interface SudokuStateSchema { states: { menu: {}, puzzle: {}, result: {} } } interface StartEvent { type: 'START', payload: { size: number } } interface SetEvent { type: 'SET', payload: { index: number, value: number } } type SudokuEvent = | StartEvent | SetEvent | { type: 'BACK' } | { type: 'GAMEOVER' } export default Machine<SudokuContext, SudokuStateSchema, SudokuEvent>({ id: 'game', context: { size: 0, cells: [], fixedCells: [] }, initial: 'menu', states: { menu: { on: { START: { target: 'puzzle', actions: ['setSize', 'createPuzzle', 'setFixedCells'] } } }, puzzle: { on: { BACK: 'menu', GAMEOVER: 'result', SET: { actions: 'setCell' } } }, result: { on: { BACK: 'menu' } } } }, { actions: { setSize: assign({ size: (context, event) => (event as StartEvent).payload.size }), createPuzzle: assign({ cells: (context, event) => { const options = puzzles[context.size] const puzzle = options[Math.floor(Math.random() * options.length)] return randomize(puzzle) } }), setFixedCells: assign({ fixedCells: (context) => context.cells.reduce((fixed, cell, i) => { if (cell) { fixed.push(i) } return fixed }, [] as number[]) }), setCell: assign({ cells: (context, event) => { const cells = [...context.cells] const { index, value } = (event as SetEvent).payload // toggle functionality, in addition to simply setting a value if (value === cells[index]) { cells[index] = 0 } else { cells[index] = value } return cells; } }) } })
senritsu/micro-color-sudoku
src/math.spec.ts
import { rotateLeft, rotateRight, mirrorHorizontally, mirrorVertically } from './math' describe('matrix rotation', () => { it('rotates 90 degrees left or 270 degrees right', () => { // 1 2 3 3 6 9 // 4 5 6 -> 2 5 8 // 7 8 9 1 4 7 const original = [1, 2, 3, 4, 5, 6, 7, 8, 9] const expected = [3, 6, 9, 2, 5, 8, 1, 4, 7] expect(rotateLeft(original)).toEqual(expected) expect(rotateRight(original, 3)).toEqual(expected) }) it('rotates 180 degrees either side', () => { // 1 2 3 9 8 7 // 4 5 6 -> 6 5 4 // 7 8 9 3 2 1 const original = [1, 2, 3, 4, 5, 6, 7, 8, 9] const expected = [9, 8, 7, 6, 5, 4, 3, 2, 1] expect(rotateLeft(original, 2)).toEqual(expected) expect(rotateRight(original, 2)).toEqual(expected) }) it('rotates 270 degrees left or 90 degrees right', () => { // 1 2 3 7 4 1 // 4 5 6 -> 8 5 2 // 7 8 9 9 6 3 const original = [1, 2, 3, 4, 5, 6, 7, 8, 9] const expected = [7, 4, 1, 8, 5, 2, 9, 6, 3] expect(rotateLeft(original, 3)).toEqual(expected) expect(rotateRight(original)).toEqual(expected) }) it('rotates 90 degrees left or 270 degrees right (4x4 matrix)', () => { // 1 2 3 4 4 8 12 16 // 5 6 7 8 -> 3 7 11 15 // 9 10 11 12 2 6 10 14 // 13 14 15 16 1 5 9 13 const original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] const expected = [4, 8, 12, 16, 3, 7, 11, 15, 2, 6, 10, 14, 1, 5, 9, 13] expect(rotateLeft(original)).toEqual(expected) expect(rotateRight(original, 3)).toEqual(expected) }) it('rotates 90 degrees left for equivalent non-standard step counts', () => { // 1 2 3 3 6 9 // 4 5 6 -> 2 5 8 // 7 8 9 1 4 7 const original = [1, 2, 3, 4, 5, 6, 7, 8, 9] const expected = [3, 6, 9, 2, 5, 8, 1, 4, 7] expect(rotateLeft(original)).toEqual(expected) expect(rotateLeft(original, 1)).toEqual(expected) expect(rotateLeft(original, 5)).toEqual(expected) expect(rotateLeft(original, 17)).toEqual(expected) expect(rotateLeft(original, -3)).toEqual(expected) expect(rotateLeft(original, -15)).toEqual(expected) }) }) describe('mirroring', () => { it('mirrors horizontally', () => { // 1 2 3 3 2 1 // 4 5 6 -> 6 5 4 // 7 8 9 9 8 7 const original = [1, 2, 3, 4, 5, 6, 7, 8, 9] const expected = [3, 2, 1, 6, 5, 4, 9, 8, 7] expect(mirrorHorizontally(original)).toEqual(expected) expect(mirrorHorizontally(mirrorHorizontally(original))).toEqual(original) }) it('mirrors vertically', () => { // 1 2 3 7 8 9 // 4 5 6 -> 4 5 6 // 7 8 9 1 2 3 const original = [1, 2, 3, 4, 5, 6, 7, 8, 9] const expected = [7, 8, 9, 4, 5, 6, 1, 2, 3] expect(mirrorVertically(original)).toEqual(expected) expect(mirrorVertically(mirrorVertically(original))).toEqual(original) }) })
senritsu/micro-color-sudoku
src/composition/layout.ts
import { Ref, computed } from 'vue' export interface Groups { rows: Ref<number[][]>, columns: Ref<number[][]>, blocks: Ref<number[][]> } interface GridPosition { gridRow: string, gridColumn: string } interface GridPositionFunction { (rowMajorIndex: number): GridPosition } interface GridPlacement { cell: GridPositionFunction, row: GridPositionFunction, column: GridPositionFunction, block: GridPositionFunction } interface GridLayout { groups: Ref<Groups>, placement: Ref<GridPlacement> } export function squarePlacement (gridSize: number) : GridPlacement { const N = gridSize const K = Math.sqrt(N) return { cell: (index : number) => ({ gridRow: `${Math.floor(index / N) + 1} / span 1`, gridColumn: `${index % N + 1} / span 1` }), row: (index : number) => ({ gridRow: `${index + 1} / span 1`, gridColumn: `1 / span ${N}` }), column: (index : number) => ({ gridRow: `1 / span ${N}`, gridColumn: `${index + 1} / span 1` }), block: (index : number) => ({ gridRow: `${1 + Math.floor(index / K) * K} / span ${K}`, gridColumn: `${1 + (index % K) * K} / span ${K}` }) } } export function useSquareLayout (cells: Ref<number[]>) : GridLayout { const N = computed(() => Math.sqrt(cells.value.length)) function forSize<T>(f: (index: number) => T) { return Array.from({ length: N.value }).map((_, i) => f(i)) } const rows = computed(() => { const n = N.value return forSize(i => cells.value.slice(n * i, n * i + n)) }) const columns = computed(() => { return forSize(i => rows.value.map(row => row[i])) }) const blocks = computed(() => { const n = N.value const k = Math.sqrt(n) return forSize(i => forSize(j => { return cells.value[j % k // block row offset = row * size * size + Math.floor(i / k) * n * k // block column offset = col * blockSize + (i % k) * k // cell row offset = cellrow * size + Math.floor(j / k) * n] })) }) const groups = computed(() => ({ rows, columns, blocks } as Groups)) const placement = computed(() => squarePlacement(N.value)) return { groups, placement } }
senritsu/micro-color-sudoku
src/composition/validation.ts
import { Ref, computed, watch } from 'vue' import { Groups } from './layout' function isFilled (group: number[]) { return group.every(x => x) } function hasError (group: number[]) { return group.some((x, i, arr) => x && (arr.indexOf(x) !== i)) } type ValidationResult = 'error' | 'correct' | 'incomplete' function getState (group: number[]) : ValidationResult { return hasError(group) ? 'error' : isFilled(group) ? 'correct' : 'incomplete' } export function useValidation (groups: Ref<Groups>) { const rowValidationStates = computed(() => groups.value.rows.value.map(getState)) const columnValidationStates = computed(() => groups.value.columns.value.map(getState)) const blockValidationStates = computed(() => groups.value.blocks.value.map(getState)) const puzzleValidationState = computed(() => { const concatenated = [...rowValidationStates.value, ...columnValidationStates.value, ...blockValidationStates.value] return concatenated.some(x => x === 'error') ? 'error' : concatenated.every(x => x === 'correct') ? 'correct' : 'incomplete' }) const validation = computed(() => ({ rows: rowValidationStates.value, columns: columnValidationStates.value, blocks: blockValidationStates.value, puzzle: puzzleValidationState.value })) return { validation } }
senritsu/micro-color-sudoku
src/math.ts
<reponame>senritsu/micro-color-sudoku<filename>src/math.ts /** * Rotates a matrix to the left * @param original Square matrix, stored as a flat array in row-major order * @param steps How many multiples of 90 degrees to rotate */ export function rotateLeft(original: number[], steps: number = 1) { steps = steps % 4 if (steps < 0) { steps += 4 } if (!steps) return [...original] return transform(original, (i, j, N) => { // 90/270 degrees: transpose if (steps % 2) { [i, j] = [j, i] } // 90/180 degrees: vertical reflection if (steps < 3) { j = N - j - 1 } // 180/270 degrees: horizontal reflection if (steps > 1) { i = N - i - 1 } return [i ,j] }) } /** * Rotates a matrix to the right * @param original Square matrix, stored as a flat array in row-major order * @param steps How many multiples of 90 degrees to rotate */ export function rotateRight(original: number[], steps: number = 1) { return rotateLeft(original, 4 - steps) } export const mirrorHorizontally = (original: number[]) => transform(original, (i, j, N) => [N - i - 1, j]) export const mirrorVertically = (original: number[]) => transform(original, (i, j, N) => [i, N - j - 1]) function transform(original: number[], calculateNewIndex: (i: number, j: number, N: number) => [iNew: number, jNew: number]) { const N = Math.sqrt(original.length) const transformed = new Array(original.length) for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { const [iNew, jNew] = calculateNewIndex(i, j, N) transformed[jNew * N + iNew] = original[j * N + i] } } return transformed }
senritsu/micro-color-sudoku
src/colors.ts
<reponame>senritsu/micro-color-sudoku<filename>src/colors.ts export default [ // empty cell '#EDEAE0', // 4x4 grid '#C41E3A', '#50C878', '#26619C', '#FFD300', // 9x9 grid '#9966CC', '#FF7A00', '#87CEFA', '#F400A1', '#2D383A' ]
senritsu/micro-color-sudoku
src/randomize.ts
import { rotateLeft, mirrorHorizontally, mirrorVertically } from './math' export default function (puzzle : number[]) { const numbers = Array.from({length: Math.sqrt(puzzle.length)}).map((_, i) => i + 1) const mapping = shuffled(numbers).reduce((map, n, i) => { map[i + 1] = n return map }, {} as { [key: number]: number }) let randomized = puzzle.map(n => mapping[n] || 0) for (const modify of [mirrorHorizontally, mirrorVertically]) { if (Math.random() < 0.25) { randomized = modify(randomized) } } const steps = Math.floor(Math.random() * 4) return rotateLeft(randomized, steps) } function shuffled (array : number[]) { const a = [...array] // Durstenfeld shuffle for (let i : number = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)) // NOTE in-place swapping with [a, b] = [b, a] results in typescript error, unsure why const prev = a[i] a[i] = a[j] a[j] = prev } return a }
senritsu/micro-color-sudoku
src/composition/layout.spec.ts
import { squarePlacement } from './layout' describe('square grid placement', () => { it('places cells correctly on a 4x4 grid', () => { const placement = squarePlacement(4) // 1 0 2 0 // 0 3 0 0 // 0 0 0 4 // 0 0 5 0 expect(placement.cell(0)).toEqual({ gridRow: '1 / span 1', gridColumn: '1 / span 1' }) expect(placement.cell(2)).toEqual({ gridRow: '1 / span 1', gridColumn: '3 / span 1' }) expect(placement.cell(5)).toEqual({ gridRow: '2 / span 1', gridColumn: '2 / span 1' }) expect(placement.cell(11)).toEqual({ gridRow: '3 / span 1', gridColumn: '4 / span 1' }) expect(placement.cell(14)).toEqual({ gridRow: '4 / span 1', gridColumn: '3 / span 1' }) }) it('places cells correctly on a 9x9 grid', () => { const placement = squarePlacement(9) expect(placement.cell(3)).toEqual({ gridRow: '1 / span 1', gridColumn: '4 / span 1' }) expect(placement.cell(37)).toEqual({ gridRow: '5 / span 1', gridColumn: '2 / span 1' }) expect(placement.cell(79)).toEqual({ gridRow: '9 / span 1', gridColumn: '8 / span 1' }) }) it('places rows correctly on a 4x4 grid', () => { const placement = squarePlacement(4) expect(placement.row(0)).toEqual({ gridRow: '1 / span 1', gridColumn: '1 / span 4' }) expect(placement.row(2)).toEqual({ gridRow: '3 / span 1', gridColumn: '1 / span 4' }) }) it('places columns correctly on a 4x4 grid', () => { const placement = squarePlacement(4) expect(placement.column(1)).toEqual({ gridRow: '1 / span 4', gridColumn: '2 / span 1' }) expect(placement.column(3)).toEqual({ gridRow: '1 / span 4', gridColumn: '4 / span 1' }) }) it('places blocks correctly on a 4x4 grid', () => { const placement = squarePlacement(4) expect(placement.block(0)).toEqual({ gridRow: '1 / span 2', gridColumn: '1 / span 2' }) expect(placement.block(3)).toEqual({ gridRow: '3 / span 2', gridColumn: '3 / span 2' }) }) })
chadoh/what-is-blockchain
src/renderBlocks/animations.ts
<filename>src/renderBlocks/animations.ts export const animationLength = 350 export const openBlock = (block: HTMLElement): void => { // 1. duplicate the element, position above old element const clone = block.cloneNode(true) as HTMLElement const rect = block.getBoundingClientRect() let styles = ` position: absolute; top: calc(${rect.top}px + 1em); left: calc(${rect.left}px - 0.35em); width: ${block.offsetWidth}px; height: ${block.offsetHeight}px; transform: rotateY(330deg) scaleX(1.1) translateZ(1em); transition: all ${animationLength}ms; ` clone.style.cssText = clone.style.cssText + ";" + styles // save values for closing block later clone.dataset.top = clone.style.top clone.dataset.left = clone.style.left clone.dataset.width = clone.style.width clone.dataset.height = clone.style.height // 2. add to #opened-block, show #opened-block const container = document.getElementById("opened-block") container.style.display = "block" container.appendChild(clone) // 3. prevent body scroll // DOES NOT WORK ON MOBILE (or at least iOS) – // consider using something like https://www.npmjs.com/package/body-scroll-lock document.body.style.overflow = "hidden" // 4. set visibility=hidden using class which can be removed when closing block.className = block.className + " opened" // timeout prevents some cross-browser bugs on opening animation setTimeout(() => { // 5. make full screen const inner = clone.querySelector(`[data-behavior="inner-height"]`) as HTMLElement styles = ` top: 1em; left: 1em; width: calc(100vw - 2em); height: ${inner.getBoundingClientRect().height}px; transform: rotateY(180deg) translateZ(1em); ` clone.style.cssText = clone.style.cssText + ";" + styles // 6. remove perspective to ensure consistent styling across browsers const wrapper = document.querySelector("#opened-block") as HTMLElement wrapper.style.perspective = "none" // 7. wait for width to adjust, then readjust height to height of inner children // (it's hard to get the height correct until the width is set) setTimeout(() => { clone.style.height = `calc(${inner.getBoundingClientRect().height}px + 1em)` }, animationLength) }, 50) } export const closeBlock = function(clone: HTMLElement): void { // 1. re-add perspective to wrapper const wrapper = document.querySelector("#opened-block") as HTMLElement wrapper.style.perspective = "1000em" // 2. set back to original dimensions let styles = ` position: fixed; top: ${clone.dataset.top}; left: ${clone.dataset.left}; width: ${clone.dataset.width}; height: ${clone.dataset.height}; transform: rotateY(330deg) scaleX(1.1) translateZ(1em); ` clone.style.cssText = clone.style.cssText + ";" + styles // 3. wait for animation to complete setTimeout(() => { // 4. make original block visible again const block = document.querySelector(".block.opened") if (block) block.className = block.className.replace(/ opened/, "") // 5. remove placeholder clone.remove() // 6. hide #opened-block const container = document.getElementById("opened-block") container.style.display = "none" document.body.style.overflow = "" }, animationLength) };
chadoh/what-is-blockchain
src/renderIdenticons.ts
import blockies from "blockies-identicon" const identicons = {} export default (): void => { Array.from( document.querySelectorAll(`[data-behavior="identicon"]`) ).forEach((div: HTMLElement) => { const title = div.getAttribute("title") identicons[title] = identicons[title] || blockies.create({ seed: title }).toDataURL() // use image rather than canvas so that cloning element works correctly const img = new Image() img.src = identicons[title] div.appendChild(img) // make sure we don't call this on the same element twice delete div.dataset.behavior }) }
chadoh/what-is-blockchain
src/renderBlocks/formatEth.test.ts
import formatEth from './formatEth'; test.each` input | output ${1} | ${"0.000"} ${1e15} | ${"0.001"} ${1e18} | ${"1"} ${2.187e17} | ${"0.219"} `("when given $input, returns $output", ({ input, output }) => { expect(formatEth(input)).toEqual(output) });
chadoh/what-is-blockchain
src/sendAsyncPromise.ts
<filename>src/sendAsyncPromise.ts // util to wrap `window.ethereum.sendAsync` in a Promise // TODO: find typedefs for Ethereum RPC return values export default function sendAsyncPromise(method: string, params: any[]): Promise<{result: any}> { return new Promise((resolve, reject) => { window.ethereum.sendAsync({ method, params }, (error, response) => { if (error) reject(error) else resolve(response) }) }) }
chadoh/what-is-blockchain
src/main.ts
<reponame>chadoh/what-is-blockchain import blockies from "blockies-identicon" import { threeConsecutive, genesis } from "./exampleData" import renderBlocks from "./renderBlocks" import renderIdenticons from "./renderIdenticons" import send from "./sendAsyncPromise" import spacer from "./spacer" document.addEventListener("click", async e => { const target = e.target as HTMLElement if (target.getAttribute("href") === "#fetch-latest") { const div = document.getElementById("recent-blocks") if (!div) return div.innerHTML = `<p>Fetching...</p>` e.preventDefault() await window.ethereum.enable() const block1 = (await send("eth_getBlockByNumber", ["latest", true])).result const mostRecentBlockNumber = parseInt(block1.number) const nextNineQueries = [] for (let i = 1; i < 10; i++) { nextNineQueries.push( send("eth_getBlockByNumber", [ "0x" + (mostRecentBlockNumber - i).toString(16), true, ]) ) } const nextNineBlocks = (await Promise.all(nextNineQueries)).map( r => r.result ) div.innerHTML = renderBlocks([block1, ...nextNineBlocks]) renderIdenticons() } }) declare global { interface Window { ethereum: any; // No available typedefs for MetaMask? } }; (() => { const example = document.getElementById("example"); if (!example) return example.innerHTML = ` ${spacer} ${renderBlocks(threeConsecutive)} ${spacer} ${renderBlocks([genesis])} ` renderIdenticons() if (window.ethereum) { const div = document.getElementById("recent-blocks") div.innerHTML = ` <p style="text-align: center"> <a href="#fetch-latest">Fetch latest blocks</a> </p> ` } })();
chadoh/what-is-blockchain
src/exampleData.test.ts
import { threeConsecutive, genesis } from './exampleData'; describe("threeConsecutive", () => { test("should be an Array", () => { expect(Array.isArray(threeConsecutive)).toBe(true) }) test("should have three items", () => { expect(threeConsecutive.length).toBe(3) }); }); describe("genesis", () => { test("should be an object", () => { expect(Object.prototype.toString.call(genesis)).toBe("[object Object]") }) test("should have block number 0", () => { expect(genesis.number).toBe("0x0") }) })
chadoh/what-is-blockchain
src/renderBlocks/index.ts
import { openBlock, closeBlock, animationLength } from "./animations" import formatEth from "./formatEth" document.addEventListener("click", e => { const target = e.target as HTMLElement if (target.dataset.behavior === "open-block") { e.preventDefault() openBlock(target.closest(".block") as HTMLElement) } if (target.getAttribute("href") === "#close-block") { e.preventDefault() closeBlock(target.closest(".block") as HTMLElement) } }) let closedAt = new Date().getTime() document.addEventListener("keyup", e => { if (e.key !== "Escape") return const now = new Date().getTime() if (now < closedAt + animationLength) return const block = document.querySelector("#opened-block .block") as HTMLElement if (!block) return closeBlock(block) closedAt = now }) export default blocks => blocks.map(block => { const blockNumber = parseInt(block.number, 16) const dateMined = (new Date(parseInt(block.timestamp) * 1000)).toLocaleString() return ` <div class="block"> <div aria-hidden="true"> <h2 class="blockNumber">${blockNumber}</h2> <div class="dateMined">${dateMined}</div> <div> ${block.transactions.length} transactions ${!block.transactions.length ? "" : ` – <a href="#${block.number}" data-behavior="open-block" > View </a> `} </div> </div> <div class="block-back"> <div class="inner" data-behavior="inner-height"> <header> <div> <h2 class="blockNumber">${blockNumber}</h2> <div class="dateMined">${dateMined}</div> </div> <a href="#close-block">&times;</a> </header> <div>${block.transactions.length} transaction${block.transactions.length > 1 ? 's' : ''}</div> <ul class="transactions"> ${block.transactions.map((transaction, i) => { const amount = formatEth(parseInt(transaction.value, 16)) return ` <li class="transaction"> <div class="sender" data-behavior="identicon" title="${transaction.from}"></div> <div class="sent">sent</div> <div class="amount">${amount}</div> <div class="to">to</div> <div class="receiver" data-behavior="identicon" title="${transaction.to}"></div> </li> ` }).join("")} </ul> </div> </div> </div> ` }).join("")
chadoh/what-is-blockchain
src/spacer.ts
// TODO: move styles to stylesheet; don't use p tag export default ` <div style="text-align: center"> <p style="display: inline-block; height: 1em; width: 1em; margin-right: .5em;"></p> <p style="display: inline-block; height: 1em; width: 1em; margin-right: .5em;"></p> <p style="display: inline-block; height: 1em; width: 1em;"></p> </div> `
chadoh/what-is-blockchain
src/renderBlocks/formatEth.ts
export default function formatEth(amountInWei: number): string { const options = { style: "decimal", minimumFractionDigits: 3 } // if its a whole, eth amount, leave off the .000 if (amountInWei % 1e18 === 0) options.minimumFractionDigits = 0 const formatter = new Intl.NumberFormat("en-US", options) return formatter.format(amountInWei / 1e18) }
YaroShkvorets/ant-design-vue
components/vc-picker/hooks/useTextValueMapping.ts
<reponame>YaroShkvorets/ant-design-vue<gh_stars>1000+ import type { ComputedRef, Ref } from 'vue'; import { ref, watch } from 'vue'; export default function useTextValueMapping({ valueTexts, onTextChange, }: { /** Must useMemo, to assume that `valueTexts` only match on the first change */ valueTexts: ComputedRef<string[]>; onTextChange: (text: string) => void; }): [Ref<string>, (text: string) => void, () => void] { const text = ref(''); function triggerTextChange(value: string) { text.value = value; onTextChange(value); } function resetText() { text.value = valueTexts.value[0]; } watch( () => [...valueTexts.value], (cur, pre = []) => { if ( cur.join('||') !== pre.join('||') && valueTexts.value.every(valText => valText !== text.value) ) { resetText(); } }, { immediate: true }, ); return [text, triggerTextChange, resetText]; }
YaroShkvorets/ant-design-vue
components/vc-picker/hooks/usePickerInput.ts
import type { ComputedRef, HTMLAttributes, Ref } from 'vue'; import { onBeforeUnmount, watchEffect, watch, ref, computed } from 'vue'; import type { FocusEventHandler } from '../../_util/EventInterface'; import KeyCode from '../../_util/KeyCode'; import { addGlobalMousedownEvent, getTargetFromEvent } from '../utils/uiUtil'; export default function usePickerInput({ open, value, isClickOutside, triggerOpen, forwardKeydown, onKeydown, blurToCancel, onSubmit, onCancel, onFocus, onBlur, }: { open: Ref<boolean>; value: Ref<string>; isClickOutside: (clickElement: EventTarget | null) => boolean; triggerOpen: (open: boolean) => void; forwardKeydown: (e: KeyboardEvent) => boolean; onKeydown: (e: KeyboardEvent, preventDefault: () => void) => void; blurToCancel?: ComputedRef<boolean>; onSubmit: () => void | boolean; onCancel: () => void; onFocus?: FocusEventHandler; onBlur?: FocusEventHandler; }): [ComputedRef<HTMLAttributes>, { focused: Ref<boolean>; typing: Ref<boolean> }] { const typing = ref(false); const focused = ref(false); /** * We will prevent blur to handle open event when user click outside, * since this will repeat trigger `onOpenChange` event. */ const preventBlurRef = ref<boolean>(false); const valueChangedRef = ref<boolean>(false); const preventDefaultRef = ref<boolean>(false); const inputProps = computed<HTMLAttributes>(() => ({ onMousedown: () => { typing.value = true; triggerOpen(true); }, onKeydown: e => { const preventDefault = (): void => { preventDefaultRef.value = true; }; onKeydown(e, preventDefault); if (preventDefaultRef.value) return; switch (e.which) { case KeyCode.ENTER: { if (!open.value) { triggerOpen(true); } else if (onSubmit() !== false) { typing.value = true; } e.preventDefault(); return; } case KeyCode.TAB: { if (typing.value && open.value && !e.shiftKey) { typing.value = false; e.preventDefault(); } else if (!typing.value && open.value) { if (!forwardKeydown(e) && e.shiftKey) { typing.value = true; e.preventDefault(); } } return; } case KeyCode.ESC: { typing.value = true; onCancel(); return; } } if (!open.value && ![KeyCode.SHIFT].includes(e.which)) { triggerOpen(true); } else if (!typing.value) { // Let popup panel handle keyboard forwardKeydown(e); } }, onFocus: e => { typing.value = true; focused.value = true; if (onFocus) { onFocus(e); } }, onBlur: e => { if (preventBlurRef.value || !isClickOutside(document.activeElement)) { preventBlurRef.value = false; return; } if (blurToCancel.value) { setTimeout(() => { let { activeElement } = document; while (activeElement && activeElement.shadowRoot) { activeElement = activeElement.shadowRoot.activeElement; } if (isClickOutside(activeElement)) { onCancel(); } }, 0); } else if (open.value) { triggerOpen(false); if (valueChangedRef.value) { onSubmit(); } } focused.value = false; if (onBlur) { onBlur(e); } }, })); // check if value changed watch(open, () => { valueChangedRef.value = false; }); watch(value, () => { valueChangedRef.value = true; }); const globalMousedownEvent = ref(); // Global click handler watchEffect( () => globalMousedownEvent.value && globalMousedownEvent.value()( (globalMousedownEvent.value = addGlobalMousedownEvent((e: MouseEvent) => { const target = getTargetFromEvent(e); if (open) { const clickedOutside = isClickOutside(target); if (!clickedOutside) { preventBlurRef.value = true; // Always set back in case `onBlur` prevented by user requestAnimationFrame(() => { preventBlurRef.value = false; }); } else if (!focused.value || clickedOutside) { triggerOpen(false); } } })), ), ); onBeforeUnmount(() => { globalMousedownEvent.value && globalMousedownEvent.value(); }); return [inputProps, { focused, typing }]; }
YaroShkvorets/ant-design-vue
plugin/md/utils/tsToJs.ts
import { transformSync } from '@babel/core'; import { CLIEngine } from 'eslint'; import path from 'path'; const engine = new CLIEngine({ fix: true, useEslintrc: false, baseConfig: require(path.join(process.cwd(), '.eslintrc.js')), }); const tsToJs = (content: string): string => { if (!content) { return ''; } const { code } = transformSync(content, { configFile: false, plugins: [ [ require.resolve('@babel/plugin-transform-typescript'), { isTSX: false, }, ], ], }); const report = engine.executeOnText(code); let output = report.results[0].output; output = output ? output.trim() : output; return output; }; export default tsToJs;
YaroShkvorets/ant-design-vue
components/vc-mentions/src/KeywordTrigger.tsx
import PropTypes from '../../_util/vue-types'; import Trigger from '../../vc-trigger'; import DropdownMenu from './DropdownMenu'; import type { PropType } from 'vue'; import { computed, defineComponent } from 'vue'; import type { OptionProps } from './Option'; const BUILT_IN_PLACEMENTS = { bottomRight: { points: ['tl', 'br'], offset: [0, 4], overflow: { adjustX: 0, adjustY: 1, }, }, bottomLeft: { points: ['tr', 'bl'], offset: [0, 4], overflow: { adjustX: 0, adjustY: 1, }, }, topRight: { points: ['bl', 'tr'], offset: [0, -4], overflow: { adjustX: 0, adjustY: 1, }, }, topLeft: { points: ['br', 'tl'], offset: [0, -4], overflow: { adjustX: 0, adjustY: 1, }, }, }; export default defineComponent({ name: 'KeywordTrigger', props: { loading: PropTypes.looseBool, options: { type: Array as PropType<OptionProps[]>, default: () => [], }, prefixCls: PropTypes.string, placement: PropTypes.string, visible: PropTypes.looseBool, transitionName: PropTypes.string, getPopupContainer: PropTypes.func, direction: PropTypes.string, }, slots: ['notFoundContent', 'option'], setup(props, { slots }) { const getDropdownPrefix = () => { return `${props.prefixCls}-dropdown`; }; const getDropdownElement = () => { const { options } = props; return ( <DropdownMenu prefixCls={getDropdownPrefix()} options={options} v-slots={{ notFoundContent: slots.notFoundContent, option: slots.option }} /> ); }; const popupPlacement = computed(() => { const { placement, direction } = props; let popupPlacement = 'topRight'; if (direction === 'rtl') { popupPlacement = placement === 'top' ? 'topLeft' : 'bottomLeft'; } else { popupPlacement = placement === 'top' ? 'topRight' : 'bottomRight'; } return popupPlacement; }); return () => { const { visible, transitionName, getPopupContainer } = props; return ( <Trigger prefixCls={getDropdownPrefix()} popupVisible={visible} popup={getDropdownElement()} popupPlacement={popupPlacement.value} popupTransitionName={transitionName} builtinPlacements={BUILT_IN_PLACEMENTS} getPopupContainer={getPopupContainer} > {slots.default?.()} </Trigger> ); }; }, });
YaroShkvorets/ant-design-vue
components/config-provider/renderEmpty.tsx
<reponame>YaroShkvorets/ant-design-vue import type { VNodeChild } from 'vue'; import { inject } from 'vue'; import Empty from '../empty'; import { defaultConfigProvider } from '.'; export interface RenderEmptyProps { componentName?: string; } const RenderEmpty = (props: RenderEmptyProps) => { const configProvider = inject('configProvider', defaultConfigProvider); const renderHtml = (componentName?: string) => { const { getPrefixCls } = configProvider; const prefix = getPrefixCls('empty'); switch (componentName) { case 'Table': case 'List': return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />; case 'Select': case 'TreeSelect': case 'Cascader': case 'Transfer': case 'Mentions': return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} class={`${prefix}-small`} />; default: return <Empty />; } }; return renderHtml(props.componentName); }; function renderEmpty(componentName?: string): VNodeChild | JSX.Element { return <RenderEmpty componentName={componentName} />; } export type RenderEmptyHandler = typeof renderEmpty; export default renderEmpty;
YaroShkvorets/ant-design-vue
components/progress/progress.tsx
<gh_stars>1000+ import type { VNodeChild } from 'vue'; import { computed, defineComponent } from 'vue'; import initDefaultProps from '../_util/props-util/initDefaultProps'; import CloseOutlined from '@ant-design/icons-vue/CloseOutlined'; import CheckOutlined from '@ant-design/icons-vue/CheckOutlined'; import CheckCircleFilled from '@ant-design/icons-vue/CheckCircleFilled'; import CloseCircleFilled from '@ant-design/icons-vue/CloseCircleFilled'; import Line from './Line'; import Circle from './Circle'; import Steps from './Steps'; import { getSuccessPercent, validProgress } from './utils'; import useConfigInject from '../_util/hooks/useConfigInject'; import devWarning from '../vc-util/devWarning'; import { progressProps, progressStatuses } from './props'; export default defineComponent({ name: 'AProgress', props: initDefaultProps(progressProps(), { type: 'line', percent: 0, showInfo: true, // null for different theme definition trailColor: null, size: 'default', gapDegree: 0, strokeLinecap: 'round', }), slots: ['format'], setup(props, { slots }) { const { prefixCls, direction } = useConfigInject('progress', props); devWarning( props.successPercent == undefined, 'Progress', '`successPercent` is deprecated. Please use `success.percent` instead.', ); const classString = computed(() => { const { type, showInfo, size } = props; const pre = prefixCls.value; return { [pre]: true, [`${pre}-${(type === 'dashboard' && 'circle') || type}`]: true, [`${pre}-show-info`]: showInfo, [`${pre}-${size}`]: size, [`${pre}-rtl`]: direction.value === 'rtl', }; }); const percentNumber = computed(() => { const { percent = 0 } = props; const successPercent = getSuccessPercent(props); return parseInt( successPercent !== undefined ? successPercent.toString() : percent.toString(), 10, ); }); const progressStatus = computed(() => { const { status } = props; if (progressStatuses.indexOf(status) < 0 && percentNumber.value >= 100) { return 'success'; } return status || 'normal'; }); const renderProcessInfo = () => { const { showInfo, format, type, percent } = props; const successPercent = getSuccessPercent(props); if (!showInfo) return null; let text: VNodeChild; const textFormatter = format || slots?.format || ((val: number) => `${val}%`); const isLineType = type === 'line'; if ( format || slots?.format || (progressStatus.value !== 'exception' && progressStatus.value !== 'success') ) { text = textFormatter(validProgress(percent), validProgress(successPercent)); } else if (progressStatus.value === 'exception') { text = isLineType ? <CloseCircleFilled /> : <CloseOutlined />; } else if (progressStatus.value === 'success') { text = isLineType ? <CheckCircleFilled /> : <CheckOutlined />; } return ( <span class={`${prefixCls.value}-text`} title={typeof text === 'string' ? text : undefined}> {text} </span> ); }; return () => { const { type, steps, strokeColor } = props; const progressInfo = renderProcessInfo(); let progress: VNodeChild; // Render progress shape if (type === 'line') { progress = steps ? ( <Steps {...props} strokeColor={typeof strokeColor === 'string' ? strokeColor : undefined} prefixCls={prefixCls.value} steps={steps} > {progressInfo} </Steps> ) : ( <Line {...props} prefixCls={prefixCls.value}> {progressInfo} </Line> ); } else if (type === 'circle' || type === 'dashboard') { progress = ( <Circle {...props} prefixCls={prefixCls.value}> {progressInfo} </Circle> ); } const classNames = { ...classString.value, [`${prefixCls.value}-status-${progressStatus.value}`]: true, }; return <div class={classNames}>{progress}</div>; }; }, });
YaroShkvorets/ant-design-vue
components/vc-progress/src/Line.tsx
<gh_stars>1000+ import useRefs from '../../_util/hooks/useRefs'; import { computed, defineComponent } from 'vue'; import initDefaultProps from '../../_util/props-util/initDefaultProps'; import { useTransitionDuration, defaultProps } from './common'; import { propTypes } from './types'; export default defineComponent({ name: 'Line', props: initDefaultProps(propTypes, defaultProps), setup(props) { const percentList = computed(() => { const { percent } = props; return Array.isArray(percent) ? percent : [percent]; }); const percentListProps = computed(() => { const { prefixCls, strokeLinecap, strokeWidth, transition } = props; let stackPtg = 0; return percentList.value.map((ptg, index) => { let dashPercent = 1; switch (strokeLinecap) { case 'round': dashPercent = 1 - strokeWidth / 100; break; case 'square': dashPercent = 1 - strokeWidth / 2 / 100; break; default: dashPercent = 1; break; } const pathStyle = { strokeDasharray: `${ptg * dashPercent}px, 100px`, strokeDashoffset: `-${stackPtg}px`, transition: transition || 'stroke-dashoffset 0.3s ease 0s, stroke-dasharray .3s ease 0s, stroke 0.3s linear', }; const color = strokeColorList.value[index] || strokeColorList.value[strokeColorList.value.length - 1]; stackPtg += ptg; const pathProps = { key: index, d: pathString.value, 'stroke-linecap': strokeLinecap, stroke: color as string, 'stroke-width': strokeWidth, 'fill-opacity': '0', class: `${prefixCls}-line-path`, style: pathStyle, }; return pathProps; }); }); const strokeColorList = computed(() => { const { strokeColor } = props; return Array.isArray(strokeColor) ? strokeColor : [strokeColor]; }); const [setRef, paths] = useRefs(); useTransitionDuration(paths); const center = computed(() => props.strokeWidth / 2); const right = computed(() => 100 - props.strokeWidth / 2); const pathString = computed( () => `M ${props.strokeLinecap === 'round' ? center.value : 0},${center.value} L ${props.strokeLinecap === 'round' ? right.value : 100},${center.value}`, ); const viewBoxString = computed(() => `0 0 100 ${props.strokeWidth}`); const pathFirst = computed(() => ({ d: pathString.value, 'stroke-linecap': props.strokeLinecap, stroke: props.trailColor, 'stroke-width': props.trailWidth || props.strokeWidth, 'fill-opacity': '0', class: `${props.prefixCls}-line-trail`, })); return () => { const { percent, prefixCls, strokeColor, strokeLinecap, strokeWidth, trailColor, trailWidth, transition, ...restProps } = props; delete restProps.gapPosition; return ( <svg class={`${prefixCls}-line`} viewBox={viewBoxString.value} preserveAspectRatio="none" {...restProps} > <path {...pathFirst.value} /> {percentListProps.value.map((pathProps, index) => { return <path ref={setRef(index)} {...pathProps} />; })} </svg> ); }; }, });
YaroShkvorets/ant-design-vue
components/badge/utils.ts
<reponame>YaroShkvorets/ant-design-vue<filename>components/badge/utils.ts import { PresetColorTypes } from '../_util/colors'; export function isPresetColor(color?: string): boolean { return (PresetColorTypes as any[]).indexOf(color) !== -1; }
YaroShkvorets/ant-design-vue
components/card/Grid.tsx
import { defineComponent, computed } from 'vue'; import useConfigInject from '../_util/hooks/useConfigInject'; export default defineComponent({ name: 'ACardGrid', __ANT_CARD_GRID: true, props: { prefixCls: String, hoverable: { type: Boolean, default: true }, }, setup(props, { slots }) { const { prefixCls } = useConfigInject('card', props); const classNames = computed(() => { return { [`${prefixCls.value}-grid`]: true, [`${prefixCls.value}-grid-hoverable`]: props.hoverable, }; }); return () => { return <div class={classNames.value}>{slots.default?.()}</div>; }; }, });
YaroShkvorets/ant-design-vue
components/breadcrumb/BreadcrumbSeparator.tsx
<reponame>YaroShkvorets/ant-design-vue import type { ExtractPropTypes } from 'vue'; import { defineComponent } from 'vue'; import PropTypes from '../_util/vue-types'; import { flattenChildren } from '../_util/props-util'; import useConfigInject from '../_util/hooks/useConfigInject'; const breadcrumbSeparatorProps = { prefixCls: PropTypes.string, }; export type BreadcrumbSeparatorProps = Partial<ExtractPropTypes<typeof breadcrumbSeparatorProps>>; export default defineComponent({ name: 'ABreadcrumbSeparator', __ANT_BREADCRUMB_SEPARATOR: true, inheritAttrs: false, props: breadcrumbSeparatorProps, setup(props, { slots, attrs }) { const { prefixCls } = useConfigInject('breadcrumb', props); return () => { const { separator, class: className, ...restAttrs } = attrs; const children = flattenChildren(slots.default?.()); return ( <span class={[`${prefixCls.value}-separator`, className]} {...restAttrs}> {children.length > 0 ? children : '/'} </span> ); }; }, });
YaroShkvorets/ant-design-vue
components/skeleton/Avatar.tsx
import { computed, defineComponent } from 'vue'; import classNames from '../_util/classNames'; import PropTypes from '../_util/vue-types'; import { tuple } from '../_util/type'; import initDefaultProps from '../_util/props-util/initDefaultProps'; import useConfigInject from '../_util/hooks/useConfigInject'; import type { SkeletonElementProps } from './Element'; import Element, { skeletonElementProps } from './Element'; export interface AvatarProps extends Omit<SkeletonElementProps, 'shape'> { shape?: 'circle' | 'square'; } export const avatarProps = initDefaultProps( { ...skeletonElementProps(), shape: PropTypes.oneOf(tuple('circle', 'square')) }, { size: 'large', }, ); const SkeletonAvatar = defineComponent({ name: 'ASkeletonAvatar', props: avatarProps, setup(props) { const { prefixCls } = useConfigInject('skeleton', props); const cls = computed(() => classNames(prefixCls.value, `${prefixCls.value}-element`, { [`${prefixCls.value}-active`]: props.active, }), ); return () => { return ( <div class={cls.value}> <Element {...props} prefixCls={`${prefixCls.value}-avatar`} /> </div> ); }; }, }); export default SkeletonAvatar;
YaroShkvorets/ant-design-vue
components/vc-tree-select/hooks/useKeyValueMap.ts
<filename>components/vc-tree-select/hooks/useKeyValueMap.ts import type { ComputedRef, Ref } from 'vue'; import { shallowRef, watchEffect } from 'vue'; import type { FlattenDataNode, Key, RawValueType } from '../interface'; /** * Return cached Key Value map with DataNode. * Only re-calculate when `flattenOptions` changed. */ export default function useKeyValueMap(flattenOptions: ComputedRef<FlattenDataNode[]>) { const cacheKeyMap: Ref<Map<Key, FlattenDataNode>> = shallowRef(new Map()); const cacheValueMap: Ref<Map<RawValueType, FlattenDataNode>> = shallowRef(new Map()); watchEffect(() => { const newCacheKeyMap = new Map(); const newCacheValueMap = new Map(); // Cache options by key flattenOptions.value.forEach((dataNode: FlattenDataNode) => { newCacheKeyMap.set(dataNode.key, dataNode); newCacheValueMap.set(dataNode.data.value, dataNode); }); cacheKeyMap.value = newCacheKeyMap; cacheValueMap.value = newCacheValueMap; }); return [cacheKeyMap, cacheValueMap]; }
YaroShkvorets/ant-design-vue
components/vc-align/index.ts
// based on rc-align 4.0.9 import Align from './Align'; export default Align;
YaroShkvorets/ant-design-vue
components/_util/responsiveObserve.ts
export type Breakpoint = 'xxl' | 'xl' | 'lg' | 'md' | 'sm' | 'xs'; export type BreakpointMap = Record<Breakpoint, string>; export type ScreenMap = Partial<Record<Breakpoint, boolean>>; export type ScreenSizeMap = Partial<Record<Breakpoint, number>>; export const responsiveArray: Breakpoint[] = ['xxl', 'xl', 'lg', 'md', 'sm', 'xs']; export const responsiveMap: BreakpointMap = { xs: '(max-width: 575px)', sm: '(min-width: 576px)', md: '(min-width: 768px)', lg: '(min-width: 992px)', xl: '(min-width: 1200px)', xxl: '(min-width: 1600px)', }; type SubscribeFunc = (screens: ScreenMap) => void; const subscribers = new Map<Number, SubscribeFunc>(); let subUid = -1; let screens = {}; const responsiveObserve = { matchHandlers: {} as { [prop: string]: { mql: MediaQueryList; listener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null; }; }, dispatch(pointMap: ScreenMap) { screens = pointMap; subscribers.forEach(func => func(screens)); return subscribers.size >= 1; }, subscribe(func: SubscribeFunc): number { if (!subscribers.size) this.register(); subUid += 1; subscribers.set(subUid, func); func(screens); return subUid; }, unsubscribe(token: number) { subscribers.delete(token); if (!subscribers.size) this.unregister(); }, unregister() { Object.keys(responsiveMap).forEach((screen: string) => { const matchMediaQuery = responsiveMap[screen]; const handler = this.matchHandlers[matchMediaQuery]; handler?.mql.removeListener(handler?.listener); }); subscribers.clear(); }, register() { Object.keys(responsiveMap).forEach((screen: string) => { const matchMediaQuery = responsiveMap[screen]; const listener = ({ matches }: { matches: boolean }) => { this.dispatch({ ...screens, [screen]: matches, }); }; const mql = window.matchMedia(matchMediaQuery); mql.addListener(listener); this.matchHandlers[matchMediaQuery] = { mql, listener, }; listener(mql); }); }, }; export default responsiveObserve;
YaroShkvorets/ant-design-vue
components/date-picker/PickerTag.tsx
<reponame>YaroShkvorets/ant-design-vue import type { TagProps } from '../tag'; import Tag from '../tag'; export default function PickerTag(props: TagProps, { slots, attrs }) { return <Tag color="blue" {...props} {...attrs} v-slots={slots} />; }
YaroShkvorets/ant-design-vue
components/slider/index.tsx
import type { CSSProperties, VNodeTypes, PropType } from 'vue'; import { computed, ref, defineComponent } from 'vue'; import VcSlider from '../vc-slider/src/Slider'; import VcRange from '../vc-slider/src/Range'; import VcHandle from '../vc-slider/src/Handle'; import type { VueNode } from '../_util/type'; import { withInstall } from '../_util/type'; import type { TooltipPlacement } from '../tooltip/Tooltip'; import useConfigInject from '../_util/hooks/useConfigInject'; import SliderTooltip from './SliderTooltip'; import classNames from '../_util/classNames'; import { useInjectFormItemContext } from '../form/FormItemContext'; export type SliderValue = number | [number, number]; interface SliderMarks { [key: number]: | VueNode | { style: CSSProperties; label: any; }; } interface HandleGeneratorInfo { value?: number; dragging?: boolean; index: number; } interface SliderRange { draggableTrack?: boolean; } export type HandleGeneratorFn = (config: { tooltipPrefixCls?: string; prefixCls?: string; info: HandleGeneratorInfo; }) => VNodeTypes; type Value = [number, number] | number; const defaultTipFormatter = (value: number) => (typeof value === 'number' ? value.toString() : ''); export const sliderProps = () => ({ id: String, prefixCls: String, tooltipPrefixCls: String, range: { type: [Boolean, Object] as PropType<boolean | SliderRange>, default: undefined }, reverse: { type: Boolean, default: undefined }, min: Number, max: Number, step: { type: [Number, Object] as PropType<null | number> }, marks: { type: Object as PropType<SliderMarks> }, dots: { type: Boolean, default: undefined }, value: { type: [Number, Array] as PropType<Value> }, defaultValue: { type: [Number, Array] as PropType<Value> }, included: { type: Boolean, default: undefined }, disabled: { type: Boolean, default: undefined }, vertical: { type: Boolean, default: undefined }, tipFormatter: { type: Function as PropType<(value?: number) => any>, default: defaultTipFormatter, }, tooltipVisible: { type: Boolean, default: undefined }, tooltipPlacement: { type: String as PropType<TooltipPlacement> }, getTooltipPopupContainer: { type: Function as PropType<(triggerNode: HTMLElement) => HTMLElement>, }, autofocus: { type: Boolean, default: undefined }, onChange: { type: Function as PropType<(value: Value) => void> }, onAfterChange: { type: Function as PropType<(value: Value) => void> }, handleStyle: { type: [Object, Array] as PropType<CSSProperties[] | CSSProperties> }, trackStyle: { type: [Object, Array] as PropType<CSSProperties[] | CSSProperties> }, }); export type Visibles = { [index: number]: boolean }; const Slider = defineComponent({ name: 'ASlider', inheritAttrs: false, props: { ...sliderProps(), }, emits: ['update:value', 'change', 'afterChange', 'blur'], slots: ['mark'], setup(props, { attrs, slots, emit, expose }) { const { prefixCls, rootPrefixCls, direction, getPopupContainer, configProvider } = useConfigInject('slider', props); const formItemContext = useInjectFormItemContext(); const sliderRef = ref(); const visibles = ref<Visibles>({}); const toggleTooltipVisible = (index: number, visible: boolean) => { visibles.value[index] = visible; }; const tooltipPlacement = computed(() => { if (props.tooltipPlacement) { return props.tooltipPlacement; } if (!props.vertical) { return 'top'; } return direction.value === 'rtl' ? 'left' : 'right'; }); const focus = () => { sliderRef.value?.focus(); }; const blur = () => { sliderRef.value?.blur(); }; const handleChange = (val: SliderValue) => { emit('update:value', val); emit('change', val); formItemContext.onFieldChange(); }; const handleBlur = () => { emit('blur'); }; expose({ focus, blur, }); const handleWithTooltip: HandleGeneratorFn = ({ tooltipPrefixCls, info: { value, dragging, index, ...restProps }, }) => { const { tipFormatter, tooltipVisible, getTooltipPopupContainer } = props; const isTipFormatter = tipFormatter ? visibles.value[index] || dragging : false; const visible = tooltipVisible || (tooltipVisible === undefined && isTipFormatter); return ( <SliderTooltip prefixCls={tooltipPrefixCls} title={tipFormatter ? tipFormatter(value) : ''} visible={visible} placement={tooltipPlacement.value} transitionName={`${rootPrefixCls.value}-zoom-down`} key={index} overlayClassName={`${prefixCls.value}-tooltip`} getPopupContainer={getTooltipPopupContainer || getPopupContainer.value} > <VcHandle {...restProps} value={value} onMouseenter={() => toggleTooltipVisible(index, true)} onMouseleave={() => toggleTooltipVisible(index, false)} /> </SliderTooltip> ); }; return () => { const { tooltipPrefixCls: customizeTooltipPrefixCls, range, id = formItemContext.id.value, ...restProps } = props; const tooltipPrefixCls = configProvider.getPrefixCls('tooltip', customizeTooltipPrefixCls); const cls = classNames(attrs.class, { [`${prefixCls.value}-rtl`]: direction.value === 'rtl', }); // make reverse default on rtl direction if (direction.value === 'rtl' && !restProps.vertical) { restProps.reverse = !restProps.reverse; } // extrack draggableTrack from range={{ ... }} let draggableTrack: boolean | undefined; if (typeof range === 'object') { draggableTrack = range.draggableTrack; } if (range) { return ( <VcRange {...restProps} step={restProps.step!} draggableTrack={draggableTrack} class={cls} ref={ref} handle={(info: HandleGeneratorInfo) => handleWithTooltip({ tooltipPrefixCls, prefixCls: prefixCls.value, info, }) } prefixCls={prefixCls.value} onChange={handleChange} v-slots={{ mark: slots.mark }} /> ); } return ( <VcSlider {...restProps} id={id} step={restProps.step!} class={cls} ref={ref} handle={(info: HandleGeneratorInfo) => handleWithTooltip({ tooltipPrefixCls, prefixCls: prefixCls.value, info, }) } prefixCls={prefixCls.value} onChange={handleChange} onBlur={handleBlur} v-slots={{ mark: slots.mark }} /> ); }; }, }); export default withInstall(Slider);
YaroShkvorets/ant-design-vue
components/vc-steps/index.ts
// base rc-steps 4.1.3 import Steps from './Steps'; import Step from './Step'; Steps.Step = Step; export { Step }; export default Steps;
YaroShkvorets/ant-design-vue
components/vc-table/FixedHolder/index.tsx
<reponame>YaroShkvorets/ant-design-vue<filename>components/vc-table/FixedHolder/index.tsx import type { HeaderProps } from '../Header/Header'; import ColGroup from '../ColGroup'; import type { ColumnsType, ColumnType, DefaultRecordType } from '../interface'; import type { Ref } from 'vue'; import { computed, defineComponent, nextTick, onBeforeUnmount, onMounted, ref, toRef, watchEffect, } from 'vue'; import { useInjectTable } from '../context/TableContext'; import classNames from '../../_util/classNames'; import addEventListenerWrap from '../../vc-util/Dom/addEventListener'; function useColumnWidth(colWidthsRef: Ref<readonly number[]>, columCountRef: Ref<number>) { return computed(() => { const cloneColumns: number[] = []; const colWidths = colWidthsRef.value; const columCount = columCountRef.value; for (let i = 0; i < columCount; i += 1) { const val = colWidths[i]; if (val !== undefined) { cloneColumns[i] = val; } else { return null; } } return cloneColumns; }); } export interface FixedHeaderProps<RecordType> extends HeaderProps<RecordType> { noData: boolean; maxContentScroll: boolean; colWidths: readonly number[]; columCount: number; direction: 'ltr' | 'rtl'; fixHeader: boolean; stickyTopOffset?: number; stickyBottomOffset?: number; stickyClassName?: string; onScroll: (info: { currentTarget: HTMLDivElement; scrollLeft?: number }) => void; } export default defineComponent<FixedHeaderProps<DefaultRecordType>>({ name: 'FixedHolder', inheritAttrs: false, props: [ 'columns', 'flattenColumns', 'stickyOffsets', 'customHeaderRow', 'noData', 'maxContentScroll', 'colWidths', 'columCount', 'direction', 'fixHeader', 'stickyTopOffset', 'stickyBottomOffset', 'stickyClassName', ] as any, emits: ['scroll'], setup(props, { attrs, slots, emit }) { const tableContext = useInjectTable(); const combinationScrollBarSize = computed(() => tableContext.isSticky && !props.fixHeader ? 0 : tableContext.scrollbarSize, ); const scrollRef = ref(); const onWheel = (e: WheelEvent) => { const { currentTarget, deltaX } = e; if (deltaX) { emit('scroll', { currentTarget, scrollLeft: (currentTarget as any).scrollLeft + deltaX }); e.preventDefault(); } }; const wheelEvent = ref(); onMounted(() => { nextTick(() => { wheelEvent.value = addEventListenerWrap(scrollRef.value, 'wheel', onWheel); }); }); onBeforeUnmount(() => { wheelEvent.value?.remove(); }); // Check if all flattenColumns has width const allFlattenColumnsWithWidth = computed(() => props.flattenColumns.every( column => column.width && column.width !== 0 && column.width !== '0px', ), ); const columnsWithScrollbar = ref<ColumnsType<unknown>>([]); const flattenColumnsWithScrollbar = ref<ColumnsType<unknown>>([]); watchEffect(() => { // Add scrollbar column const lastColumn = props.flattenColumns[props.flattenColumns.length - 1]; const ScrollBarColumn: ColumnType<unknown> & { scrollbar: true } = { fixed: lastColumn ? lastColumn.fixed : null, scrollbar: true, customHeaderCell: () => ({ class: `${tableContext.prefixCls}-cell-scrollbar`, }), }; columnsWithScrollbar.value = combinationScrollBarSize.value ? [...props.columns, ScrollBarColumn] : props.columns; flattenColumnsWithScrollbar.value = combinationScrollBarSize.value ? [...props.flattenColumns, ScrollBarColumn] : props.flattenColumns; }); // Calculate the sticky offsets const headerStickyOffsets = computed(() => { const { stickyOffsets, direction } = props; const { right, left } = stickyOffsets; return { ...stickyOffsets, left: direction === 'rtl' ? [...left.map(width => width + combinationScrollBarSize.value), 0] : left, right: direction === 'rtl' ? right : [...right.map(width => width + combinationScrollBarSize.value), 0], isSticky: tableContext.isSticky, }; }); const mergedColumnWidth = useColumnWidth(toRef(props, 'colWidths'), toRef(props, 'columCount')); return () => { const { noData, columCount, stickyTopOffset, stickyBottomOffset, stickyClassName, maxContentScroll, } = props; const { isSticky } = tableContext; return ( <div style={{ overflow: 'hidden', ...(isSticky ? { top: `${stickyTopOffset}px`, bottom: `${stickyBottomOffset}px` } : {}), }} ref={scrollRef} class={classNames(attrs.class, { [stickyClassName]: !!stickyClassName, })} > <table style={{ tableLayout: 'fixed', visibility: noData || mergedColumnWidth.value ? null : 'hidden', }} > {(!noData || !maxContentScroll || allFlattenColumnsWithWidth.value) && ( <ColGroup colWidths={ mergedColumnWidth.value ? [...mergedColumnWidth.value, combinationScrollBarSize.value] : [] } columCount={columCount + 1} columns={flattenColumnsWithScrollbar.value} /> )} {slots.default?.({ ...props, stickyOffsets: headerStickyOffsets.value, columns: columnsWithScrollbar.value, flattenColumns: flattenColumnsWithScrollbar.value, })} </table> </div> ); }; }, });
YaroShkvorets/ant-design-vue
typings/vue-tsx-shim.d.ts
<gh_stars>1000+ import 'vue'; type EventHandler = (...args: any[]) => void; declare module 'vue' { interface ComponentCustomProps { role?: string; tabindex?: number | string; // should be removed after Vue supported component events typing // see: https://github.com/vuejs/vue-next/issues/1553 // https://github.com/vuejs/vue-next/issues/3029 onBlur?: EventHandler; onOpen?: EventHandler; onEdit?: EventHandler; onLoad?: EventHandler; onClose?: EventHandler; onFocus?: EventHandler; onInput?: EventHandler; onClick?: EventHandler; onPress?: EventHandler; onCancel?: EventHandler; onChange?: EventHandler; onDelete?: EventHandler; onScroll?: EventHandler; onSubmit?: EventHandler; onSelect?: EventHandler; onConfirm?: EventHandler; onPreview?: EventHandler; onKeypress?: EventHandler; onTouchend?: EventHandler; onTouchmove?: EventHandler; onTouchstart?: EventHandler; onTouchcancel?: EventHandler; onMouseenter?: EventHandler; onMouseleave?: EventHandler; onMousemove?: EventHandler; onKeydown?: EventHandler; onKeyup?: EventHandler; onDeselect?: EventHandler; onClear?: EventHandler; } }
YaroShkvorets/ant-design-vue
components/vc-mentions/src/Mentions.tsx
import type { ExtractPropTypes } from 'vue'; import { toRef, watchEffect, defineComponent, provide, withDirectives, ref, reactive, onUpdated, nextTick, computed, } from 'vue'; import classNames from '../../_util/classNames'; import KeyCode from '../../_util/KeyCode'; import { initDefaultProps } from '../../_util/props-util'; import { getBeforeSelectionText, getLastMeasureIndex, replaceWithMeasure, setInputSelection, } from './util'; import KeywordTrigger from './KeywordTrigger'; import { vcMentionsProps, defaultProps } from './mentionsProps'; import type { OptionProps } from './Option'; import MentionsContextKey from './MentionsContext'; import antInputDirective from '../../_util/antInputDirective'; import omit from '../../_util/omit'; import type { EventHandler } from '../../_util/EventInterface'; export type MentionsProps = Partial<ExtractPropTypes<typeof vcMentionsProps>>; function noop() {} export default defineComponent({ name: 'Mentions', inheritAttrs: false, props: initDefaultProps(vcMentionsProps, defaultProps), slots: ['notFoundContent', 'option'], emits: ['change', 'select', 'search', 'focus', 'blur', 'pressenter'], setup(props, { emit, attrs, expose, slots }) { const measure = ref(null); const textarea = ref(null); const focusId = ref(); const state = reactive({ value: props.value || '', measuring: false, measureLocation: 0, measureText: null, measurePrefix: '', activeIndex: 0, isFocus: false, }); watchEffect(() => { state.value = props.value; }); const triggerChange = (val: string) => { emit('change', val); }; const onChange: EventHandler = ({ target: { value, composing }, isComposing }) => { if (isComposing || composing) return; triggerChange(value); }; const startMeasure = (measureText: string, measurePrefix: string, measureLocation: number) => { Object.assign(state, { measuring: true, measureText, measurePrefix, measureLocation, activeIndex: 0, }); }; const stopMeasure = (callback?: () => void) => { Object.assign(state, { measuring: false, measureLocation: 0, measureText: null, }); callback?.(); }; const onKeyDown = (event: KeyboardEvent) => { const { which } = event; // Skip if not measuring if (!state.measuring) { return; } if (which === KeyCode.UP || which === KeyCode.DOWN) { // Control arrow function const optionLen = options.value.length; const offset = which === KeyCode.UP ? -1 : 1; const newActiveIndex = (state.activeIndex + offset + optionLen) % optionLen; state.activeIndex = newActiveIndex; event.preventDefault(); } else if (which === KeyCode.ESC) { stopMeasure(); } else if (which === KeyCode.ENTER) { // Measure hit event.preventDefault(); if (!options.value.length) { stopMeasure(); return; } const option = options.value[state.activeIndex]; selectOption(option); } }; const onKeyUp = (event: KeyboardEvent) => { const { key, which } = event; const { measureText: prevMeasureText, measuring } = state; const { prefix, validateSearch } = props; const target = event.target as HTMLTextAreaElement; if ((target as any).composing) { return; } const selectionStartText = getBeforeSelectionText(target); const { location: measureIndex, prefix: measurePrefix } = getLastMeasureIndex( selectionStartText, prefix, ); // Skip if match the white key list if ([KeyCode.ESC, KeyCode.UP, KeyCode.DOWN, KeyCode.ENTER].indexOf(which) !== -1) { return; } if (measureIndex !== -1) { const measureText = selectionStartText.slice(measureIndex + measurePrefix.length); const validateMeasure = validateSearch(measureText, props); const matchOption = !!getOptions(measureText).length; if (validateMeasure) { if ( key === measurePrefix || key === 'Shift' || measuring || (measureText !== prevMeasureText && matchOption) ) { startMeasure(measureText, measurePrefix, measureIndex); } } else if (measuring) { // Stop if measureText is invalidate stopMeasure(); } /** * We will trigger `onSearch` to developer since they may use for async update. * If met `space` means user finished searching. */ if (validateMeasure) { emit('search', measureText, measurePrefix); } } else if (measuring) { stopMeasure(); } }; const onPressEnter = event => { if (!state.measuring) { emit('pressenter', event); } }; const onInputFocus = (event: Event) => { onFocus(event); }; const onInputBlur = (event: Event) => { onBlur(event); }; const onFocus = (event: Event) => { window.clearTimeout(focusId.value); const { isFocus } = state; if (!isFocus && event) { emit('focus', event); } state.isFocus = true; }; const onBlur = (event: Event) => { focusId.value = window.setTimeout(() => { state.isFocus = false; stopMeasure(); emit('blur', event); }, 100); }; const selectOption = (option: OptionProps) => { const { split } = props; const { value: mentionValue = '' } = option; const { text, selectionLocation } = replaceWithMeasure(state.value, { measureLocation: state.measureLocation, targetText: mentionValue, prefix: state.measurePrefix, selectionStart: textarea.value.selectionStart, split, }); triggerChange(text); stopMeasure(() => { // We need restore the selection position setInputSelection(textarea.value, selectionLocation); }); emit('select', option, state.measurePrefix); }; const setActiveIndex = (activeIndex: number) => { state.activeIndex = activeIndex; }; const getOptions = (measureText?: string) => { const targetMeasureText = measureText || state.measureText || ''; const { filterOption } = props; const list = props.options.filter((option: OptionProps) => { /** Return all result if `filterOption` is false. */ if (!!filterOption === false) { return true; } return (filterOption as Function)(targetMeasureText, option); }); return list; }; const options = computed(() => { return getOptions(); }); const focus = () => { textarea.value.focus(); }; const blur = () => { textarea.value.blur(); }; expose({ blur, focus }); provide(MentionsContextKey, { activeIndex: toRef(state, 'activeIndex'), setActiveIndex, selectOption, onFocus, onBlur, loading: toRef(props, 'loading'), }); onUpdated(() => { nextTick(() => { if (state.measuring) { measure.value.scrollTop = textarea.value.scrollTop; } }); }); return () => { const { measureLocation, measurePrefix, measuring } = state; const { prefixCls, placement, transitionName, getPopupContainer, direction, ...restProps } = props; const { class: className, style, ...otherAttrs } = attrs; const inputProps = omit(restProps, [ 'value', 'prefix', 'split', 'validateSearch', 'filterOption', 'options', 'loading', ]); const textareaProps = { ...inputProps, ...otherAttrs, onChange: noop, onSelect: noop, value: state.value, onInput: onChange, onBlur: onInputBlur, onKeydown: onKeyDown, onKeyup: onKeyUp, onFocus: onInputFocus, onPressenter: onPressEnter, }; return ( <div class={classNames(prefixCls, className)} style={style}> {withDirectives(<textarea ref={textarea} {...textareaProps} />, [[antInputDirective]])} {measuring && ( <div ref={measure} class={`${prefixCls}-measure`}> {state.value.slice(0, measureLocation)} <KeywordTrigger prefixCls={prefixCls} transitionName={transitionName} placement={placement} options={measuring ? options.value : []} visible direction={direction} getPopupContainer={getPopupContainer} v-slots={{ notFoundContent: slots.notFoundContent, option: slots.option }} > <span>{measurePrefix}</span> </KeywordTrigger> {state.value.slice(measureLocation + measurePrefix.length)} </div> )} </div> ); }; }, });
YaroShkvorets/ant-design-vue
components/calendar/dayjs.tsx
import generateConfig from '../vc-picker/generate/dayjs'; import { withInstall } from '../_util/type'; import type { CalendarProps } from './generateCalendar'; import generateCalendar from './generateCalendar'; const Calendar = generateCalendar(generateConfig); export type { CalendarProps }; export default withInstall(Calendar);
YaroShkvorets/ant-design-vue
components/time-picker/locale/ga_IE.tsx
<filename>components/time-picker/locale/ga_IE.tsx import type { TimePickerLocale } from '../index'; const locale: TimePickerLocale = { placeholder: 'Roghnaigh am', rangePlaceholder: ['Am tosaigh', 'Am deiridh'], }; export default locale;
YaroShkvorets/ant-design-vue
components/typography/index.tsx
<reponame>YaroShkvorets/ant-design-vue import type { App, Plugin } from 'vue'; import Base from './Base'; import Link from './Link'; import Paragraph from './Paragraph'; import Text from './Text'; import Title from './Title'; import Typography from './Typography'; export type { TypographyProps } from './Typography'; Typography.Text = Text; Typography.Title = Title; Typography.Paragraph = Paragraph; Typography.Link = Link; Typography.Base = Base; Typography.install = function (app: App) { app.component(Typography.name, Typography); app.component(Typography.Text.displayName, Text); app.component(Typography.Title.displayName, Title); app.component(Typography.Paragraph.displayName, Paragraph); app.component(Typography.Link.displayName, Link); return app; }; export { Text as TypographyText, Title as TypographyTitle, Paragraph as TypographyParagraph, Link as TypographyLink, }; export default Typography as typeof Typography & Plugin & { readonly Text: typeof Text; readonly Title: typeof Title; readonly Paragraph: typeof Paragraph; readonly Link: typeof Link; readonly Base: typeof Base; };
YaroShkvorets/ant-design-vue
components/_util/vue-types/index.ts
<gh_stars>1000+ import type { CSSProperties } from 'vue'; import type { VueTypeValidableDef, VueTypesInterface } from 'vue-types'; import { createTypes } from 'vue-types'; import type { VueNode } from '../type'; const PropTypes = createTypes({ func: undefined, bool: undefined, string: undefined, number: undefined, array: undefined, object: undefined, integer: undefined, }); PropTypes.extend([ { name: 'looseBool', getter: true, type: Boolean, default: undefined, }, { name: 'style', getter: true, type: [String, Object], default: undefined, }, { name: 'VNodeChild', getter: true, type: null, }, ]); export function withUndefined<T extends { default?: any }>(type: T): T { type.default = undefined; return type; } export default PropTypes as VueTypesInterface & { readonly looseBool: VueTypeValidableDef<boolean>; readonly style: VueTypeValidableDef<CSSProperties>; readonly VNodeChild: VueTypeValidableDef<VueNode>; };
YaroShkvorets/ant-design-vue
components/vc-table/context/ResizeContext.tsx
<filename>components/vc-table/context/ResizeContext.tsx import type { InjectionKey } from 'vue'; import { inject, provide } from 'vue'; import type { Key } from '../interface'; interface ResizeContextProps { onColumnResize: (columnKey: Key, width: number) => void; } export const ResizeContextKey: InjectionKey<ResizeContextProps> = Symbol('ResizeContextProps'); export const useProvideResize = (props: ResizeContextProps) => { provide(ResizeContextKey, props); }; export const useInjectResize = () => { return inject(ResizeContextKey, { onColumnResize: () => {} }); };
YaroShkvorets/ant-design-vue
components/radio/interface.ts
<filename>components/radio/interface.ts import type { RadioProps } from './Radio'; import type { Ref } from 'vue'; export interface RadioChangeEventTarget extends RadioProps { checked: boolean; } export interface RadioChangeEvent { target: RadioChangeEventTarget; stopPropagation: () => void; preventDefault: () => void; nativeEvent: MouseEvent; } export interface RadioGroupContext { stateValue: Ref; props: RadioProps; onRadioChange: (e: RadioChangeEvent) => void; }
YaroShkvorets/ant-design-vue
components/vc-table/sugar/ColumnGroup.tsx
<filename>components/vc-table/sugar/ColumnGroup.tsx import type { ColumnType } from '../interface'; import type { FunctionalComponent } from 'vue'; /* istanbul ignore next */ /** * This is a syntactic sugar for `columns` prop. * So HOC will not work on this. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars export type ColumnGroupProps<RecordType> = ColumnType<RecordType>; const ColumnGroup: { <T>(arg: T): FunctionalComponent<ColumnGroupProps<T>> } = () => null; export default ColumnGroup;
YaroShkvorets/ant-design-vue
components/vc-tree-select/props.ts
<reponame>YaroShkvorets/ant-design-vue<gh_stars>1000+ import type { ExtractPropTypes, PropType } from 'vue'; import type { DataNode, ChangeEventExtra, DefaultValueType, FieldNames, FlattenDataNode, LabelValueType, LegacyDataNode, RawValueType, SimpleModeConfig, } from './interface'; import { selectBaseProps } from '../vc-select'; import type { FilterFunc } from '../vc-select/interface/generator'; import omit from '../_util/omit'; import type { Key } from '../_util/type'; import PropTypes from '../_util/vue-types'; import type { CheckedStrategy } from './utils/strategyUtil'; export function optionListProps<OptionsType>() { return { prefixCls: String, id: String, options: { type: Array as PropType<OptionsType[]> }, flattenOptions: { type: Array as PropType<FlattenDataNode[]> }, height: Number, itemHeight: Number, virtual: { type: Boolean, default: undefined }, values: { type: Set as PropType<Set<RawValueType>> }, multiple: { type: Boolean, default: undefined }, open: { type: Boolean, default: undefined }, defaultActiveFirstOption: { type: Boolean, default: undefined }, notFoundContent: PropTypes.any, menuItemSelectedIcon: PropTypes.any, childrenAsData: { type: Boolean, default: undefined }, searchValue: String, onSelect: { type: Function as PropType<(value: RawValueType, option: { selected: boolean }) => void>, }, onToggleOpen: { type: Function as PropType<(open?: boolean) => void> }, /** Tell Select that some value is now active to make accessibility work */ onActiveValue: { type: Function as PropType<(value: RawValueType, index: number) => void> }, onScroll: { type: Function as PropType<(e: UIEvent) => void> }, onMouseenter: { type: Function as PropType<() => void> }, }; } export function treeSelectProps<ValueType = DefaultValueType>() { const selectProps = omit(selectBaseProps<DataNode, ValueType>(), [ 'onChange', 'mode', 'menuItemSelectedIcon', 'dropdownAlign', 'backfill', 'getInputElement', 'optionLabelProp', 'tokenSeparators', 'filterOption', ]); return { ...selectProps, multiple: { type: Boolean, default: undefined }, showArrow: { type: Boolean, default: undefined }, showSearch: { type: Boolean, default: undefined }, open: { type: Boolean, default: undefined }, defaultOpen: { type: Boolean, default: undefined }, value: { type: [String, Number, Object, Array] as PropType<ValueType> }, defaultValue: { type: [String, Number, Object, Array] as PropType<ValueType> }, disabled: { type: Boolean, default: undefined }, placeholder: PropTypes.any, /** @deprecated Use `searchValue` instead */ inputValue: String, searchValue: String, autoClearSearchValue: { type: Boolean, default: undefined }, maxTagPlaceholder: { type: Function as PropType<(omittedValues: LabelValueType[]) => any> }, fieldNames: { type: Object as PropType<FieldNames> }, loadData: { type: Function as PropType<(dataNode: LegacyDataNode) => Promise<unknown>> }, treeNodeFilterProp: String, treeNodeLabelProp: String, treeDataSimpleMode: { type: [Boolean, Object] as PropType<boolean | SimpleModeConfig>, default: undefined, }, treeExpandedKeys: { type: Array as PropType<Key[]> }, treeDefaultExpandedKeys: { type: Array as PropType<Key[]> }, treeLoadedKeys: { type: Array as PropType<Key[]> }, treeCheckable: { type: Boolean, default: undefined }, treeCheckStrictly: { type: Boolean, default: undefined }, showCheckedStrategy: { type: String as PropType<CheckedStrategy> }, treeDefaultExpandAll: { type: Boolean, default: undefined }, treeData: { type: Array as PropType<DataNode[]> }, treeLine: { type: Boolean, default: undefined }, treeIcon: PropTypes.any, showTreeIcon: { type: Boolean, default: undefined }, switcherIcon: PropTypes.any, treeMotion: PropTypes.any, children: Array, filterTreeNode: { type: [Boolean, Function] as PropType<boolean | FilterFunc<LegacyDataNode>>, default: undefined, }, dropdownPopupAlign: PropTypes.any, // Event onSearch: { type: Function as PropType<(value: string) => void> }, onChange: { type: Function as PropType< (value: ValueType, labelList: any[], extra: ChangeEventExtra) => void >, }, onTreeExpand: { type: Function as PropType<(expandedKeys: Key[]) => void> }, onTreeLoad: { type: Function as PropType<(loadedKeys: Key[]) => void> }, onDropdownVisibleChange: { type: Function as PropType<(open: boolean) => void> }, // Legacy /** `searchPlaceholder` has been removed since search box has been merged into input box */ searchPlaceholder: PropTypes.any, /** @private This is not standard API since we only used in `rc-cascader`. Do not use in your production */ labelRender: { type: Function as PropType<(entity: FlattenDataNode) => any> }, }; } class Helper<T> { ReturnOptionListProps = optionListProps<T>(); ReturnTreeSelectProps = treeSelectProps<T>(); } export type OptionListProps = Partial<ExtractPropTypes<Helper<DataNode>['ReturnOptionListProps']>>; export type TreeSelectProps<T = DefaultValueType> = Partial< ExtractPropTypes<Helper<T>['ReturnTreeSelectProps']> >;
YaroShkvorets/ant-design-vue
components/vc-pagination/index.ts
<filename>components/vc-pagination/index.ts<gh_stars>1000+ // based on rc-pagination 3.1.9 export { default } from './Pagination';
YaroShkvorets/ant-design-vue
components/vc-picker/PanelContext.tsx
<filename>components/vc-picker/PanelContext.tsx<gh_stars>1000+ import type { InjectionKey, Ref } from 'vue'; import { inject, provide } from 'vue'; import type { OnSelect, PanelMode } from './interface'; export type ContextOperationRefProps = { onKeydown?: (e: KeyboardEvent) => boolean; onClose?: () => void; }; export type PanelContextProps = { operationRef?: Ref<ContextOperationRefProps | null>; /** Only work with time panel */ hideHeader?: Ref<boolean>; panelRef?: Ref<HTMLDivElement>; hidePrevBtn?: Ref<boolean>; hideNextBtn?: Ref<boolean>; onDateMouseenter?: (date: any) => void; onDateMouseleave?: (date: any) => void; onSelect?: OnSelect<any>; hideRanges?: Ref<boolean>; open?: Ref<boolean>; mode?: Ref<PanelMode>; /** Only used for TimePicker and this is a deprecated prop */ defaultOpenValue?: Ref<any>; }; const PanelContextKey: InjectionKey<PanelContextProps> = Symbol('PanelContextProps'); export const useProvidePanel = (props: PanelContextProps) => { provide(PanelContextKey, props); }; export const useInjectPanel = () => { return inject(PanelContextKey, {}); }; export default PanelContextKey;
YaroShkvorets/ant-design-vue
components/vc-drawer/src/IDrawerPropTypes.ts
<reponame>YaroShkvorets/ant-design-vue import PropTypes from '../../_util/vue-types'; import type { PropType } from 'vue'; export type IPlacement = 'left' | 'top' | 'right' | 'bottom'; type ILevelMove = number | [number, number]; const props = () => ({ prefixCls: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), style: PropTypes.style, class: PropTypes.string, placement: { type: String as PropType<IPlacement>, }, wrapperClassName: PropTypes.string, level: { type: [String, Array] as PropType<string | string[]> }, levelMove: { type: [Number, Function, Array] as PropType< ILevelMove | ((e: { target: HTMLElement; open: boolean }) => ILevelMove) >, }, duration: PropTypes.string, ease: PropTypes.string, showMask: PropTypes.looseBool, maskClosable: PropTypes.looseBool, maskStyle: PropTypes.style, afterVisibleChange: PropTypes.func, keyboard: PropTypes.looseBool, contentWrapperStyle: PropTypes.style, autofocus: PropTypes.looseBool, open: PropTypes.looseBool, }); const drawerProps = () => ({ ...props(), forceRender: PropTypes.looseBool, getContainer: PropTypes.oneOfType([ PropTypes.string, PropTypes.func, PropTypes.object, PropTypes.looseBool, ]), }); const drawerChildProps = () => ({ ...props(), getContainer: PropTypes.func, getOpenCount: PropTypes.func, scrollLocker: PropTypes.any, switchScrollingEffect: PropTypes.func, }); export { drawerProps, drawerChildProps };
YaroShkvorets/ant-design-vue
components/date-picker/index.tsx
import DatePicker from './dayjs'; export * from './dayjs'; export default DatePicker;
YaroShkvorets/ant-design-vue
components/time-picker/locale/sr_RS.tsx
import type { TimePickerLocale } from '../index'; const locale: TimePickerLocale = { placeholder: 'Izaberi vreme', rangePlaceholder: ['Vreme početka', 'Vreme završetka'], }; export default locale;
YaroShkvorets/ant-design-vue
components/vc-table/Body/BodyRow.tsx
import Cell from '../Cell'; import { getColumnsKey } from '../utils/valueUtil'; import type { CustomizeComponent, GetComponentProps, Key, GetRowKey } from '../interface'; import ExpandedRow from './ExpandedRow'; import { computed, defineComponent, ref, watchEffect } from 'vue'; import { useInjectTable } from '../context/TableContext'; import { useInjectBody } from '../context/BodyContext'; import classNames from '../../_util/classNames'; import { parseStyleText } from '../../_util/props-util'; export interface BodyRowProps<RecordType> { record: RecordType; index: number; recordKey: Key; expandedKeys: Set<Key>; rowComponent: CustomizeComponent; cellComponent: CustomizeComponent; customRow: GetComponentProps<RecordType>; rowExpandable: (record: RecordType) => boolean; indent?: number; rowKey: Key; getRowKey: GetRowKey<RecordType>; childrenColumnName: string; } export default defineComponent<BodyRowProps<unknown>>({ name: 'BodyRow', inheritAttrs: false, props: [ 'record', 'index', 'recordKey', 'expandedKeys', 'rowComponent', 'cellComponent', 'customRow', 'rowExpandable', 'indent', 'rowKey', 'getRowKey', 'childrenColumnName', ] as any, setup(props, { attrs }) { const tableContext = useInjectTable(); const bodyContext = useInjectBody(); const expandRended = ref(false); const expanded = computed(() => props.expandedKeys && props.expandedKeys.has(props.recordKey)); watchEffect(() => { if (expanded.value) { expandRended.value = true; } }); const rowSupportExpand = computed( () => bodyContext.expandableType === 'row' && (!props.rowExpandable || props.rowExpandable(props.record)), ); // Only when row is not expandable and `children` exist in record const nestExpandable = computed(() => bodyContext.expandableType === 'nest'); const hasNestChildren = computed( () => props.childrenColumnName && props.record && props.record[props.childrenColumnName], ); const mergedExpandable = computed(() => rowSupportExpand.value || nestExpandable.value); const onInternalTriggerExpand = (record, event) => { bodyContext.onTriggerExpand(record, event); }; // =========================== onRow =========================== const additionalProps = computed<Record<string, any>>( () => props.customRow?.(props.record, props.index) || {}, ); const onClick = (event, ...args) => { if (bodyContext.expandRowByClick && mergedExpandable.value) { onInternalTriggerExpand(props.record, event); } if (additionalProps.value?.onClick) { additionalProps.value.onClick(event, ...args); } }; const computeRowClassName = computed(() => { const { record, index, indent } = props; const { rowClassName } = bodyContext; if (typeof rowClassName === 'string') { return rowClassName; } else if (typeof rowClassName === 'function') { return rowClassName(record, index, indent); } return ''; }); const columnsKey = computed(() => getColumnsKey(bodyContext.flattenColumns)); return () => { const { class: className, style } = attrs as any; const { record, index, rowKey, indent = 0, rowComponent: RowComponent, cellComponent, } = props; const { prefixCls, fixedInfoList, transformCellText } = tableContext; const { fixHeader, fixColumn, horizonScroll, componentWidth, flattenColumns, expandedRowClassName, indentSize, expandIcon, expandedRowRender, expandIconColumnIndex, } = bodyContext; const baseRowNode = ( <RowComponent {...additionalProps.value} data-row-key={rowKey} class={classNames( className, `${prefixCls}-row`, `${prefixCls}-row-level-${indent}`, computeRowClassName.value, additionalProps.value.class, )} style={{ ...style, ...parseStyleText(additionalProps.value.style), }} onClick={onClick} > {flattenColumns.map((column, colIndex) => { const { customRender, dataIndex, className: columnClassName } = column; const key = columnsKey[colIndex]; const fixedInfo = fixedInfoList[colIndex]; let additionalCellProps; if (column.customCell) { additionalCellProps = column.customCell(record, index); } return ( <Cell cellType="body" class={columnClassName} ellipsis={column.ellipsis} align={column.align} component={cellComponent} prefixCls={prefixCls} key={key} record={record} index={index} dataIndex={dataIndex} customRender={customRender} {...fixedInfo} additionalProps={additionalCellProps} column={column} transformCellText={transformCellText} v-slots={{ // ============= Used for nest expandable ============= appendNode: colIndex === (expandIconColumnIndex || 0) && nestExpandable.value ? () => { return ( <> <span style={{ paddingLeft: `${indentSize * indent}px` }} class={`${prefixCls}-row-indent indent-level-${indent}`} /> {expandIcon({ prefixCls, expanded: expanded.value, expandable: hasNestChildren.value, record, onExpand: onInternalTriggerExpand, })} </> ); } : undefined, }} /> ); })} </RowComponent> ); // ======================== Expand Row ========================= let expandRowNode; if (rowSupportExpand.value && (expandRended.value || expanded.value)) { const expandContent = expandedRowRender({ record, index, indent: indent + 1, expanded: expanded.value, }); const computedExpandedRowClassName = expandedRowClassName && expandedRowClassName(record, index, indent); expandRowNode = ( <ExpandedRow expanded={expanded.value} class={classNames( `${prefixCls}-expanded-row`, `${prefixCls}-expanded-row-level-${indent + 1}`, computedExpandedRowClassName, )} prefixCls={prefixCls} fixHeader={fixHeader} fixColumn={fixColumn} horizonScroll={horizonScroll} component={RowComponent} componentWidth={componentWidth} cellComponent={cellComponent} colSpan={flattenColumns.length} > {expandContent} </ExpandedRow> ); } return ( <> {baseRowNode} {expandRowNode} </> ); }; }, });
YaroShkvorets/ant-design-vue
components/table/ColumnGroup.tsx
<reponame>YaroShkvorets/ant-design-vue<filename>components/table/ColumnGroup.tsx import { defineComponent } from 'vue'; import type { ColumnGroupProps } from '../vc-table/sugar/ColumnGroup'; export default defineComponent<ColumnGroupProps<any>>({ name: 'ATableColumnGroup', slots: ['title'], __ANT_TABLE_COLUMN_GROUP: true, render() { return null; }, });
YaroShkvorets/ant-design-vue
components/date-picker/locale/nb_NO.tsx
import CalendarLocale from '../../vc-picker/locale/nb_NO'; import TimePickerLocale from '../../time-picker/locale/nb_NO'; import type { PickerLocale } from '../generatePicker'; // Merge into a locale object const locale: PickerLocale = { lang: { placeholder: 'Velg dato', yearPlaceholder: 'Velg år', quarterPlaceholder: 'Velg kvartal', monthPlaceholder: 'Velg måned', weekPlaceholder: 'Velg uke', rangePlaceholder: ['Startdato', 'Sluttdato'], rangeYearPlaceholder: ['Startår', 'Sluttår'], rangeMonthPlaceholder: ['Startmåned', 'Sluttmåned'], rangeWeekPlaceholder: ['Start uke', 'Sluttuke'], ...CalendarLocale, }, timePickerLocale: { ...TimePickerLocale, }, }; // All settings at: // https://github.com/ant-design/ant-design/blob/master/components/date-picker/locale/example.json export default locale;
YaroShkvorets/ant-design-vue
plugin/docs/vueToMarkdown.ts
import path from 'path'; import LRUCache from 'lru-cache'; import slash from 'slash'; import fetchCode from '../md/utils/fetchCode'; // eslint-disable-next-line @typescript-eslint/no-var-requires const debug = require('debug')('vitepress:md'); const cache = new LRUCache<string, MarkdownCompileResult>({ max: 1024 }); interface MarkdownCompileResult { vueSrc: string; } export function createVueToMarkdownRenderFn(root: string = process.cwd()): any { return (src: string, file: string): MarkdownCompileResult => { const relativePath = slash(path.relative(root, file)); const cached = cache.get(src); if (cached) { debug(`[cache hit] ${relativePath}`); return cached; } const start = Date.now(); const docs = fetchCode(src, 'docs')?.trim(); const template = fetchCode(src, 'template'); const script = fetchCode(src, 'script'); const style = fetchCode(src, 'style'); const newContent = `${docs} \`\`\`vue ${template} ${script} ${style} \`\`\` `; debug(`[render] ${file} in ${Date.now() - start}ms.`); const result = { vueSrc: newContent?.trim(), ignore: !docs, }; cache.set(src, result); return result; }; }
YaroShkvorets/ant-design-vue
components/vc-tree/index.ts
<gh_stars>1000+ import type { TreeProps, TreeNodeProps } from './props'; import Tree from './Tree'; import TreeNode from './TreeNode'; export { TreeNode }; export type { TreeProps, TreeNodeProps }; export default Tree;
YaroShkvorets/ant-design-vue
components/vc-picker/panels/MonthPanel/MonthBody.tsx
import type { GenerateConfig } from '../../generate'; import type { Locale } from '../../interface'; import { formatValue, isSameMonth } from '../../utils/dateUtil'; import { useInjectRange } from '../../RangeContext'; import useCellClassName from '../../hooks/useCellClassName'; import PanelBody from '../PanelBody'; import type { VueNode } from '../../../_util/type'; import useMergeProps from '../../hooks/useMergeProps'; export const MONTH_COL_COUNT = 3; const MONTH_ROW_COUNT = 4; export type MonthCellRender<DateType> = (obj: { current: DateType; locale: Locale }) => VueNode; export type MonthBodyProps<DateType> = { prefixCls: string; locale: Locale; generateConfig: GenerateConfig<DateType>; value?: DateType | null; viewDate: DateType; disabledDate?: (date: DateType) => boolean; monthCellRender?: MonthCellRender<DateType>; onSelect: (value: DateType) => void; }; function MonthBody<DateType>(_props: MonthBodyProps<DateType>) { const props = useMergeProps(_props); const { prefixCls, locale, value, viewDate, generateConfig, monthCellRender } = props; const { rangedValue, hoverRangedValue } = useInjectRange(); const cellPrefixCls = `${prefixCls}-cell`; const getCellClassName = useCellClassName({ cellPrefixCls, value, generateConfig, rangedValue: rangedValue.value, hoverRangedValue: hoverRangedValue.value, isSameCell: (current, target) => isSameMonth(generateConfig, current, target), isInView: () => true, offsetCell: (date, offset) => generateConfig.addMonth(date, offset), }); const monthsLocale: string[] = locale.shortMonths || (generateConfig.locale.getShortMonths ? generateConfig.locale.getShortMonths(locale.locale) : []); const baseMonth = generateConfig.setMonth(viewDate, 0); const getCellNode = monthCellRender ? (date: DateType) => monthCellRender({ current: date, locale }) : undefined; return ( <PanelBody {...props} rowNum={MONTH_ROW_COUNT} colNum={MONTH_COL_COUNT} baseDate={baseMonth} getCellNode={getCellNode} getCellText={date => locale.monthFormat ? formatValue(date, { locale, format: locale.monthFormat, generateConfig, }) : monthsLocale[generateConfig.getMonth(date)] } getCellClassName={getCellClassName} getCellDate={generateConfig.addMonth} titleCell={date => formatValue(date, { locale, format: 'YYYY-MM', generateConfig, }) } /> ); } MonthBody.displayName = 'MonthBody'; MonthBody.inheritAttrs = false; export default MonthBody;
YaroShkvorets/ant-design-vue
components/vc-drawer/src/DrawerWrapper.tsx
<reponame>YaroShkvorets/ant-design-vue import Child from './DrawerChild'; import { initDefaultProps } from '../../_util/props-util'; import { defineComponent, ref } from 'vue'; import { drawerProps } from './IDrawerPropTypes'; import PortalWrapper from '../../_util/PortalWrapper'; const DrawerWrapper = defineComponent({ inheritAttrs: false, props: initDefaultProps(drawerProps(), { prefixCls: 'drawer', placement: 'left', getContainer: 'body', level: 'all', duration: '.3s', ease: 'cubic-bezier(0.78, 0.14, 0.15, 0.86)', afterVisibleChange: () => {}, showMask: true, maskClosable: true, maskStyle: {}, wrapperClassName: '', keyboard: true, forceRender: false, autofocus: true, }), emits: ['handleClick', 'close'], slots: ['handler'], setup(props, { emit, slots }) { const dom = ref<HTMLElement>(null); const onHandleClick = (e: MouseEvent | KeyboardEvent) => { emit('handleClick', e); }; const onClose = (e: MouseEvent | KeyboardEvent) => { emit('close', e); }; return () => { const { afterVisibleChange, getContainer, wrapperClassName, forceRender, ...otherProps } = props; let portal = null; if (!getContainer) { return ( <div class={wrapperClassName} ref={dom}> <Child v-slots={slots} {...otherProps} open={props.open} getContainer={() => dom.value} onClose={onClose} onHandleClick={onHandleClick} ></Child> </div> ); } // 如果有 handler 为内置强制渲染; const $forceRender = !!slots.handler || forceRender; if ($forceRender || props.open || dom.value) { portal = ( <PortalWrapper visible={props.open} forceRender={$forceRender} getContainer={getContainer} wrapperClassName={wrapperClassName} v-slots={{ default: ({ visible, afterClose, ...rest }) => ( <Child ref={dom} v-slots={slots} {...otherProps} {...rest} open={visible !== undefined ? visible : props.open} afterVisibleChange={ afterClose !== undefined ? afterClose : props.afterVisibleChange } onClose={onClose} onHandleClick={onHandleClick} /> ), }} ></PortalWrapper> ); } return portal; }; }, }); export default DrawerWrapper;
YaroShkvorets/ant-design-vue
components/vc-pagination/locale/pl_PL.ts
<gh_stars>1000+ export default { // Options.jsx items_per_page: 'na stronę', jump_to: 'Idź do', jump_to_confirm: 'potwierdź', page: '', // Pagination.jsx prev_page: 'Poprzednia strona', next_page: 'Następna strona', prev_5: 'Poprzednie 5 stron', next_5: 'Następne 5 stron', prev_3: 'Poprzednie 3 strony', next_3: 'Następne 3 strony', };
YaroShkvorets/ant-design-vue
components/_util/hooks/usePrefixCls.ts
<filename>components/_util/hooks/usePrefixCls.ts import type { ComputedRef } from 'vue'; import { computed, inject } from 'vue'; import { defaultConfigProvider } from '../../config-provider'; export default (name: string, props: Record<any, any>): ComputedRef<string> => { const configProvider = inject('configProvider', defaultConfigProvider); const prefixCls = computed(() => configProvider.getPrefixCls(name, props.prefixCls)); return prefixCls; };
YaroShkvorets/ant-design-vue
components/menu/src/SubMenuList.tsx
import classNames from '../../_util/classNames'; import type { FunctionalComponent } from 'vue'; import { useInjectMenu } from './hooks/useMenuContext'; const InternalSubMenuList: FunctionalComponent<any> = (_props, { slots, attrs }) => { const { prefixCls, mode } = useInjectMenu(); return ( <ul {...attrs} class={classNames( prefixCls.value, `${prefixCls.value}-sub`, `${prefixCls.value}-${mode.value === 'inline' ? 'inline' : 'vertical'}`, )} data-menu-list > {slots.default?.()} </ul> ); }; InternalSubMenuList.displayName = 'SubMenuList'; export default InternalSubMenuList;
YaroShkvorets/ant-design-vue
components/date-picker/locale/az_AZ.tsx
import CalendarLocale from '../../vc-picker/locale/az_AZ'; import TimePickerLocale from '../../time-picker/locale/az_AZ'; import type { PickerLocale } from '../generatePicker'; const locale: PickerLocale = { lang: { placeholder: 'Tarix seçin', rangePlaceholder: ['Başlama tarixi', 'Bitmə tarixi'], ...CalendarLocale, }, timePickerLocale: { ...TimePickerLocale, }, }; export default locale;
YaroShkvorets/ant-design-vue
components/vc-picker/utils/miscUtil.ts
<filename>components/vc-picker/utils/miscUtil.ts<gh_stars>1000+ export function leftPad(str: string | number, length: number, fill = '0') { let current = String(str); while (current.length < length) { current = `${fill}${str}`; } return current; } export const tuple = <T extends string[]>(...args: T) => args; export function toArray<T>(val: T | T[]): T[] { if (val === null || val === undefined) { return []; } return Array.isArray(val) ? val : [val]; } export default function getDataOrAriaProps(props: any) { const retProps: any = {}; Object.keys(props).forEach(key => { if ( (key.substr(0, 5) === 'data-' || key.substr(0, 5) === 'aria-' || key === 'role' || key === 'name') && key.substr(0, 7) !== 'data-__' ) { retProps[key] = props[key]; } }); return retProps; } export function getValue<T>(values: null | undefined | (T | null)[], index: number): T | null { return values ? values[index] : null; } type UpdateValue<T> = (prev: T) => T; export function updateValues<T, R = [T | null, T | null] | null>( values: [T | null, T | null] | null, value: T | UpdateValue<T>, index: number, ): R { const newValues: [T | null, T | null] = [getValue(values, 0), getValue(values, 1)]; newValues[index] = typeof value === 'function' ? (value as UpdateValue<T | null>)(newValues[index]) : value; if (!newValues[0] && !newValues[1]) { return null as unknown as R; } return newValues as unknown as R; }
YaroShkvorets/ant-design-vue
components/skeleton/index.tsx
<gh_stars>1000+ import type { App, Plugin } from 'vue'; import Skeleton from './Skeleton'; import SkeletonButton from './Button'; import SkeletonInput from './Input'; import SkeletonImage from './Image'; import SkeletonAvatar from './Avatar'; export type { SkeletonProps } from './Skeleton'; export { skeletonProps } from './Skeleton'; Skeleton.Button = SkeletonButton; Skeleton.Avatar = SkeletonAvatar; Skeleton.Input = SkeletonInput; Skeleton.Image = SkeletonImage; /* istanbul ignore next */ Skeleton.install = function (app: App) { app.component(Skeleton.name, Skeleton); app.component(Skeleton.Button.name, SkeletonButton); app.component(Skeleton.Avatar.name, SkeletonAvatar); app.component(Skeleton.Input.name, SkeletonInput); app.component(Skeleton.Image.name, SkeletonImage); return app; }; export { SkeletonButton, SkeletonAvatar, SkeletonInput, SkeletonImage }; export default Skeleton as typeof Skeleton & Plugin & { readonly Button: typeof SkeletonButton; readonly Avatar: typeof SkeletonAvatar; readonly Input: typeof SkeletonInput; readonly Image: typeof SkeletonImage; };
YaroShkvorets/ant-design-vue
components/vc-picker/panels/TimePanel/TimeUnitColumn.tsx
<gh_stars>1000+ import { scrollTo, waitElementReady } from '../../utils/uiUtil'; import { useInjectPanel } from '../../PanelContext'; import classNames from '../../../_util/classNames'; import { ref, onBeforeUnmount, watch, defineComponent, nextTick } from 'vue'; export type Unit = { label: any; value: number; disabled: boolean; }; export type TimeUnitColumnProps = { prefixCls?: string; units?: Unit[]; value?: number; active?: boolean; hideDisabledOptions?: boolean; onSelect?: (value: number) => void; }; export default defineComponent<TimeUnitColumnProps>({ name: 'TimeUnitColumn', props: ['prefixCls', 'units', 'onSelect', 'value', 'active', 'hideDisabledOptions'] as any, setup(props) { const { open } = useInjectPanel(); const ulRef = ref<HTMLUListElement>(null); const liRefs = ref<Map<number, HTMLElement | null>>(new Map()); const scrollRef = ref<Function>(); watch( () => props.value, () => { const li = liRefs.value.get(props.value!); if (li && open.value !== false) { scrollTo(ulRef.value!, li.offsetTop, 120); } }, ); onBeforeUnmount(() => { scrollRef.value?.(); }); watch( open, () => { scrollRef.value?.(); nextTick(() => { if (open.value) { const li = liRefs.value.get(props.value!); if (li) { scrollRef.value = waitElementReady(li, () => { scrollTo(ulRef.value!, li.offsetTop, 0); }); } } }); }, { immediate: true, flush: 'post' }, ); return () => { const { prefixCls, units, onSelect, value, active, hideDisabledOptions } = props; const cellPrefixCls = `${prefixCls}-cell`; return ( <ul class={classNames(`${prefixCls}-column`, { [`${prefixCls}-column-active`]: active, })} ref={ulRef} style={{ position: 'relative' }} > {units!.map(unit => { if (hideDisabledOptions && unit.disabled) { return null; } return ( <li key={unit.value} ref={element => { liRefs.value.set(unit.value, element as HTMLElement); }} class={classNames(cellPrefixCls, { [`${cellPrefixCls}-disabled`]: unit.disabled, [`${cellPrefixCls}-selected`]: value === unit.value, })} onClick={() => { if (unit.disabled) { return; } onSelect!(unit.value); }} > <div class={`${cellPrefixCls}-inner`}>{unit.label}</div> </li> ); })} </ul> ); }; }, });
YaroShkvorets/ant-design-vue
components/tabs/src/hooks/useOffsets.ts
import type { Ref } from 'vue'; import { ref, watchEffect } from 'vue'; import type { TabSizeMap, TabOffsetMap, Tab, TabOffset } from '../interface'; const DEFAULT_SIZE = { width: 0, height: 0, left: 0, top: 0 }; export default function useOffsets( tabs: Ref<Tab[]>, tabSizes: Ref<TabSizeMap>, // holderScrollWidth: Ref<number>, ): Ref<TabOffsetMap> { const offsetMap = ref<TabOffsetMap>(new Map()); watchEffect(() => { const map: TabOffsetMap = new Map(); const tabsValue = tabs.value; const lastOffset = tabSizes.value.get(tabsValue[0]?.key) || DEFAULT_SIZE; const rightOffset = lastOffset.left + lastOffset.width; for (let i = 0; i < tabsValue.length; i += 1) { const { key } = tabsValue[i]; let data = tabSizes.value.get(key); // Reuse last one when not exist yet if (!data) { data = tabSizes.value.get(tabsValue[i - 1]?.key) || DEFAULT_SIZE; } const entity = (map.get(key) || { ...data }) as TabOffset; // Right entity.right = rightOffset - entity.left - entity.width; // Update entity map.set(key, entity); } offsetMap.value = new Map(map); }); return offsetMap; }
YaroShkvorets/ant-design-vue
site/src/SymbolKey.ts
export const GLOBAL_CONFIG = Symbol('globalConfig');
YaroShkvorets/ant-design-vue
components/table/index.tsx
import Table, { tableProps } from './Table'; import Column from './Column'; import ColumnGroup from './ColumnGroup'; import type { TableProps, TablePaginationConfig } from './Table'; import { defineComponent } from 'vue'; import type { App } from 'vue'; import { Summary, SummaryCell, SummaryRow } from '../vc-table'; import { SELECTION_ALL, SELECTION_INVERT, SELECTION_NONE } from './hooks/useSelection'; export type { ColumnProps } from './Column'; export type { ColumnsType, ColumnType, ColumnGroupType } from './interface'; export type { TableProps, TablePaginationConfig }; const TableSummaryRow = defineComponent({ ...SummaryRow, name: 'ATableSummaryRow' }); const TableSummaryCell = defineComponent({ ...SummaryCell, name: 'ATableSummaryCell' }); const TempSummary = defineComponent({ ...Summary, name: 'ATableSummary', }); const TableSummary = TempSummary as typeof TempSummary & { Cell: typeof TableSummaryCell; Row: typeof TableSummaryRow; }; TableSummary.Cell = TableSummaryCell; TableSummary.Row = TableSummaryRow; const T = Table as typeof Table & Plugin & { Column: typeof Column; ColumnGroup: typeof ColumnGroup; Summary: typeof TableSummary; SELECTION_ALL: typeof SELECTION_ALL; SELECTION_INVERT: typeof SELECTION_INVERT; SELECTION_NONE: typeof SELECTION_NONE; }; T.SELECTION_ALL = SELECTION_ALL; T.SELECTION_INVERT = SELECTION_INVERT; T.SELECTION_NONE = SELECTION_NONE; T.Column = Column; T.ColumnGroup = ColumnGroup; T.Summary = TableSummary; /* istanbul ignore next */ T.install = function (app: App) { app.component(TableSummary.name, TableSummary); app.component(TableSummaryCell.name, TableSummaryCell); app.component(TableSummaryRow.name, TableSummaryRow); app.component(T.name, T); app.component(T.Column.name, Column); app.component(T.ColumnGroup.name, ColumnGroup); return app; }; export { tableProps, TableSummary, TableSummaryRow, TableSummaryCell, Column as TableColumn, ColumnGroup as TableColumnGroup, }; export default T;
YaroShkvorets/ant-design-vue
components/col/index.ts
import { Col } from '../grid'; import { withInstall } from '../_util/type'; export type { ColProps } from '../grid'; export default withInstall(Col);
YaroShkvorets/ant-design-vue
components/table/util.ts
<reponame>YaroShkvorets/ant-design-vue import { camelize } from 'vue'; import { flattenChildren } from '../_util/props-util'; import type { ColumnType, ColumnsType, ColumnTitle, ColumnTitleProps, Key } from './interface'; export function getColumnKey<RecordType>(column: ColumnType<RecordType>, defaultKey: string): Key { if ('key' in column && column.key !== undefined && column.key !== null) { return column.key; } if (column.dataIndex) { return (Array.isArray(column.dataIndex) ? column.dataIndex.join('.') : column.dataIndex) as Key; } return defaultKey; } export function getColumnPos(index: number, pos?: string) { return pos ? `${pos}-${index}` : `${index}`; } export function renderColumnTitle<RecordType>( title: ColumnTitle<RecordType>, props: ColumnTitleProps<RecordType>, ) { if (typeof title === 'function') { return title(props); } return title; } export function convertChildrenToColumns<RecordType>( elements: any[] = [], ): ColumnsType<RecordType> { const flattenElements = flattenChildren(elements); const columns = []; flattenElements.forEach(element => { if (!element) { return; } const key = element.key; const style = element.props?.style || {}; const cls = element.props?.class || ''; const props = element.props || {}; for (const [k, v] of Object.entries(props)) { props[camelize(k)] = v; } const { default: children, ...restSlots } = element.children || {}; const column = { ...restSlots, ...props, style, class: cls }; if (key) { column.key = key; } if (element.type?.__ANT_TABLE_COLUMN_GROUP) { column.children = convertChildrenToColumns( typeof children === 'function' ? children() : children, ); } else { const customRender = element.children?.default; column.customRender = column.customRender || customRender; } columns.push(column); }); return columns; }
YaroShkvorets/ant-design-vue
components/table/hooks/useLazyKVMap.ts
<filename>components/table/hooks/useLazyKVMap.ts import type { Ref } from 'vue'; import { watch, shallowRef } from 'vue'; import type { Key, GetRowKey } from '../interface'; interface MapCache<RecordType> { kvMap?: Map<Key, RecordType>; } export default function useLazyKVMap<RecordType>( dataRef: Ref<readonly RecordType[]>, childrenColumnNameRef: Ref<string>, getRowKeyRef: Ref<GetRowKey<RecordType>>, ) { const mapCacheRef = shallowRef<MapCache<RecordType>>({}); watch( [dataRef, childrenColumnNameRef, getRowKeyRef], () => { const kvMap = new Map<Key, RecordType>(); const getRowKey = getRowKeyRef.value; const childrenColumnName = childrenColumnNameRef.value; /* eslint-disable no-inner-declarations */ function dig(records: readonly RecordType[]) { records.forEach((record, index) => { const rowKey = getRowKey(record, index); kvMap.set(rowKey, record); if (record && typeof record === 'object' && childrenColumnName in record) { dig((record as any)[childrenColumnName] || []); } }); } /* eslint-enable */ dig(dataRef.value); mapCacheRef.value = { kvMap, }; }, { deep: false, immediate: true, }, ); function getRecordByKey(key: Key): RecordType { return mapCacheRef.value.kvMap!.get(key)!; } return [getRecordByKey]; }
YaroShkvorets/ant-design-vue
components/vc-pagination/locale/gl_ES.ts
<gh_stars>1000+ export default { // Options.jsx items_per_page: '/ páxina', jump_to: 'Ir a', jump_to_confirm: 'confirmar', page: '', // Pagination.jsx prev_page: 'Páxina anterior', next_page: 'Páxina seguinte', prev_5: '5 páxinas previas', next_5: '5 páxinas seguintes', prev_3: '3 páxinas previas', next_3: '3 páxinas seguintes', };
YaroShkvorets/ant-design-vue
components/vc-overflow/context.ts
import type { ComputedRef, InjectionKey, PropType } from 'vue'; import { computed, defineComponent, inject, provide } from 'vue'; import type { Key } from '../_util/type'; export interface OverflowContextProviderValueType { prefixCls: string; responsive: boolean; order: number; registerSize: (key: Key, width: number | null) => void; display: boolean; invalidate: boolean; // Item Usage item?: any; itemKey?: Key; // Rest Usage className?: string; } const OverflowContextProviderKey: InjectionKey< ComputedRef<OverflowContextProviderValueType | null> > = Symbol('OverflowContextProviderKey'); export const OverflowContextProvider = defineComponent({ name: 'OverflowContextProvider', inheritAttrs: false, props: { value: { type: Object as PropType<OverflowContextProviderValueType> }, }, setup(props, { slots }) { provide( OverflowContextProviderKey, computed(() => props.value), ); return () => slots.default?.(); }, }); export const useInjectOverflowContext = (): ComputedRef<OverflowContextProviderValueType | null> => { return inject( OverflowContextProviderKey, computed(() => null), ); };
YaroShkvorets/ant-design-vue
components/vc-picker/RangeContext.tsx
<reponame>YaroShkvorets/ant-design-vue<filename>components/vc-picker/RangeContext.tsx import type { InjectionKey, PropType, Ref } from 'vue'; import { defineComponent, inject, provide, ref, toRef, watch } from 'vue'; import type { NullableDateType, RangeValue } from './interface'; export type RangeContextProps = { /** * Set displayed range value style. * Panel only has one value, this is only style effect. */ rangedValue?: Ref<[NullableDateType<any>, NullableDateType<any>] | null>; hoverRangedValue?: Ref<RangeValue<any>>; inRange?: Ref<boolean>; panelPosition?: Ref<'left' | 'right' | false>; }; type RangeContextProviderValue = { /** * Set displayed range value style. * Panel only has one value, this is only style effect. */ rangedValue?: [NullableDateType<any>, NullableDateType<any>] | null; hoverRangedValue?: RangeValue<any>; inRange?: boolean; panelPosition?: 'left' | 'right' | false; }; const RangeContextKey: InjectionKey<RangeContextProps> = Symbol('RangeContextProps'); export const useProvideRange = (props: RangeContextProps) => { provide(RangeContextKey, props); }; export const useInjectRange = () => { return inject(RangeContextKey, { rangedValue: ref(), hoverRangedValue: ref(), inRange: ref(), panelPosition: ref(), }); }; export const RangeContextProvider = defineComponent({ name: 'PanelContextProvider', inheritAttrs: false, props: { value: { type: Object as PropType<RangeContextProviderValue>, default: () => ({} as RangeContextProviderValue), }, }, setup(props, { slots }) { const value: RangeContextProps = { rangedValue: ref(props.value.rangedValue), hoverRangedValue: ref(props.value.hoverRangedValue), inRange: ref(props.value.inRange), panelPosition: ref(props.value.panelPosition), }; useProvideRange(value); toRef; watch( () => props.value, () => { Object.keys(props.value).forEach(key => { if (value[key]) { value[key].value = props.value[key]; } }); }, ); return () => slots.default?.(); }, }); export default RangeContextKey;
YaroShkvorets/ant-design-vue
components/vc-table/hooks/useSticky.ts
<gh_stars>1000+ import canUseDom from '../../_util/canUseDom'; import type { ComputedRef, Ref } from 'vue'; import { computed } from 'vue'; import type { TableSticky } from '../interface'; // fix ssr render const defaultContainer = canUseDom() ? window : null; /** Sticky header hooks */ export default function useSticky( stickyRef: Ref<boolean | TableSticky>, prefixClsRef: Ref<string>, ): ComputedRef<{ isSticky: boolean; offsetHeader: number; offsetSummary: number; offsetScroll: number; stickyClassName: string; container: Window | HTMLElement; }> { return computed(() => { const { offsetHeader = 0, offsetSummary = 0, offsetScroll = 0, getContainer = () => defaultContainer, } = typeof stickyRef.value === 'object' ? stickyRef.value : {}; const container = getContainer() || defaultContainer; const isSticky = !!stickyRef.value; return { isSticky, stickyClassName: isSticky ? `${prefixClsRef.value}-sticky-holder` : '', offsetHeader, offsetSummary, offsetScroll, container, }; }); }
YaroShkvorets/ant-design-vue
components/vc-resize-observer/index.tsx
// based on rc-resize-observer 1.0.0 import type { PropType } from 'vue'; import ResizeObserver from 'resize-observer-polyfill'; import { defineComponent, getCurrentInstance, onMounted, onUnmounted, onUpdated, reactive, watch, } from 'vue'; import { findDOMNode } from '../_util/props-util'; interface ResizeObserverState { height: number; width: number; offsetHeight: number; offsetWidth: number; } export default defineComponent({ name: 'ResizeObserver', props: { disabled: Boolean, onResize: Function as PropType< ( size: { width: number; height: number; offsetWidth: number; offsetHeight: number; }, element: HTMLElement, ) => void >, }, emits: ['resize'], setup(props, { slots }) { const state = reactive<ResizeObserverState>({ width: 0, height: 0, offsetHeight: 0, offsetWidth: 0, }); let currentElement: Element | null = null; let resizeObserver: ResizeObserver | null = null; const destroyObserver = () => { if (resizeObserver) { resizeObserver.disconnect(); resizeObserver = null; } }; const onResize: ResizeObserverCallback = (entries: ResizeObserverEntry[]) => { const { onResize } = props; const target = entries[0].target as HTMLElement; const { width, height } = target.getBoundingClientRect(); const { offsetWidth, offsetHeight } = target; /** * Resize observer trigger when content size changed. * In most case we just care about element size, * let's use `boundary` instead of `contentRect` here to avoid shaking. */ const fixedWidth = Math.floor(width); const fixedHeight = Math.floor(height); if ( state.width !== fixedWidth || state.height !== fixedHeight || state.offsetWidth !== offsetWidth || state.offsetHeight !== offsetHeight ) { const size = { width: fixedWidth, height: fixedHeight, offsetWidth, offsetHeight }; Object.assign(state, size); if (onResize) { // defer the callback but not defer to next frame Promise.resolve().then(() => { onResize( { ...size, offsetWidth, offsetHeight, }, target, ); }); } } }; const instance = getCurrentInstance(); const registerObserver = () => { const { disabled } = props; // Unregister if disabled if (disabled) { destroyObserver(); return; } // Unregister if element changed const element = findDOMNode(instance) as Element; const elementChanged = element !== currentElement; if (elementChanged) { destroyObserver(); currentElement = element; } if (!resizeObserver && element) { resizeObserver = new ResizeObserver(onResize); resizeObserver.observe(element); } }; onMounted(() => { registerObserver(); }); onUpdated(() => { registerObserver(); }); onUnmounted(() => { destroyObserver(); }); watch( () => props.disabled, () => { registerObserver(); }, { flush: 'post' }, ); return () => { return slots.default?.()[0]; }; }, });
YaroShkvorets/ant-design-vue
components/date-picker/util.ts
<filename>components/date-picker/util.ts import type { PickerMode } from '../vc-picker/interface'; import type { PickerLocale } from './generatePicker'; export function getPlaceholder( picker: PickerMode | undefined, locale: PickerLocale, customizePlaceholder?: string, ): string { if (customizePlaceholder !== undefined) { return customizePlaceholder; } if (picker === 'year' && locale.lang.yearPlaceholder) { return locale.lang.yearPlaceholder; } if (picker === 'quarter' && locale.lang.quarterPlaceholder) { return locale.lang.quarterPlaceholder; } if (picker === 'month' && locale.lang.monthPlaceholder) { return locale.lang.monthPlaceholder; } if (picker === 'week' && locale.lang.weekPlaceholder) { return locale.lang.weekPlaceholder; } if (picker === 'time' && locale.timePickerLocale.placeholder) { return locale!.timePickerLocale.placeholder; } return locale.lang.placeholder; } export function getRangePlaceholder( picker: PickerMode | undefined, locale: PickerLocale, customizePlaceholder?: [string, string], ) { if (customizePlaceholder !== undefined) { return customizePlaceholder; } if (picker === 'year' && locale.lang.yearPlaceholder) { return locale.lang.rangeYearPlaceholder; } if (picker === 'month' && locale.lang.monthPlaceholder) { return locale.lang.rangeMonthPlaceholder; } if (picker === 'week' && locale.lang.weekPlaceholder) { return locale.lang.rangeWeekPlaceholder; } if (picker === 'time' && locale.timePickerLocale.placeholder) { return locale!.timePickerLocale.rangePlaceholder; } return locale.lang.rangePlaceholder; }
YaroShkvorets/ant-design-vue
components/radio/Group.tsx
import { provide, nextTick, defineComponent, ref, watch } from 'vue'; import type { PropType, ExtractPropTypes } from 'vue'; import classNames from '../_util/classNames'; import PropTypes from '../_util/vue-types'; import Radio from './Radio'; import useConfigInject from '../_util/hooks/useConfigInject'; import { tuple } from '../_util/type'; import type { RadioChangeEvent } from './interface'; import { useInjectFormItemContext } from '../form/FormItemContext'; const RadioGroupSizeTypes = tuple('large', 'default', 'small'); export type RadioGroupSize = typeof RadioGroupSizeTypes[number]; const RadioGroupOptionTypes = tuple('default', 'button'); export type RadioGroupOption = typeof RadioGroupOptionTypes[number]; export type RadioGroupChildOption = { label: any; value: any; disabled?: boolean; }; const radioGroupProps = { prefixCls: PropTypes.string, value: PropTypes.any, size: PropTypes.oneOf(RadioGroupSizeTypes).def('default'), options: { type: Array as PropType<Array<String | RadioGroupChildOption>>, }, disabled: PropTypes.looseBool, name: PropTypes.string, buttonStyle: PropTypes.string.def('outline'), id: PropTypes.string, optionType: PropTypes.oneOf(RadioGroupOptionTypes).def('default'), }; export type RadioGroupProps = Partial<ExtractPropTypes<typeof radioGroupProps>>; export default defineComponent({ name: 'ARadioGroup', props: radioGroupProps, emits: ['update:value', 'change'], setup(props, { slots, emit }) { const formItemContext = useInjectFormItemContext(); const { prefixCls, direction, size } = useConfigInject('radio', props); const stateValue = ref(props.value); const updatingValue = ref<boolean>(false); watch( () => props.value, val => { stateValue.value = val; updatingValue.value = false; }, ); const onRadioChange = (ev: RadioChangeEvent) => { const lastValue = stateValue.value; const { value } = ev.target; if (!('value' in props)) { stateValue.value = value; } // nextTick for https://github.com/vueComponent/ant-design-vue/issues/1280 if (!updatingValue.value && value !== lastValue) { updatingValue.value = true; emit('update:value', value); emit('change', ev); formItemContext.onFieldChange(); } nextTick(() => { updatingValue.value = false; }); }; provide('radioGroupContext', { onRadioChange, stateValue, props, }); return () => { const { options, optionType, buttonStyle, id = formItemContext.id.value } = props; const groupPrefixCls = `${prefixCls.value}-group`; const classString = classNames(groupPrefixCls, `${groupPrefixCls}-${buttonStyle}`, { [`${groupPrefixCls}-${size.value}`]: size.value, [`${groupPrefixCls}-rtl`]: direction.value === 'rtl', }); let children = null; if (options && options.length > 0) { const optionsPrefixCls = optionType === 'button' ? `${prefixCls.value}-button` : prefixCls.value; children = options.map(option => { if (typeof option === 'string') { return ( <Radio key={option} prefixCls={optionsPrefixCls} disabled={props.disabled} value={option} checked={stateValue.value === option} > {option} </Radio> ); } const { value, disabled, label } = option as RadioGroupChildOption; return ( <Radio key={`radio-group-value-options-${value}`} prefixCls={optionsPrefixCls} disabled={disabled || props.disabled} value={value} checked={stateValue.value === value} > {label} </Radio> ); }); } else { children = slots.default?.(); } return ( <div class={classString} id={id}> {children} </div> ); }; }, });
YaroShkvorets/ant-design-vue
components/transfer/ListBody.tsx
<gh_stars>1000+ import type { ExtractPropTypes } from 'vue'; import { defineComponent, computed, ref, watch } from 'vue'; import classNames from '../_util/classNames'; import ListItem from './ListItem'; import Pagination from '../pagination'; import PropTypes from '../_util/vue-types'; import type { TransferItem } from '.'; export const transferListBodyProps = { prefixCls: PropTypes.string, filteredRenderItems: PropTypes.array.def([]), selectedKeys: PropTypes.array, disabled: PropTypes.looseBool, showRemove: PropTypes.looseBool, pagination: PropTypes.any, onItemSelect: PropTypes.func, onScroll: PropTypes.func, onItemRemove: PropTypes.func, }; export type TransferListBodyProps = Partial<ExtractPropTypes<typeof transferListBodyProps>>; function parsePagination(pagination) { if (!pagination) { return null; } const defaultPagination = { pageSize: 10, }; if (typeof pagination === 'object') { return { ...defaultPagination, ...pagination, }; } return defaultPagination; } const ListBody = defineComponent({ name: 'ListBody', inheritAttrs: false, props: transferListBodyProps, emits: ['itemSelect', 'itemRemove', 'scroll'], setup(props, { emit, expose }) { const current = ref(1); const handleItemSelect = (item: TransferItem) => { const { selectedKeys } = props; const checked = selectedKeys.indexOf(item.key) >= 0; emit('itemSelect', item.key, !checked); }; const handleItemRemove = (item: TransferItem) => { emit('itemRemove', item.key); }; const handleScroll = (e: Event) => { emit('scroll', e); }; const mergedPagination = computed(() => parsePagination(props.pagination)); watch( [mergedPagination, () => props.filteredRenderItems], () => { if (mergedPagination.value) { // Calculate the page number const maxPageCount = Math.ceil( props.filteredRenderItems.length / mergedPagination.value.pageSize, ); if (current.value > maxPageCount) { current.value = maxPageCount; } } }, { immediate: true }, ); const items = computed(() => { const { filteredRenderItems } = props; let displayItems = filteredRenderItems; if (mergedPagination.value) { displayItems = filteredRenderItems.slice( (current.value - 1) * mergedPagination.value.pageSize, current.value * mergedPagination.value.pageSize, ); } return displayItems; }); const onPageChange = (cur: number) => { current.value = cur; }; expose({ items }); return () => { const { prefixCls, filteredRenderItems, selectedKeys, disabled: globalDisabled, showRemove, } = props; let paginationNode = null; if (mergedPagination.value) { paginationNode = ( <Pagination simple size="small" disabled={globalDisabled} class={`${prefixCls}-pagination`} total={filteredRenderItems.length} pageSize={mergedPagination.value.pageSize} current={current.value} onChange={onPageChange} /> ); } const itemsList = items.value.map(({ renderedEl, renderedText, item }: any) => { const { disabled } = item; const checked = selectedKeys.indexOf(item.key) >= 0; return ( <ListItem disabled={globalDisabled || disabled} key={item.key} item={item} renderedText={renderedText} renderedEl={renderedEl} checked={checked} prefixCls={prefixCls} onClick={handleItemSelect} onRemove={handleItemRemove} showRemove={showRemove} /> ); }); return ( <> <ul class={classNames(`${prefixCls}-content`, { [`${prefixCls}-content-show-remove`]: showRemove, })} onScroll={handleScroll} > {itemsList} </ul> {paginationNode} </> ); }; }, }); export default ListBody;
YaroShkvorets/ant-design-vue
components/vc-virtual-list/hooks/useHeights.tsx
<reponame>YaroShkvorets/ant-design-vue import type { VNodeProps } from 'vue'; import { reactive } from 'vue'; import type { GetKey } from '../interface'; type CacheMap = Record<string, number>; export default function useHeights<T>( getKey: GetKey<T>, onItemAdd?: ((item: T) => void) | null, onItemRemove?: ((item: T) => void) | null, ): [(item: T, instance: HTMLElement) => void, () => void, CacheMap] { const instance = new Map<VNodeProps['key'], HTMLElement>(); const heights = reactive({}); let heightUpdateId = 0; function collectHeight() { heightUpdateId += 1; const currentId = heightUpdateId; Promise.resolve().then(() => { // Only collect when it's latest call if (currentId !== heightUpdateId) return; // let changed = false; instance.forEach((element, key) => { if (element && element.offsetParent) { const { offsetHeight } = element; if (heights[key!] !== offsetHeight) { //changed = true; heights[key!] = element.offsetHeight; } } }); }); } function setInstance(item: T, ins: HTMLElement) { const key = getKey(item); const origin = instance.get(key); if (ins) { instance.set(key, (ins as any).$el || ins); collectHeight(); } else { instance.delete(key); } // Instance changed if (!origin !== !ins) { if (ins) { onItemAdd?.(item); } else { onItemRemove?.(item); } } } return [setInstance, collectHeight, heights]; }
YaroShkvorets/ant-design-vue
components/_util/hooks/useFlexGapSupport.ts
<gh_stars>1000+ import { onMounted, ref } from 'vue'; import { detectFlexGapSupported } from '../styleChecker'; export default () => { const flexible = ref(false); onMounted(() => { flexible.value = detectFlexGapSupported(); }); return flexible; };
YaroShkvorets/ant-design-vue
site/src/typings.d.ts
interface Window { docsearch: any; notBlockEnabled: any; } interface Header { level: number; title: string; slug: string; content: string; } interface PageData { title: string; description: string; headers: Header[]; frontmatter: Record<string, any>; } declare module '*.md' { import type { DefineComponent } from 'vue'; // eslint-disable-next-line @typescript-eslint/ban-types const component: DefineComponent<any, any, any> & { readonly pageDate?: PageData }; export default component; } declare module '*.svg';
YaroShkvorets/ant-design-vue
components/vc-pagination/locale/ja_JP.ts
export default { // Options.jsx items_per_page: '件 / ページ', jump_to: '移動', jump_to_confirm: '確認する', page: 'ページ', // Pagination.jsx prev_page: '前のページ', next_page: '次のページ', prev_5: '前 5ページ', next_5: '次 5ページ', prev_3: '前 3ページ', next_3: '次 3ページ', };
YaroShkvorets/ant-design-vue
components/vc-slider/src/common/Steps.tsx
import type { CSSProperties } from 'vue'; import classNames from '../../../_util/classNames'; import type { VueNode } from '../../../_util/type'; import warning from '../../../_util/warning'; const calcPoints = ( _vertical: boolean, marks: Record<number, VueNode | { style?: CSSProperties; label?: string }>, dots: boolean, step: number, min: number, max: number, ) => { warning( dots ? step > 0 : true, 'Slider', '`Slider[step]` should be a positive number in order to make Slider[dots] work.', ); const points = Object.keys(marks) .map(parseFloat) .sort((a, b) => a - b); if (dots && step) { for (let i = min; i <= max; i += step) { if (points.indexOf(i) === -1) { points.push(i); } } } return points; }; const Steps = (_: any, { attrs }) => { const { prefixCls, vertical, reverse, marks, dots, step, included, lowerBound, upperBound, max, min, dotStyle, activeDotStyle, } = attrs; const range = max - min; const elements = calcPoints(vertical, marks, dots, step, min, max).map(point => { const offset = `${(Math.abs(point - min) / range) * 100}%`; const isActived = (!included && point === upperBound) || (included && point <= upperBound && point >= lowerBound); let style = vertical ? { ...dotStyle, [reverse ? 'top' : 'bottom']: offset } : { ...dotStyle, [reverse ? 'right' : 'left']: offset }; if (isActived) { style = { ...style, ...activeDotStyle }; } const pointClassName = classNames({ [`${prefixCls}-dot`]: true, [`${prefixCls}-dot-active`]: isActived, [`${prefixCls}-dot-reverse`]: reverse, }); return <span class={pointClassName} style={style} key={point} />; }); return <div class={`${prefixCls}-step`}>{elements}</div>; }; Steps.inheritAttrs = false; export default Steps;
YaroShkvorets/ant-design-vue
components/progress/Circle.tsx
<reponame>YaroShkvorets/ant-design-vue import type { CSSProperties } from 'vue'; import { computed, defineComponent } from 'vue'; import { presetPrimaryColors } from '@ant-design/colors'; import { Circle as VCCircle } from '../vc-progress'; import { getSuccessPercent, validProgress } from './utils'; import type { ProgressProps } from './props'; import { progressProps } from './props'; export type CircleProps = ProgressProps; function getPercentage({ percent, success, successPercent }: CircleProps) { const realSuccessPercent = validProgress(getSuccessPercent({ success, successPercent })); return [realSuccessPercent, validProgress(validProgress(percent) - realSuccessPercent)]; } export default defineComponent({ inheritAttrs: false, props: progressProps(), setup(props, { slots }) { const gapDeg = computed(() => { // Support gapDeg = 0 when type = 'dashboard' if (props.gapDegree || props.gapDegree === 0) { return props.gapDegree; } if (props.type === 'dashboard') { return 75; } return undefined; }); const circleStyle = computed<CSSProperties>(() => { const circleSize = props.width || 120; return { width: typeof circleSize === 'number' ? `${circleSize}px` : circleSize, height: typeof circleSize === 'number' ? `${circleSize}px` : circleSize, fontSize: `${circleSize * 0.15 + 6}px`, }; }); const circleWidth = computed(() => props.strokeWidth || 6); const gapPos = computed( () => props.gapPosition || (props.type === 'dashboard' && 'bottom') || 'top', ); // using className to style stroke color const strokeColor = computed(() => [presetPrimaryColors.green, props.strokeColor || null]); const percent = computed(() => getPercentage(props)); const isGradient = computed( () => Object.prototype.toString.call(props.strokeColor) === '[object Object]', ); const wrapperClassName = computed(() => ({ [`${props.prefixCls}-inner`]: true, [`${props.prefixCls}-circle-gradient`]: isGradient.value, })); return () => ( <div class={wrapperClassName.value} style={circleStyle.value}> <VCCircle percent={percent.value} strokeWidth={circleWidth.value} trailWidth={circleWidth.value} strokeColor={strokeColor.value} strokeLinecap={props.strokeLinecap} trailColor={props.trailColor} prefixCls={props.prefixCls} gapDegree={gapDeg.value} gapPosition={gapPos.value} /> {slots.default?.()} </div> ); }, });
YaroShkvorets/ant-design-vue
components/vc-table/context/TableContext.tsx
<reponame>YaroShkvorets/ant-design-vue import type { InjectionKey } from 'vue'; import { inject, provide } from 'vue'; import type { GetComponent, TransformCellText } from '../interface'; import type { FixedInfo } from '../utils/fixUtil'; export interface TableContextProps { // Table context prefixCls: string; getComponent: GetComponent; scrollbarSize: number; direction: 'ltr' | 'rtl'; fixedInfoList: readonly FixedInfo[]; isSticky: boolean; summaryCollect: (uniKey: string, fixed: boolean | string) => void; transformCellText: TransformCellText<unknown>; } export const TableContextKey: InjectionKey<TableContextProps> = Symbol('TableContextProps'); export const useProvideTable = (props: TableContextProps) => { provide(TableContextKey, props); }; export const useInjectTable = () => { return inject(TableContextKey, {} as TableContextProps); };
YaroShkvorets/ant-design-vue
components/divider/index.tsx
import { flattenChildren } from '../_util/props-util'; import type { ExtractPropTypes, PropType } from 'vue'; import { computed, defineComponent, inject } from 'vue'; import { defaultConfigProvider } from '../config-provider'; import { withInstall } from '../_util/type'; export const dividerProps = { prefixCls: String, type: { type: String as PropType<'horizontal' | 'vertical' | ''>, default: 'horizontal', }, dashed: { type: Boolean, default: false, }, orientation: { type: String as PropType<'left' | 'right' | 'center'>, default: 'center', }, plain: { type: Boolean, default: false, }, }; export type DividerProps = Partial<ExtractPropTypes<typeof dividerProps>>; const Divider = defineComponent({ name: 'ADivider', props: dividerProps, setup(props, { slots }) { const configProvider = inject('configProvider', defaultConfigProvider); const prefixClsRef = computed(() => configProvider.getPrefixCls('divider', props.prefixCls)); const classString = computed(() => { const { type, dashed, plain } = props; const prefixCls = prefixClsRef.value; return { [prefixCls]: true, [`${prefixCls}-${type}`]: true, [`${prefixCls}-dashed`]: !!dashed, [`${prefixCls}-plain`]: !!plain, [`${prefixCls}-rtl`]: configProvider.direction === 'rtl', }; }); const orientationPrefix = computed(() => props.orientation.length > 0 ? '-' + props.orientation : props.orientation, ); return () => { const children = flattenChildren(slots.default?.()); return ( <div class={[ classString.value, children.length ? `${prefixClsRef.value}-with-text ${prefixClsRef.value}-with-text${orientationPrefix.value}` : '', ]} role="separator" > {children.length ? ( <span class={`${prefixClsRef.value}-inner-text`}>{children}</span> ) : null} </div> ); }; }, }); export default withInstall(Divider);
YaroShkvorets/ant-design-vue
components/vc-dropdown/Dropdown.tsx
import { computed, defineComponent, ref, watch } from 'vue'; import PropTypes from '../_util/vue-types'; import Trigger from '../vc-trigger'; import placements from './placements'; import { cloneElement } from '../_util/vnode'; import classNames from '../_util/classNames'; export default defineComponent({ props: { minOverlayWidthMatchTrigger: PropTypes.looseBool, arrow: PropTypes.looseBool.def(false), prefixCls: PropTypes.string.def('rc-dropdown'), transitionName: PropTypes.string, overlayClassName: PropTypes.string.def(''), openClassName: PropTypes.string, animation: PropTypes.any, align: PropTypes.object, overlayStyle: PropTypes.style, placement: PropTypes.string.def('bottomLeft'), overlay: PropTypes.any, trigger: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]).def( 'hover', ), alignPoint: PropTypes.looseBool, showAction: PropTypes.array, hideAction: PropTypes.array, getPopupContainer: PropTypes.func, visible: PropTypes.looseBool, defaultVisible: PropTypes.looseBool.def(false), mouseEnterDelay: PropTypes.number.def(0.15), mouseLeaveDelay: PropTypes.number.def(0.1), }, emits: ['visibleChange', 'overlayClick'], slots: ['overlay'], setup(props, { slots, emit, expose }) { const triggerVisible = ref(!!props.visible); watch( () => props.visible, val => { if (val !== undefined) { triggerVisible.value = val; } }, ); const triggerRef = ref(); expose({ triggerRef, }); const onClick = (e: MouseEvent) => { if (props.visible === undefined) { triggerVisible.value = false; } emit('overlayClick', e); }; const onVisibleChange = (visible: boolean) => { if (props.visible === undefined) { triggerVisible.value = visible; } emit('visibleChange', visible); }; const getMenuElement = () => { const overlayElement = slots.overlay?.(); const extraOverlayProps = { prefixCls: `${props.prefixCls}-menu`, onClick, getPopupContainer: () => triggerRef.value.getPopupDomNode(), }; return ( <> {props.arrow && <div class={`${props.prefixCls}-arrow`} />} {cloneElement(overlayElement, extraOverlayProps, false)} </> ); }; const minOverlayWidthMatchTrigger = computed(() => { const { minOverlayWidthMatchTrigger: matchTrigger = !props.alignPoint } = props; return matchTrigger; }); const renderChildren = () => { const children = slots.default?.(); return triggerVisible.value && children ? cloneElement( children[0], { class: props.openClassName || `${props.prefixCls}-open` }, false, ) : children; }; const triggerHideAction = computed(() => { if (!props.hideAction && props.trigger.indexOf('contextmenu') !== -1) { return ['click']; } return props.hideAction; }); return () => { const { prefixCls, arrow, showAction, overlayStyle, trigger, placement, align, getPopupContainer, transitionName, animation, overlayClassName, ...otherProps } = props; return ( <Trigger {...otherProps} prefixCls={prefixCls} ref={triggerRef} popupClassName={classNames(overlayClassName, { [`${prefixCls}-show-arrow`]: arrow, })} popupStyle={overlayStyle} builtinPlacements={placements} action={trigger} showAction={showAction} hideAction={triggerHideAction.value || []} popupPlacement={placement} popupAlign={align} popupTransitionName={transitionName} popupAnimation={animation} popupVisible={triggerVisible.value} stretch={minOverlayWidthMatchTrigger.value ? 'minWidth' : ''} onPopupVisibleChange={onVisibleChange} getPopupContainer={getPopupContainer} v-slots={{ popup: getMenuElement, default: renderChildren }} ></Trigger> ); }; }, });
YaroShkvorets/ant-design-vue
plugin/md/index.ts
import { createMarkdownToVueRenderFn } from './markdownToVue'; import type { MarkdownOptions } from './markdown/markdown'; import type { Plugin } from 'vite'; interface Options { root?: string; markdown?: MarkdownOptions; } export default (options: Options = {}): Plugin => { const { root, markdown } = options; const markdownToVue = createMarkdownToVueRenderFn(root, markdown); return { name: 'mdToVue', transform(code, id) { if (id.endsWith('.md')) { // transform .md files into vueSrc so plugin-vue can handle it return { code: markdownToVue(code, id).vueSrc, map: null }; } }, }; };
YaroShkvorets/ant-design-vue
components/vc-picker/utils/dateUtil.ts
import { DECADE_UNIT_DIFF } from '../panels/DecadePanel/index'; import type { PanelMode, NullableDateType, PickerMode, Locale, CustomFormat } from '../interface'; import type { GenerateConfig } from '../generate'; export const WEEK_DAY_COUNT = 7; export function isNullEqual<T>(value1: T, value2: T): boolean | undefined { if (!value1 && !value2) { return true; } if (!value1 || !value2) { return false; } return undefined; } export function isSameDecade<DateType>( generateConfig: GenerateConfig<DateType>, decade1: NullableDateType<DateType>, decade2: NullableDateType<DateType>, ) { const equal = isNullEqual(decade1, decade2); if (typeof equal === 'boolean') { return equal; } const num1 = Math.floor(generateConfig.getYear(decade1!) / 10); const num2 = Math.floor(generateConfig.getYear(decade2!) / 10); return num1 === num2; } export function isSameYear<DateType>( generateConfig: GenerateConfig<DateType>, year1: NullableDateType<DateType>, year2: NullableDateType<DateType>, ) { const equal = isNullEqual(year1, year2); if (typeof equal === 'boolean') { return equal; } return generateConfig.getYear(year1!) === generateConfig.getYear(year2!); } export function getQuarter<DateType>(generateConfig: GenerateConfig<DateType>, date: DateType) { const quota = Math.floor(generateConfig.getMonth(date) / 3); return quota + 1; } export function isSameQuarter<DateType>( generateConfig: GenerateConfig<DateType>, quarter1: NullableDateType<DateType>, quarter2: NullableDateType<DateType>, ) { const equal = isNullEqual(quarter1, quarter2); if (typeof equal === 'boolean') { return equal; } return ( isSameYear(generateConfig, quarter1, quarter2) && getQuarter(generateConfig, quarter1!) === getQuarter(generateConfig, quarter2!) ); } export function isSameMonth<DateType>( generateConfig: GenerateConfig<DateType>, month1: NullableDateType<DateType>, month2: NullableDateType<DateType>, ) { const equal = isNullEqual(month1, month2); if (typeof equal === 'boolean') { return equal; } return ( isSameYear(generateConfig, month1, month2) && generateConfig.getMonth(month1!) === generateConfig.getMonth(month2!) ); } export function isSameDate<DateType>( generateConfig: GenerateConfig<DateType>, date1: NullableDateType<DateType>, date2: NullableDateType<DateType>, ) { const equal = isNullEqual(date1, date2); if (typeof equal === 'boolean') { return equal; } return ( generateConfig.getYear(date1!) === generateConfig.getYear(date2!) && generateConfig.getMonth(date1!) === generateConfig.getMonth(date2!) && generateConfig.getDate(date1!) === generateConfig.getDate(date2!) ); } export function isSameTime<DateType>( generateConfig: GenerateConfig<DateType>, time1: NullableDateType<DateType>, time2: NullableDateType<DateType>, ) { const equal = isNullEqual(time1, time2); if (typeof equal === 'boolean') { return equal; } return ( generateConfig.getHour(time1!) === generateConfig.getHour(time2!) && generateConfig.getMinute(time1!) === generateConfig.getMinute(time2!) && generateConfig.getSecond(time1!) === generateConfig.getSecond(time2!) ); } export function isSameWeek<DateType>( generateConfig: GenerateConfig<DateType>, locale: string, date1: NullableDateType<DateType>, date2: NullableDateType<DateType>, ) { const equal = isNullEqual(date1, date2); if (typeof equal === 'boolean') { return equal; } return ( generateConfig.locale.getWeek(locale, date1!) === generateConfig.locale.getWeek(locale, date2!) ); } export function isEqual<DateType>( generateConfig: GenerateConfig<DateType>, value1: NullableDateType<DateType>, value2: NullableDateType<DateType>, ) { return isSameDate(generateConfig, value1, value2) && isSameTime(generateConfig, value1, value2); } /** Between in date but not equal of date */ export function isInRange<DateType>( generateConfig: GenerateConfig<DateType>, startDate: NullableDateType<DateType>, endDate: NullableDateType<DateType>, current: NullableDateType<DateType>, ) { if (!startDate || !endDate || !current) { return false; } return ( !isSameDate(generateConfig, startDate, current) && !isSameDate(generateConfig, endDate, current) && generateConfig.isAfter(current, startDate) && generateConfig.isAfter(endDate, current) ); } export function getWeekStartDate<DateType>( locale: string, generateConfig: GenerateConfig<DateType>, value: DateType, ) { const weekFirstDay = generateConfig.locale.getWeekFirstDay(locale); const monthStartDate = generateConfig.setDate(value, 1); const startDateWeekDay = generateConfig.getWeekDay(monthStartDate); let alignStartDate = generateConfig.addDate(monthStartDate, weekFirstDay - startDateWeekDay); if ( generateConfig.getMonth(alignStartDate) === generateConfig.getMonth(value) && generateConfig.getDate(alignStartDate) > 1 ) { alignStartDate = generateConfig.addDate(alignStartDate, -7); } return alignStartDate; } export function getClosingViewDate<DateType>( viewDate: DateType, picker: PickerMode, generateConfig: GenerateConfig<DateType>, offset = 1, ): DateType { switch (picker) { case 'year': return generateConfig.addYear(viewDate, offset * 10); case 'quarter': case 'month': return generateConfig.addYear(viewDate, offset); default: return generateConfig.addMonth(viewDate, offset); } } export function formatValue<DateType>( value: DateType, { generateConfig, locale, format, }: { generateConfig: GenerateConfig<DateType>; locale: Locale; format: string | CustomFormat<DateType>; }, ) { return typeof format === 'function' ? format(value) : generateConfig.locale.format(locale.locale, value, format); } export function parseValue<DateType>( value: string, { generateConfig, locale, formatList, }: { generateConfig: GenerateConfig<DateType>; locale: Locale; formatList: (string | CustomFormat<DateType>)[]; }, ) { if (!value || typeof formatList[0] === 'function') { return null; } return generateConfig.locale.parse(locale.locale, value, formatList as string[]); } // eslint-disable-next-line consistent-return export function getCellDateDisabled<DateType>({ cellDate, mode, disabledDate, generateConfig, }: { cellDate: DateType; mode: Omit<PanelMode, 'time'>; generateConfig: GenerateConfig<DateType>; disabledDate?: (date: DateType) => boolean; }): boolean { if (!disabledDate) return false; // Whether cellDate is disabled in range const getDisabledFromRange = ( currentMode: 'date' | 'month' | 'year', start: number, end: number, ) => { let current = start; while (current <= end) { let date: DateType; switch (currentMode) { case 'date': { date = generateConfig.setDate(cellDate, current); if (!disabledDate(date)) { return false; } break; } case 'month': { date = generateConfig.setMonth(cellDate, current); if ( !getCellDateDisabled({ cellDate: date, mode: 'month', generateConfig, disabledDate, }) ) { return false; } break; } case 'year': { date = generateConfig.setYear(cellDate, current); if ( !getCellDateDisabled({ cellDate: date, mode: 'year', generateConfig, disabledDate, }) ) { return false; } break; } } current += 1; } return true; }; switch (mode) { case 'date': case 'week': { return disabledDate(cellDate); } case 'month': { const startDate = 1; const endDate = generateConfig.getDate(generateConfig.getEndDate(cellDate)); return getDisabledFromRange('date', startDate, endDate); } case 'quarter': { const startMonth = Math.floor(generateConfig.getMonth(cellDate) / 3) * 3; const endMonth = startMonth + 2; return getDisabledFromRange('month', startMonth, endMonth); } case 'year': { return getDisabledFromRange('month', 0, 11); } case 'decade': { const year = generateConfig.getYear(cellDate); const startYear = Math.floor(year / DECADE_UNIT_DIFF) * DECADE_UNIT_DIFF; const endYear = startYear + DECADE_UNIT_DIFF - 1; return getDisabledFromRange('year', startYear, endYear); } } }
YaroShkvorets/ant-design-vue
components/grid/context.ts
import { computed, inject, provide } from 'vue'; import type { Ref, InjectionKey, ComputedRef } from 'vue'; export interface RowContext { gutter: ComputedRef<[number, number]>; wrap: ComputedRef<boolean>; supportFlexGap: Ref<boolean>; } export const RowContextKey: InjectionKey<RowContext> = Symbol('rowContextKey'); const useProvideRow = (state: RowContext) => { provide(RowContextKey, state); }; const useInjectRow = () => { return inject(RowContextKey, { gutter: computed(() => undefined), wrap: computed(() => undefined), supportFlexGap: computed(() => undefined), }); }; export { useInjectRow, useProvideRow }; export default useProvideRow;
YaroShkvorets/ant-design-vue
components/vc-table/ColGroup.tsx
import type { ColumnType } from './interface'; import { INTERNAL_COL_DEFINE } from './utils/legacyUtil'; export interface ColGroupProps<RecordType> { colWidths: readonly (number | string)[]; columns?: readonly ColumnType<RecordType>[]; columCount?: number; } function ColGroup<RecordType>({ colWidths, columns, columCount }: ColGroupProps<RecordType>) { const cols = []; const len = columCount || columns.length; // Only insert col with width & additional props // Skip if rest col do not have any useful info let mustInsert = false; for (let i = len - 1; i >= 0; i -= 1) { const width = colWidths[i]; const column = columns && columns[i]; const additionalProps = column && column[INTERNAL_COL_DEFINE]; if (width || additionalProps || mustInsert) { cols.unshift( <col key={i} style={{ width: typeof width === 'number' ? `${width}px` : width }} {...additionalProps} />, ); mustInsert = true; } } return <colgroup>{cols}</colgroup>; } export default ColGroup;
YaroShkvorets/ant-design-vue
components/menu/src/Divider.tsx
<gh_stars>1000+ import { defineComponent } from 'vue'; import { useInjectMenu } from './hooks/useMenuContext'; export default defineComponent({ name: 'AMenuDivider', setup() { const { prefixCls } = useInjectMenu(); return () => { return <li class={`${prefixCls.value}-item-divider`} />; }; }, });
YaroShkvorets/ant-design-vue
components/vc-select/Selector/index.tsx
/** * Cursor rule: * 1. Only `showSearch` enabled * 2. Only `open` is `true` * 3. When typing, set `open` to `true` which hit rule of 2 * * Accessibility: * - https://www.w3.org/TR/wai-aria-practices/examples/combobox/aria1.1pattern/listbox-combo.html */ import KeyCode from '../../_util/KeyCode'; import MultipleSelector from './MultipleSelector'; import SingleSelector from './SingleSelector'; import type { LabelValueType, RawValueType, CustomTagProps } from '../interface/generator'; import type { RenderNode, Mode } from '../interface'; import useLock from '../hooks/useLock'; import type { VNodeChild, PropType } from 'vue'; import { defineComponent } from 'vue'; import createRef from '../../_util/createRef'; import PropTypes from '../../_util/vue-types'; import type { VueNode } from '../../_util/type'; import type { EventHandler } from '../../_util/EventInterface'; export interface SelectorProps { id: string; prefixCls: string; showSearch?: boolean; open: boolean; /** Display in the Selector value, it's not same as `value` prop */ values: LabelValueType[]; multiple: boolean; mode: Mode; searchValue: string; activeValue: string; inputElement: VueNode; autofocus?: boolean; accessibilityIndex: number; tabindex?: number | string; disabled?: boolean; placeholder?: VNodeChild; removeIcon?: RenderNode; // Tags maxTagCount?: number | 'responsive'; maxTagTextLength?: number; maxTagPlaceholder?: VNodeChild | ((omittedValues: LabelValueType[]) => VNodeChild); tagRender?: (props: CustomTagProps) => VNodeChild; /** Check if `tokenSeparators` contains `\n` or `\r\n` */ tokenWithEnter?: boolean; // Motion choiceTransitionName?: string; onToggleOpen: (open?: boolean) => void | any; /** `onSearch` returns go next step boolean to check if need do toggle open */ onSearch: (searchText: string, fromTyping: boolean, isCompositing: boolean) => boolean; onSearchSubmit: (searchText: string) => void; onSelect: (value: RawValueType, option: { selected: boolean }) => void; onInputKeyDown?: (e: KeyboardEvent) => void; /** * @private get real dom for trigger align. * This may be removed after React provides replacement of `findDOMNode` */ domRef: () => HTMLDivElement; } const Selector = defineComponent<SelectorProps>({ name: 'Selector', inheritAttrs: false, props: { id: PropTypes.string, prefixCls: PropTypes.string, showSearch: PropTypes.looseBool, open: PropTypes.looseBool, /** Display in the Selector value, it's not same as `value` prop */ values: PropTypes.array, multiple: PropTypes.looseBool, mode: PropTypes.string, searchValue: PropTypes.string, activeValue: PropTypes.string, inputElement: PropTypes.any, autofocus: PropTypes.looseBool, accessibilityIndex: PropTypes.number, tabindex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), disabled: PropTypes.looseBool, placeholder: PropTypes.any, removeIcon: PropTypes.any, // Tags maxTagCount: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), maxTagTextLength: PropTypes.number, maxTagPlaceholder: PropTypes.any, tagRender: PropTypes.func, /** Check if `tokenSeparators` contains `\n` or `\r\n` */ tokenWithEnter: PropTypes.looseBool, // Motion choiceTransitionName: PropTypes.string, onToggleOpen: { type: Function as PropType<(open?: boolean) => void> }, /** `onSearch` returns go next step boolean to check if need do toggle open */ onSearch: PropTypes.func, onSearchSubmit: PropTypes.func, onSelect: PropTypes.func, onInputKeyDown: { type: Function as PropType<EventHandler> }, /** * @private get real dom for trigger align. * This may be removed after React provides replacement of `findDOMNode` */ domRef: PropTypes.func, } as any, setup(props) { const inputRef = createRef(); let compositionStatus = false; // ====================== Input ====================== const [getInputMouseDown, setInputMouseDown] = useLock(0); const onInternalInputKeyDown = (event: KeyboardEvent) => { const { which } = event; if (which === KeyCode.UP || which === KeyCode.DOWN) { event.preventDefault(); } if (props.onInputKeyDown) { props.onInputKeyDown(event); } if (which === KeyCode.ENTER && props.mode === 'tags' && !compositionStatus && !props.open) { // When menu isn't open, OptionList won't trigger a value change // So when enter is pressed, the tag's input value should be emitted here to let selector know props.onSearchSubmit((event.target as HTMLInputElement).value); } if (![KeyCode.SHIFT, KeyCode.TAB, KeyCode.BACKSPACE, KeyCode.ESC].includes(which)) { props.onToggleOpen(true); } }; /** * We can not use `findDOMNode` sine it will get warning, * have to use timer to check if is input element. */ const onInternalInputMouseDown = () => { setInputMouseDown(true); }; // When paste come, ignore next onChange let pastedText = null; const triggerOnSearch = (value: string) => { if (props.onSearch(value, true, compositionStatus) !== false) { props.onToggleOpen(true); } }; const onInputCompositionStart = () => { compositionStatus = true; }; const onInputCompositionEnd = (e: InputEvent) => { compositionStatus = false; // Trigger search again to support `tokenSeparators` with typewriting if (props.mode !== 'combobox') { triggerOnSearch((e.target as HTMLInputElement).value); } }; const onInputChange = (event: { target: { value: any } }) => { let { target: { value }, } = event; // Pasted text should replace back to origin content if (props.tokenWithEnter && pastedText && /[\r\n]/.test(pastedText)) { // CRLF will be treated as a single space for input element const replacedText = pastedText .replace(/[\r\n]+$/, '') .replace(/\r\n/g, ' ') .replace(/[\r\n]/g, ' '); value = value.replace(replacedText, pastedText); } pastedText = null; triggerOnSearch(value); }; const onInputPaste = (e: ClipboardEvent) => { const { clipboardData } = e; const value = clipboardData.getData('text'); pastedText = value; }; const onClick = ({ target }) => { if (target !== inputRef.current) { // Should focus input if click the selector const isIE = (document.body.style as any).msTouchAction !== undefined; if (isIE) { setTimeout(() => { inputRef.current.focus(); }); } else { inputRef.current.focus(); } } }; const onMousedown = (event: MouseEvent) => { const inputMouseDown = getInputMouseDown(); if (event.target !== inputRef.current && !inputMouseDown) { event.preventDefault(); } if ((props.mode !== 'combobox' && (!props.showSearch || !inputMouseDown)) || !props.open) { if (props.open) { props.onSearch('', true, false); } props.onToggleOpen(); } }; return { focus: () => { inputRef.current.focus(); }, blur: () => { inputRef.current.blur(); }, onMousedown, onClick, onInputPaste, inputRef, onInternalInputKeyDown, onInternalInputMouseDown, onInputChange, onInputCompositionEnd, onInputCompositionStart, }; }, render() { const { prefixCls, domRef, multiple } = this.$props as SelectorProps; const { onMousedown, onClick, inputRef, onInputPaste, onInternalInputKeyDown, onInternalInputMouseDown, onInputChange, onInputCompositionStart, onInputCompositionEnd, } = this as any; const sharedProps = { inputRef, onInputKeyDown: onInternalInputKeyDown, onInputMouseDown: onInternalInputMouseDown, onInputChange, onInputPaste, onInputCompositionStart, onInputCompositionEnd, }; const selectNode = multiple ? ( <MultipleSelector {...this.$props} {...sharedProps} /> ) : ( <SingleSelector {...this.$props} {...sharedProps} /> ); return ( <div ref={domRef} class={`${prefixCls}-selector`} onClick={onClick} onMousedown={onMousedown}> {selectNode} </div> ); }, }); export default Selector;
YaroShkvorets/ant-design-vue
components/table/context.ts
<gh_stars>1-10 import type { ComputedRef, InjectionKey } from 'vue'; import { computed, inject, provide } from 'vue'; import type { ColumnType } from './interface'; export type ContextSlots = { emptyText?: (...args: any[]) => any; expandIcon?: (...args: any[]) => any; title?: (...args: any[]) => any; footer?: (...args: any[]) => any; summary?: (...args: any[]) => any; bodyCell?: (...args: any[]) => any; headerCell?: (...args: any[]) => any; customFilterIcon?: (...args: any[]) => any; customFilterDropdown?: (...args: any[]) => any; // 兼容 2.x 的 columns slots 配置 [key: string]: ((...args: any[]) => any) | undefined; }; type SlotsContextProps = ComputedRef<ContextSlots>; const SlotsContextKey: InjectionKey<SlotsContextProps> = Symbol('SlotsContextProps'); export const useProvideSlots = (props: SlotsContextProps) => { provide(SlotsContextKey, props); }; export const useInjectSlots = () => { return inject(SlotsContextKey, computed(() => ({})) as SlotsContextProps); }; type ContextProps = { onResizeColumn: (w: number, column: ColumnType<any>) => void; }; const ContextKey: InjectionKey<ContextProps> = Symbol('ContextProps'); export const useProvideTableContext = (props: ContextProps) => { provide(ContextKey, props); }; export const useInjectTableContext = () => { return inject(ContextKey, { onResizeColumn: () => {} } as ContextProps); };
YaroShkvorets/ant-design-vue
components/progress/Steps.tsx
<reponame>YaroShkvorets/ant-design-vue<gh_stars>1000+ import type { ExtractPropTypes, PropType, VNodeChild } from 'vue'; import { computed, defineComponent } from 'vue'; import PropTypes from '../_util/vue-types'; import type { ProgressSize } from './props'; import { progressProps } from './props'; const stepsProps = { ...progressProps(), steps: PropTypes.number, size: { type: String as PropType<ProgressSize>, }, strokeColor: PropTypes.string, trailColor: PropTypes.string, }; export type StepsProps = Partial<ExtractPropTypes<typeof stepsProps>>; export default defineComponent({ props: stepsProps, setup(props, { slots }) { const current = computed(() => Math.round(props.steps * ((props.percent || 0) / 100))); const stepWidth = computed(() => (props.size === 'small' ? 2 : 14)); const styledSteps = computed(() => { const { steps, strokeWidth = 8, strokeColor, trailColor, prefixCls } = props; const temp: VNodeChild[] = []; for (let i = 0; i < steps; i += 1) { const cls = { [`${prefixCls}-steps-item`]: true, [`${prefixCls}-steps-item-active`]: i <= current.value - 1, }; temp.push( <div key={i} class={cls} style={{ backgroundColor: i <= current.value - 1 ? strokeColor : trailColor, width: `${stepWidth.value}px`, height: `${strokeWidth}px`, }} />, ); } return temp; }); return () => ( <div class={`${props.prefixCls}-steps-outer`}> {styledSteps.value} {slots.default?.()} </div> ); }, });
YaroShkvorets/ant-design-vue
components/vc-picker/panels/DatetimePanel/index.tsx
import type { DatePanelProps } from '../DatePanel'; import DatePanel from '../DatePanel'; import type { SharedTimeProps } from '../TimePanel'; import TimePanel from '../TimePanel'; import { tuple } from '../../utils/miscUtil'; import { setDateTime as setTime } from '../../utils/timeUtil'; import type { PanelRefProps, DisabledTime } from '../../interface'; import KeyCode from '../../../_util/KeyCode'; import classNames from '../../../_util/classNames'; import { ref } from 'vue'; import useMergeProps from '../../hooks/useMergeProps'; export type DatetimePanelProps<DateType> = { disabledTime?: DisabledTime<DateType>; showTime?: boolean | SharedTimeProps<DateType>; defaultValue?: DateType; } & Omit<DatePanelProps<DateType>, 'disabledHours' | 'disabledMinutes' | 'disabledSeconds'>; const ACTIVE_PANEL = tuple('date', 'time'); type ActivePanelType = typeof ACTIVE_PANEL[number]; function DatetimePanel<DateType>(_props: DatetimePanelProps<DateType>) { const props = useMergeProps(_props); const { prefixCls, operationRef, generateConfig, value, defaultValue, disabledTime, showTime, onSelect, } = props; const panelPrefixCls = `${prefixCls}-datetime-panel`; const activePanel = ref<ActivePanelType | null>(null); const dateOperationRef = ref<PanelRefProps>({}); const timeOperationRef = ref<PanelRefProps>({}); const timeProps = typeof showTime === 'object' ? { ...showTime } : {}; // ======================= Keyboard ======================= function getNextActive(offset: number) { const activeIndex = ACTIVE_PANEL.indexOf(activePanel.value!) + offset; const nextActivePanel = ACTIVE_PANEL[activeIndex] || null; return nextActivePanel; } const onBlur = (e?: FocusEvent) => { if (timeOperationRef.value.onBlur) { timeOperationRef.value.onBlur(e!); } activePanel.value = null; }; operationRef.value = { onKeydown: (event: KeyboardEvent) => { // Switch active panel if (event.which === KeyCode.TAB) { const nextActivePanel = getNextActive(event.shiftKey ? -1 : 1); activePanel.value = nextActivePanel; if (nextActivePanel) { event.preventDefault(); } return true; } // Operate on current active panel if (activePanel.value) { const ref = activePanel.value === 'date' ? dateOperationRef : timeOperationRef; if (ref.value && ref.value.onKeydown) { ref.value.onKeydown(event); } return true; } // Switch first active panel if operate without panel if ([KeyCode.LEFT, KeyCode.RIGHT, KeyCode.UP, KeyCode.DOWN].includes(event.which)) { activePanel.value = 'date'; return true; } return false; }, onBlur, onClose: onBlur, }; // ======================== Events ======================== const onInternalSelect = (date: DateType, source: 'date' | 'time') => { let selectedDate = date; if (source === 'date' && !value && timeProps.defaultValue) { // Date with time defaultValue selectedDate = generateConfig.setHour( selectedDate, generateConfig.getHour(timeProps.defaultValue), ); selectedDate = generateConfig.setMinute( selectedDate, generateConfig.getMinute(timeProps.defaultValue), ); selectedDate = generateConfig.setSecond( selectedDate, generateConfig.getSecond(timeProps.defaultValue), ); } else if (source === 'time' && !value && defaultValue) { selectedDate = generateConfig.setYear(selectedDate, generateConfig.getYear(defaultValue)); selectedDate = generateConfig.setMonth(selectedDate, generateConfig.getMonth(defaultValue)); selectedDate = generateConfig.setDate(selectedDate, generateConfig.getDate(defaultValue)); } if (onSelect) { onSelect(selectedDate, 'mouse'); } }; // ======================== Render ======================== const disabledTimes = disabledTime ? disabledTime(value || null) : {}; return ( <div class={classNames(panelPrefixCls, { [`${panelPrefixCls}-active`]: activePanel.value, })} > <DatePanel {...props} operationRef={dateOperationRef} active={activePanel.value === 'date'} onSelect={date => { onInternalSelect( setTime( generateConfig, date, showTime && typeof showTime === 'object' ? showTime.defaultValue : null, ), 'date', ); }} /> <TimePanel {...props} format={undefined} {...timeProps} {...disabledTimes} defaultValue={undefined} operationRef={timeOperationRef} active={activePanel.value === 'time'} onSelect={date => { onInternalSelect(date, 'time'); }} /> </div> ); } DatetimePanel.displayName = 'DatetimePanel'; DatetimePanel.inheritAttrs = false; export default DatetimePanel;
YaroShkvorets/ant-design-vue
components/_util/Portal.tsx
import PropTypes from './vue-types'; import { defineComponent, nextTick, onBeforeUnmount, onUpdated, Teleport } from 'vue'; export default defineComponent({ name: 'Portal', inheritAttrs: false, props: { getContainer: PropTypes.func.isRequired, didUpdate: PropTypes.func, }, setup(props, { slots }) { // getContainer 不会改变,不用响应式 const container = props.getContainer(); onUpdated(() => { nextTick(() => { props.didUpdate?.(props); }); }); onBeforeUnmount(() => { if (container && container.parentNode) { container.parentNode.removeChild(container); } }); return () => { return container ? <Teleport to={container} v-slots={slots}></Teleport> : null; }; }, });
YaroShkvorets/ant-design-vue
components/tree/utils/dropIndicator.tsx
import type { CSSProperties } from 'vue'; export const offset = 4; export default function dropIndicatorRender(props: { dropPosition: -1 | 0 | 1; dropLevelOffset: number; indent: number; prefixCls: string; direction: 'ltr' | 'rtl'; }) { const { dropPosition, dropLevelOffset, prefixCls, indent, direction = 'ltr' } = props; const startPosition = direction === 'ltr' ? 'left' : 'right'; const endPosition = direction === 'ltr' ? 'right' : 'left'; const style: CSSProperties = { [startPosition]: `${-dropLevelOffset * indent + offset}px`, [endPosition]: 0, }; switch (dropPosition) { case -1: style.top = `${-3}px`; break; case 1: style.bottom = `${-3}px`; break; default: // dropPosition === 0 style.bottom = `${-3}px`; style[startPosition] = `${indent + offset}px`; break; } return <div style={style} class={`${prefixCls}-drop-indicator`} />; }
YaroShkvorets/ant-design-vue
components/_util/hooks/useBreakpoint.ts
import type { Ref } from 'vue'; import { onMounted, onUnmounted, ref } from 'vue'; import type { ScreenMap } from '../../_util/responsiveObserve'; import ResponsiveObserve from '../../_util/responsiveObserve'; function useBreakpoint(): Ref<ScreenMap> { const screens = ref<ScreenMap>({}); let token = null; onMounted(() => { token = ResponsiveObserve.subscribe(supportScreens => { screens.value = supportScreens; }); }); onUnmounted(() => { ResponsiveObserve.unsubscribe(token); }); return screens; } export default useBreakpoint;
YaroShkvorets/ant-design-vue
components/skeleton/Image.tsx
<reponame>YaroShkvorets/ant-design-vue import { computed, defineComponent } from 'vue'; import classNames from '../_util/classNames'; import useConfigInject from '../_util/hooks/useConfigInject'; import type { SkeletonElementProps } from './Element'; import { skeletonElementProps } from './Element'; export type SkeletonImageProps = Omit<SkeletonElementProps, 'size' | 'shape' | 'active'>; const path = 'M365.714286 329.142857q0 45.714286-32.036571 77.677714t-77.677714 32.036571-77.677714-32.036571-32.036571-77.677714 32.036571-77.677714 77.677714-32.036571 77.677714 32.036571 32.036571 77.677714zM950.857143 548.571429l0 256-804.571429 0 0-109.714286 182.857143-182.857143 91.428571 91.428571 292.571429-292.571429zM1005.714286 146.285714l-914.285714 0q-7.460571 0-12.873143 5.412571t-5.412571 12.873143l0 694.857143q0 7.460571 5.412571 12.873143t12.873143 5.412571l914.285714 0q7.460571 0 12.873143-5.412571t5.412571-12.873143l0-694.857143q0-7.460571-5.412571-12.873143t-12.873143-5.412571zM1097.142857 164.571429l0 694.857143q0 37.741714-26.843429 64.585143t-64.585143 26.843429l-914.285714 0q-37.741714 0-64.585143-26.843429t-26.843429-64.585143l0-694.857143q0-37.741714 26.843429-64.585143t64.585143-26.843429l914.285714 0q37.741714 0 64.585143 26.843429t26.843429 64.585143z'; const SkeletonImage = defineComponent({ name: 'ASkeletonImage', props: skeletonElementProps(), setup(props) { const { prefixCls } = useConfigInject('skeleton', props); const cls = computed(() => classNames(prefixCls.value, `${prefixCls.value}-element`)); return () => { return ( <div class={cls.value}> <div class={`${prefixCls.value}-image`}> <svg viewBox="0 0 1098 1024" xmlns="http://www.w3.org/2000/svg" class={`${prefixCls.value}-image-svg`} > <path d={path} class={`${prefixCls.value}-image-path`} /> </svg> </div> </div> ); }; }, }); export default SkeletonImage;