diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 81d992c092039..67524e6158eed 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -201,6 +201,7 @@ packages/react-components/react-avatar-context @microsoft/teams-prg packages/react-components/react-infobutton @microsoft/cxe-red @sopranopillow packages/react-migration-v8-v9 @microsoft/cxe-coastal @geoffcoxmsft packages/react-components/react-tree @microsoft/teams-prg +packages/react-components/react-virtualizer @microsoft/xc-uxe @Mitch-At-Work packages/react-components/react-skeleton @microsoft/cxe-red packages/tokens @microsoft/teams-prg packages/react-components/react-tags @microsoft/cxe-coastal @TristanWatanabe diff --git a/change/@fluentui-react-components-b74a6283-d65f-4c27-9a78-fa1003628656.json b/change/@fluentui-react-components-b74a6283-d65f-4c27-9a78-fa1003628656.json new file mode 100644 index 0000000000000..5210050b83a76 --- /dev/null +++ b/change/@fluentui-react-components-b74a6283-d65f-4c27-9a78-fa1003628656.json @@ -0,0 +1,7 @@ +{ + "type": "patch", + "comment": "feat: Export 'Virtualizer' as unstable", + "packageName": "@fluentui/react-components", + "email": "mifraser@microsoft.com", + "dependentChangeType": "patch" +} diff --git a/change/@fluentui-virtualizer-8e97ec39-c768-4e8b-85fc-5a50b7b425e1.json b/change/@fluentui-virtualizer-8e97ec39-c768-4e8b-85fc-5a50b7b425e1.json new file mode 100644 index 0000000000000..0ff11938311ed --- /dev/null +++ b/change/@fluentui-virtualizer-8e97ec39-c768-4e8b-85fc-5a50b7b425e1.json @@ -0,0 +1,7 @@ +{ + "type": "prerelease", + "comment": "feat: Initial unstable release of the Virtualizer", + "packageName": "@fluentui/react-virtualizer", + "email": "mifraser@microsoft.com", + "dependentChangeType": "patch" +} diff --git a/packages/react-components/react-components/etc/react-components.unstable.api.md b/packages/react-components/react-components/etc/react-components.unstable.api.md index 93e731a823473..9be7423956b64 100644 --- a/packages/react-components/react-components/etc/react-components.unstable.api.md +++ b/packages/react-components/react-components/etc/react-components.unstable.api.md @@ -166,6 +166,7 @@ import { renderTableHeader_unstable } from '@fluentui/react-table'; import { renderTableHeaderCell_unstable } from '@fluentui/react-table'; import { renderTableRow_unstable } from '@fluentui/react-table'; import { renderTableSelectionCell_unstable } from '@fluentui/react-table'; +import { renderVirtualizer_unstable } from '@fluentui/react-virtualizer'; import { Select } from '@fluentui/react-select'; import { selectClassNames } from '@fluentui/react-select'; import { SelectField_unstable as SelectField } from '@fluentui/react-select'; @@ -283,6 +284,7 @@ import { useField_unstable } from '@fluentui/react-field'; import { useFieldStyles_unstable } from '@fluentui/react-field'; import { useInfoButton_unstable } from '@fluentui/react-infobutton'; import { useInfoButtonStyles_unstable } from '@fluentui/react-infobutton'; +import { useIntersectionObserver } from '@fluentui/react-virtualizer'; import { useListbox_unstable } from '@fluentui/react-combobox'; import { useListboxContextValues } from '@fluentui/react-combobox'; import { useListboxStyles_unstable } from '@fluentui/react-combobox'; @@ -318,6 +320,14 @@ import { useTableSelectionCell_unstable } from '@fluentui/react-table'; import { useTableSelectionCellStyles_unstable } from '@fluentui/react-table'; import { useTableSort } from '@fluentui/react-table'; import { useTableStyles_unstable } from '@fluentui/react-table'; +import { useVirtualizer_unstable } from '@fluentui/react-virtualizer'; +import { useVirtualizerStyles_unstable } from '@fluentui/react-virtualizer'; +import { Virtualizer } from '@fluentui/react-virtualizer'; +import { VirtualizerChildRenderFunction } from '@fluentui/react-virtualizer'; +import { virtualizerClassNames } from '@fluentui/react-virtualizer'; +import { VirtualizerProps } from '@fluentui/react-virtualizer'; +import { VirtualizerSlots } from '@fluentui/react-virtualizer'; +import { VirtualizerState } from '@fluentui/react-virtualizer'; export { Alert } @@ -643,6 +653,8 @@ export { renderTableRow_unstable } export { renderTableSelectionCell_unstable } +export { renderVirtualizer_unstable } + export { Select } export { selectClassNames } @@ -877,6 +889,8 @@ export { useInfoButton_unstable } export { useInfoButtonStyles_unstable } +export { useIntersectionObserver } + export { useListbox_unstable } export { useListboxContextValues } @@ -947,6 +961,22 @@ export { useTableSort } export { useTableStyles_unstable } +export { useVirtualizer_unstable } + +export { useVirtualizerStyles_unstable } + +export { Virtualizer } + +export { VirtualizerChildRenderFunction } + +export { virtualizerClassNames } + +export { VirtualizerProps } + +export { VirtualizerSlots } + +export { VirtualizerState } + // (No @packageDocumentation comment for this package) ``` diff --git a/packages/react-components/react-components/package.json b/packages/react-components/react-components/package.json index cc1f29d7e74a3..813a486a98b78 100644 --- a/packages/react-components/react-components/package.json +++ b/packages/react-components/react-components/package.json @@ -72,6 +72,7 @@ "@fluentui/react-tooltip": "^9.1.9", "@fluentui/react-utilities": "^9.4.0", "@fluentui/react-text": "^9.1.13", + "@fluentui/react-virtualizer": "9.0.0-alpha.0", "@griffel/react": "^1.5.2", "tslib": "^2.1.0" }, diff --git a/packages/react-components/react-components/src/unstable/index.ts b/packages/react-components/react-components/src/unstable/index.ts index 076110b4ce194..fa524b6a2f5a6 100644 --- a/packages/react-components/react-components/src/unstable/index.ts +++ b/packages/react-components/react-components/src/unstable/index.ts @@ -330,3 +330,18 @@ export { useProgressBar_unstable, } from '@fluentui/react-progress'; export type { ProgressBarProps, ProgressBarState, ProgressBarSlots } from '@fluentui/react-progress'; + +export { + Virtualizer, + virtualizerClassNames, + useVirtualizer_unstable, + renderVirtualizer_unstable, + useVirtualizerStyles_unstable, + useIntersectionObserver, +} from '@fluentui/react-virtualizer'; +export type { + VirtualizerProps, + VirtualizerState, + VirtualizerSlots, + VirtualizerChildRenderFunction, +} from '@fluentui/react-virtualizer'; diff --git a/packages/react-components/react-virtualizer/.babelrc.json b/packages/react-components/react-virtualizer/.babelrc.json new file mode 100644 index 0000000000000..40e01373083ce --- /dev/null +++ b/packages/react-components/react-virtualizer/.babelrc.json @@ -0,0 +1,4 @@ +{ + "presets": ["@griffel"], + "plugins": ["annotate-pure-calls", "@babel/transform-react-pure-annotations"] +} diff --git a/packages/react-components/react-virtualizer/.eslintrc.json b/packages/react-components/react-virtualizer/.eslintrc.json new file mode 100644 index 0000000000000..ceea884c70dcc --- /dev/null +++ b/packages/react-components/react-virtualizer/.eslintrc.json @@ -0,0 +1,4 @@ +{ + "extends": ["plugin:@fluentui/eslint-plugin/react"], + "root": true +} diff --git a/packages/react-components/react-virtualizer/.npmignore b/packages/react-components/react-virtualizer/.npmignore new file mode 100644 index 0000000000000..f7ce568a6dbf7 --- /dev/null +++ b/packages/react-components/react-virtualizer/.npmignore @@ -0,0 +1,30 @@ +.storybook/ +.vscode/ +bundle-size/ +config/ +coverage/ +docs/ +etc/ +node_modules/ +src/ +stories/ +dist/types/ +temp/ +__fixtures__ +__mocks__ +__tests__ + +*.api.json +*.log +*.spec.* +*.cy.* +*.test.* +*.yml + +# config files +*config.* +*rc.* +.editorconfig +.eslint* +.git* +.prettierignore diff --git a/packages/react-components/react-virtualizer/.storybook/main.js b/packages/react-components/react-virtualizer/.storybook/main.js new file mode 100644 index 0000000000000..26536b61b387f --- /dev/null +++ b/packages/react-components/react-virtualizer/.storybook/main.js @@ -0,0 +1,14 @@ +const rootMain = require('../../../../.storybook/main'); + +module.exports = /** @type {Omit} */ ({ + ...rootMain, + stories: [...rootMain.stories, '../stories/**/*.stories.mdx', '../stories/**/index.stories.@(ts|tsx)'], + addons: [...rootMain.addons], + webpackFinal: (config, options) => { + const localConfig = { ...rootMain.webpackFinal(config, options) }; + + // add your own webpack tweaks if needed + + return localConfig; + }, +}); diff --git a/packages/react-components/react-virtualizer/.storybook/preview.js b/packages/react-components/react-virtualizer/.storybook/preview.js new file mode 100644 index 0000000000000..1939500a3d18c --- /dev/null +++ b/packages/react-components/react-virtualizer/.storybook/preview.js @@ -0,0 +1,7 @@ +import * as rootPreview from '../../../../.storybook/preview'; + +/** @type {typeof rootPreview.decorators} */ +export const decorators = [...rootPreview.decorators]; + +/** @type {typeof rootPreview.parameters} */ +export const parameters = { ...rootPreview.parameters }; diff --git a/packages/react-components/react-virtualizer/.storybook/tsconfig.json b/packages/react-components/react-virtualizer/.storybook/tsconfig.json new file mode 100644 index 0000000000000..ea89218a3d916 --- /dev/null +++ b/packages/react-components/react-virtualizer/.storybook/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "", + "allowJs": true, + "checkJs": true, + "types": ["static-assets", "environment", "storybook__addons"] + }, + "include": ["../stories/**/*.stories.ts", "../stories/**/*.stories.tsx", "*.js"] +} diff --git a/packages/react-components/react-virtualizer/LICENSE b/packages/react-components/react-virtualizer/LICENSE new file mode 100644 index 0000000000000..5f1de3d373b12 --- /dev/null +++ b/packages/react-components/react-virtualizer/LICENSE @@ -0,0 +1,15 @@ +@fluentui/react-virtualizer + +Copyright (c) Microsoft Corporation + +All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Note: Usage of the fonts and icons referenced in Fluent UI React is subject to the terms listed at https://aka.ms/fluentui-assets-license diff --git a/packages/react-components/react-virtualizer/README.md b/packages/react-components/react-virtualizer/README.md new file mode 100644 index 0000000000000..1b42359ffa534 --- /dev/null +++ b/packages/react-components/react-virtualizer/README.md @@ -0,0 +1,5 @@ +# @fluentui/react-virtualizer + +**Virtualizer components for [Fluent UI React](https://react.fluentui.dev/)** + +These are not production-ready components and **should never be used in product**. This space is useful for testing new components whose APIs might change before final release. diff --git a/packages/react-components/react-virtualizer/config/api-extractor.json b/packages/react-components/react-virtualizer/config/api-extractor.json new file mode 100644 index 0000000000000..e533bf30b48a2 --- /dev/null +++ b/packages/react-components/react-virtualizer/config/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "@fluentui/scripts-api-extractor/api-extractor.common.v-next.json" +} diff --git a/packages/react-components/react-virtualizer/config/tests.js b/packages/react-components/react-virtualizer/config/tests.js new file mode 100644 index 0000000000000..2e211ae9e2142 --- /dev/null +++ b/packages/react-components/react-virtualizer/config/tests.js @@ -0,0 +1 @@ +/** Jest test setup file. */ diff --git a/packages/react-components/react-virtualizer/etc/react-virtualizer.api.md b/packages/react-components/react-virtualizer/etc/react-virtualizer.api.md new file mode 100644 index 0000000000000..9c9a26dbbc2f8 --- /dev/null +++ b/packages/react-components/react-virtualizer/etc/react-virtualizer.api.md @@ -0,0 +1,80 @@ +## API Report File for "@fluentui/react-virtualizer" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import type { ComponentProps } from '@fluentui/react-utilities'; +import type { ComponentState } from '@fluentui/react-utilities'; +import type { Dispatch } from 'react'; +import type { FC } from 'react'; +import type { MutableRefObject } from 'react'; +import * as React_2 from 'react'; +import type { SetStateAction } from 'react'; +import type { Slot } from '@fluentui/react-utilities'; +import type { SlotClassNames } from '@fluentui/react-utilities'; + +// @public (undocumented) +export const renderVirtualizer_unstable: (state: VirtualizerState) => JSX.Element; + +// @public +export const useIntersectionObserver: (callback: IntersectionObserverCallback, options?: IntersectionObserverInit | undefined) => { + setObserverList: Dispatch>; + setObserverInit: Dispatch>; + observer: MutableRefObject; +}; + +// @public (undocumented) +export function useVirtualizer_unstable(props: VirtualizerProps): VirtualizerState; + +// @public +export const useVirtualizerStyles_unstable: (state: VirtualizerState) => VirtualizerState; + +// @public +export const Virtualizer: FC; + +// @public (undocumented) +export type VirtualizerChildRenderFunction = (index: number) => React_2.ReactNode; + +// @public (undocumented) +export const virtualizerClassNames: SlotClassNames; + +// @public (undocumented) +export type VirtualizerProps = ComponentProps> & { + children: VirtualizerChildRenderFunction; + itemSize: number; + numItems: number; + virtualizerLength: number; + bufferItems?: number; + bufferSize?: number; + intersectionObserverRoot?: React_2.MutableRefObject; + axis?: 'vertical' | 'horizontal'; + reversed?: boolean; + getItemSize?: (index: number) => number; + onUpdateIndex?: (index: number, prevIndex: number) => void; + onCalculateIndex?: (newIndex: number) => number; +}; + +// @public (undocumented) +export type VirtualizerSlots = { + before: NonNullable>; + beforeContainer: NonNullable>; + after: NonNullable>; + afterContainer: NonNullable>; +}; + +// @public (undocumented) +export type VirtualizerState = ComponentState & { + virtualizedChildren: React_2.ReactNode[]; + virtualizerStartIndex: number; + afterBufferHeight: number; + beforeBufferHeight: number; + totalVirtualizerHeight: number; + axis?: 'vertical' | 'horizontal'; + reversed?: boolean; + bufferSize: number; +}; + +// (No @packageDocumentation comment for this package) + +``` diff --git a/packages/react-components/react-virtualizer/jest.config.js b/packages/react-components/react-virtualizer/jest.config.js new file mode 100644 index 0000000000000..606059485bce0 --- /dev/null +++ b/packages/react-components/react-virtualizer/jest.config.js @@ -0,0 +1,21 @@ +// @ts-check + +/** + * @type {import('@jest/types').Config.InitialOptions} + */ +module.exports = { + displayName: 'virtualizer', + preset: '../../../jest.preset.js', + globals: { + 'ts-jest': { + tsconfig: '/tsconfig.spec.json', + diagnostics: false, + }, + }, + transform: { + '^.+\\.tsx?$': 'ts-jest', + }, + coverageDirectory: './coverage', + setupFilesAfterEnv: ['./config/tests.js'], + snapshotSerializers: ['@griffel/jest-serializer'], +}; diff --git a/packages/react-components/react-virtualizer/just.config.ts b/packages/react-components/react-virtualizer/just.config.ts new file mode 100644 index 0000000000000..b10db31a6aca5 --- /dev/null +++ b/packages/react-components/react-virtualizer/just.config.ts @@ -0,0 +1,3 @@ +import { preset } from '@fluentui/scripts-tasks'; + +preset(); diff --git a/packages/react-components/react-virtualizer/package.json b/packages/react-components/react-virtualizer/package.json new file mode 100644 index 0000000000000..227d7870960f1 --- /dev/null +++ b/packages/react-components/react-virtualizer/package.json @@ -0,0 +1,59 @@ +{ + "name": "@fluentui/react-virtualizer", + "version": "9.0.0-alpha.0", + "description": "Generic and composable virtualizer framework built on browser intersection observer", + "main": "lib-commonjs/index.js", + "module": "lib/index.js", + "typings": "./dist/index.d.ts", + "sideEffects": false, + "repository": { + "type": "git", + "url": "https://github.com/microsoft/fluentui" + }, + "license": "MIT", + "scripts": { + "build": "just-scripts build", + "clean": "just-scripts clean", + "code-style": "just-scripts code-style", + "just": "just-scripts", + "lint": "just-scripts lint", + "test": "jest --passWithNoTests", + "storybook": "start-storybook", + "start": "yarn storybook", + "generate-api": "tsc -p ./tsconfig.lib.json --emitDeclarationOnly && just-scripts api-extractor", + "type-check": "tsc -b tsconfig.json" + }, + "devDependencies": { + "@fluentui/eslint-plugin": "*", + "@fluentui/react-conformance": "*", + "@fluentui/react-conformance-griffel": "9.0.0-beta.19", + "@fluentui/scripts-api-extractor": "*", + "@fluentui/scripts-tasks": "*" + }, + "dependencies": { + "@fluentui/react-utilities": "^9.4.0", + "@griffel/react": "^1.5.2", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "@types/react": ">=16.8.0 <18.0.0", + "@types/react-dom": ">=16.8.0 <18.0.0", + "react": ">=16.8.0 <18.0.0", + "react-dom": ">=16.8.0 <18.0.0" + }, + "beachball": { + "disallowedChangeTypes": [ + "major", + "minor", + "patch" + ] + }, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./lib/index.js", + "require": "./lib-commonjs/index.js" + }, + "./package.json": "./package.json" + } +} diff --git a/packages/react-components/react-virtualizer/src/Hooks.ts b/packages/react-components/react-virtualizer/src/Hooks.ts new file mode 100644 index 0000000000000..429b7dfe4e808 --- /dev/null +++ b/packages/react-components/react-virtualizer/src/Hooks.ts @@ -0,0 +1 @@ +export * from './hooks/index'; diff --git a/packages/react-components/react-virtualizer/src/Virtualizer.ts b/packages/react-components/react-virtualizer/src/Virtualizer.ts new file mode 100644 index 0000000000000..5e125d9783e42 --- /dev/null +++ b/packages/react-components/react-virtualizer/src/Virtualizer.ts @@ -0,0 +1 @@ +export * from './components/Virtualizer/index'; diff --git a/packages/react-components/react-virtualizer/src/components/Virtualizer/Virtualizer.ts b/packages/react-components/react-virtualizer/src/components/Virtualizer/Virtualizer.ts new file mode 100644 index 0000000000000..be635314677d1 --- /dev/null +++ b/packages/react-components/react-virtualizer/src/components/Virtualizer/Virtualizer.ts @@ -0,0 +1,19 @@ +import type { VirtualizerProps } from './Virtualizer.types'; +import { useVirtualizerStyles_unstable } from './useVirtualizerStyles'; +import { useVirtualizer_unstable } from './useVirtualizer'; +import { renderVirtualizer_unstable } from './renderVirtualizer'; +import type { FC } from 'react'; + +/** + * Virtualizer pseudo-component, this functional wrapper + * provides a simple interface for reducing the total number + * of elements rendered at one time in large lists. + */ +export const Virtualizer: FC = (props: VirtualizerProps) => { + const state = useVirtualizer_unstable(props); + useVirtualizerStyles_unstable(state); + + return renderVirtualizer_unstable(state); +}; + +Virtualizer.displayName = 'Virtualizer'; diff --git a/packages/react-components/react-virtualizer/src/components/Virtualizer/Virtualizer.types.ts b/packages/react-components/react-virtualizer/src/components/Virtualizer/Virtualizer.types.ts new file mode 100644 index 0000000000000..16bce33460eb9 --- /dev/null +++ b/packages/react-components/react-virtualizer/src/components/Virtualizer/Virtualizer.types.ts @@ -0,0 +1,144 @@ +import * as React from 'react'; +import type { ComponentProps, ComponentState, Slot } from '@fluentui/react-utilities'; + +export type VirtualizerSlots = { + /** + * The intersection observed 'before' element will detect when scrolling towards the beginning. + */ + before: NonNullable>; + /** + * A block place holding whitespace at the beginning of current DOM children. + */ + beforeContainer: NonNullable>; + /** + * The intersection observed 'after' element will detect when scrolling towards the end. + */ + after: NonNullable>; + /** + * A block place holding whitespace after the end of current DOM children. + */ + afterContainer: NonNullable>; +}; + +export type VirtualizerState = ComponentState & { + /** + * The current virtualized array of children to show in the DOM. + */ + virtualizedChildren: React.ReactNode[]; + /** + * The current start index for the virtualizer, all previous index's will be removed from DOM. + */ + virtualizerStartIndex: number; + /** + * Current buffer height required at beginning of array. + */ + afterBufferHeight: number; + /** + * Current buffer height required at end of array. + */ + beforeBufferHeight: number; + /** + * The total current height of the scrollView/child content. + */ + totalVirtualizerHeight: number; + /** + * The scroll direction + * @default vertical + */ + axis?: 'vertical' | 'horizontal'; + /** + * Tells the virtualizer to measure in the reverse direction (for column-reverse order etc.) + */ + reversed?: boolean; + /** + * Tells the virtualizer how much + */ + bufferSize: number; +}; + +// Virtualizer render function to procedurally generate children elements as rows or columns via index. +// Q: Use generic typing and passing through object data or a simple index system? +export type VirtualizerChildRenderFunction = (index: number) => React.ReactNode; + +export type VirtualizerProps = ComponentProps> & { + /** + * Child render function. + * Iteratively called to return current virtualizer DOM children. + * Will act as a row or column indexer depending on Virtualizer settings. + * Can be used dynamically. + */ + children: VirtualizerChildRenderFunction; + + /** + * Default cell size to use if no custom callback provided. + * If implementing `getItemSize` this should be the initial and ideally minimum cell size. + */ + itemSize: number; + + /** + * The total number of items to be virtualized. + */ + numItems: number; + + /** + * Number of children to render in the DOM during virtualization. + * Constraints: + * - Large enough that the items rendered in DOM cover the viewport + * and intersection observer buffers (buffersize) at both ends. + */ + virtualizerLength: number; + + /** + * Defaults to 1/4th of virtualizerLength. + * Controls the number of elements rendered before the current index entering the virtualized viewport. + * Constraints: + * - Large enough to cover bufferSize (prevents buffers intersecting into the viewport during rest state). + * - Small enough that the end buffer and end index (start index + virtualizerLength) is not within viewport at rest. + */ + bufferItems?: number; + + /** + * Defaults to half of bufferItems size (in pixels). + * The length (in pixels) before the end/start DOM index where the virtualizer recalculation will be triggered. + * Increasing this reduces whitespace on ultra-fast scroll, as additional elements + * are buffered to appear while virtualization recalculates. + * Constraints: + * - At least 1px - although this will only trigger the recalculation after bookends (whitespace) enter viewport. + * - BufferSize must be smaller than bufferItems pixel size, as it prevents bookends entering viewport at rest. + */ + bufferSize?: number; + + /** + * Enables users to override the intersectionObserverRoot. + * @default null + */ + intersectionObserverRoot?: React.MutableRefObject; + + /** + * The scroll direction + * @default vertical + */ + axis?: 'vertical' | 'horizontal'; + + /** + * Tells the virtualizer to measure in the reverse direction (for column-reverse order etc.) + * This value should be flipped in RTL implementation (TBD whether automate RTL). + */ + reversed?: boolean; + + /** + * Callback for acquiring size of individual items + * @param index - the index of the requested size's child + */ + getItemSize?: (index: number) => number; + + /** + * Notify users of index changes + */ + onUpdateIndex?: (index: number, prevIndex: number) => void; + + /** + * Allow users to intervene in index calculation changes + */ + onCalculateIndex?: (newIndex: number) => number; +}; diff --git a/packages/react-components/react-virtualizer/src/components/Virtualizer/index.ts b/packages/react-components/react-virtualizer/src/components/Virtualizer/index.ts new file mode 100644 index 0000000000000..537d649a93d29 --- /dev/null +++ b/packages/react-components/react-virtualizer/src/components/Virtualizer/index.ts @@ -0,0 +1,5 @@ +export * from './Virtualizer'; +export * from './Virtualizer.types'; +export * from './useVirtualizer'; +export * from './renderVirtualizer'; +export * from './useVirtualizerStyles'; diff --git a/packages/react-components/react-virtualizer/src/components/Virtualizer/renderVirtualizer.tsx b/packages/react-components/react-virtualizer/src/components/Virtualizer/renderVirtualizer.tsx new file mode 100644 index 0000000000000..bcc999560a09e --- /dev/null +++ b/packages/react-components/react-virtualizer/src/components/Virtualizer/renderVirtualizer.tsx @@ -0,0 +1,22 @@ +import * as React from 'react'; +import { getSlots } from '@fluentui/react-utilities'; +import { VirtualizerSlots, VirtualizerState } from './Virtualizer.types'; + +export const renderVirtualizer_unstable = (state: VirtualizerState) => { + const { slots, slotProps } = getSlots(state); + + return ( + + {/* The 'before' bookend to hold items in place and detect scroll previous */} + + + + {/* The reduced list of non-virtualized children to be rendered */} + {state.virtualizedChildren} + {/* The 'after' bookend to hold items in place and detect scroll next */} + + + + + ); +}; diff --git a/packages/react-components/react-virtualizer/src/components/Virtualizer/useVirtualizer.ts b/packages/react-components/react-virtualizer/src/components/Virtualizer/useVirtualizer.ts new file mode 100644 index 0000000000000..208ec69c3f20f --- /dev/null +++ b/packages/react-components/react-virtualizer/src/components/Virtualizer/useVirtualizer.ts @@ -0,0 +1,443 @@ +import { useIntersectionObserver } from '../../hooks/useIntersectionObserver'; +import type { ReactNode } from 'react'; +import { useEffect, useRef, useState, useCallback, useReducer } from 'react'; + +import type { VirtualizerProps, VirtualizerState } from './Virtualizer.types'; +import { resolveShorthand } from '@fluentui/react-utilities'; +import { flushSync } from 'react-dom'; + +export function useVirtualizer_unstable(props: VirtualizerProps): VirtualizerState { + const { + itemSize, + numItems, + virtualizerLength, + children: renderChild, + getItemSize, + bufferItems = Math.round(virtualizerLength / 4.0), + bufferSize = Math.floor(bufferItems / 2.0) * itemSize, + intersectionObserverRoot, + axis = 'vertical', + reversed = false, + onUpdateIndex, + onCalculateIndex, + } = props; + + // Tracks the initial item to start virtualizer at, -1 implies first render cycle + const [virtualizerStartIndex, setVirtualizerStartIndex] = useState(-1); + + // Store ref to before padding element + const beforeElementRef = useRef(null); + + // Store ref to before padding element + const afterElementRef = useRef(null); + + // We need to store an array to track dynamic sizes, we can use this to incrementally update changes + const childSizes = useRef(new Array(getItemSize ? numItems : 0)); + + /* We keep track of the progressive sizing/placement down the list, + this helps us skip re-calculations unless children/size changes */ + const childProgressiveSizes = useRef(new Array(getItemSize ? numItems : 0)); + + // The internal tracking REF for child array (updates often). + const childArray = useRef(new Array(virtualizerLength)); + + // We want to be methodical about updating the render with child reference array + const forceUpdate = useReducer(() => ({}), {})[1]; + + const horizontal = axis === 'horizontal'; + + const populateSizeArrays = () => { + if (!getItemSize) { + // Static sizes, never mind! + return; + } + + if (numItems !== childSizes.current.length) { + childSizes.current = new Array(numItems); + } + + if (numItems !== childProgressiveSizes.current.length) { + childProgressiveSizes.current = new Array(numItems); + } + + for (let index = 0; index < numItems; index++) { + childSizes.current[index] = getItemSize(index); + + if (index === 0) { + childProgressiveSizes.current[index] = childSizes.current[index]; + } else { + childProgressiveSizes.current[index] = childProgressiveSizes.current[index - 1] + childSizes.current[index]; + } + } + }; + + const batchUpdateNewIndex = (index: number) => { + // Local updates + onUpdateIndex?.(index, virtualizerStartIndex); + updateChildRows(index); + updateCurrentItemSizes(index); + + // State setters + setVirtualizerStartIndex(index); + }; + + // Observe intersections of virtualized components + const { setObserverList } = useIntersectionObserver( + (entries: IntersectionObserverEntry[], observer: IntersectionObserver) => { + /* Sanity check - do we even need virtualization? */ + if (virtualizerLength > numItems) { + if (virtualizerStartIndex !== 0) { + batchUpdateNewIndex(0); + } + // No-op + return; + } + + /* IO initiates this function when needed (bookend entering view) */ + let measurementPos = 0; + let bufferCount = bufferItems; + + // Grab latest entry that is intersecting + const latestEntry = + entries.length === 1 + ? entries[0] + : entries + .sort((entry1, entry2) => entry2.time - entry1.time) + .find(entry => { + return entry.intersectionRatio > 0; + }); + + if (!latestEntry) { + // If we don't find an intersecting area, ignore for now. + return; + } + + if (latestEntry.target === afterElementRef.current) { + // We need to inverse the buffer count + bufferCount = virtualizerLength - bufferItems; + measurementPos = reversed ? calculateAfter() : calculateTotalSize() - calculateAfter(); + if (!horizontal) { + if (reversed) { + // Scrolling 'up' and hit the after element below + measurementPos -= Math.abs(latestEntry.boundingClientRect.bottom); + } else if (latestEntry.boundingClientRect.top < 0) { + // Scrolling 'down' and hit the after element above top: 0 + measurementPos -= latestEntry.boundingClientRect.top; + } + } else { + if (reversed) { + // Scrolling 'left' and hit the after element + measurementPos -= Math.abs(latestEntry.boundingClientRect.right); + } else if (latestEntry.boundingClientRect.left < 0) { + // Scrolling 'right' and hit the after element + measurementPos -= latestEntry.boundingClientRect.left; + } + } + } else if (latestEntry.target === beforeElementRef.current) { + measurementPos = reversed ? calculateTotalSize() - calculateBefore() : calculateBefore(); + if (!horizontal) { + if (!reversed) { + measurementPos -= Math.abs(latestEntry.boundingClientRect.bottom); + } else if (latestEntry.boundingClientRect.top < 0) { + // Scrolling 'down' in reverse order and hit the before element above top: 0 + measurementPos -= latestEntry.boundingClientRect.top; + } + } else { + if (!reversed) { + measurementPos -= Math.abs(latestEntry.boundingClientRect.right); + } else if (latestEntry.boundingClientRect.left < 0) { + // Scrolling 'left' and hit before element + measurementPos -= latestEntry.boundingClientRect.left; + } + } + } + + if (reversed) { + // We're reversed, up is down, left is right, invert the scroll measure. + measurementPos = Math.max(calculateTotalSize() - Math.abs(measurementPos), 0); + } + + // For now lets use hardcoded size to assess current element to paginate on + const startIndex = getIndexFromScrollPosition(measurementPos); + let bufferedIndex = Math.max(startIndex - bufferCount, 0); + + if (onCalculateIndex) { + // User has chance to intervene/customize prior to render + // They may want to normalize this value. + bufferedIndex = onCalculateIndex(bufferedIndex); + } + + // Safety limits + const maxIndex = Math.max(numItems - virtualizerLength, 0); + const newStartIndex = Math.min(Math.max(bufferedIndex, 0), maxIndex); + + if (virtualizerStartIndex !== newStartIndex) { + // We flush sync this and perform an immediate state update + // due to virtualizerStartIndex invalidation. + flushSync(() => { + batchUpdateNewIndex(newStartIndex); + }); + } + }, + { + root: intersectionObserverRoot ? intersectionObserverRoot?.current : null, + rootMargin: '0px', + threshold: 0, + }, + ); + + const findIndexRecursive = (scrollPos: number, lowIndex: number, highIndex: number): number => { + if (lowIndex > highIndex) { + // We shouldn't get here - but no-op the index if we do. + return virtualizerStartIndex; + } + const midpoint = Math.floor((lowIndex + highIndex) / 2); + const iBefore = Math.max(midpoint - 1, 0); + const iAfter = Math.min(midpoint + 1, childProgressiveSizes.current.length - 1); + const indexValue = childProgressiveSizes.current[midpoint]; + const afterIndexValue = childProgressiveSizes.current[iAfter]; + const beforeIndexValue = childProgressiveSizes.current[iBefore]; + if (scrollPos <= afterIndexValue && scrollPos >= beforeIndexValue) { + /* We've found our index - if we are exactly matching before/after index that's ok, + better to reduce checks if it's right on the boundary. */ + return midpoint; + } + + if (indexValue > scrollPos) { + return findIndexRecursive(scrollPos, lowIndex, midpoint - 1); + } else { + return findIndexRecursive(scrollPos, midpoint + 1, highIndex); + } + }; + + const getIndexFromSizeArray = (scrollPos: number): number => { + /* Quick searches our progressive height array */ + if ( + scrollPos === 0 || + childProgressiveSizes.current.length === 0 || + scrollPos <= childProgressiveSizes.current[0] + ) { + // Check start + return 0; + } + + if (scrollPos >= childProgressiveSizes.current[childProgressiveSizes.current.length - 1]) { + // Check end + return childProgressiveSizes.current.length - 1; + } + + return findIndexRecursive(scrollPos, 0, childProgressiveSizes.current.length - 1); + }; + + const getIndexFromScrollPosition = (scrollPos: number) => { + if (!getItemSize) { + return Math.round(scrollPos / itemSize); + } + + return getIndexFromSizeArray(scrollPos); + }; + + const calculateTotalSize = () => { + if (!getItemSize) { + return itemSize * numItems; + } + + // Time for custom size calcs + return childProgressiveSizes.current[numItems - 1]; + }; + + const calculateBefore = () => { + if (!getItemSize) { + // The missing items from before virtualization starts height + return virtualizerStartIndex * itemSize; + } + + if (virtualizerStartIndex <= 0) { + return 0; + } + + // Time for custom size calcs + return childProgressiveSizes.current[virtualizerStartIndex - 1]; + }; + + const calculateAfter = () => { + if (numItems === 0) { + return 0; + } + + const lastItemIndex = Math.min(virtualizerStartIndex + virtualizerLength, numItems - 1); + if (!getItemSize) { + // The missing items from after virtualization ends height + const remainingItems = numItems - lastItemIndex - 1; + return remainingItems * itemSize; + } + + // Time for custom size calcs + return childProgressiveSizes.current[numItems - 1] - childProgressiveSizes.current[lastItemIndex]; + }; + + const updateChildRows = (newIndex: number) => { + if (numItems === 0) { + /* Nothing to virtualize */ + + return []; + } + + if (childArray.current.length !== numItems) { + childArray.current = new Array(virtualizerLength); + } + const actualIndex = Math.max(newIndex, 0); + const end = Math.min(actualIndex + virtualizerLength, numItems); + + for (let i = actualIndex; i < end; i++) { + childArray.current[i - actualIndex] = renderChild(i); + } + }; + + const setBeforeRef = useCallback( + (element: HTMLDivElement) => { + if (!element || beforeElementRef.current === element) { + return; + } + beforeElementRef.current = element; + const newList = []; + + newList.push(beforeElementRef.current); + + if (afterElementRef.current) { + newList.push(afterElementRef.current); + } + + // Ensure we update array if before element changed + setObserverList(newList); + }, + [setObserverList], + ); + + const setAfterRef = useCallback( + (element: HTMLDivElement) => { + if (!element || afterElementRef.current === element) { + return; + } + afterElementRef.current = element; + const newList = []; + + if (beforeElementRef.current) { + newList.push(beforeElementRef.current); + } + + newList.push(afterElementRef.current); + + // Ensure we update array if after element changed + setObserverList(newList); + }, + [setObserverList], + ); + + const updateCurrentItemSizes = (newIndex: number) => { + if (!getItemSize) { + // Static sizes, not required. + return; + } + // We should always call our size function on index change (only for the items that will be rendered) + // This ensures we request the latest data for incoming items in case sizing has changed. + const endIndex = Math.min(newIndex + virtualizerLength, numItems); + const startIndex = Math.max(newIndex, 0); + + let didUpdate = false; + for (let i = startIndex; i < endIndex; i++) { + const newSize = getItemSize(i); + if (newSize !== childSizes.current[i]) { + childSizes.current[i] = newSize; + didUpdate = true; + } + } + + if (didUpdate) { + // Update our progressive size array + for (let i = startIndex; i < numItems; i++) { + const prevSize = i > 0 ? childProgressiveSizes.current[i - 1] : 0; + childProgressiveSizes.current[i] = prevSize + childSizes.current[i]; + } + } + }; + + // Initialize the size array before first render. + const hasInitialized = useRef(false); + const initializeSizeArray = () => { + if (hasInitialized.current === false) { + hasInitialized.current = true; + populateSizeArrays(); + } + }; + + // Initialization on mount - update array index to 0 (ready state). + // Only fire on mount (no deps). + useEffect(() => { + if (virtualizerStartIndex < 0) { + batchUpdateNewIndex(0); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + // If the user passes in an updated renderChild function - update current children + useEffect(() => { + if (virtualizerStartIndex >= 0) { + updateChildRows(virtualizerStartIndex); + forceUpdate(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [renderChild]); + + // Ensure we have run through and updated the whole size list array at least once. + initializeSizeArray(); + + if (getItemSize && (numItems !== childSizes.current.length || numItems !== childProgressiveSizes.current.length)) { + // Child length mismatch, repopulate size arrays. + populateSizeArrays(); + } + + const isFullyInitialized = hasInitialized.current && virtualizerStartIndex >= 0; + return { + components: { + before: 'div', + after: 'div', + beforeContainer: 'div', + afterContainer: 'div', + }, + virtualizedChildren: childArray.current, + before: resolveShorthand(props.before, { + required: true, + defaultProps: { + ref: setBeforeRef, + role: 'none', + }, + }), + after: resolveShorthand(props.after, { + required: true, + defaultProps: { + ref: setAfterRef, + role: 'none', + }, + }), + beforeContainer: resolveShorthand(props.beforeContainer, { + required: true, + defaultProps: { + role: 'none', + }, + }), + afterContainer: resolveShorthand(props.afterContainer, { + required: true, + defaultProps: { + role: 'none', + }, + }), + beforeBufferHeight: isFullyInitialized ? calculateBefore() : 0, + afterBufferHeight: isFullyInitialized ? calculateAfter() : 0, + totalVirtualizerHeight: isFullyInitialized ? calculateTotalSize() : virtualizerLength * itemSize, + virtualizerStartIndex, + axis, + bufferSize, + reversed, + }; +} diff --git a/packages/react-components/react-virtualizer/src/components/Virtualizer/useVirtualizerStyles.ts b/packages/react-components/react-virtualizer/src/components/Virtualizer/useVirtualizerStyles.ts new file mode 100644 index 0000000000000..0f11ce8778d7b --- /dev/null +++ b/packages/react-components/react-virtualizer/src/components/Virtualizer/useVirtualizerStyles.ts @@ -0,0 +1,122 @@ +import { makeStyles, mergeClasses } from '@griffel/react'; +import { VirtualizerSlots, VirtualizerState } from './Virtualizer.types'; +import type { SlotClassNames } from '@fluentui/react-utilities'; + +const virtualizerClassName = 'fui-Virtualizer'; +export const virtualizerClassNames: SlotClassNames = { + before: `${virtualizerClassName}__before`, + beforeContainer: `${virtualizerClassName}__beforeContainer`, + after: `${virtualizerClassName}__after`, + afterContainer: `${virtualizerClassName}__afterContainer`, +}; + +const useStyles = makeStyles({ + base: { + display: 'block', + pointerEvents: 'none', + }, + relative: { + position: 'relative', + }, + horizontal: { + minHeight: '100%', + }, + vertical: { + minWidth: '100%', + }, +}); + +/** + * Apply styling to the Virtualizer states + */ +export const useVirtualizerStyles_unstable = (state: VirtualizerState): VirtualizerState => { + const styles = useStyles(); + const { reversed, axis, beforeBufferHeight, afterBufferHeight, bufferSize } = state; + const horizontal = axis === 'horizontal'; + + state.before.className = mergeClasses( + virtualizerClassNames.before, + styles.base, + styles.relative, + horizontal ? styles.horizontal : styles.vertical, + state.before.className, + ); + + state.after.className = mergeClasses( + virtualizerClassNames.after, + styles.base, + styles.relative, + horizontal ? styles.horizontal : styles.vertical, + state.after.className, + ); + + state.beforeContainer.className = mergeClasses( + virtualizerClassNames.beforeContainer, + styles.base, + horizontal ? styles.horizontal : styles.vertical, + state.beforeContainer.className, + ); + + state.afterContainer.className = mergeClasses( + virtualizerClassNames.afterContainer, + styles.base, + horizontal ? styles.horizontal : styles.vertical, + state.afterContainer.className, + ); + + const beforeHeightPx = beforeBufferHeight + 'px'; + const afterHeightPx = afterBufferHeight + 'px'; + const beforeBufferHeightPx = beforeBufferHeight + bufferSize + 'px'; + const afterBufferHeightPx = afterBufferHeight + bufferSize + 'px'; + const bufferPx = bufferSize + 'px'; + + const beforeBuffer = { + // Column + ...(!reversed && !horizontal && { marginBottom: `-${bufferPx}` }), + // Column-Reverse + ...(reversed && !horizontal && { marginTop: `-${bufferPx}` }), + // Row + ...(!reversed && horizontal && { marginLeft: `-${bufferPx}` }), + // Row-Reverse + ...(reversed && horizontal && { marginRight: `-${bufferPx}` }), + }; + + const afterBuffer = { + // Column + ...(!reversed && !horizontal && { marginTop: `-${bufferPx}` }), + // Column-Reverse + ...(reversed && !horizontal && { marginBottom: `-${bufferPx}` }), + // Row + ...(!reversed && horizontal && { marginLeft: `-${bufferPx}` }), + // Row-Reverse + ...(reversed && horizontal && { marginRight: `-${bufferPx}` }), + }; + + state.before.style = { + height: horizontal ? '100%' : beforeBufferHeightPx, + width: horizontal ? beforeBufferHeightPx : '100%', + ...beforeBuffer, + ...state.before.style, + }; + + state.beforeContainer.style = { + height: horizontal ? 'auto' : beforeHeightPx, + width: horizontal ? beforeHeightPx : 'auto', + ...state.beforeContainer.style, + }; + + state.after.style = { + height: horizontal ? '100%' : afterBufferHeightPx, + width: horizontal ? afterBufferHeightPx : '100%', + ...afterBuffer, + ...state.after.style, + }; + + state.afterContainer.style = { + height: horizontal ? 'auto' : afterHeightPx, + width: horizontal ? afterHeightPx : 'auto', + ...state.afterContainer.style, + }; + + return state; +}; diff --git a/packages/react-components/react-virtualizer/src/hooks/index.ts b/packages/react-components/react-virtualizer/src/hooks/index.ts new file mode 100644 index 0000000000000..97e1994797fa2 --- /dev/null +++ b/packages/react-components/react-virtualizer/src/hooks/index.ts @@ -0,0 +1 @@ +export * from './useIntersectionObserver'; diff --git a/packages/react-components/react-virtualizer/src/hooks/useIntersectionObserver.ts b/packages/react-components/react-virtualizer/src/hooks/useIntersectionObserver.ts new file mode 100644 index 0000000000000..cfceb58f66a02 --- /dev/null +++ b/packages/react-components/react-virtualizer/src/hooks/useIntersectionObserver.ts @@ -0,0 +1,58 @@ +import type { Dispatch, MutableRefObject, SetStateAction } from 'react'; +import * as React from 'react'; +import { useIsomorphicLayoutEffect } from '@fluentui/react-utilities'; + +const { useState, useRef } = React; + +/** + * React hook that allows easy usage of the browser API IntersectionObserver within React + * @param callback - A function called when the percentage of the target element is visible crosses a threshold. + * @param options - An optional object which customizes the observer. If options isn't specified, the observer uses the + * document's viewport as the root, with no margin, and a 0% threshold (meaning that even a one-pixel change is + * enough to trigger a callback). + * @returns An array containing a callback to update the list of Elements the observer should listen to, a callback to + * update the init options of the IntersectionObserver and a ref to the IntersectionObserver instance itself. + */ + +export const useIntersectionObserver = ( + callback: IntersectionObserverCallback, + options?: IntersectionObserverInit, +): { + setObserverList: Dispatch>; + setObserverInit: Dispatch>; + observer: MutableRefObject; +} => { + // export const useIntersectionObserver = ( + // callback: IntersectionObserverCallback, + // options?: IntersectionObserverInit, + // ): [ + // Dispatch>, + // Dispatch>, + // MutableRefObject, + // ] => { + const observer = useRef(); + const [observerList, setObserverList] = useState(); + const [observerInit, setObserverInit] = useState(options); + + // Observer elements in passed in list and clean up previous list + // This effect is only triggered when observerList is updated + useIsomorphicLayoutEffect(() => { + observer.current = new IntersectionObserver(callback, observerInit); + + // If we have an instance of IO and a list with elements, observer the elements + if (observer.current && observerList && observerList.length > 0) { + observerList.forEach(element => { + observer.current?.observe(element); + }); + } + + // clean up previous elements being listened to + return () => { + if (observer.current) { + observer.current.disconnect(); + } + }; + }, [observerList, observerInit, callback]); + + return { setObserverList, setObserverInit, observer }; +}; diff --git a/packages/react-components/react-virtualizer/src/index.ts b/packages/react-components/react-virtualizer/src/index.ts new file mode 100644 index 0000000000000..3d8f72a15d351 --- /dev/null +++ b/packages/react-components/react-virtualizer/src/index.ts @@ -0,0 +1,14 @@ +export { + Virtualizer, + virtualizerClassNames, + useVirtualizer_unstable, + renderVirtualizer_unstable, + useVirtualizerStyles_unstable, +} from './Virtualizer'; +export type { + VirtualizerProps, + VirtualizerState, + VirtualizerSlots, + VirtualizerChildRenderFunction, +} from './Virtualizer'; +export { useIntersectionObserver } from './Hooks'; diff --git a/packages/react-components/react-virtualizer/src/testing/useVirtualizer.test.ts b/packages/react-components/react-virtualizer/src/testing/useVirtualizer.test.ts new file mode 100644 index 0000000000000..1205684eb4d34 --- /dev/null +++ b/packages/react-components/react-virtualizer/src/testing/useVirtualizer.test.ts @@ -0,0 +1,38 @@ +import { renderHook } from '@testing-library/react-hooks'; +import { useVirtualizer_unstable } from '../components/Virtualizer/useVirtualizer'; + +describe('useVirtualizer', () => { + beforeEach(() => { + // IntersectionObserver isn't available in test environment + const mockIntersectionObserver = jest.fn(); + mockIntersectionObserver.mockReturnValue({ + observe: () => null, + unobserve: () => null, + disconnect: () => null, + }); + window.IntersectionObserver = mockIntersectionObserver; + }); + + it('should have the correct number of initial items', () => { + const virtualizerLength = 50; + const actualLength = 250; + const divArr = new Array(actualLength).fill('Test-Node'); + + const rowFunc = (index: number) => { + return divArr[index]; + }; + const { result } = renderHook(() => + useVirtualizer_unstable({ + numItems: divArr.length, + virtualizerLength, + itemSize: 100, // 100 pixels + children: rowFunc, + }), + ); + + // Initial render shows only first 100 items + expect(result.current.virtualizedChildren.length).toBe(virtualizerLength); + // The start index should be 0 once mounted + expect(result.current.virtualizerStartIndex).toBe(0); + }); +}); diff --git a/packages/react-components/react-virtualizer/stories/Virtualizer/Default.stories.tsx b/packages/react-components/react-virtualizer/stories/Virtualizer/Default.stories.tsx new file mode 100644 index 0000000000000..cbeabffb5cbc0 --- /dev/null +++ b/packages/react-components/react-virtualizer/stories/Virtualizer/Default.stories.tsx @@ -0,0 +1,43 @@ +import * as React from 'react'; +import { Virtualizer } from '@fluentui/react-components/unstable'; +import { makeStyles } from '@fluentui/react-components'; + +const useStyles = makeStyles({ + container: { + display: 'flex', + flexDirection: 'column', + overflowAnchor: 'none', + overflowY: 'auto', + width: '100%', + height: '100%', + maxHeight: '750px', + }, + child: { + height: '100px', + lineHeight: '100px', + width: '100%', + }, +}); + +export const Default = () => { + const styles = useStyles(); + const childLength = 1000; + + return ( +
+ + {index => { + return ( + {`Node-${index}`} + ); + }} + +
+ ); +}; diff --git a/packages/react-components/react-virtualizer/stories/Virtualizer/Dynamic.stories.tsx b/packages/react-components/react-virtualizer/stories/Virtualizer/Dynamic.stories.tsx new file mode 100644 index 0000000000000..73000e8da9fe5 --- /dev/null +++ b/packages/react-components/react-virtualizer/stories/Virtualizer/Dynamic.stories.tsx @@ -0,0 +1,80 @@ +import * as React from 'react'; +import { Virtualizer } from '@fluentui/react-components/unstable'; +import { makeStyles } from '@fluentui/react-components'; + +const smallSize = 100; +const largeSize = 200; +const useStyles = makeStyles({ + container: { + display: 'flex', + flexDirection: 'column', + overflowAnchor: 'none', + overflowY: 'auto', + width: '100%', + height: '100%', + maxHeight: '750px', + }, + child: { + height: `${smallSize}px`, + lineHeight: `${smallSize}px`, + width: '100%', + backgroundColor: '#BBBBBB', + }, + childLarge: { + height: `${largeSize}px`, + lineHeight: `${largeSize}px`, + width: '100%', + backgroundColor: '#DDDDDD', + }, +}); + +export const Dynamic = () => { + const [flag, toggleFlag] = React.useState(false); + const styles = useStyles(); + const childLength = 1000; + + React.useEffect(() => { + updateTimeout(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + const updateTimeout = () => + setTimeout(() => { + toggleFlag(iFlag => !iFlag); + updateTimeout(); + }, 2000); + + const getSizeForIndex = (index: number): number => { + const sizeValue1 = flag ? largeSize : smallSize; + const sizeValue2 = flag ? smallSize : largeSize; + + const sizeValue = index % 2 === 0 ? sizeValue1 : sizeValue2; + return sizeValue; + }; + + return ( +
+ getSizeForIndex(index)} + numItems={childLength} + bufferSize={50} + virtualizerLength={25} + itemSize={100} + > + {(index: number) => { + const sizeValue = getSizeForIndex(index); + const sizeClass = sizeValue === smallSize ? styles.child : styles.childLarge; + return ( +
{`Node-${index}-size-${sizeValue}`}
+ ); + }} +
+
+ ); +}; diff --git a/packages/react-components/react-virtualizer/stories/Virtualizer/Horizontal.stories.tsx b/packages/react-components/react-virtualizer/stories/Virtualizer/Horizontal.stories.tsx new file mode 100644 index 0000000000000..4832d1c21491a --- /dev/null +++ b/packages/react-components/react-virtualizer/stories/Virtualizer/Horizontal.stories.tsx @@ -0,0 +1,43 @@ +import * as React from 'react'; +import { Virtualizer } from '@fluentui/react-components/unstable'; +import { makeStyles } from '@fluentui/react-components'; + +const useStyles = makeStyles({ + container: { + display: 'flex', + flexDirection: 'row', + overflowAnchor: 'none', + overflowY: 'auto', + width: '100%', + height: '100%', + maxHeight: '750px', + }, + child: { + minWidth: '100px', + minHeight: '100px', + height: '100%', + }, +}); + +export const Horizontal = () => { + const styles = useStyles(); + const childLength = 1000; + + return ( +
+ + {index => { + return ( + {`Node-${index}`} + ); + }} + +
+ ); +}; diff --git a/packages/react-components/react-virtualizer/stories/Virtualizer/RTL.stories.tsx b/packages/react-components/react-virtualizer/stories/Virtualizer/RTL.stories.tsx new file mode 100644 index 0000000000000..20b75d0dbc387 --- /dev/null +++ b/packages/react-components/react-virtualizer/stories/Virtualizer/RTL.stories.tsx @@ -0,0 +1,44 @@ +import * as React from 'react'; +import { Virtualizer } from '@fluentui/react-components/unstable'; +import { makeStyles } from '@fluentui/react-components'; + +const useStyles = makeStyles({ + container: { + display: 'flex', + flexDirection: 'row', + overflowAnchor: 'none', + overflowY: 'auto', + width: '100%', + height: '100%', + maxHeight: '750px', + direction: 'rtl', + }, + child: { + minWidth: '100px', + minHeight: '100px', + height: '100%', + }, +}); + +export const RTL = () => { + const styles = useStyles(); + const childLength = 1000; + + return ( +
+ + {index => { + return ( + {`Node-${index}`} + ); + }} + +
+ ); +}; diff --git a/packages/react-components/react-virtualizer/stories/Virtualizer/Reversed.stories.tsx b/packages/react-components/react-virtualizer/stories/Virtualizer/Reversed.stories.tsx new file mode 100644 index 0000000000000..6da429c29a1f3 --- /dev/null +++ b/packages/react-components/react-virtualizer/stories/Virtualizer/Reversed.stories.tsx @@ -0,0 +1,43 @@ +import * as React from 'react'; +import { Virtualizer } from '@fluentui/react-components/unstable'; +import { makeStyles } from '@fluentui/react-components'; + +const useStyles = makeStyles({ + container: { + display: 'flex', + flexDirection: 'column-reverse', + overflowAnchor: 'none', + overflowY: 'auto', + width: '100%', + height: '100%', + maxHeight: '750px', + }, + child: { + height: '100px', + lineHeight: '100px', + width: '100%', + }, +}); + +export const Reversed = () => { + const styles = useStyles(); + const childLength = 1000; + + return ( +
+ + {index => { + return ( + {`Node-${index}`} + ); + }} + +
+ ); +}; diff --git a/packages/react-components/react-virtualizer/stories/Virtualizer/ReversedHorizontal.stories.tsx b/packages/react-components/react-virtualizer/stories/Virtualizer/ReversedHorizontal.stories.tsx new file mode 100644 index 0000000000000..3da7b1af43b4e --- /dev/null +++ b/packages/react-components/react-virtualizer/stories/Virtualizer/ReversedHorizontal.stories.tsx @@ -0,0 +1,43 @@ +import * as React from 'react'; +import { Virtualizer } from '@fluentui/react-components/unstable'; +import { makeStyles } from '@fluentui/react-components'; + +const useStyles = makeStyles({ + container: { + display: 'flex', + flexDirection: 'row-reverse', + overflowAnchor: 'none', + overflowY: 'auto', + width: '100%', + height: '100%', + maxHeight: '750px', + }, + child: { + minWidth: '100px', + minHeight: '100px', + height: '100%', + }, +}); + +export const ReversedHorizontal = () => { + const styles = useStyles(); + const childLength = 1000; + + return ( +
+ + {index => { + return ( + {`Node-${index}`} + ); + }} + +
+ ); +}; diff --git a/packages/react-components/react-virtualizer/stories/Virtualizer/VirtualizerDescription.md b/packages/react-components/react-virtualizer/stories/Virtualizer/VirtualizerDescription.md new file mode 100644 index 0000000000000..1bfbae160e2c3 --- /dev/null +++ b/packages/react-components/react-virtualizer/stories/Virtualizer/VirtualizerDescription.md @@ -0,0 +1,12 @@ + + +> **⚠️ Preview components are considered unstable:** +> +> ```jsx +> +> import { Virtualizer } from '@fluentui/react-components/unstable'; +> +> ``` +> +> - Features and APIs may change before final release +> - Please contact us if you intend to use this in your product diff --git a/packages/react-components/react-virtualizer/stories/Virtualizer/index.stories.ts b/packages/react-components/react-virtualizer/stories/Virtualizer/index.stories.ts new file mode 100644 index 0000000000000..af6b333589a67 --- /dev/null +++ b/packages/react-components/react-virtualizer/stories/Virtualizer/index.stories.ts @@ -0,0 +1,21 @@ +import { Virtualizer } from '../../src/Virtualizer'; +import descriptionMd from './VirtualizerDescription.md'; + +export { Default } from './Default.stories'; +export { Dynamic } from './Dynamic.stories'; +export { Horizontal } from './Horizontal.stories'; +export { ReversedHorizontal } from './ReversedHorizontal.stories'; +export { Reversed } from './Reversed.stories'; +export { RTL } from './RTL.stories'; + +export default { + title: 'Preview Components/Virtualizer', + component: Virtualizer, + parameters: { + docs: { + description: { + component: [descriptionMd].join('\n'), + }, + }, + }, +}; diff --git a/packages/react-components/react-virtualizer/tsconfig.json b/packages/react-components/react-virtualizer/tsconfig.json new file mode 100644 index 0000000000000..1941a041d46c1 --- /dev/null +++ b/packages/react-components/react-virtualizer/tsconfig.json @@ -0,0 +1,25 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "target": "ES2019", + "noEmit": true, + "isolatedModules": true, + "importHelpers": true, + "jsx": "react", + "noUnusedLocals": true, + "preserveConstEnums": true + }, + "include": [], + "files": [], + "references": [ + { + "path": "./tsconfig.lib.json" + }, + { + "path": "./tsconfig.spec.json" + }, + { + "path": "./.storybook/tsconfig.json" + } + ] +} diff --git a/packages/react-components/react-virtualizer/tsconfig.lib.json b/packages/react-components/react-virtualizer/tsconfig.lib.json new file mode 100644 index 0000000000000..6f90cf95c005b --- /dev/null +++ b/packages/react-components/react-virtualizer/tsconfig.lib.json @@ -0,0 +1,22 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "lib": ["ES2019", "dom"], + "declaration": true, + "declarationDir": "../../../dist/out-tsc/types", + "outDir": "../../../dist/out-tsc", + "inlineSources": true, + "types": ["static-assets", "environment"] + }, + "exclude": [ + "./src/testing/**", + "**/*.spec.ts", + "**/*.spec.tsx", + "**/*.test.ts", + "**/*.test.tsx", + "**/*.stories.ts", + "**/*.stories.tsx" + ], + "include": ["./src/**/*.ts", "./src/**/*.tsx"] +} diff --git a/packages/react-components/react-virtualizer/tsconfig.spec.json b/packages/react-components/react-virtualizer/tsconfig.spec.json new file mode 100644 index 0000000000000..911456fe4b4d9 --- /dev/null +++ b/packages/react-components/react-virtualizer/tsconfig.spec.json @@ -0,0 +1,17 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "CommonJS", + "outDir": "dist", + "types": ["jest", "node"] + }, + "include": [ + "**/*.spec.ts", + "**/*.spec.tsx", + "**/*.test.ts", + "**/*.test.tsx", + "**/*.d.ts", + "./src/testing/**/*.ts", + "./src/testing/**/*.tsx" + ] +} diff --git a/tsconfig.base.json b/tsconfig.base.json index 582cca768f579..429306e6f2d87 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -77,7 +77,8 @@ "@fluentui/react-tree": ["packages/react-components/react-tree/src/index.ts"], "@fluentui/react-utilities": ["packages/react-components/react-utilities/src/index.ts"], "@fluentui/theme-designer": ["packages/react-components/theme-designer/src/index.ts"], - "@fluentui/tokens": ["packages/tokens/src/index.ts"] + "@fluentui/tokens": ["packages/tokens/src/index.ts"], + "@fluentui/react-virtualizer": ["packages/react-components/react-virtualizer/src/index.ts"] } }, "exclude": ["node_modules"] diff --git a/workspace.json b/workspace.json index 67495f14ad895..bd874eed5a5ac 100644 --- a/workspace.json +++ b/workspace.json @@ -1070,6 +1070,13 @@ "projectType": "library", "implicitDependencies": [] }, + "@fluentui/react-virtualizer": { + "root": "packages/react-components/react-virtualizer", + "projectType": "library", + "implicitDependencies": [], + "sourceRoot": "packages/react-components/react-virtualizer/src", + "tags": ["vNext", "platform:web"] + }, "@fluentui/vr-tests": { "root": "apps/vr-tests", "projectType": "application",