#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
import React, {
useCallback,
useEffect,
useMemo,
useState,
Suspense,
} from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Icon } from "@editor/ui/Icon";
import { useTranslation } from "react-i18next";
import { LoadingFallback } from "@editor/components/shared/LoadingFallback";
import { useSectionHeadings } from "@editor/components/settings/useSectionHeadings";
import { useActiveHeading } from "@editor/components/settings/useActiveHeading";
import { InfoTooltip } from "@editor/ui/InfoTooltip";
import LoginRequiredBanner from "@editor/components/shared/config/LoginRequiredBanner";
import { Badge, Tooltip } from "@mantine/core";
import { SettingsMobileBackButton } from "@editor/components/shared/config/SettingsMobileBackButton";
import { SettingsNavChevron } from "@editor/components/shared/config/SettingsNavChevron";
import { useSettingsNav } from "@editor/components/settings/useSettingsNav";
import SuperSearch from "@editor/components/shared/superSearch/SuperSearch";
import { useEditorSearchScopes } from "@editor/hooks/useSuperSearch";
import { useTitleBarStrip } from "@editor/contexts/TitleBarStripContext";
import type { NavKey } from "@editor/components/shared/config/types";
import { useIsMobile } from "@editor/hooks/useIsMobile";
import { useLicenseAlert } from "@editor/hooks/useLicenseAlert";
import {
UnsavedChangesProvider,
useUnsavedChanges,
} from "@editor/contexts/UnsavedChangesContext";
import { QuickNavHostBridge } from "@editor/components/shared/quickNav/QuickNavHostBridge";
import { EDITOR_BASENAME } from "@editor/routes/editorBasename";
import { READER_PATH } from "@editor/routes/readerRoute";
import { usePreferences } from "@editor/contexts/PreferencesContext";
import { stripBasePath } from "@editor/constants/app";
import { Z_INDEX_OVER_CONFIG_MODAL } from "@editor/styles/zIndex";
import "@editor/components/shared/config/settingsSections.css";
import "@editor/pages/SettingsPage.css";
const ANCHOR_POLL_MS = 150;
const ANCHOR_WAIT_MS = 5000;
/** `/settings/people` -> "people". Null for `/settings` itself. */
function sectionFromPath(pathname: string): string | null {
const match = stripBasePath(pathname).match(/\/settings\/([^/?#]+)/);
return match?.[1] ?? null;
}
const SettingsPageInner: React.FC = () => {
const { t } = useTranslation();
const [contentRef, setContentRef] = useState<HTMLDivElement | null>(null);
const navigate = useNavigate();
const location = useLocation();
const isMobile = useIsMobile();
const licenseAlert = useLicenseAlert();
const { confirmIfDirty } = useUnsavedChanges();
const { preferences } = usePreferences();
const goToStartupView = () => {
const view = preferences.defaultStartupView;
navigate(
view === "read"
? READER_PATH
: view === "automate"
? "/automate"
: EDITOR_BASENAME,
);
};
// The same bar as the editor and the processor, so search is one thing
// everywhere; settings results deep-link straight back into this page.
const searchScopes = useEditorSearchScopes();
// A title-bar strip already hosts the one Super Search; don't add a second here.
const strip = useTitleBarStrip();
const [mobilePane, setMobilePane] = useState<"nav" | "content">(() =>
sectionFromPath(window.location.pathname) ? "content" : "nav",
);
// Always the editor, not where settings was opened from: the Help tours
// walk the editor's own controls, which the reader and processor don't render.
const leave = useCallback(() => {
navigate(EDITOR_BASENAME, { replace: true });
}, [navigate]);
const { sections, overlay, aliases, pending } = useSettingsNav(leave);
const items = useMemo(() => sections.flatMap((s) => s.items), [sections]);
const urlSection = sectionFromPath(location.pathname);
const activeItem = useMemo(
() => items.find((i) => i.key === urlSection) ?? null,
[items, urlSection],
);
const activeGroup = useMemo(
() =>
sections.find((s) => s.items.some((i) => i.key === activeItem?.key))
?.title,
[sections, activeItem],
);
// The URL always names what is shown. `/settings` and an unknown key land on
// the first section; a retired key (an old bookmark, an older search result)
// follows its alias to whatever replaced it.
useEffect(() => {
// `pending` matters as much as an empty list: the permission-gated sections
// arrive a request later, so a deep link to one of them is not unknown yet.
if (items.length === 0 || activeItem || pending) return;
const alias = urlSection ? aliases?.[urlSection] : undefined;
const target = alias ?? items.find((i) => !i.disabled)?.key ?? items[0].key;
// An aliased link keeps its hash; without one it lands on the card that
// took the retired row's key as its id.
const hash = location.hash || (alias ? `#${urlSection}` : "");
navigate(`/settings/${target}${location.search}${hash}`, {
replace: true,
});
}, [
items,
activeItem,
pending,
urlSection,
aliases,
location.search,
location.hash,
navigate,
]);
// Replace, not push: Back should leave settings, not walk the tabs you opened.
const switchSection = useCallback(
(key: NavKey) => {
navigate(`/settings/${key}`, { replace: true });
},
[navigate],
);
const handleNavigation = useCallback(
async (key: NavKey) => {
if (!(await confirmIfDirty())) return;
switchSection(key);
setMobilePane("content");
},
[confirmIfDirty, switchSection],
);
const handleMobileBack = useCallback(async () => {
if (!(await confirmIfDirty())) return;
setMobilePane("nav");
}, [confirmIfDirty]);
// The rail sits beside the page, so its entries are exits too.
const requestNavigation = useCallback(
(go: () => void) => {
void confirmIfDirty().then((ok) => {
if (ok) go();
});
},
[confirmIfDirty],
);
// Sections dispatch `appConfig:navigate` to send the user to a sibling tab.
useEffect(() => {
const handler = (ev: Event) => {
const key = (ev as CustomEvent<{ key?: NavKey }>).detail?.key;
if (key) switchSection(key);
};
window.addEventListener("appConfig:navigate", handler);
return () => window.removeEventListener("appConfig:navigate", handler);
}, [switchSection]);
const headings = useSectionHeadings(activeItem?.key, contentRef);
const { active: activeHeading, focus: focusHeading } = useActiveHeading(
contentRef,
headings,
);
// On phones the headings are listed on the nav pane, so a heading tap has to
// reveal the content before the scroll can measure it.
const jumpToHeading = useCallback(
(id: string) => {
if (!isMobile) {
focusHeading(id, { moveFocus: true });
return;
}
setMobilePane("content");
window.requestAnimationFrame(() => focusHeading(id, { moveFocus: true }));
},
[focusHeading, isMobile],
);
const anchor = decodeURIComponent(location.hash.replace(/^#/, ""));
const activeKey = activeItem?.key;
// Deep link: /settings/{section}#{slug} scrolls to and briefly highlights one
// control. The slug is the only address; the super search builds the same URL.
//
// Keyed on the section key, never on the item object: the nav builders return
// fresh arrays each render, so depending on the item would re-arm the jump on
// every scroll-spy re-render and pin the reader to the anchor. Sections mount
// lazily, so it polls for the target instead of firing once and missing it.
useEffect(() => {
if (!anchor || !activeKey) return;
let raf = 0;
let timer = 0;
const giveUpAt = Date.now() + ANCHOR_WAIT_MS;
const attempt = () => {
if (document.getElementById(anchor)) {
raf = window.requestAnimationFrame(() => focusHeading(anchor));
} else if (Date.now() < giveUpAt) {
timer = window.setTimeout(attempt, ANCHOR_POLL_MS);
}
};
timer = window.setTimeout(attempt, ANCHOR_POLL_MS);
return () => {
window.clearTimeout(timer);
if (raf) window.cancelAnimationFrame(raf);
};
}, [activeKey, anchor, focusHeading]);
// Sections that bring their own page header get the whole pane; on mobile the
// bar stays anyway, because it carries the only way back to the list.
const fullBleed = activeItem?.fullBleed ?? false;
return (
<div className="settings-page">
<QuickNavHostBridge
requestNavigation={requestNavigation}
onGoToStartupView={goToStartupView}
/>
<aside
className={`settings-page__nav modal-nav ${isMobile ? "mobile" : ""}`}
style={
isMobile && mobilePane !== "nav" ? { display: "none" } : undefined
}
aria-label={t("settings.title", "Settings")}
>
<div className="settings-page__nav-head">
<span className="settings-page__nav-title">
{t("settings.title", "Settings")}
</span>
</div>
<div className="modal-nav-scroll">
{sections.map((section) => {
const groupId = section.id ?? section.title;
// A header that toggles a single row costs a line and a click to
// show what it already named; the row stands on its own instead.
const solo = section.items.length === 1;
return (
<div
key={groupId}
className="modal-nav-section"
data-group={!solo || undefined}
>
{!solo && (
// A plain label, not a disclosure: the rail is short enough
// that hiding rows only cost a click to find them again.
<h2 className="settings-page__group">{section.title}</h2>
)}
<div
id={`settings-group-${groupId}`}
className="modal-nav-section-items"
>
{section.items.map((item) => {
const isActive = activeItem?.key === item.key;
const isDisabled = item.disabled ?? false;
const showPlanWarning =
item.key === "adminPlan" &&
licenseAlert.active &&
licenseAlert.audience === "admin";
const row = (
<button
type="button"
onClick={() => {
if (!isDisabled) void handleNavigation(item.key);
}}
className={`modal-nav-item ${isActive ? "active" : ""} ${isMobile ? "mobile" : ""}`}
data-tour={`admin-${item.key}-nav`}
aria-current={isActive ? "page" : undefined}
// Not `disabled`: it stays focusable, so the tooltip
// saying why it is off is reachable by keyboard.
aria-disabled={isDisabled || undefined}
>
<Icon
name={item.icon}
size={18}
className="settings-page__nav-icon"
/>
<span className="settings-page__nav-label">
{item.label}
</span>
{item.badge && (
<Badge
size="xs"
variant="light"
color={item.badgeColor ?? "orange"}
className="modal-nav-item-badge"
>
{item.badge}
</Badge>
)}
{showPlanWarning && (
<Icon
name="triangle-alert"
size={14}
className="settings-page__nav-warning"
/>
)}
<SettingsNavChevron show={isMobile} />
</button>
);
return isDisabled && item.disabledTooltip ? (
<Tooltip
key={item.key}
label={item.disabledTooltip}
position="right"
withArrow
zIndex={Z_INDEX_OVER_CONFIG_MODAL}
>
{row}
</Tooltip>
) : (
<React.Fragment key={item.key}>
{row}
{isActive && headings.length > 1 && (
<ul className="settings-page__subnav">
{headings.map((h) => (
<li key={h.id}>
<a
href={`#${h.id}`}
className="settings-page__subnav-item"
aria-current={
activeHeading === h.id ? "true" : undefined
}
onClick={(event) => {
event.preventDefault();
jumpToHeading(h.id);
}}
>
{h.label}
</a>
</li>
))}
</ul>
)}
</React.Fragment>
);
})}
</div>
</div>
);
})}
</div>
</aside>
<div
className="settings-page__main modal-content"
style={
isMobile && mobilePane !== "content" ? { display: "none" } : undefined
}
>
{!strip.enabled && (
<div className="settings-page__search-bar">
<SuperSearch
inputId="settings-search-input"
scopes={searchScopes}
dropdownClassName="settings-search-dropdown"
/>
</div>
)}
<div className="modal-content-scroll" ref={setContentRef}>
{isMobile && (
<div className="settings-page__mobile-bar modal-header">
<SettingsMobileBackButton
show
onClick={() => void handleMobileBack()}
/>
<span className="settings-page__mobile-bar-title">
{activeGroup}
</span>
</div>
)}
<div className={`modal-body${fullBleed ? " is-full-bleed" : ""}`}>
{activeItem && !fullBleed && (
<header className="settings-page__header">
{activeGroup && (
<span className="settings-page__eyebrow">{activeGroup}</span>
)}
<div className="settings-page__title-row">
<h1 className="settings-page__title">{activeItem.label}</h1>
{activeItem.description && (
<InfoTooltip
label={activeItem.description}
position="right"
/>
)}
</div>
</header>
)}
{/* Once, here: every admin section used to draw this itself, so an
admin with login off met the same block on all thirteen. */}
<LoginRequiredBanner show={activeItem?.disabled ?? false} />
{/* Its own boundary: a section that suspends must not take the
nav and the header down with it. */}
<Suspense fallback={<LoadingFallback />}>
{activeItem?.component}
</Suspense>
</div>
</div>
</div>
{overlay}
</div>
);
};
/** Full-page settings: account, preferences and every server setting. */
export default function SettingsPage() {
return (
<UnsavedChangesProvider>
<SettingsPageInner />
</UnsavedChangesProvider>
);
}