Skip to content

Commit

Permalink
feat(floating-ui): added floating-ui action
Browse files Browse the repository at this point in the history
  • Loading branch information
N00nDay committed May 11, 2023
1 parent baf87b6 commit 21af0cb
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 1 deletion.
85 changes: 85 additions & 0 deletions src/lib/actions/floating-ui/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import {
autoUpdate,
computePosition,
flip,
offset,
type DetectOverflowOptions,
type Placement,
type MiddlewareState,
type Coords,
type Strategy,
type ReferenceElement
} from '@floating-ui/dom';

interface IAutoUpdateOptions {
ancestorScroll?: boolean;
ancestorResize?: boolean;
elementResize?: boolean;
animationFrame?: boolean;
}

interface IFlipOptions extends DetectOverflowOptions {
mainAxis?: boolean;
crossAxis?: boolean;
fallbackAxisSideDirection?: 'none' | 'start' | 'end';
flipAlignment?: boolean;
fallbackPlacements?: Array<Placement>;
fallbackStrategy?: 'bestFit' | 'initialPlacement';
}

interface IAxesOffsets {
mainAxis?: number;
crossAxis?: number;
alignmentAxis?: number | null;
}

type TOffsetOptions = number | IAxesOffsets | ((state: MiddlewareState) => number | IAxesOffsets);

interface IShiftOptions extends DetectOverflowOptions {
mainAxis?: boolean;
crossAxis?: boolean;
limiter?: {
fn: (state: MiddlewareState) => Coords;
options?: unknown;
};
}

interface IConfig {
autoUpdate?: IAutoUpdateOptions;
placement?: Placement;
strategy?: Strategy;
offset?: TOffsetOptions;
shift?: IShiftOptions;
flip?: IFlipOptions;
}

export default function floatingUI(
node: HTMLElement,
config: IConfig = {
placement: 'bottom-start',
strategy: 'absolute'
}
): { destroy: () => void } {
const referenceEl = node.previousElementSibling as ReferenceElement;

function updatePosition() {
computePosition(referenceEl, node, {
placement: config?.placement,
strategy: config?.strategy,
middleware: [offset(config.offset), flip()]
}).then(({ x, y }) => {
Object.assign(node.style, {
left: `${x}px`,
top: `${y}px`
});
});
}

const cleanup = autoUpdate(referenceEl, node, updatePosition, config?.autoUpdate);

return {
destroy() {
cleanup();
}
};
}
4 changes: 3 additions & 1 deletion src/lib/actions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import useActions, {
type ActionArray
} from './use-actions';
import clipboard from './clipboard';
import floatingUI from './floating-ui';

export {
tooltip,
Expand All @@ -27,5 +28,6 @@ export {
SVGActionEntry,
SVGActionArray,
ActionArray,
clipboard
clipboard,
floatingUI
};

0 comments on commit 21af0cb

Please sign in to comment.