Files
Tom Moor b72f11b01e chore: Enforce more codebase conventions with lint rules (#14310)
* chore: Enforce more codebase conventions with lint rules

Add lint rules for request.origin, deferred useLocation reads, # private
members, lodash and date-fns subpath imports, and button types. Fix the
existing violations.

* fix: Only flag useLocation reads in event handlers and useCallback

* test: Use a fixed member name in users.list name query test
2026-10-24 13:23:25 -04:00

92 lines
2.6 KiB
TypeScript

import { observer } from "mobx-react";
import * as React from "react";
import type { Props as TooltipProps } from "~/components/Tooltip";
import Tooltip from "~/components/Tooltip";
import { performAction, resolve } from "~/actions";
import useActionContext from "~/hooks/useActionContext";
import type { ActionVariant, ActionWithChildren } from "~/types";
export type Props = React.HTMLAttributes<HTMLButtonElement> & {
/** Show the button in a disabled state */
disabled?: boolean;
/** Hide the button entirely if action is not applicable */
hideOnActionDisabled?: boolean;
/** Action to use on button */
action?: Exclude<ActionVariant, ActionWithChildren>;
/** If tooltip props are provided the button will be wrapped in a tooltip */
tooltip?: Omit<TooltipProps, "children">;
/** The button type, defaults to "button" */
type?: "button" | "submit" | "reset";
};
/**
* Button that can be used to trigger an action definition.
*/
function ActionButton({
action,
tooltip,
hideOnActionDisabled,
ref,
type = "button",
...rest
}: Props & { ref?: React.Ref<HTMLButtonElement> }) {
const actionContext = useActionContext({
isButton: true,
});
const [executing, setExecuting] = React.useState(false);
if (!actionContext || !action) {
// oxlint-disable-next-line react/button-has-type -- type defaults to "button"
return <button {...rest} type={type} ref={ref} />;
}
const actionIsDisabled =
action.visible && !resolve<boolean>(action.visible, actionContext);
if (actionIsDisabled && hideOnActionDisabled) {
return null;
}
const disabled = rest.disabled || actionIsDisabled;
const label =
rest["aria-label"] ??
(typeof action.name === "function"
? action.name(actionContext)
: action.name);
const button = (
<button
{...rest}
// oxlint-disable-next-line react/button-has-type -- type defaults to "button"
type={type}
aria-label={typeof label === "string" ? label : undefined}
disabled={disabled || executing}
ref={ref}
onClick={
actionContext
? (ev) => {
ev.preventDefault();
ev.stopPropagation();
const response = performAction(action, actionContext);
if (response?.finally) {
setExecuting(true);
void response.finally(() => setExecuting(false));
}
}
: rest.onClick
}
>
{rest.children ?? label}
</button>
);
if (tooltip) {
return <Tooltip {...tooltip}>{button}</Tooltip>;
}
return button;
}
export default observer(ActionButton);