Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

refactor(app): simplify slider, tab and floating pane math

Hampus13baa1cc1104
diff --git a/fluxer_app/src/features/ui/action_menu/items/CloneExpressionMenuItem.tsx b/fluxer_app/src/features/ui/action_menu/items/CloneExpressionMenuItem.tsx
index 267df4348..19f7f61da 100644
--- a/fluxer_app/src/features/ui/action_menu/items/CloneExpressionMenuItem.tsx
+++ b/fluxer_app/src/features/ui/action_menu/items/CloneExpressionMenuItem.tsx
@@ -46,11 +46,7 @@ export const CloneExpressionMenuItem = observer(
if (!emoji.id) return null;
const emojiId = emoji.id;
- const cloningAllowed = sourceGuild
- ? config.cloningAllowed(sourceGuild)
- : metadataState?.data
- ? metadataState.data.allowCloning
- : null;
+ const cloningAllowed = sourceGuild ? config.cloningAllowed(sourceGuild) : metadataState?.data?.allowCloning;
const isLoadingPermission = needsMetadataLookup && (metadataState?.loading ?? false);
if (cloningAllowed !== true && !isLoadingPermission) return null;
const eligible = Guilds.getGuilds()
diff --git a/fluxer_app/src/features/ui/character_counter/CharacterCounter.tsx b/fluxer_app/src/features/ui/character_counter/CharacterCounter.tsx
index 9a782754c..6f79ce0b0 100644
--- a/fluxer_app/src/features/ui/character_counter/CharacterCounter.tsx
+++ b/fluxer_app/src/features/ui/character_counter/CharacterCounter.tsx
@@ -33,15 +33,18 @@ export const CharacterCounter = observer(
const isNearingLimit = remaining < 50;
const showPremiumFeatures = shouldShowPremiumFeatures();
const needsPremium = canUpgrade && showPremiumFeatures && (isNearingLimit || isOverLimit);
- const tooltipText = needsPremium
- ? i18n._(CHARACTERS_LEFT_GET_TO_WRITE_UP_TO_CHARACTERS_DESCRIPTOR, {
- remaining,
- premiumProductName: getPremiumProductName(),
- premiumMaxLength,
- })
- : isOverLimit
- ? i18n._(MESSAGE_IS_TOO_LONG_DESCRIPTOR)
- : i18n._(CHARACTERS_LEFT_DESCRIPTOR, {remaining});
+ let tooltipText: string;
+ if (needsPremium) {
+ tooltipText = i18n._(CHARACTERS_LEFT_GET_TO_WRITE_UP_TO_CHARACTERS_DESCRIPTOR, {
+ remaining,
+ premiumProductName: getPremiumProductName(),
+ premiumMaxLength,
+ });
+ } else if (isOverLimit) {
+ tooltipText = i18n._(MESSAGE_IS_TOO_LONG_DESCRIPTOR);
+ } else {
+ tooltipText = i18n._(CHARACTERS_LEFT_DESCRIPTOR, {remaining});
+ }
const colorClass = isOverLimit || isNearingLimit ? styles.textDanger : styles.textTertiary;
const counter = needsPremium ? (
<Tooltip text={tooltipText} data-flx="ui.character-counter.character-counter.tooltip">
diff --git a/fluxer_app/src/features/ui/commands/ContextMenuCommands.ts b/fluxer_app/src/features/ui/commands/ContextMenuCommands.ts
index d0ad2beff..1623f4488 100644
--- a/fluxer_app/src/features/ui/commands/ContextMenuCommands.ts
+++ b/fluxer_app/src/features/ui/commands/ContextMenuCommands.ts
@@ -109,14 +109,13 @@ export function openFromEvent(
nativeEvent.detail === 0 &&
nativeEvent.button === 0
);
- const point = hasPointerCoords
- ? {x: event.clientX + 2, y: event.clientY + 2}
- : anchor
- ? (() => {
- const c = getViewportCenterForElement(anchor);
- return {x: c.x + 2, y: c.y + 2};
- })()
- : {x: 0, y: 0};
+ let point = {x: 0, y: 0};
+ if (hasPointerCoords) {
+ point = {x: event.clientX + 2, y: event.clientY + 2};
+ } else if (anchor) {
+ const center = getViewportCenterForElement(anchor);
+ point = {x: center.x + 2, y: center.y + 2};
+ }
openAtPoint(point, render, config, anchor ?? nativeContextMenuTarget);
}
diff --git a/fluxer_app/src/features/ui/components/Scroller.tsx b/fluxer_app/src/features/ui/components/Scroller.tsx
index c45b6e091..2bca2365d 100644
--- a/fluxer_app/src/features/ui/components/Scroller.tsx
+++ b/fluxer_app/src/features/ui/components/Scroller.tsx
@@ -82,7 +82,6 @@ interface ScrollerProps
children: ReactNode;
className?: string;
contentClassName?: string;
- dir?: 'ltr' | 'rtl';
orientation?: ScrollAxis;
overflow?: ScrollOverflow;
fade?: boolean;
@@ -204,7 +203,6 @@ export const Scroller = forwardRef<ScrollerHandle, ScrollerProps>(function Scrol
children,
className,
contentClassName,
- dir = 'ltr',
orientation = 'vertical',
overflow = 'auto',
fade = true,
@@ -716,12 +714,13 @@ export const Scroller = forwardRef<ScrollerHandle, ScrollerProps>(function Scrol
estimatedContentSize != null && Number.isFinite(estimatedContentSize)
? Math.max(0, Math.floor(estimatedContentSize))
: null;
- const contentStyle: CSSProperties | undefined =
- normalizedEstimatedContentSize != null
- ? orientation === 'vertical'
+ let contentStyle: CSSProperties | undefined;
+ if (normalizedEstimatedContentSize != null) {
+ contentStyle =
+ orientation === 'vertical'
? {minHeight: `${normalizedEstimatedContentSize}px`}
- : {minWidth: `${normalizedEstimatedContentSize}px`}
- : undefined;
+ : {minWidth: `${normalizedEstimatedContentSize}px`};
+ }
const shouldReserveTrackSpace = scrollbarTrackMode === 'reserve';
const containerClassName = clsx(styles.scrollerWrap, {
[styles.horizontal]: orientation === 'horizontal',
@@ -751,7 +750,7 @@ export const Scroller = forwardRef<ScrollerHandle, ScrollerProps>(function Scrol
data-fluxer-scroll-container="true"
className={scrollerClassName}
style={scrollerStyle}
- dir={dir}
+ dir={orientation === 'horizontal' ? 'ltr' : undefined}
onScroll={handleScroll}
onKeyDown={handleScrollerKeyDown}
onTouchStart={handleScrollerTouchStart}
diff --git a/fluxer_app/src/features/ui/components/slider/SliderMath.ts b/fluxer_app/src/features/ui/components/slider/SliderMath.ts
index cefe824e5..380ec9118 100644
--- a/fluxer_app/src/features/ui/components/slider/SliderMath.ts
+++ b/fluxer_app/src/features/ui/components/slider/SliderMath.ts
@@ -64,12 +64,19 @@ export function buildMarkerState({
const min = sortedMarkers[0];
const max = sortedMarkers[sortedMarkers.length - 1];
const range = max - min;
- const markerPositions =
- sortedMarkers.length === 1
- ? [0]
- : equidistant
- ? sortedMarkers.map((_, i) => i * (100 / (sortedMarkers.length - 1)))
- : sortedMarkers.map((marker) => scaleValue({min, range}, marker));
+ let markerPositions: Array<number>;
+ if (sortedMarkers.length === 1) {
+ markerPositions = [0];
+ } else if (equidistant) {
+ markerPositions = sortedMarkers.map((_, i) => i * (100 / (sortedMarkers.length - 1)));
+ } else {
+ markerPositions = sortedMarkers.map((marker) => {
+ if (range === 0) {
+ return 0;
+ }
+ return (100 * (marker - min)) / range;
+ });
+ }
return {
min,
max,
@@ -80,11 +87,6 @@ export function buildMarkerState({
};
}
-function scaleValue(markerState: Pick<MarkerState, 'min' | 'range'>, value: number): number {
- if (markerState.range === 0) return 0;
- return (100 * (value - markerState.min)) / markerState.range;
-}
-
export function scaleValueEquidistant(markers: ReadonlyArray<number>, value: number): number {
if (markers.length < 2) return 0;
const boundedValue = clamp(value, markers[0], markers[markers.length - 1]);
diff --git a/fluxer_app/src/features/ui/floating_pane/FloatingPaneMath.ts b/fluxer_app/src/features/ui/floating_pane/FloatingPaneMath.ts
index c50102d96..ee1226c66 100644
--- a/fluxer_app/src/features/ui/floating_pane/FloatingPaneMath.ts
+++ b/fluxer_app/src/features/ui/floating_pane/FloatingPaneMath.ts
@@ -56,18 +56,12 @@ export interface ResizeStart {
paneStartY: number;
}
-export interface FlingOptions {
+interface FlingOptions {
lookaheadSeconds: number;
strongVelocity: number;
axisVelocityFloor: number;
}
-const DEFAULT_FLING_OPTIONS: FlingOptions = {
- lookaheadSeconds: 0.2,
- strongVelocity: 550,
- axisVelocityFloor: 180,
-};
-
function isFiniteNumber(value: number): boolean {
return typeof value === 'number' && Number.isFinite(value);
}
@@ -140,59 +134,38 @@ function snapPointToCorner(point: Point, bounds: DragBounds): Corner {
const midY = (bounds.minY + bounds.maxY) / 2;
const isRight = point.x >= midX;
const isBottom = point.y >= midY;
- return `${isBottom ? 'bottom' : 'top'}-${isRight ? 'right' : 'left'}` as Corner;
+ return `${isBottom ? 'bottom' : 'top'}-${isRight ? 'right' : 'left'}`;
}
-export function pickCornerForFling(
- point: Point,
- velocity: Point,
- bounds: DragBounds,
- options: FlingOptions = DEFAULT_FLING_OPTIONS,
-): Corner {
+export function pickCornerForFling(point: Point, velocity: Point, bounds: DragBounds, options: FlingOptions): Corner {
const projectedX = clamp(point.x + velocity.x * options.lookaheadSeconds, bounds.minX, bounds.maxX);
const projectedY = clamp(point.y + velocity.y * options.lookaheadSeconds, bounds.minY, bounds.maxY);
const speed = Math.hypot(velocity.x, velocity.y);
const midX = (bounds.minX + bounds.maxX) / 2;
const midY = (bounds.minY + bounds.maxY) / 2;
if (speed >= options.strongVelocity) {
- const horizontal =
- Math.abs(velocity.x) >= options.axisVelocityFloor
- ? velocity.x >= 0
- ? 'right'
- : 'left'
- : projectedX >= midX
- ? 'right'
- : 'left';
- const vertical =
- Math.abs(velocity.y) >= options.axisVelocityFloor
- ? velocity.y >= 0
- ? 'bottom'
- : 'top'
- : projectedY >= midY
- ? 'bottom'
- : 'top';
- return `${vertical}-${horizontal}` as Corner;
+ let horizontal: 'left' | 'right';
+ if (Math.abs(velocity.x) >= options.axisVelocityFloor) {
+ horizontal = velocity.x >= 0 ? 'right' : 'left';
+ } else {
+ horizontal = projectedX >= midX ? 'right' : 'left';
+ }
+ let vertical: 'top' | 'bottom';
+ if (Math.abs(velocity.y) >= options.axisVelocityFloor) {
+ vertical = velocity.y >= 0 ? 'bottom' : 'top';
+ } else {
+ vertical = projectedY >= midY ? 'bottom' : 'top';
+ }
+ return `${vertical}-${horizontal}`;
}
return snapPointToCorner({x: projectedX, y: projectedY}, bounds);
}
-export interface ResizeResult {
+interface ResizeResult {
width: number;
offset: Point;
}
-function computeRawWidthDelta(edge: ResizeEdge, deltaX: number, deltaY: number, aspectRatio: number): number {
- const fromHorizontal = edge.includes('right') ? deltaX : edge.includes('left') ? -deltaX : 0;
- const fromVertical = edge.includes('bottom')
- ? deltaY * aspectRatio
- : edge.includes('top')
- ? -deltaY * aspectRatio
- : 0;
- if (edge === 'top' || edge === 'bottom') return fromVertical;
- if (edge === 'left' || edge === 'right') return fromHorizontal;
- return fromHorizontal + fromVertical;
-}
-
export function computeResize(
start: ResizeStart,
pointerX: number,
@@ -203,7 +176,26 @@ export function computeResize(
const {aspectRatio} = geometry;
const deltaX = pointerX - pointerStartX;
const deltaY = pointerY - pointerStartY;
- const rawWidthDelta = computeRawWidthDelta(edge, deltaX, deltaY, aspectRatio);
+ let fromHorizontal = 0;
+ if (edge.includes('right')) {
+ fromHorizontal = deltaX;
+ } else if (edge.includes('left')) {
+ fromHorizontal = -deltaX;
+ }
+ let fromVertical = 0;
+ if (edge.includes('bottom')) {
+ fromVertical = deltaY * aspectRatio;
+ } else if (edge.includes('top')) {
+ fromVertical = -deltaY * aspectRatio;
+ }
+ let rawWidthDelta: number;
+ if (edge === 'top' || edge === 'bottom') {
+ rawWidthDelta = fromVertical;
+ } else if (edge === 'left' || edge === 'right') {
+ rawWidthDelta = fromHorizontal;
+ } else {
+ rawWidthDelta = fromHorizontal + fromVertical;
+ }
const nextWidth = clampWidth(startWidth + rawWidthDelta, geometry);
const appliedWidthDelta = nextWidth - startWidth;
const appliedHeightDelta = appliedWidthDelta / aspectRatio;
diff --git a/fluxer_app/src/features/ui/hooks/useResizablePane.ts b/fluxer_app/src/features/ui/hooks/useResizablePane.ts
index 207b494cf..2841224b1 100644
--- a/fluxer_app/src/features/ui/hooks/useResizablePane.ts
+++ b/fluxer_app/src/features/ui/hooks/useResizablePane.ts
@@ -564,19 +564,12 @@ export function useResizablePane(
let requestedSize = measuredSize;
if (event.key === 'Home' || event.key === 'End') {
const setMaximum = event.key === 'End';
+ const limitSize = setMaximum
+ ? {width: Number.MAX_SAFE_INTEGER, height: Number.MAX_SAFE_INTEGER}
+ : optionsRef.current.minSize;
requestedSize = {
- width:
- edge.includes('left') || edge.includes('right')
- ? setMaximum
- ? Number.MAX_SAFE_INTEGER
- : optionsRef.current.minSize.width
- : measuredSize.width,
- height:
- edge.includes('top') || edge.includes('bottom')
- ? setMaximum
- ? Number.MAX_SAFE_INTEGER
- : optionsRef.current.minSize.height
- : measuredSize.height,
+ width: edge.includes('left') || edge.includes('right') ? limitSize.width : measuredSize.width,
+ height: edge.includes('top') || edge.includes('bottom') ? limitSize.height : measuredSize.height,
};
} else {
const step = event.shiftKey ? RESIZABLE_PANE_KEYBOARD_LARGE_STEP : RESIZABLE_PANE_KEYBOARD_STEP;
diff --git a/fluxer_app/src/features/ui/scroller/ScrollerTrack.tsx b/fluxer_app/src/features/ui/scroller/ScrollerTrack.tsx
index b37be9934..85b48ee09 100644
--- a/fluxer_app/src/features/ui/scroller/ScrollerTrack.tsx
+++ b/fluxer_app/src/features/ui/scroller/ScrollerTrack.tsx
@@ -42,7 +42,7 @@ export function ScrollerTrack({
[styles.visible]: isVisible,
});
const thumbClassName = clsx(styles.thumb, {[styles.active]: isDragging});
- const trackPointerEvents = isTouchDevice ? 'none' : isVisible ? 'auto' : 'none';
+ const trackPointerEvents = !isTouchDevice && isVisible ? 'auto' : 'none';
return (
<div
ref={trackRef}
diff --git a/fluxer_app/src/features/ui/tabs/TabKeyboardNavigation.ts b/fluxer_app/src/features/ui/tabs/TabKeyboardNavigation.ts
index 71a036e4b..415efe760 100644
--- a/fluxer_app/src/features/ui/tabs/TabKeyboardNavigation.ts
+++ b/fluxer_app/src/features/ui/tabs/TabKeyboardNavigation.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-export type TabListOrientation = 'horizontal' | 'vertical' | 'both';
+type TabListOrientation = 'horizontal' | 'vertical' | 'both';
export type TabNavigationDirection = 'previous' | 'next' | 'first' | 'last';
export function getTabNavigationDirection(key: string, orientation: TabListOrientation): TabNavigationDirection | null {
@@ -21,17 +21,24 @@ export function getNextTabIndex(
currentIndex: number,
itemCount: number,
direction: TabNavigationDirection,
- loop = true,
): number | null {
- if (itemCount <= 0) return null;
- if (direction === 'first') return 0;
- if (direction === 'last') return itemCount - 1;
- const current = currentIndex >= 0 && currentIndex < itemCount ? currentIndex : direction === 'next' ? -1 : 0;
- let nextIndex = current + (direction === 'next' ? 1 : -1);
- if (loop) {
- nextIndex = (nextIndex + itemCount) % itemCount;
+ if (itemCount <= 0) {
+ return null;
+ }
+ if (direction === 'first') {
+ return 0;
+ }
+ if (direction === 'last') {
+ return itemCount - 1;
+ }
+ let current: number;
+ if (currentIndex >= 0 && currentIndex < itemCount) {
+ current = currentIndex;
+ } else if (direction === 'next') {
+ current = -1;
} else {
- nextIndex = Math.min(Math.max(nextIndex, 0), itemCount - 1);
+ current = 0;
}
- return nextIndex;
+ const nextIndex = current + (direction === 'next' ? 1 : -1);
+ return (nextIndex + itemCount) % itemCount;
}
diff --git a/fluxer_app/src/features/ui/toast/Toast.tsx b/fluxer_app/src/features/ui/toast/Toast.tsx
index ac564f63e..a8cb5f198 100644
--- a/fluxer_app/src/features/ui/toast/Toast.tsx
+++ b/fluxer_app/src/features/ui/toast/Toast.tsx
@@ -71,7 +71,8 @@ export const Toast = observer(
className={`${styles.icon} ${styles.iconSuccess} ${isMobileExperience ? styles.iconMobile : styles.iconDesktop}`}
data-flx="ui.toast.toast.icon"
/>
- ) : type === 'error' ? (
+ ) : null}
+ {type === 'error' ? (
<XIcon
weight="bold"
className={`${styles.icon} ${styles.iconError} ${isMobileExperience ? styles.iconMobile : styles.iconDesktop}`}