aa-geuthur-react
v2.0.0
Published
Shared React base for the Alliance Auth apps by Geuthur: BaseTable, BaseModal, loaders, menu, hooks and the page layout
Downloads
2,493
Maintainers
Readme
AA Geuthur React
Shared React base for the Alliance Auth apps by Geuthur: the table and modal components, loaders, the navigation menu, hooks, the page layout and the API client that every app with a React frontend uses. The apps install the package and extend it instead of copying the files.
Installation
npm install aa-geuthur-reactThe package is built only at build time of the app, the users of the app get the compiled frontend inside the Python package. It ships ESM with type declarations and expects these peer dependencies in the app: react, react-dom, react-bootstrap, react-router-dom, @tanstack/react-query, @tanstack/react-table, react-i18next, i18next, i18next-http-backend, lucide-react, js-cookie, nuqs and openapi-fetch.
Setup
Provider and routing
The menus, hooks and pages need the names of the app. Wrap the routing with AaReactProvider:
import { AaReactProvider, AuthBase, ErrorPage } from "aa-geuthur-react";
<AaReactProvider projectName="example" appName="aa-example">
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<Routes>
<Route path="/example/" element={<AuthBase />}>
<Route index element={<MainPage />} />
<Route path="*" element={<ErrorPage />} />
</Route>
</Routes>
</BrowserRouter>
</QueryClientProvider>
</AaReactProvider>;projectNameis the URL prefix of the app (/example/api/menu/).appNameis the name of the package (aa-example).menuRefetchInterval(optional, milliseconds) letsuseMenureload the menu in that interval, so badges stay live. Off by default.useAaReact()returns both inside the provider and throws outside of it.
Create the QueryClient with createQueryClient() instead of new QueryClient():
import { createQueryClient } from "aa-geuthur-react";
const queryClient = createQueryClient();- Queries are retried only after a network error (
TypeErroroffetch) or a short outage of the server (502, 503 or 504, thrown by the client ofcreateApiClientasServiceUnavailableError), at most three times. Every other answer of the server (4xx and 500) is shown at once; the rule is exported asshouldRetryQuery(failureCount, error). - For 502, 503 and 504 queries and mutations show the fixed message of
ServiceUnavailableErrorinstead ofapiErrorMessage. - Own options are merged and win:
createQueryClient({ defaultOptions: { queries: { staleTime: 60000 } } }). Mutations keep the defaults of react-query.
Styles
The components use Bootstrap utilities and a few global classes (aa-table-*, aa-react.container, aa-shake, aa-menu-badge-pulse, aa-nav-danger, aa-tooltip). Import the stylesheet once, before the stylesheet of the app so the app can override it:
import "aa-geuthur-react/styles.css";
import "@/Styles/index.css";The stylesheet also holds the shared design tokens (--aa-*, --font-hud, --font-mono) for the dark default and the light and dark themes (data-theme="flatly"/"darkly", data-bs-theme="light"/"dark"), the classes of the status indicator (aa-status-*) and the keyframes aa-pending-ping, aa-pending-glow and aa-danger-glow. The token selectors are wrapped in :where() and have no specificity, so any :root or html[data-theme=…] rule of the app overrides a value:
@import url("aa-geuthur-react/styles.css");
:root {
--font-mono: ui-monospace, monospace;
}Translations
Every text of the package lives in the i18next namespace aa-geuthur-react and is bundled into the package. AaReactProvider registers the translations with the i18next instance of the app when it mounts (addResourceBundle, texts the app already has for the namespace are kept), so the app lists only its own namespace and copies nothing. Untranslated texts are missing from the language files, so i18next falls back to English through fallbackLng.
initI18n(projectName, rootElementId) initializes i18next for the app. Call it in Main.tsx before rendering; finding the container and createRoot(...).render(...) stay in the app:
import { initI18n } from "aa-geuthur-react";
initI18n(ProjectName, `${AppName}-root`);
const container = document.getElementById(`${AppName}-root`);
if (container) {
ReactDOM.createRoot(container).render(<Routing />);
}- The language is the
langattribute of the root element (Django'sLANGUAGE_CODE),enwithout the attribute or the element. - The texts of the app are loaded with
i18next-http-backendfrom/static/<projectName>/i18n/<lng>/translation.json. - Fixed options:
fallbackLng: "en",ns: ["translation"],defaultNS: "translation",returnEmptyString: false(Weblate writes empty plural forms for untranslated texts, they fall back to English),keySeparator: false,nsSeparator: false,interpolation.escapeValue: false,react.useSuspense: false. - It returns the promise of
i18n.init; rendering does not have to wait for it.
The constants I18N_NAMESPACE (aa-geuthur-react) and I18N_FALLBACK_NAMESPACE (translation) are exported. Menu link names come from the app, so the menu tries the package namespace first and the namespace of the app second. registerI18nResources(i18n) adds the translations to an instance outside of the provider, e.g. in a test.
The source files i18n/<lng>/aa-geuthur-react.json (12 languages: en, de, es, fr-FR, it-IT, ja, ko-KR, nl-NL, pl-PL, ru, uk, zh-Hans) are translated in Weblate; en is the template with key equal value and the only file make translations maintains. The other languages hold real translations only, Weblate leaves untranslated texts out. They stay exported as aa-geuthur-react/i18n/<lng>/aa-geuthur-react.json.
API client
createApiClient<paths>() creates an openapi-fetch client with baseUrl: "/", credentials: "same-origin" and the Django CSRF token (csrftoken cookie) as X-CSRFToken header. The app passes the paths type generated from its OpenAPI schema:
import { createApiClient } from "aa-geuthur-react";
import type { paths } from "@/Api/OpenApi";
export const apiClient = createApiClient<paths>();loadMenu(projectName) and loadUserData(projectName) call the endpoints every app provides (<project>/api/menu/ and <project>/api/user/) and are used by useMenu and useUserData. loadUserSettings(projectName) and updateUserSettings(projectName, settings) call GET and PUT <project>/api/settings/ of an app with user settings and are used by useUserSettings. apiErrorMessage(error, fallback) returns the message the API sent with a failed request: the string below error (ErrorSchema of the apps), otherwise the string below detail (Django Ninja), otherwise fallback. The four calls use it, so a failed request throws the message of the API and only without one the fixed text (Failed to load menu, Failed to load user data, Failed to load user settings, Failed to update user settings). Apps use it the same way: throw new Error(apiErrorMessage(error, "Failed to load items")). queryKeys holds the query keys Menu, User and UserSettings.
ESLint rule
The rule import-headings groups imports under heading comments like isort does. In eslint.config.js of the app:
import importHeadingsRule from "aa-geuthur-react/eslint-rules/import-headings";
const importHeadingsPlugin = { rules: { "import-headings": importHeadingsRule } };
// plugins: { "import-headings": importHeadingsPlugin }
// rules: { "import-headings/import-headings": ["error", { groups: [{ heading: "// React", pattern: "^react($|/)" }, ...] }] }Components
BaseTable
Sortable, filterable and paginated table on TanStack Table v9 with CSV export.
import { BaseTable, createBaseColumnHelper } from "aa-geuthur-react";
const columnHelper = createBaseColumnHelper<Row>();
const columns = [columnHelper.accessor("name", { header: "Name" })];
<BaseTable columns={columns} data={rows} />;| Prop | Description |
| :-------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------ |
| columns, data | Column definitions (BaseColumnDef) and rows |
| isLoading, loadingText, isFetching, isError | Loading state (dims the rows and locks the controls), refresh indicator and error row |
| serverPagination | { page, pageSize, total, onPageChange, onPageSizeChange, totalText? }: the server pages the rows; sorting, filters and CSV export are off |
| initialState, pageSizeOptions, enableFilters, striped, hover, variant (default, light), debugTable | Table options |
| rowSelection, onRowSelectionChange, enableRowSelection, getRowId, onRowClick, getRowClassName | Row selection and row handlers |
| emptyText, emptyState, toolbar, footer, showFooter | Empty row text or element, slot above the table, slot below the page controls, column footer definitions as summary row |
| className, tableClassName, headerClassName, bodyClassName, rowClassName, footClassName, footerClassName | Extra classes for the shell, <table>, <thead>, <tbody>, every row, the <tfoot> summary row and the footer with page size, status and pagination |
| exportFileName | File name of the CSV export |
Column meta supports align (left, right, center) and filterOptionLabel for the select filter. Also exported: BaseTableHeader, BaseTablePages, BaseTableForm, BaseToolbar, the filters (Filter, TextFilter, SelectFilter, NumberFilter, BoolFilter), baseTableFeatures, exportToCSV.
BaseModal
Bootstrap modal in two variants. Both share size (ModalSize), centered, scrollable, backdrop, restoreFocus, closeButton, closeText, closeVariant, className, bodyClassName, titleClassName, onShow, onEnter, onExited.
- Default:
show,onHide,title,children,footer(replaces the close button),hideFooter. - Confirm (
variant="confirm"):data(ModalData),showModal,setShowModal,onApprove({ url, formData }),isPending,validate,initialFormData,title,confirmText,confirmVariant;childrenmay be a render function({ formData, onChange }) => ...for a form.
useApproveMutation(queryKey) and useFormApproveMutation(queryKey) post to the modal URL and invalidate the given queries. useModalQueryState(modalKey, entityKey) keeps the open modal and entity id in the URL with nuqs.
Loaders
FetchingLoader: centered spinner;message,className,spinnerClassName.ErrorLoader: warning icon;title,message,className,iconClassName.ErrorBoundary: catches render errors of its children and shows error and component stack;traceClassName.
BaseSectionHeader
Card header with a title (name) and buttons or badges as children.
Menu
AuthLeftMenuAsyncandAuthRightMenuAsyncload the menu withuseMenuand render the links into thenav-leftandnav-rightelements of the Alliance Auth template.AuthLeftMenuandAuthRightMenurender given links (data,isLoading,error).MenuItemrenders one link: internal links as router links below the project prefix, external links ashref, abadgecount in red (pulsing whilehas_errorsis set). A link toadministrationrenders asAdministrationMenuItemwith a shield icon.toProjectPath(projectName, link)builds the route of a link.
Pages
AuthBase: layout of a page; renders the menus and the routed page (Outlet, orchildren) inside theaa-react containerwrapper (640px to 1280px wide) with anErrorBoundary.classNameadds classes to the wrapper.fluidOnSmallScreens(optional, off by default) drops the minimum width of 640px so the page fits on phones narrower than that.ErrorPage: 404 page.
Hooks
useUserData(): the current user ({ user: UserData }), cached for 5 minutes.useUserSettings(): the settings of the current user (UserSettings) as query result plusupdateMutation.updateMutation.mutate(settings)shows the new values at once, restores the previous settings when the request fails and stores the answer of the API when it succeeds. An app with more fields passes its types:useUserSettings<AppSettings>(), oruseUserSettings<AppSettings, AppSettingsUpdate>()whenPUT settings/takes single fields; the sent fields are merged into the loaded settings.useMenu(): the menu links (MenuSchema), one retry.useCooldown():{ seconds, start(duration) }, counts down once per second.useOwnerCooldowns():{ cooldowns, start(ownerId, duration) }, one cooldown per owner id.useFeedback(timeoutMs):{ feedback, showFeedback(variant, text), clearFeedback() }, clears itself after the timeout.
Utils
format:formatDate,formatRelativeTime,formatNumber,formatCompactNumber,formatIsk(locale from i18next,enfallback).eveOnline:shipImageUrl,characterImageUrl,corporationImageUrl,allianceImageUrl,itemImageUrl,getSecColor,formatEveTime.bootsTrap:renderTooltip(message, children).
Types of the API contract
The package defines the types of the endpoints every app provides and does not use the generated OpenAPI types of an app: MenuLink, MenuSchema, UserData, UserSettings, UserSettingsUpdateRequest, ModalSchema (ModalData), ErrorSchema, ActionResponse. The Ninja schemas of the apps follow these types; both change together.
Extending instead of copying
- The files of this package are never changed in an app. What an app needs differently is built in the app by wrapping or composing:
const LedgerTable = (props) => <BaseTable showFooter {...props} />. - Overrides come from outside: every component takes
classNameprops per area and slots (toolbar,footer,emptyState). Bootstrap classes of the app override the look without touching the package. - A new capability comes into this package as a pull request, as an opt-in prop with the current behaviour as default. Then a release and a Dependabot bump in every app. No app runs a special version.
- Contracts are types: the package defines
MenuLink,MenuSchema,UserDataandUserSettings; the Python side delivers matching schemas.
Development
npm ci
make lint # ESLint and Stylelint
make test # Vitest
make build # types and ESM bundle into dist/
make translationsmake lists every target. The tests live in src/__tests__/, the test of the ESLint rule in eslint-rules/.
Release
make prepare-release: scans the translations, moves the changelog entries into a version section and sets the version inpackage.jsonandpackage-lock.json.- Merge the
[RELEASE]pull request. - Create the tag
v<version>and a GitHub release. TheReleaseworkflow checks that the version matches the tag, runs lint, tests and build, attaches the tarball to the release and publishes to npm with trusted publishing (OIDC from GitHub Actions, no token). The trusted publisher on npmjs.com is this repository with the workflowrelease.ymland the environmentnpm-release.
Contributing
You want to improve the project? Please ensure you read the Contribution Guidelines
