Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Re-enable typed linting and ban unnecessary type assertions (#8178)

James Brunton33862040f429
diff --git a/frontend/.storybook/preview.tsx b/frontend/.storybook/preview.tsx
index 5d36a0ca16..54af3381a4 100644
--- a/frontend/.storybook/preview.tsx
+++ b/frontend/.storybook/preview.tsx
@@ -63,7 +63,7 @@ for (const [path, raw] of Object.entries(localeModules)) {
if (!lng) continue;
let translation: Record<string, unknown>;
try {
- translation = parseToml(raw) as Record<string, unknown>;
+ translation = parseToml(raw);
} catch {
translation = {};
}
diff --git a/frontend/editor/scripts/generate-tool-api-types.mts b/frontend/editor/scripts/generate-tool-api-types.mts
index b30640b2be..ce1c384556 100644
--- a/frontend/editor/scripts/generate-tool-api-types.mts
+++ b/frontend/editor/scripts/generate-tool-api-types.mts
@@ -159,7 +159,7 @@ function queryParameters(pathItem: Json): { props: Json; required: string[] } {
)
continue;
if (!isObject(param.schema)) continue;
- const schema = structuredClone(param.schema) as Json;
+ const schema = structuredClone(param.schema);
if (!("description" in schema) && typeof param.description === "string") {
schema.description = param.description;
}
@@ -387,10 +387,10 @@ async function main(): Promise<void> {
const component = components[refComponent];
if (!isObject(component)) continue;
className = refComponent;
- modelSchema = structuredClone(component) as Json;
+ modelSchema = structuredClone(component);
} else {
className = pathToClassName(path);
- modelSchema = structuredClone(bodySchema) as Json;
+ modelSchema = structuredClone(bodySchema);
}
// A component shared by several endpoints (e.g. GeneralFile) is only defined once.
@@ -398,7 +398,7 @@ async function main(): Promise<void> {
const uniqueName = dedupe(className, usedClassNames);
className = uniqueName;
const bodyProps: Json = isObject(modelSchema.properties)
- ? (structuredClone(modelSchema.properties) as Json)
+ ? structuredClone(modelSchema.properties)
: {};
const query = queryParameters(pathItem);
// Body wins over query on a name collision.
@@ -468,7 +468,7 @@ async function main(): Promise<void> {
if (name in definitions) continue;
const component = components[name];
if (!isObject(component)) continue;
- const cloned = structuredClone(component) as Json;
+ const cloned = structuredClone(component);
cloned.title = name;
const nested = new Set<string>();
rewriteRefs(cloned, nested);
@@ -504,7 +504,7 @@ async function compileAndWrite(
properties: Object.fromEntries(
uniqueClassNames.map((name) => [name, { $ref: `#/definitions/${name}` }]),
),
- definitions: definitions as Record<string, JSONSchema>,
+ definitions: definitions,
};
// Canonicalize key order so a reordering in SwaggerDoc.json can never change
diff --git a/frontend/editor/src/core/api/toolRecommendations.test.ts b/frontend/editor/src/core/api/toolRecommendations.test.ts
index 1c0ef245be..01390d0bb3 100644
--- a/frontend/editor/src/core/api/toolRecommendations.test.ts
+++ b/frontend/editor/src/core/api/toolRecommendations.test.ts
@@ -37,7 +37,7 @@ describe("toolRecommendations api", () => {
const result = await fetchToolRecommendations("compare", 6);
expect(result).toEqual([{ toolKey: "ocr", score: 5 }]);
- const url = mockGet.mock.calls[0][0] as string;
+ const url = mockGet.mock.calls[0][0];
expect(url).toContain("currentTool=compare");
expect(url).toContain("limit=6");
});
diff --git a/frontend/editor/src/core/components/annotation/shared/PropertiesPopover.tsx b/frontend/editor/src/core/components/annotation/shared/PropertiesPopover.tsx
index 3d8b0c3114..080a972cb3 100644
--- a/frontend/editor/src/core/components/annotation/shared/PropertiesPopover.tsx
+++ b/frontend/editor/src/core/components/annotation/shared/PropertiesPopover.tsx
@@ -33,9 +33,8 @@ export function PropertiesPopover({
strokeWidth?: number;
}
- const obj = annotation?.object as
- | (PdfAnnotationObject & AnnotationObjectProps)
- | undefined;
+ const obj: (PdfAnnotationObject & AnnotationObjectProps) | undefined =
+ annotation?.object;
// Get current values
const fontSize = obj?.fontSize ?? 14;
diff --git a/frontend/editor/src/core/components/easterEgg/brickGame/brickGameEngine.test.ts b/frontend/editor/src/core/components/easterEgg/brickGame/brickGameEngine.test.ts
index f3da54d6c5..52fe287be3 100644
--- a/frontend/editor/src/core/components/easterEgg/brickGame/brickGameEngine.test.ts
+++ b/frontend/editor/src/core/components/easterEgg/brickGame/brickGameEngine.test.ts
@@ -369,12 +369,10 @@ describe("BrickGame", () => {
["fast", 0.85],
["reverse", 0.97],
])("runs the %s effect when that drop is caught", (kind, roll) => {
- alwaysDrop(roll as number);
+ alwaysDrop(roll);
const harness = setup();
harness.game.act();
- expect(
- peak(harness, (s) => effectSeconds(s, kind as string)),
- ).toBeGreaterThan(0);
+ expect(peak(harness, (s) => effectSeconds(s, kind))).toBeGreaterThan(0);
});
it("clears the board's effects when a ball is conceded", () => {
diff --git a/frontend/editor/src/core/components/filesPage/DiskLinkBadge.stories.tsx b/frontend/editor/src/core/components/filesPage/DiskLinkBadge.stories.tsx
index 46bc68ec82..895494d5c2 100644
--- a/frontend/editor/src/core/components/filesPage/DiskLinkBadge.stories.tsx
+++ b/frontend/editor/src/core/components/filesPage/DiskLinkBadge.stories.tsx
@@ -24,7 +24,7 @@ function stub(overrides: Partial<StirlingFileStub>): StirlingFileStub {
originalFileId: "story-file",
versionNumber: 1,
...overrides,
- } as StirlingFileStub;
+ };
}
/** Its original was deleted or moved; this copy is the only one left. */
diff --git a/frontend/editor/src/core/components/filesPage/FileDetailsPanel.stories.tsx b/frontend/editor/src/core/components/filesPage/FileDetailsPanel.stories.tsx
index 76306785ea..01e3cc53fd 100644
--- a/frontend/editor/src/core/components/filesPage/FileDetailsPanel.stories.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileDetailsPanel.stories.tsx
@@ -13,7 +13,7 @@ const buildFileStub = (
size: 245_760,
lastModified: Date.now(),
isLeaf: true,
- originalFileId: "file-1" as FileId,
+ originalFileId: "file-1",
versionNumber: 1,
...overrides,
});
diff --git a/frontend/editor/src/core/components/filesPage/FileGrid.render.test.tsx b/frontend/editor/src/core/components/filesPage/FileGrid.render.test.tsx
index 5e143cead3..d29e60684d 100644
--- a/frontend/editor/src/core/components/filesPage/FileGrid.render.test.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileGrid.render.test.tsx
@@ -30,19 +30,18 @@ vi.mock("@app/components/shared/PolicyBadges", () => ({
return null;
},
}));
-const buildStub = (id: string, name: string): StirlingFileStub =>
- ({
- id: id as FileId,
- name,
- type: "application/pdf",
- size: 1_000,
- lastModified: 0,
- isLeaf: true,
- originalFileId: id,
- versionNumber: 1,
- // Set so useLazyThumbnail short-circuits instead of reading IndexedDB.
- thumbnailUrl: "data:image/svg+xml,%3Csvg/%3E",
- }) as StirlingFileStub;
+const buildStub = (id: string, name: string): StirlingFileStub => ({
+ id: id as FileId,
+ name,
+ type: "application/pdf",
+ size: 1_000,
+ lastModified: 0,
+ isLeaf: true,
+ originalFileId: id,
+ versionNumber: 1,
+ // Set so useLazyThumbnail short-circuits instead of reading IndexedDB.
+ thumbnailUrl: "data:image/svg+xml,%3Csvg/%3E",
+});
describe("FileGrid item memoization", () => {
it("re-renders only the cards whose selection changed", () => {
diff --git a/frontend/editor/src/core/components/filesPage/FileGrid.touch.test.tsx b/frontend/editor/src/core/components/filesPage/FileGrid.touch.test.tsx
index 3761f35e86..fed0542bac 100644
--- a/frontend/editor/src/core/components/filesPage/FileGrid.touch.test.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileGrid.touch.test.tsx
@@ -18,18 +18,17 @@ vi.mock("@app/components/shared/PolicyBadges", () => ({
const render = (ui: Parameters<typeof baseRender>[0]) =>
baseRender(ui, { wrapper: MantineProvider });
-const stub = (id: string): StirlingFileStub =>
- ({
- id: id as FileId,
- name: `${id}.pdf`,
- type: "application/pdf",
- size: 1_000,
- lastModified: 0,
- isLeaf: true,
- originalFileId: id,
- versionNumber: 1,
- thumbnailUrl: "data:image/svg+xml,%3Csvg/%3E",
- }) as StirlingFileStub;
+const stub = (id: string): StirlingFileStub => ({
+ id: id as FileId,
+ name: `${id}.pdf`,
+ type: "application/pdf",
+ size: 1_000,
+ lastModified: 0,
+ isLeaf: true,
+ originalFileId: id,
+ versionNumber: 1,
+ thumbnailUrl: "data:image/svg+xml,%3Csvg/%3E",
+});
function renderGrid(
viewMode: "grid" | "list",
diff --git a/frontend/editor/src/core/components/filesPage/LibraryToolbar.tsx b/frontend/editor/src/core/components/filesPage/LibraryToolbar.tsx
index 3c9b3a9922..2af4293ebe 100644
--- a/frontend/editor/src/core/components/filesPage/LibraryToolbar.tsx
+++ b/frontend/editor/src/core/components/filesPage/LibraryToolbar.tsx
@@ -129,7 +129,7 @@ export function LibraryToolbar({
value={viewMode}
onChange={(v) => {
if (!(FILES_PAGE_VIEW_MODES as readonly string[]).includes(v)) return;
- setViewMode(v as FilesPageViewMode);
+ setViewMode(v);
}}
aria-label={t("filesPage.viewMode.label", "View mode")}
options={[
diff --git a/frontend/editor/src/core/components/filesPage/VersionHistoryModal.stories.tsx b/frontend/editor/src/core/components/filesPage/VersionHistoryModal.stories.tsx
index 1d5ce95e13..3cb0eb3d31 100644
--- a/frontend/editor/src/core/components/filesPage/VersionHistoryModal.stories.tsx
+++ b/frontend/editor/src/core/components/filesPage/VersionHistoryModal.stories.tsx
@@ -14,7 +14,7 @@ const mockFile: StirlingFileStub = {
size: 110592,
lastModified: 0,
isLeaf: true,
- originalFileId: "file-1" as FileId,
+ originalFileId: "file-1",
versionNumber: 3,
};
diff --git a/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.test.tsx b/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.test.tsx
index 71658a5e01..bdea80405b 100644
--- a/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.test.tsx
+++ b/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.test.tsx
@@ -329,7 +329,7 @@ describe("a lost session that comes back", () => {
store: ReturnType<typeof makeStore>,
) =>
view.rerender(
- <FileStoreContext.Provider value={store as never}>
+ <FileStoreContext.Provider value={store}>
<FileActionsContext.Provider
value={{ actions, dispatch: vi.fn() } as never}
>
@@ -367,7 +367,7 @@ describe("a lost session that comes back", () => {
// Let the fingerprint land: writes hold off while a known identity has none yet.
await act(async () => {});
store.state.files.ids = ["f2" as never];
- store.state.files.byId = { f2: stub("f2", "root-b") } as never;
+ store.state.files.byId = { f2: stub("f2", "root-b") };
act(() => store.notify());
view.unmount();
expect(JSON.parse(sessionStorage.getItem(SESSION_KEY)!).fileIds).toEqual([
@@ -394,7 +394,7 @@ describe("on the login screen", () => {
// And the unmount flush must not write either.
store.state.files.ids = ["f1" as never];
- store.state.files.byId = { f1: stub("f1", "f1") } as never;
+ store.state.files.byId = { f1: stub("f1", "f1") };
act(() => store.notify());
unmount();
expect(JSON.parse(sessionStorage.getItem(SESSION_KEY)!).fileIds).toEqual([
@@ -410,7 +410,7 @@ describe("writer", () => {
mount(store);
store.state.files.ids = ["v2" as never];
- store.state.files.byId = { v2: stub("v2", "root-a", 2) } as never;
+ store.state.files.byId = { v2: stub("v2", "root-a", 2) };
store.state.ui.selectedFileIds = ["v2"];
act(() => store.notify());
@@ -464,7 +464,7 @@ describe("writer", () => {
const { unmount } = mount(store);
store.state.files.ids = ["f1" as never];
- store.state.files.byId = { f1: stub("f1", "f1") } as never;
+ store.state.files.byId = { f1: stub("f1", "f1") };
act(() => store.notify());
unmount();
diff --git a/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.tsx b/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.tsx
index cb500ae827..425aa6340d 100644
--- a/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.tsx
+++ b/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.tsx
@@ -259,7 +259,7 @@ export function WorkbenchSessionPersistence() {
const active = saved.activeFileId
? leaves.get(saved.activeFileId)?.id
: undefined;
- if (active) setActiveFileId(active as string);
+ if (active) setActiveFileId(active);
if (view && held !== null) {
reopenView(store, navigationActions.restoreWorkbench, {
view,
diff --git a/frontend/editor/src/core/components/shared/BulkUploadToServerModal.stories.tsx b/frontend/editor/src/core/components/shared/BulkUploadToServerModal.stories.tsx
index 0b800195f5..9d69337fb7 100644
--- a/frontend/editor/src/core/components/shared/BulkUploadToServerModal.stories.tsx
+++ b/frontend/editor/src/core/components/shared/BulkUploadToServerModal.stories.tsx
@@ -13,7 +13,7 @@ const mockFiles: StirlingFileStub[] = [
size: 2_400_000,
lastModified: Date.now(),
isLeaf: true,
- originalFileId: "file-1" as FileId,
+ originalFileId: "file-1",
versionNumber: 1,
},
{
@@ -23,7 +23,7 @@ const mockFiles: StirlingFileStub[] = [
size: 512_000,
lastModified: Date.now(),
isLeaf: true,
- originalFileId: "file-2" as FileId,
+ originalFileId: "file-2",
versionNumber: 1,
},
];
diff --git a/frontend/editor/src/core/components/shared/FileSelectorPicker.tsx b/frontend/editor/src/core/components/shared/FileSelectorPicker.tsx
index 744698e612..03c6ab03f4 100644
--- a/frontend/editor/src/core/components/shared/FileSelectorPicker.tsx
+++ b/frontend/editor/src/core/components/shared/FileSelectorPicker.tsx
@@ -10,7 +10,6 @@ import {
createNewStirlingFileStub,
} from "@app/types/fileContext";
import type { StirlingFile, StirlingFileStub } from "@app/types/fileContext";
-import type { FileId } from "@app/types/file";
import { useAllFiles } from "@app/contexts/FileContext";
import { useIndexedDB } from "@app/contexts/IndexedDBContext";
import { useFileContext } from "@app/contexts/file/fileHooks";
@@ -44,7 +43,7 @@ function lsGet<const T extends readonly string[]>(
try {
const v = localStorage.getItem(key);
const allowed = valid as readonly string[];
- if (v && allowed.includes(v)) return v as T[number];
+ if (v && allowed.includes(v)) return v;
} catch {
/* ignore */
}
@@ -155,15 +154,12 @@ export function FileSelectorPicker({
setHoveredThumbnail(null);
(async () => {
try {
- const file = await indexedDB.loadFile(hoveredStub.stub.id as FileId);
+ const file = await indexedDB.loadFile(hoveredStub.stub.id);
if (!file || thumbCancelRef.current) return;
const thumbnail = await generateThumbnailForFile(file);
if (thumbCancelRef.current || !thumbnail) return;
setHoveredThumbnail(thumbnail);
- void indexedDB.updateThumbnail(
- hoveredStub.stub.id as FileId,
- thumbnail,
- );
+ void indexedDB.updateThumbnail(hoveredStub.stub.id, thumbnail);
} catch {
// non-critical
}
@@ -261,11 +257,10 @@ export function FileSelectorPicker({
// Workbench file — get StirlingFile directly from FileContext (no loading needed)
if (workbenchIdSet.has(stub.id)) {
- const sf = selectors.getFile(stub.id as FileId);
+ const sf = selectors.getFile(stub.id);
if (sf) {
// Prefer the workbench stub (has thumbnail) over the saved stub (may not)
- const workbenchStub =
- selectors.getStirlingFileStub(stub.id as FileId) ?? stub;
+ const workbenchStub = selectors.getStirlingFileStub(stub.id) ?? stub;
onSelect({ stub: workbenchStub, stirlingFile: sf });
setIsOpen(false);
}
@@ -311,8 +306,7 @@ export function FileSelectorPicker({
parseContentDispositionFilename(disp) || stub.name,
ct,
);
- if (files[0])
- stirlingFile = createStirlingFile(files[0], stub.id as FileId);
+ if (files[0]) stirlingFile = createStirlingFile(files[0], stub.id);
} else {
// Local IndexedDB file
const localFile = await fileStorage.getStirlingFile(stub.id);
@@ -329,7 +323,7 @@ export function FileSelectorPicker({
resolvedStub = { ...stub, thumbnailUrl: thumbnail };
// Persist so subsequent opens don't regenerate
void fileStorage.updateThumbnail(
- stirlingFile.fileId as FileId,
+ stirlingFile.fileId,
thumbnail,
);
}
diff --git a/frontend/editor/src/core/components/shared/FileSidebar.tsx b/frontend/editor/src/core/components/shared/FileSidebar.tsx
index 4f4113262c..40da26485a 100644
--- a/frontend/editor/src/core/components/shared/FileSidebar.tsx
+++ b/frontend/editor/src/core/components/shared/FileSidebar.tsx
@@ -205,7 +205,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
useEffect(
() =>
onRecordUnreadable((fileId) =>
- setLostFileIds((prev) => new Set(prev).add(fileId as string)),
+ setLostFileIds((prev) => new Set(prev).add(fileId)),
),
[],
);
@@ -379,7 +379,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
await downloadFileWithPolicy({
data: file,
filename: stub?.name ?? file.name,
- fileId: fileId as string,
+ fileId: fileId,
});
} catch (error) {
console.error("[FileSidebar] Download failed:", error);
@@ -487,7 +487,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
const lineageCounts = useMemo(() => {
const counts = new Map<string, number>();
for (const s of allFileStubs) {
- const k = (s.originalFileId ?? s.id) as string;
+ const k = s.originalFileId ?? s.id;
counts.set(k, (counts.get(k) ?? 0) + 1);
}
return counts;
@@ -527,7 +527,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
// Its bytes are gone; opening it can only fail. Say so instead of a
// click that goes nowhere.
- if (stub.dataUnavailable || lostFileIds.has(fileId as string)) {
+ if (stub.dataUnavailable || lostFileIds.has(fileId)) {
alert({
alertType: "warning",
title: t("fileSidebar.dataLostTitle", "File data is unavailable"),
@@ -605,8 +605,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
if (!stub) return;
const isCurrentlyViewed = !!(
- viewedWorkbenchId &&
- (viewedWorkbenchId as string) === (stub.id as string)
+ viewedWorkbenchId && viewedWorkbenchId === (stub.id as string)
);
if (isCurrentlyViewed) {
@@ -630,7 +629,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
}
// Route through pendingViewFileId so both setActiveFileIndex + setWorkbench fire together.
- setPendingViewFileId(stub.id as string);
+ setPendingViewFileId(stub.id);
};
if (currentWorkbench === "viewer" && viewedWorkbenchId) {
@@ -756,8 +755,8 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
const eligibleFileIds = useToolEligibleFileIds();
const renderFileRow = (stub: StirlingFileStub) => {
- const isInWorkbench = workbenchIds.has(stub.id as string);
- const workbenchFileId = isInWorkbench ? (stub.id as FileId) : undefined;
+ const isInWorkbench = workbenchIds.has(stub.id);
+ const workbenchFileId = isInWorkbench ? stub.id : undefined;
const isViewedInViewer = !!(
viewedWorkbenchId && viewedWorkbenchId === (stub.id as string)
);
@@ -770,9 +769,9 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
: undefined) || stub.thumbnailUrl;
const fileOrigin = getFileOrigin(stub);
const dataUnavailable =
- stub.dataUnavailable === true || lostFileIds.has(stub.id as string);
+ stub.dataUnavailable === true || lostFileIds.has(stub.id);
// Lineage keys preserve rows across version changes; split siblings need unique leaf IDs.
- const lineageKey = (stub.originalFileId ?? stub.id) as string;
+ const lineageKey = stub.originalFileId ?? stub.id;
const rowKey =
(lineageCounts.get(lineageKey) ?? 0) > 1
? (stub.id as string)
@@ -796,7 +795,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
onClick={handleFileClick}
onEyeClick={handleEyeClick}
dataUnavailable={dataUnavailable}
- policies={policyFileBadges.get(stub.id as string) ?? NO_POLICIES}
+ policies={policyFileBadges.get(stub.id) ?? NO_POLICIES}
onDelete={handleSidebarDelete}
onDownload={handleDownload}
onRename={handleRename}
diff --git a/frontend/editor/src/core/components/shared/LanguageSelector.tsx b/frontend/editor/src/core/components/shared/LanguageSelector.tsx
index e9810e6d06..445f7e53a1 100644
--- a/frontend/editor/src/core/components/shared/LanguageSelector.tsx
+++ b/frontend/editor/src/core/components/shared/LanguageSelector.tsx
@@ -221,7 +221,7 @@ const LanguageSelector: React.FC<LanguageSelectorProps> = ({
};
const currentLanguage =
- supportedLanguages[i18n.language as keyof typeof supportedLanguages] ||
+ supportedLanguages[i18n.language] ||
supportedLanguages["en-US"] ||
"English"; // Fallback if supportedLanguages lookup fails
diff --git a/frontend/editor/src/core/components/shared/PageEditorFileDropdown.tsx b/frontend/editor/src/core/components/shared/PageEditorFileDropdown.tsx
index 4089ebd77e..bd8fc784ef 100644
--- a/frontend/editor/src/core/components/shared/PageEditorFileDropdown.tsx
+++ b/frontend/editor/src/core/components/shared/PageEditorFileDropdown.tsx
@@ -98,18 +98,16 @@ const FileMenuItem: React.FC<FileMenuItemProps> = ({
}}
onMouseEnter={(e) => {
if (!isDragging) {
- (e.currentTarget as HTMLDivElement).style.backgroundColor =
- "rgba(0, 0, 0, 0.05)";
- (e.currentTarget as HTMLDivElement).style.borderLeftColor =
- fileColorBorderHover;
+ e.currentTarget.style.backgroundColor = "rgba(0, 0, 0, 0.05)";
+ e.currentTarget.style.borderLeftColor = fileColorBorderHover;
}
}}
onMouseLeave={(e) => {
if (!isDragging) {
- (e.currentTarget as HTMLDivElement).style.backgroundColor =
- file.isSelected ? "rgba(0, 0, 0, 0.05)" : "transparent";
- (e.currentTarget as HTMLDivElement).style.borderLeftColor =
- fileColorBorder;
+ e.currentTarget.style.backgroundColor = file.isSelected
+ ? "rgba(0, 0, 0, 0.05)"
+ : "transparent";
+ e.currentTarget.style.borderLeftColor = fileColorBorder;
}
}}
>
@@ -204,7 +202,7 @@ export const PageEditorFileDropdown: React.FC<PageEditorFileDropdownProps> = ({
}}
>
{files.map((file, index) => {
- const colorIndex = fileColorMap.get(file.fileId as string) ?? 0;
+ const colorIndex = fileColorMap.get(file.fileId) ?? 0;
return (
<FileMenuItem
@@ -233,12 +231,10 @@ export const PageEditorFileDropdown: React.FC<PageEditorFileDropdownProps> = ({
transition: "background-color 0.15s ease",
}}
onMouseEnter={(e) => {
- (e.currentTarget as HTMLDivElement).style.backgroundColor =
- "rgba(59, 130, 246, 0.25)";
+ e.currentTarget.style.backgroundColor = "rgba(59, 130, 246, 0.25)";
}}
onMouseLeave={(e) => {
- (e.currentTarget as HTMLDivElement).style.backgroundColor =
- "transparent";
+ e.currentTarget.style.backgroundColor = "transparent";
}}
>
<Group gap="xs" style={{ width: "100%" }}>
diff --git a/frontend/editor/src/core/components/shared/Tooltip.tsx b/frontend/editor/src/core/components/shared/Tooltip.tsx
index d8829556eb..b4d320ffbb 100644
--- a/frontend/editor/src/core/components/shared/Tooltip.tsx
+++ b/frontend/editor/src/core/components/shared/Tooltip.tsx
@@ -141,10 +141,10 @@ export const Tooltip: React.FC<TooltipProps> = ({
typeof document !== "undefined" ? document.documentElement.dir : "ltr";
const isRTL = htmlDir === "rtl";
const base = position ?? "right";
- if (!isRTL) return base as NonNullable<TooltipProps["position"]>;
+ if (!isRTL) return base;
if (base === "left") return "right";
if (base === "right") return "left";
- return base as NonNullable<TooltipProps["position"]>;
+ return base;
}, [position]);
const setOpen = useCallback(
@@ -383,8 +383,7 @@ export const Tooltip: React.FC<TooltipProps> = ({
).ref;
if (typeof originalRef === "function") originalRef(node);
else if (originalRef && typeof originalRef === "object")
- (originalRef as React.MutableRefObject<HTMLElement | null>).current =
- node;
+ originalRef.current = node;
},
"aria-describedby": open ? tooltipIdRef.current : undefined,
onPointerEnter: handlePointerEnter,
diff --git a/frontend/editor/src/core/components/shared/TopControls.tsx b/frontend/editor/src/core/components/shared/TopControls.tsx
index a93a3a34f4..d178bb7344 100644
--- a/frontend/editor/src/core/components/shared/TopControls.tsx
+++ b/frontend/editor/src/core/components/shared/TopControls.tsx
@@ -66,14 +66,14 @@ const createViewOptions = (
const pageEditorOption = {
label: showPageEditorDropdown ? (
<PageEditorFileDropdown
- files={pageEditorState!.files}
- onToggleSelection={pageEditorState!.onToggleSelection}
- onReorder={pageEditorState!.onReorder}
+ files={pageEditorState.files}
+ onToggleSelection={pageEditorState.onToggleSelection}
+ onReorder={pageEditorState.onReorder}
switchingTo={switchingTo}
viewOptionStyle={viewOptionStyle}
- fileColorMap={pageEditorState!.fileColorMap}
- selectedCount={pageEditorState!.selectedCount}
- totalCount={pageEditorState!.totalCount}
+ fileColorMap={pageEditorState.fileColorMap}
+ selectedCount={pageEditorState.selectedCount}
+ totalCount={pageEditorState.totalCount}
/>
) : (
<div style={viewOptionStyle}>
@@ -106,7 +106,7 @@ const createViewOptions = (
.filter((view) => view.data != null)
.map((view) => ({
label: (
- <div style={viewOptionStyle as React.CSSProperties}>
+ <div style={viewOptionStyle}>
{switchingTo === view.workbenchId ? (
<Loader size="sm" />
) : (
diff --git a/frontend/editor/src/core/components/shared/UploadToServerModal.stories.tsx b/frontend/editor/src/core/components/shared/UploadToServerModal.stories.tsx
index 50f1e9e0ad..5e6b161a96 100644
--- a/frontend/editor/src/core/components/shared/UploadToServerModal.stories.tsx
+++ b/frontend/editor/src/core/components/shared/UploadToServerModal.stories.tsx
@@ -12,14 +12,14 @@ const mockFile: StirlingFileStub = {
size: 2_400_000,
lastModified: Date.now(),
isLeaf: true,
- originalFileId: "file-1" as FileId,
+ originalFileId: "file-1",
versionNumber: 1,
};
const mockUploadedFile: StirlingFileStub = {
...mockFile,
id: "file-2" as FileId,
- originalFileId: "file-2" as FileId,
+ originalFileId: "file-2",
remoteStorageId: 2,
};
diff --git a/frontend/editor/src/core/components/shared/WorkbenchBar.tsx b/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
index 22e5062d1d..c664c8f8e5 100644
--- a/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
+++ b/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
@@ -244,11 +244,11 @@ export default function WorkbenchBar({
let enforced: File[];
try {
enforced = await enforceExportPolicies(
- filesToExport as File[],
+ filesToExport,
stubs.map((s) => s?.id),
);
} catch {
- enforced = filesToExport as File[];
+ enforced = filesToExport;
showAlert({
alertType: "warning",
title: t("policies.enforcement.exportFailureTitle"),
@@ -402,7 +402,7 @@ export default function WorkbenchBar({
const ariaLabel =
btn.ariaLabel ||
- (typeof btn.tooltip === "string" ? (btn.tooltip as string) : btn.id);
+ (typeof btn.tooltip === "string" ? btn.tooltip : btn.id);
const buttonNode = (
<ActionIcon
variant={isActive ? "primary" : "quiet"}
@@ -435,7 +435,7 @@ export default function WorkbenchBar({
},
]),
{
- value: "fileEditor" as WorkbenchType,
+ value: "fileEditor",
label: t("workbenchBar.activeFiles", "Active Files"),
icon: <Icon name="folder" size={20} />,
},
diff --git a/frontend/editor/src/core/components/shared/config/configSections/GeneralSection.tsx b/frontend/editor/src/core/components/shared/config/configSections/GeneralSection.tsx
index 413706fb8b..0231729c42 100644
--- a/frontend/editor/src/core/components/shared/config/configSections/GeneralSection.tsx
+++ b/frontend/editor/src/core/components/shared/config/configSections/GeneralSection.tsx
@@ -20,7 +20,6 @@ import { usePreferences } from "@app/contexts/PreferencesContext";
import { useAppConfig } from "@app/contexts/AppConfigContext";
import { useTheme } from "@app/components/shared/ThemeProvider";
import LanguageSelector from "@app/components/shared/LanguageSelector";
-import { type ThemeMode } from "@app/constants/theme";
import type { ToolPanelMode } from "@app/constants/toolPanel";
import {
type StartupView,
@@ -487,7 +486,7 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({
</div>
<SegmentedControl
value={themeMode}
- onChange={(val) => setTheme(val as ThemeMode)}
+ onChange={(val) => setTheme(val)}
options={[
{
label: t("settings.general.themeLight", "Light"),
diff --git a/frontend/editor/src/core/components/shared/config/configSections/HotkeysSection.tsx b/frontend/editor/src/core/components/shared/config/configSections/HotkeysSection.tsx
index 013d73d8c1..80126bfc26 100644
--- a/frontend/editor/src/core/components/shared/config/configSections/HotkeysSection.tsx
+++ b/frontend/editor/src/core/components/shared/config/configSections/HotkeysSection.tsx
@@ -98,7 +98,7 @@ const HotkeysSection: React.FC = () => {
event.preventDefault();
event.stopPropagation();
- const binding = eventToBinding(event as KeyboardEvent);
+ const binding = eventToBinding(event);
if (!binding) {
const osKey = isMac ? "mac" : "windows";
setError(t(`settings.hotkeys.errorModifier.${osKey}`));
@@ -116,7 +116,7 @@ const HotkeysSection: React.FC = () => {
const conflictKey = conflictEntry[0];
const conflictTool =
conflictKey in toolRegistry
- ? toolRegistry[conflictKey as ToolId]?.name
+ ? toolRegistry[conflictKey]?.name
: conflictKey;
setError(
t(
diff --git a/frontend/editor/src/core/components/shared/config/configSections/preferences/AppearanceCard.tsx b/frontend/editor/src/core/components/shared/config/configSections/preferences/AppearanceCard.tsx
index 7ea5847b10..38373c8014 100644
--- a/frontend/editor/src/core/components/shared/config/configSections/preferences/AppearanceCard.tsx
+++ b/frontend/editor/src/core/components/shared/config/configSections/preferences/AppearanceCard.tsx
@@ -4,7 +4,6 @@ import { useTranslation } from "react-i18next";
import { SegmentedControl } from "@app/ui/SegmentedControl";
import { useTheme } from "@app/components/shared/ThemeProvider";
import LanguageSelector from "@app/components/shared/LanguageSelector";
-import { type ThemeMode } from "@app/constants/theme";
/** How the app looks: theme and display language. Both write through at once. */
export function AppearanceCard() {
@@ -35,7 +34,7 @@ export function AppearanceCard() {
</div>
<SegmentedControl
value={themeMode}
- onChange={(val) => setTheme(val as ThemeMode)}
+ onChange={(val) => setTheme(val)}
options={[
{
label: t("settings.general.themeLight", "Light"),
diff --git a/frontend/editor/src/core/components/shared/config/configSections/preferences/HotkeysCard.tsx b/frontend/editor/src/core/components/shared/config/configSections/preferences/HotkeysCard.tsx
index 6b62315666..974b0cb4ca 100644
--- a/frontend/editor/src/core/components/shared/config/configSections/preferences/HotkeysCard.tsx
+++ b/frontend/editor/src/core/components/shared/config/configSections/preferences/HotkeysCard.tsx
@@ -143,7 +143,7 @@ export function HotkeysCard() {
event.preventDefault();
event.stopPropagation();
- const binding = eventToBinding(event as KeyboardEvent);
+ const binding = eventToBinding(event);
if (!binding) {
const osKey = isMac ? "mac" : "windows";
setError(t(`settings.hotkeys.errorModifier.${osKey}`));
@@ -161,7 +161,7 @@ export function HotkeysCard() {
const conflictKey = conflictEntry[0];
const conflictTool =
conflictKey in toolRegistry
- ? toolRegistry[conflictKey as ToolId]?.name
+ ? toolRegistry[conflictKey]?.name
: conflictKey;
setError(
t(
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.identity.test.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.identity.test.tsx
index 216ca271f6..3af180e70e 100644
--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.identity.test.tsx
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.identity.test.tsx
@@ -2,6 +2,7 @@ import { act, render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MemoryRouter } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { useAuth } from "@app/auth/UseSession";
import { AppConfigProvider } from "@app/contexts/AppConfigContext";
import {
QuickNavHostProvider,
@@ -10,15 +11,14 @@ import {
import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";
import { QuickNavRailAccount } from "@app/components/shared/quickNav/QuickNavRailAccount";
-const { auth, picture, getAccountData } = vi.hoisted(() => ({
- auth: {
- displayName: "Ada" as string | null,
- loading: false,
- isAnonymous: false,
- },
- picture: { url: "/ada.png" as string | null, loading: false },
- getAccountData: vi.fn(),
+const auth = vi.hoisted<
+ Pick<ReturnType<typeof useAuth>, "displayName" | "loading" | "isAnonymous">
+>(() => ({ displayName: "Ada", loading: false, isAnonymous: false }));
+const picture = vi.hoisted<{ url: string | null; loading: boolean }>(() => ({
+ url: "/ada.png",
+ loading: false,
}));
+const getAccountData = vi.hoisted(() => vi.fn());
vi.mock("@app/auth/UseSession", () => ({ useAuth: () => auth }));
vi.mock("@app/hooks/useProfilePictureUrl", () => ({
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.state.test.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.state.test.tsx
index f49018b557..ca2a479945 100644
--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.state.test.tsx
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.state.test.tsx
@@ -2,6 +2,7 @@ import { act, render, screen, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MemoryRouter } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { useAuth } from "@app/auth/UseSession";
import { AppConfigProvider } from "@app/contexts/AppConfigContext";
import {
QuickNavHostProvider,
@@ -12,10 +13,10 @@ import { fetchSigningSessions, type SigningSessions } from "@app/api/signing";
import { alert } from "@app/components/toast";
import { expectConsole } from "@app/tests/failOnConsole";
-const { auth, access } = vi.hoisted(() => ({
- auth: { user: { id: "ada" } as { id: string } | null, loading: false },
- access: { granted: true, settled: true },
-}));
+const auth = vi.hoisted<Pick<ReturnType<typeof useAuth>, "user" | "loading">>(
+ () => ({ user: { id: "ada" }, loading: false }),
+);
+const access = vi.hoisted(() => ({ granted: true, settled: true }));
vi.mock("@app/auth/UseSession", () => ({
useAuth: () => ({
diff --git a/frontend/editor/src/core/components/shared/updatePopupGate.test.ts b/frontend/editor/src/core/components/shared/updatePopupGate.test.ts
index b42bdf55b5..a34d823cd2 100644
--- a/frontend/editor/src/core/components/shared/updatePopupGate.test.ts
+++ b/frontend/editor/src/core/components/shared/updatePopupGate.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from "vitest";
-import type { AppConfig } from "@app/types/appConfig";
import { isUpdatePopupAllowed } from "@app/components/shared/updatePopupGate";
describe("isUpdatePopupAllowed", () => {
@@ -8,26 +7,20 @@ describe("isUpdatePopupAllowed", () => {
});
it("shows on desktop when the backend allows it", () => {
- expect(
- isUpdatePopupAllowed({ shouldShowUpdate: true } as AppConfig, false),
- ).toBe(true);
+ expect(isUpdatePopupAllowed({ shouldShowUpdate: true }, false)).toBe(true);
});
it("never shows on a mobile / narrow viewport", () => {
- expect(
- isUpdatePopupAllowed({ shouldShowUpdate: true } as AppConfig, true),
- ).toBe(false);
+ expect(isUpdatePopupAllowed({ shouldShowUpdate: true }, true)).toBe(false);
});
it("hides when the backend says not to (non-admin / showUpdate disabled)", () => {
- expect(
- isUpdatePopupAllowed({ shouldShowUpdate: false } as AppConfig, false),
- ).toBe(false);
+ expect(isUpdatePopupAllowed({ shouldShowUpdate: false }, false)).toBe(
+ false,
+ );
});
it("fails closed when the backend omits the decision (e.g. 401 fallback)", () => {
- expect(
- isUpdatePopupAllowed({ enableLogin: true } as AppConfig, false),
- ).toBe(false);
+ expect(isUpdatePopupAllowed({ enableLogin: true }, false)).toBe(false);
});
});
diff --git a/frontend/editor/src/core/components/startup/StartupPrompts.test.tsx b/frontend/editor/src/core/components/startup/StartupPrompts.test.tsx
index a57278e4fe..c558332b5e 100644
--- a/frontend/editor/src/core/components/startup/StartupPrompts.test.tsx
+++ b/frontend/editor/src/core/components/startup/StartupPrompts.test.tsx
@@ -7,7 +7,15 @@ import {
screen,
waitFor,
} from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+ type Mock,
+} from "vitest";
import { MemoryRouter, useNavigate } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MantineProvider } from "@mantine/core";
@@ -20,10 +28,19 @@ import { AppRoot } from "@app/components/layout/AppRoot";
import { BannerProvider } from "@app/contexts/BannerContext";
import type StaticOnboardingSlide from "@app/components/onboarding/StaticOnboardingSlide";
import type { AccountData } from "@app/services/accountService";
+import type { useAuth } from "@app/auth/UseSession";
-const h = vi.hoisted(() => ({
+const h = vi.hoisted<{
+ auth: Pick<ReturnType<typeof useAuth>, "user" | "loading" | "isAnonymous"> & {
+ signOut: Mock;
+ };
+ get: Mock;
+ post: Mock;
+ logout: Mock;
+ tracking: Mock;
+}>(() => ({
auth: {
- user: { id: "admin" } as { id: string } | null,
+ user: { id: "admin" },
loading: false,
isAnonymous: false,
signOut: vi.fn(),
diff --git a/frontend/editor/src/core/components/tools/addStamp/StampPositionFormattingSettings.tsx b/frontend/editor/src/core/components/tools/addStamp/StampPositionFormattingSettings.tsx
index 606dd5f073..6cf4a9be51 100644
--- a/frontend/editor/src/core/components/tools/addStamp/StampPositionFormattingSettings.tsx
+++ b/frontend/editor/src/core/components/tools/addStamp/StampPositionFormattingSettings.tsx
@@ -159,7 +159,7 @@ const StampPositionFormattingSettings = ({
/>
<Slider
value={parameters.fontSize}
- onChange={(v) => onParameterChange("fontSize", v as number)}
+ onChange={(v) => onParameterChange("fontSize", v)}
min={1}
max={400}
step={1}
@@ -190,7 +190,7 @@ const StampPositionFormattingSettings = ({
/>
<Slider
value={parameters.rotation}
- onChange={(v) => onParameterChange("rotation", v as number)}
+ onChange={(v) => onParameterChange("rotation", v)}
min={-180}
max={180}
step={1}
@@ -219,7 +219,7 @@ const StampPositionFormattingSettings = ({
/>
<Slider
value={parameters.opacity}
- onChange={(v) => onParameterChange("opacity", v as number)}
+ onChange={(v) => onParameterChange("opacity", v)}
min={0}
max={100}
step={1}
diff --git a/frontend/editor/src/core/components/tools/addStamp/StampPreview.tsx b/frontend/editor/src/core/components/tools/addStamp/StampPreview.tsx
index 93d3a1e874..dc7c1ee1ad 100644
--- a/frontend/editor/src/core/components/tools/addStamp/StampPreview.tsx
+++ b/frontend/editor/src/core/components/tools/addStamp/StampPreview.tsx
@@ -376,7 +376,7 @@ export default function StampPreview({
<div
ref={containerRef}
className={`${styles.container} ${styles.containerBorder} ${pageThumbnail ? styles.containerWithThumbnail : styles.containerWithoutThumbnail}`}
- style={style.container as React.CSSProperties}
+ style={style.container}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
>
@@ -393,7 +393,7 @@ export default function StampPreview({
{parameters.stampType === "text" && (
<div
className={`${styles.stampItem} ${styles.stampItemGridMode}`}
- style={style.item as React.CSSProperties}
+ style={style.item}
data-user-content-preview=""
>
{(parameters.stampText || "").split("\n").map((line, idx) => (
@@ -415,7 +415,7 @@ export default function StampPreview({
{parameters.stampType === "image" && imageMeta && (
<div
className={`${styles.stampItem} ${showQuickGrid ? styles.stampItemGridMode : styles.stampItemDraggable}`}
- style={style.item as React.CSSProperties}
+ style={style.item}
onPointerDown={(e) => handlePointerDown(e, "move")}
>
<img
@@ -444,10 +444,7 @@ export default function StampPreview({
// Clear overrides to use grid positioning and set position
onParameterChange("overrideX", -1);
onParameterChange("overrideY", -1);
- onParameterChange(
- "position",
- idx as AddStampParameters["position"],
- );
+ onParameterChange("position", idx);
}}
onMouseEnter={() => setHoverTile(idx)}
onMouseLeave={() => setHoverTile(null)}
diff --git a/frontend/editor/src/core/components/tools/automate/ToolSelector.tsx b/frontend/editor/src/core/components/tools/automate/ToolSelector.tsx
index 2dd482863d..f39c6688b9 100644
--- a/frontend/editor/src/core/components/tools/automate/ToolSelector.tsx
+++ b/frontend/editor/src/core/components/tools/automate/ToolSelector.tsx
@@ -69,7 +69,7 @@ export default function ToolSelector({
const filteredToolRegistry = useMemo(() => {
const registry: Partial<ToolRegistry> = {};
baseFilteredTools.forEach(([key, tool]) => {
- registry[key as ToolId] = tool;
+ registry[key] = tool;
});
return registry;
}, [baseFilteredTools]);
@@ -77,7 +77,7 @@ export default function ToolSelector({
// Transform filteredTools to the expected format for useToolSections
const transformedFilteredTools = useMemo(() => {
return filteredTools.map(([id, tool]) => ({
- item: [id as ToolId, tool] as [ToolId, ToolRegistryEntry],
+ item: [id, tool] as [ToolId, ToolRegistryEntry],
}));
}, [filteredTools]);
diff --git a/frontend/editor/src/core/components/viewer/AnnotationTypeButtons.tsx b/frontend/editor/src/core/components/viewer/AnnotationTypeButtons.tsx
index 10b4e616dc..d3bdd491c7 100644
--- a/frontend/editor/src/core/components/viewer/AnnotationTypeButtons.tsx
+++ b/frontend/editor/src/core/components/viewer/AnnotationTypeButtons.tsx
@@ -3,10 +3,7 @@ import type { TrackedAnnotation } from "@embedpdf/plugin-annotation";
import type { PdfAnnotationObject } from "@embedpdf/models";
import { OpacityControl } from "@app/components/annotation/shared/OpacityControl";
import { WidthControl } from "@app/components/annotation/shared/WidthControl";
-import {
- PropertiesPopover,
- type PropertiesAnnotationType,
-} from "@app/components/annotation/shared/PropertiesPopover";
+import { PropertiesPopover } from "@app/components/annotation/shared/PropertiesPopover";
import { ColorControl } from "@app/components/annotation/shared/ColorControl";
import {
DeleteButton,
@@ -16,7 +13,6 @@ import {
LinkButton,
} from "@app/components/viewer/AnnotationMenuButtons";
import type {
- AnnotationType,
AnnotationMenuState,
AnnotationMenuHandlers,
} from "@app/components/viewer/useAnnotationMenuHandlers";
@@ -70,7 +66,7 @@ export function AnnotationTypeButtons(props: AnnotationTypeButtonsProps) {
/>
);
- switch (annotationType as AnnotationType) {
+ switch (annotationType) {
case "textMarkup":
return (
<>
@@ -141,7 +137,7 @@ export function AnnotationTypeButtons(props: AnnotationTypeButtonsProps) {
/>
<EditTextButton onEdit={onEdit} />
<PropertiesPopover
- annotationType={annotationType as PropertiesAnnotationType}
+ annotationType={annotationType}
annotation={annotation}
onUpdate={onPropertiesUpdate}
/>
diff --git a/frontend/editor/src/core/components/viewer/BookmarkSidebar.tsx b/frontend/editor/src/core/components/viewer/BookmarkSidebar.tsx
index 4b94a696b0..b2868ee4a5 100644
--- a/frontend/editor/src/core/components/viewer/BookmarkSidebar.tsx
+++ b/frontend/editor/src/core/components/viewer/BookmarkSidebar.tsx
@@ -13,7 +13,7 @@ import { ActionIcon } from "@app/ui/ActionIcon";
import { useViewer } from "@app/contexts/ViewerContext";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
import { useFileContext } from "@app/contexts/FileContext";
-import { isStirlingFile, type FileId } from "@app/types/fileContext";
+import { isStirlingFile } from "@app/types/fileContext";
import { createStirlingFilesAndStubs } from "@app/services/fileStubHelpers";
import apiClient from "@app/services/apiClient";
import { openExternalTab } from "@app/platform/openExternalTab";
@@ -375,9 +375,7 @@ export const BookmarkSidebar = ({
? allFiles.find((f) => isStirlingFile(f) && f.fileId === activeFileId)
: (allFiles[activeFileIndex] ?? allFiles[0]);
const resolvedFileId =
- resolvedFile && isStirlingFile(resolvedFile)
- ? (resolvedFile.fileId as FileId)
- : null;
+ resolvedFile && isStirlingFile(resolvedFile) ? resolvedFile.fileId : null;
if (!resolvedFileId) {
handleFallbackToTool();
return;
diff --git a/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx b/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx
index b09eb1c58a..d0a80e5111 100644
--- a/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx
+++ b/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx
@@ -42,10 +42,7 @@ const STANDALONE_COMMENT_SUBTYPES = new Set([
]);
function isStandaloneCommentType(type: number | undefined): boolean {
- return (
- type !== undefined &&
- STANDALONE_COMMENT_SUBTYPES.has(type as PdfAnnotationSubtype)
- );
+ return type !== undefined && STANDALONE_COMMENT_SUBTYPES.has(type);
}
const ANNOTATE_PANEL_ID = "annotate" as const;
@@ -381,10 +378,7 @@ export function CommentsSidebar({
);
if (!pageEl || !ann?.rect) return;
const zoom = getZoomState?.()?.currentZoom ?? 1;
- const { origin, size } = ann.rect as {
- origin: { x: number; y: number };
- size: { width: number; height: number };
- };
+ const { origin, size } = ann.rect;
const flashEl = document.createElement("div");
// Append to page element so it scrolls with the page (position: absolute relative to page)
flashEl.style.cssText = `
@@ -695,7 +689,7 @@ export function CommentsSidebar({
const handleCancelPlacingComment = useCallback(() => {
// De-arm the textComment tool. The panel's activateAnnotationTool
// takes the AnnotationToolId "select" to reset to no-tool state.
- activateAnnotationToolRef.current?.("select" as never);
+ activateAnnotationToolRef.current?.("select");
setActiveAnnotationToolId(null);
}, [activateAnnotationToolRef, setActiveAnnotationToolId]);
diff --git a/frontend/editor/src/core/components/viewer/LinkLayer.tsx b/frontend/editor/src/core/components/viewer/LinkLayer.tsx
index e68c541fd8..0be5ee64e3 100644
--- a/frontend/editor/src/core/components/viewer/LinkLayer.tsx
+++ b/frontend/editor/src/core/components/viewer/LinkLayer.tsx
@@ -281,7 +281,7 @@ export const LinkLayer: React.FC<LinkLayerProps> = ({
ta.commitState !== "deleted" &&
ta.object.type === PdfAnnotationSubtype.LINK
) {
- const annotationLink = ta.object as PdfLinkAnnoObject;
+ const annotationLink = ta.object;
if (
annotationLink.rect.size.width > 0 &&
annotationLink.rect.size.height > 0
diff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
index f84f413744..5a3a64b2c0 100644
--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
@@ -51,10 +51,7 @@ import {
AnnotationLayer,
AnnotationPluginPackage,
} from "@embedpdf/plugin-annotation/react";
-import type {
- AnnotationTool,
- AnnotationEvent,
-} from "@embedpdf/plugin-annotation";
+import type { AnnotationEvent } from "@embedpdf/plugin-annotation";
import { PdfAnnotationSubtype } from "@embedpdf/models";
import type { PdfAnnotationObject, Rect } from "@embedpdf/models";
import {
@@ -346,7 +343,7 @@ export function LocalEmbedPDF({
// Keyed by fileStableKey to avoid recomputing on every FileContext re-render.
const exportFileName = useMemo(() => {
if (fileName) return fileName;
- if (file && "name" in file) return (file as File).name;
+ if (file && "name" in file) return file.name;
if (url) return url.split("/").pop()?.split("?")[0] || "document.pdf";
return "document.pdf";
}, [fileStableKey, fileName, url]);
@@ -430,8 +427,8 @@ export function LocalEmbedPDF({
err,
);
};
- if (file && typeof (file as Blob).arrayBuffer === "function") {
- (file as Blob)
+ if (file && typeof file.arrayBuffer === "function") {
+ file
.arrayBuffer()
.then((buf) => {
if (cancelled) return;
@@ -783,7 +780,7 @@ export function LocalEmbedPDF({
const ensureTool = (tool: LooseAnnotationTool) => {
const existing = annotationApi.getTool?.(tool.id);
if (!existing) {
- annotationApi.addTool(tool as unknown as AnnotationTool);
+ annotationApi.addTool(tool);
}
};
diff --git a/frontend/editor/src/core/components/viewer/NonPdfViewer.tsx b/frontend/editor/src/core/components/viewer/NonPdfViewer.tsx
index 0878ab53c4..3926bc3516 100644
--- a/frontend/editor/src/core/components/viewer/NonPdfViewer.tsx
+++ b/frontend/editor/src/core/components/viewer/NonPdfViewer.tsx
@@ -94,17 +94,15 @@ export function NonPdfViewer({ file }: NonPdfViewerProps) {
return (
<Stack
gap={0}
- style={
- {
- height: "100%",
- flex: 1,
- overflow: "hidden",
- position: "relative",
- // The Convert button floats over the content; viewers that draw their
- // own top bar read this to keep their text clear of it.
- "--nonpdf-action-inset": isConvertAvailable ? "11rem" : "0rem",
- } as React.CSSProperties
- }
+ style={{
+ height: "100%",
+ flex: 1,
+ overflow: "hidden",
+ position: "relative",
+ // The Convert button floats over the content; viewers that draw their
+ // own top bar read this to keep their text clear of it.
+ "--nonpdf-action-inset": isConvertAvailable ? "11rem" : "0rem",
+ }}
>
<NonPdfBanner
onConvertToPdf={isConvertAvailable ? handleConvertToPdf : undefined}
diff --git a/frontend/editor/src/core/components/viewer/RulerOverlay.tsx b/frontend/editor/src/core/components/viewer/RulerOverlay.tsx
index f580bcde4b..ad8a251ea9 100644
--- a/frontend/editor/src/core/components/viewer/RulerOverlay.tsx
+++ b/frontend/editor/src/core/components/viewer/RulerOverlay.tsx
@@ -71,7 +71,7 @@ function dist(a: Point, b: Point): number {
function normalizeRotation(rotation: number | null | undefined): Rotation {
const value =
typeof rotation === "number" && Number.isFinite(rotation) ? rotation : 0;
- return (((Math.round(value) % 4) + 4) % 4) as Rotation;
+ return ((Math.round(value) % 4) + 4) % 4;
}
function getPageRotation(pageEl: HTMLElement): Rotation {
diff --git a/frontend/editor/src/core/components/viewer/SignatureAPIBridge.tsx b/frontend/editor/src/core/components/viewer/SignatureAPIBridge.tsx
index d2f072b219..aee7fd8a52 100644
--- a/frontend/editor/src/core/components/viewer/SignatureAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/SignatureAPIBridge.tsx
@@ -70,7 +70,7 @@ const extractDataUrl = (
if (result) return result;
}
} else {
- for (const key of Object.keys(value as Record<string, unknown>)) {
+ for (const key of Object.keys(value)) {
const result = extractDataUrl(
(value as Record<string, unknown>)[key],
depth + 1,
@@ -349,11 +349,11 @@ export const SignatureAPIBridge = forwardRef<
pageAnnotationsTask
.toPromise()
.then((pageAnnotations: PdfAnnotationObject[]) => {
- const currentAnn = pageAnnotations?.find(
- (ann: PdfAnnotationObject) => ann.id === id,
- );
- const imageSrc = (currentAnn as StampAnnotation | undefined)
- ?.imageSrc;
+ const currentAnn: StampAnnotation | undefined =
+ pageAnnotations?.find(
+ (ann: PdfAnnotationObject) => ann.id === id,
+ );
+ const imageSrc = currentAnn?.imageSrc;
if (typeof imageSrc === "string") {
// Ensure the image data is stored in our persistent store
storeImageData(id, imageSrc);
@@ -492,11 +492,11 @@ export const SignatureAPIBridge = forwardRef<
pageAnnotationsTask
.toPromise()
.then((pageAnnotations: PdfAnnotationObject[]) => {
- const annotation = pageAnnotations?.find(
- (ann: PdfAnnotationObject) => ann.id === annotationId,
- );
- const imageSrc = (annotation as StampAnnotation | undefined)
- ?.imageSrc;
+ const annotation: StampAnnotation | undefined =
+ pageAnnotations?.find(
+ (ann: PdfAnnotationObject) => ann.id === annotationId,
+ );
+ const imageSrc = annotation?.imageSrc;
if (
annotation &&
annotation.type === PdfAnnotationSubtype.STAMP &&
diff --git a/frontend/editor/src/core/components/viewer/ViewerDocumentBridges.test.tsx b/frontend/editor/src/core/components/viewer/ViewerDocumentBridges.test.tsx
index a0aa69680b..687df76056 100644
--- a/frontend/editor/src/core/components/viewer/ViewerDocumentBridges.test.tsx
+++ b/frontend/editor/src/core/components/viewer/ViewerDocumentBridges.test.tsx
@@ -4,6 +4,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { SpreadAPIBridge } from "@app/components/viewer/SpreadAPIBridge";
import { ScrollAPIBridge } from "@app/components/viewer/ScrollAPIBridge";
import { RotateAPIBridge } from "@app/components/viewer/RotateAPIBridge";
+import type { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";
+
+const activeDocument = vi.hoisted<{
+ id: ReturnType<typeof useActiveDocumentId>;
+}>(() => ({ id: "first" }));
const fixture = vi.hoisted(() => {
const document = () => ({
@@ -19,7 +24,6 @@ const fixture = vi.hoisted(() => {
{ api: Record<string, (value: number) => void> }
>();
return {
- activeId: "first" as "first" | "second",
documents: { first: document(), second: document() },
bridges,
registerBridge: (
@@ -34,7 +38,7 @@ const fixture = vi.hoisted(() => {
});
vi.mock("@app/components/viewer/useActiveDocumentId", () => ({
- useActiveDocumentId: () => fixture.activeId,
+ useActiveDocumentId: () => activeDocument.id,
useDocumentReady: () => true,
}));
vi.mock("@app/contexts/ViewerContext", () => ({
@@ -75,7 +79,7 @@ function RestoreOnLayout({ kind, action }: { kind: string; action: string }) {
describe("viewer controls after replacing a document", () => {
beforeEach(() => {
vi.clearAllMocks();
- fixture.activeId = "first";
+ activeDocument.id = "first";
fixture.bridges.clear();
});
@@ -107,7 +111,7 @@ describe("viewer controls after replacing a document", () => {
const { rerender } = render(view());
expect(fixture.documents.first[action]).toHaveBeenCalledOnce();
- fixture.activeId = "second";
+ activeDocument.id = "second";
rerender(view());
expect(fixture.documents.first[action]).toHaveBeenCalledOnce();
diff --git a/frontend/editor/src/core/components/viewer/useAnnotationMenuHandlers.ts b/frontend/editor/src/core/components/viewer/useAnnotationMenuHandlers.ts
index a66a096d4c..e4e5b450c2 100644
--- a/frontend/editor/src/core/components/viewer/useAnnotationMenuHandlers.ts
+++ b/frontend/editor/src/core/components/viewer/useAnnotationMenuHandlers.ts
@@ -161,10 +161,7 @@ export function useAnnotationMenuHandlers({
const toolId = (annotation?.object as AnnotationObject | undefined)
?.customData?.toolId;
- if (
- type !== undefined &&
- TEXT_MARKUP_SUBTYPES.includes(type as PdfAnnotationSubtype)
- )
+ if (type !== undefined && TEXT_MARKUP_SUBTYPES.includes(type))
return "textMarkup";
if (type === PdfAnnotationSubtype.INK)
return toolId === "inkHighlighter" ? "inkHighlighter" : "ink";
@@ -180,16 +177,8 @@ export function useAnnotationMenuHandlers({
)
return "comment";
if (type === PdfAnnotationSubtype.FREETEXT) return "note";
- if (
- type !== undefined &&
- SHAPE_SUBTYPES.includes(type as PdfAnnotationSubtype)
- )
- return "shape";
- if (
- type !== undefined &&
- LINE_SUBTYPES.includes(type as PdfAnnotationSubtype)
- )
- return "line";
+ if (type !== undefined && SHAPE_SUBTYPES.includes(type)) return "shape";
+ if (type !== undefined && LINE_SUBTYPES.includes(type)) return "line";
if (type === PdfAnnotationSubtype.STAMP) return "stamp";
return "unknown";
}, [annotation]);
@@ -205,10 +194,7 @@ export function useAnnotationMenuHandlers({
const type = obj.type;
if (type === PdfAnnotationSubtype.FREETEXT)
return obj.textColor || obj.color || "#000000";
- if (
- type !== undefined &&
- STROKE_COLOR_SUBTYPES.includes(type as PdfAnnotationSubtype)
- )
+ if (type !== undefined && STROKE_COLOR_SUBTYPES.includes(type))
return obj.strokeColor || obj.color || "#000000";
return obj.color || obj.strokeColor || "#000000";
})();
@@ -280,18 +266,12 @@ export function useAnnotationMenuHandlers({
patch.contents = obj?.contents ?? "";
} else {
patch.color = color;
- if (
- type !== undefined &&
- TEXT_MARKUP_SUBTYPES.includes(type as PdfAnnotationSubtype)
- ) {
+ if (type !== undefined && TEXT_MARKUP_SUBTYPES.includes(type)) {
patch.strokeColor = color;
patch.fillColor = color;
patch.opacity = obj?.opacity ?? 1;
}
- if (
- type !== undefined &&
- LINE_SUBTYPES.includes(type as PdfAnnotationSubtype)
- ) {
+ if (type !== undefined && LINE_SUBTYPES.includes(type)) {
patch.strokeColor = color;
patch.strokeWidth = obj?.strokeWidth ?? obj?.lineWidth ?? 2;
patch.lineWidth = obj?.lineWidth ?? obj?.strokeWidth ?? 2;
diff --git a/frontend/editor/src/core/contexts/AppConfigContext.test.tsx b/frontend/editor/src/core/contexts/AppConfigContext.test.tsx
index 35a313fa44..91beab4d39 100644
--- a/frontend/editor/src/core/contexts/AppConfigContext.test.tsx
+++ b/frontend/editor/src/core/contexts/AppConfigContext.test.tsx
@@ -10,10 +10,6 @@ import { TestQueryProvider } from "@app/tests/utils/TestQueryProvider";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactNode } from "react";
-// The mocks below supply only the fields the code under test reads; cast the
-// partial to apiClient.get's real resolved type (per-platform: axios or Tauri).
-type GetResponse = Awaited<ReturnType<typeof apiClient.get>>;
-
// Mock apiClient
vi.mock("@app/services/apiClient");
@@ -47,7 +43,7 @@ describe("AppConfigContext", () => {
vi.mocked(apiClient.get).mockResolvedValueOnce({
status: 200,
data: mockConfig,
- } as GetResponse);
+ });
const { result } = renderHook(() => useAppConfig(), { wrapper });
@@ -185,7 +181,7 @@ describe("AppConfigContext", () => {
vi.mocked(apiClient.get).mockResolvedValueOnce({
status: 200,
data: initialConfig,
- } as GetResponse);
+ });
const { result } = renderHook(() => useAppConfig(), { wrapper });
@@ -197,7 +193,7 @@ describe("AppConfigContext", () => {
vi.mocked(apiClient.get).mockResolvedValueOnce({
status: 200,
data: updatedConfig,
- } as GetResponse);
+ });
// Trigger jwt-available event wrapped in act
await act(async () => {
@@ -222,7 +218,7 @@ describe("AppConfigContext", () => {
vi.mocked(apiClient.get).mockResolvedValue({
status: 200,
data: mockConfig,
- } as GetResponse);
+ });
const { result } = renderHook(() => useAppConfig(), { wrapper });
@@ -246,7 +242,7 @@ describe("AppConfigContext", () => {
vi.mocked(apiClient.get).mockResolvedValue({
status: 200,
data: mockConfig,
- } as GetResponse);
+ });
const { result } = renderHook(() => useAppConfig(), { wrapper });
@@ -303,7 +299,7 @@ describe("AppConfigContext", () => {
vi.mocked(apiClient.get).mockReturnValue(
new Promise((resolve) => {
resolveFetch = resolve;
- }) as never,
+ }),
);
const { result } = renderHook(() => useAppConfig(), { wrapper });
@@ -369,7 +365,7 @@ describe("AppConfigContext", () => {
vi.mocked(apiClient.get).mockReturnValue(
new Promise((resolve) => {
resolveFetch = resolve;
- }) as never,
+ }),
);
const { result } = renderHook(() => useAppConfig(), {
@@ -403,7 +399,7 @@ describe("AppConfigContext", () => {
vi.mocked(apiClient.get).mockResolvedValue({
status: 200,
data: { enableLogin: false },
- } as GetResponse);
+ });
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -514,7 +510,7 @@ describe("AppConfigContext", () => {
vi.mocked(apiClient.get).mockResolvedValueOnce({
status: 200,
data: mockConfig,
- } as GetResponse);
+ });
renderHook(() => useAppConfig(), { wrapper });
diff --git a/frontend/editor/src/core/contexts/FilesModalContext.tsx b/frontend/editor/src/core/contexts/FilesModalContext.tsx
index 3b7d0c45ee..1660f5c3d8 100644
--- a/frontend/editor/src/core/contexts/FilesModalContext.tsx
+++ b/frontend/editor/src/core/contexts/FilesModalContext.tsx
@@ -103,10 +103,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
const idMap = new Map<string, FileId>();
for (let i = 0; i < stirlingFiles.length; i += 1) {
- idMap.set(
- sortedEntries[i].logicalId,
- stirlingFiles[i].fileId as FileId,
- );
+ idMap.set(sortedEntries[i].logicalId, stirlingFiles[i].fileId);
}
const rootIdMap = new Map<string, FileId>();
diff --git a/frontend/editor/src/core/contexts/FilesPageContext.upload.test.tsx b/frontend/editor/src/core/contexts/FilesPageContext.upload.test.tsx
index 7056f42f2d..4418b580fc 100644
--- a/frontend/editor/src/core/contexts/FilesPageContext.upload.test.tsx
+++ b/frontend/editor/src/core/contexts/FilesPageContext.upload.test.tsx
@@ -66,7 +66,7 @@ vi.mock("@app/auth/UseSession", () => ({
const stub = (id: string): StirlingFileStub => ({
id: id as FileId,
- originalFileId: id as FileId,
+ originalFileId: id,
name: `${id}.pdf`,
isLeaf: true,
versionNumber: 1,
diff --git a/frontend/editor/src/core/contexts/FolderContext.test.tsx b/frontend/editor/src/core/contexts/FolderContext.test.tsx
index 6ce550bc7a..9646e7ece5 100644
--- a/frontend/editor/src/core/contexts/FolderContext.test.tsx
+++ b/frontend/editor/src/core/contexts/FolderContext.test.tsx
@@ -1,5 +1,6 @@
import React from "react";
import { describe, expect, test, vi, beforeEach } from "vitest";
+import type { useAuth } from "@app/auth/UseSession";
import { render, screen, waitFor, act } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
@@ -47,14 +48,11 @@ vi.mock("@app/services/folderSyncService", () => ({
// FolderProvider only pulls from the server for a confirmed, non-anonymous
// user (guests have no cloud storage). Mock useAuth as a signed-in user so the
// pull runs; the guest-skip path is covered by its own test below.
-const { mockAuth } = vi.hoisted(() => ({
- mockAuth: {
- user: { id: "test-user", is_anonymous: false } as Record<
- string,
- unknown
- > | null,
- isAnonymous: false,
- },
+const mockAuth = vi.hoisted<
+ Pick<ReturnType<typeof useAuth>, "user" | "isAnonymous">
+>(() => ({
+ user: { id: "test-user", is_anonymous: false },
+ isAnonymous: false,
}));
vi.mock("@app/auth/UseSession", () => ({
useAuth: () => ({
@@ -492,7 +490,7 @@ describe("FolderContext disk subfolder resolution", () => {
directory: MOUNT_DIR,
createdAt: 0,
updatedAt: 0,
- } as FolderRecord;
+ };
}
type DiskProbeApi = {
diff --git a/frontend/editor/src/core/contexts/FolderContext.tsx b/frontend/editor/src/core/contexts/FolderContext.tsx
index e567eabc22..1be3d70d9c 100644
--- a/frontend/editor/src/core/contexts/FolderContext.tsx
+++ b/frontend/editor/src/core/contexts/FolderContext.tsx
@@ -274,7 +274,7 @@ function shouldStrandedReset(
for (let i = 0; i < 50 && cursor; i++) {
if (removedSet.has(cursor)) return true;
const node = byId.get(cursor);
- cursor = (node?.parentFolderId ?? null) as FolderId | null;
+ cursor = node?.parentFolderId ?? null;
}
return false;
}
diff --git a/frontend/editor/src/core/contexts/PageEditorContentRevision.test.tsx b/frontend/editor/src/core/contexts/PageEditorContentRevision.test.tsx
index a9d8a9669a..2dcf29f71e 100644
--- a/frontend/editor/src/core/contexts/PageEditorContentRevision.test.tsx
+++ b/frontend/editor/src/core/contexts/PageEditorContentRevision.test.tsx
@@ -31,10 +31,7 @@ const setFiles = (entries: [string, Partial<StirlingFileStub>][]) => {
fileState.state = {
files: {
ids: entries.map(([id]) => id as FileId),
- byId: Object.fromEntries(entries) as Record<
- FileId,
- Partial<StirlingFileStub>
- >,
+ byId: Object.fromEntries(entries),
},
};
};
diff --git a/frontend/editor/src/core/data/useProprietaryToolRegistry.tsx b/frontend/editor/src/core/data/useProprietaryToolRegistry.tsx
index 8b0d0440cf..51fa7a83eb 100644
--- a/frontend/editor/src/core/data/useProprietaryToolRegistry.tsx
+++ b/frontend/editor/src/core/data/useProprietaryToolRegistry.tsx
@@ -11,5 +11,6 @@ import { type ProprietaryToolRegistry } from "@app/data/toolsTaxonomy";
// Empty hook that returns empty registry (overridden in proprietary version)
export function useProprietaryToolRegistry(): ProprietaryToolRegistry {
+ // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- proprietary builds run this stub, where ProprietaryToolId is not empty
return useMemo(() => ({}) as ProprietaryToolRegistry, []);
}
diff --git a/frontend/editor/src/core/hooks/signing/useSigningSessions.ts b/frontend/editor/src/core/hooks/signing/useSigningSessions.ts
index 0f28efe7c5..2c8761924e 100644
--- a/frontend/editor/src/core/hooks/signing/useSigningSessions.ts
+++ b/frontend/editor/src/core/hooks/signing/useSigningSessions.ts
@@ -95,7 +95,7 @@ export const useSigningSessions = (
mySessions: data?.mySessions ?? EMPTY_SESSIONS,
loading: isLoading || refreshing,
settled: data !== undefined && !isFetching && error === null,
- error: (error as Error | null) ?? null,
+ error: error ?? null,
refetch: explicitRefetch,
};
};
diff --git a/frontend/editor/src/core/hooks/useFooterInfo.ts b/frontend/editor/src/core/hooks/useFooterInfo.ts
index 021c02e0d5..4748aba425 100644
--- a/frontend/editor/src/core/hooks/useFooterInfo.ts
+++ b/frontend/editor/src/core/hooks/useFooterInfo.ts
@@ -19,6 +19,6 @@ export function useFooterInfo() {
// Callers render legal links off this, so a failure must still yield an object.
footerInfo: data ?? (error ? FALLBACK : null),
loading: isPending,
- error: (error as Error | null) ?? null,
+ error: error ?? null,
};
}
diff --git a/frontend/editor/src/core/hooks/useIndexedDBThumbnail.ts b/frontend/editor/src/core/hooks/useIndexedDBThumbnail.ts
index 3b454e6849..6f0a043866 100644
--- a/frontend/editor/src/core/hooks/useIndexedDBThumbnail.ts
+++ b/frontend/editor/src/core/hooks/useIndexedDBThumbnail.ts
@@ -2,7 +2,6 @@ import { useState, useEffect } from "react";
import { StirlingFileStub } from "@app/types/fileContext";
import { useIndexedDB } from "@app/contexts/IndexedDBContext";
import { generateThumbnailForFile } from "@app/utils/thumbnailUtils";
-import { FileId } from "@app/types/fileContext";
import { useFileManagement } from "@app/contexts/FileContext";
/**
@@ -53,7 +52,7 @@ export function useIndexedDBThumbnail(
);
}
- const loadedFile = await indexedDB.loadFile(file.id as FileId);
+ const loadedFile = await indexedDB.loadFile(file.id);
if (!loadedFile) {
throw new Error("not in IndexedDB (likely remote-only stub)");
}
@@ -65,12 +64,12 @@ export function useIndexedDBThumbnail(
if (file.id && indexedDB && thumbnail) {
try {
- await indexedDB.updateThumbnail(file.id as FileId, thumbnail);
+ await indexedDB.updateThumbnail(file.id, thumbnail);
// Also sync the in-memory stub so subsequent re-mounts hit tier 1
// instead of regenerating. IndexedDB persistence alone only helps
// the next page load; the current session reads file.thumbnailUrl
// from the FileContext stub.
- updateStirlingFileStub(file.id as FileId, {
+ updateStirlingFileStub(file.id, {
thumbnailUrl: thumbnail,
});
} catch (error) {
diff --git a/frontend/editor/src/core/hooks/useLicenseAlert.ts b/frontend/editor/src/core/hooks/useLicenseAlert.ts
index 4372b2d996..b8a567f105 100644
--- a/frontend/editor/src/core/hooks/useLicenseAlert.ts
+++ b/frontend/editor/src/core/hooks/useLicenseAlert.ts
@@ -41,16 +41,10 @@ export function useLicenseAlert(): LicenseAlertState {
}
};
- window.addEventListener(
- UPGRADE_BANNER_ALERT_EVENT,
- handleAlert as EventListener,
- );
+ window.addEventListener(UPGRADE_BANNER_ALERT_EVENT, handleAlert);
return () => {
- window.removeEventListener(
- UPGRADE_BANNER_ALERT_EVENT,
- handleAlert as EventListener,
- );
+ window.removeEventListener(UPGRADE_BANNER_ALERT_EVENT, handleAlert);
};
}, []);
diff --git a/frontend/editor/src/core/hooks/useToolSections.ts b/frontend/editor/src/core/hooks/useToolSections.ts
index 84ccc22c83..518477fca8 100644
--- a/frontend/editor/src/core/hooks/useToolSections.ts
+++ b/frontend/editor/src/core/hooks/useToolSections.ts
@@ -143,12 +143,12 @@ export function useToolSections(
const subMap = {} as SubcategoryIdMap;
const seen = new Set<ToolId>();
filteredTools.forEach(({ item: [id, tool] }) => {
- const toolId = id as ToolId;
+ const toolId = id;
if (seen.has(toolId)) return;
seen.add(toolId);
const sub = tool.subcategoryId;
if (!subMap[sub]) subMap[sub] = [];
- subMap[sub].push({ id: toolId as ToolId, tool });
+ subMap[sub].push({ id: toolId, tool });
});
const entries = Object.entries(subMap);
@@ -165,7 +165,7 @@ export function useToolSections(
const ai = order.indexOf(a as SubcategoryId);
const bi = order.indexOf(b as SubcategoryId);
if (ai !== bi) return ai - bi;
- return (a as SubcategoryId).localeCompare(b as SubcategoryId);
+ return (a as SubcategoryId).localeCompare(b);
})
.map(
([subcategoryId, tools]) =>
diff --git a/frontend/editor/src/core/hooks/useUrlSync.test.tsx b/frontend/editor/src/core/hooks/useUrlSync.test.tsx
index 456c75b266..3de6c30bdd 100644
--- a/frontend/editor/src/core/hooks/useUrlSync.test.tsx
+++ b/frontend/editor/src/core/hooks/useUrlSync.test.tsx
@@ -45,7 +45,7 @@ describe("useNavigationUrlSync — startup-view selections", () => {
// Writing it to the address turned every visit to /editor into /read.
it("never writes the URL for the startup-applied tool", () => {
const { rerender } = renderHook(
- ({ tool }: { tool: ToolId | null }) => useHarness(tool, "read" as ToolId),
+ ({ tool }: { tool: ToolId | null }) => useHarness(tool, "read"),
{ initialProps: { tool: null as ToolId | null }, wrapper },
);
rerender({ tool: "read" as ToolId });
@@ -56,7 +56,7 @@ describe("useNavigationUrlSync — startup-view selections", () => {
// was consumed on first sight let the second run write /read anyway.
it("survives a re-run for the same tool", () => {
const { rerender } = renderHook(
- ({ tool }: { tool: ToolId | null }) => useHarness(tool, "read" as ToolId),
+ ({ tool }: { tool: ToolId | null }) => useHarness(tool, "read"),
{ initialProps: { tool: null as ToolId | null }, wrapper },
);
rerender({ tool: "read" as ToolId });
@@ -67,7 +67,7 @@ describe("useNavigationUrlSync — startup-view selections", () => {
it("still writes the URL when the user picks a different tool", () => {
const { rerender } = renderHook(
- ({ tool }: { tool: ToolId | null }) => useHarness(tool, "read" as ToolId),
+ ({ tool }: { tool: ToolId | null }) => useHarness(tool, "read"),
{ initialProps: { tool: null as ToolId | null }, wrapper },
);
rerender({ tool: "read" as ToolId });
diff --git a/frontend/editor/src/core/icons/IconAudit.stories.tsx b/frontend/editor/src/core/icons/IconAudit.stories.tsx
index 2190b922c1..17fbd1572a 100644
--- a/frontend/editor/src/core/icons/IconAudit.stories.tsx
+++ b/frontend/editor/src/core/icons/IconAudit.stories.tsx
@@ -16,10 +16,7 @@ const meta = {
export default meta;
type LegacyEntry = { viewBox: string; body: string };
-const legacy = legacyGlyphs as {
- mui: Record<string, LegacyEntry>;
- materialSymbols: Record<string, LegacyEntry>;
-};
+const legacy = legacyGlyphs;
function LegacyGlyph({ entry }: { entry: LegacyEntry }) {
return (
diff --git a/frontend/editor/src/core/icons/IconRegistry.stories.tsx b/frontend/editor/src/core/icons/IconRegistry.stories.tsx
index 83d78bf14e..efa170a42a 100644
--- a/frontend/editor/src/core/icons/IconRegistry.stories.tsx
+++ b/frontend/editor/src/core/icons/IconRegistry.stories.tsx
@@ -118,7 +118,7 @@ export const CustomIcons: StoryObj = {
<Gallery
heading="Our own icons"
note="Drawn in Lucide's grammar and living in src/core/icons/svg/stirling."
- names={[...CUSTOM].sort() as IconName[]}
+ names={[...CUSTOM].sort()}
/>
),
};
diff --git a/frontend/editor/src/core/pages/SettingsPage.tsx b/frontend/editor/src/core/pages/SettingsPage.tsx
index 2e868a7743..6f1ccb2ce6 100644
--- a/frontend/editor/src/core/pages/SettingsPage.tsx
+++ b/frontend/editor/src/core/pages/SettingsPage.tsx
@@ -146,12 +146,8 @@ const SettingsPageInner: React.FC = () => {
const key = (ev as CustomEvent<{ key?: NavKey }>).detail?.key;
if (key) switchSection(key);
};
- window.addEventListener("appConfig:navigate", handler as EventListener);
- return () =>
- window.removeEventListener(
- "appConfig:navigate",
- handler as EventListener,
- );
+ window.addEventListener("appConfig:navigate", handler);
+ return () => window.removeEventListener("appConfig:navigate", handler);
}, [switchSection]);
const headings = useSectionHeadings(activeItem?.key, contentRef);
diff --git a/frontend/editor/src/core/services/fileClassification.ts b/frontend/editor/src/core/services/fileClassification.ts
index 379b79e180..6c727337cb 100644
--- a/frontend/editor/src/core/services/fileClassification.ts
+++ b/frontend/editor/src/core/services/fileClassification.ts
@@ -8,7 +8,6 @@
import { fileStorage } from "@app/services/fileStorage";
import { extractPDFMetadata } from "@app/services/pdfMetadataService";
-import type { FileId } from "@app/types/file";
import type { StirlingFileStub } from "@app/types/fileContext";
export const CLASSIFICATION_METADATA_KEY = "StirlingPDFClassification";
@@ -61,9 +60,7 @@ export async function readStubClassificationLabels(
): Promise<string[] | null> {
if (stub.type && !stub.type.toLowerCase().includes("pdf")) return null;
if (stub.size > MAX_READ_BYTES) return null;
- const file = await fileStorage
- .getStirlingFile(stub.id as FileId)
- .catch(() => null);
+ const file = await fileStorage.getStirlingFile(stub.id).catch(() => null);
if (!file) return null;
return readClassificationLabelsFromFile(file);
}
diff --git a/frontend/editor/src/core/services/fileStorage.blobFallback.test.ts b/frontend/editor/src/core/services/fileStorage.blobFallback.test.ts
index d6f1c4b89d..251a0051d6 100644
--- a/frontend/editor/src/core/services/fileStorage.blobFallback.test.ts
+++ b/frontend/editor/src/core/services/fileStorage.blobFallback.test.ts
@@ -365,8 +365,8 @@ describe("orphanedAncestorIds", () => {
test("takes the superseded versions with the leaf", async () => {
const { fileStorage } = await freshFileStorage();
instrumentAdd({ rejectBlobs: false });
- await store(fileStorage as never, "v1", undefined, false);
- await store(fileStorage as never, "v2", "v1", true);
+ await store(fileStorage, "v1", undefined, false);
+ await store(fileStorage, "v2", "v1", true);
expect(await fileStorage.orphanedAncestorIds(["v2" as never])).toEqual([
"v1",
@@ -377,9 +377,9 @@ describe("orphanedAncestorIds", () => {
const { fileStorage } = await freshFileStorage();
instrumentAdd({ rejectBlobs: false });
// Distinct ids: the fake database outlives the module reset between tests.
- await store(fileStorage as never, "split-root", undefined, false);
- await store(fileStorage as never, "split-a", "split-root", true);
- await store(fileStorage as never, "split-b", "split-root", true);
+ await store(fileStorage, "split-root", undefined, false);
+ await store(fileStorage, "split-a", "split-root", true);
+ await store(fileStorage, "split-b", "split-root", true);
// `split-b` still descends from the root, so deleting `split-a` can't strip it.
expect(await fileStorage.orphanedAncestorIds(["split-a" as never])).toEqual(
diff --git a/frontend/editor/src/core/services/fileStorage.migration.test.ts b/frontend/editor/src/core/services/fileStorage.migration.test.ts
index 28ee69e8da..796e4f856b 100644
--- a/frontend/editor/src/core/services/fileStorage.migration.test.ts
+++ b/frontend/editor/src/core/services/fileStorage.migration.test.ts
@@ -26,7 +26,7 @@ function record(
versionNumber: 1,
data: new ArrayBuffer(0),
...overrides,
- } as StoredStirlingFileRecord;
+ };
}
describe("legacyDerivedFromTool — IndexedDB backfill for pre-upgrade files", () => {
diff --git a/frontend/editor/src/core/services/fileStorage.ts b/frontend/editor/src/core/services/fileStorage.ts
index e05f884a45..39759d4f43 100644
--- a/frontend/editor/src/core/services/fileStorage.ts
+++ b/frontend/editor/src/core/services/fileStorage.ts
@@ -1020,9 +1020,7 @@ class FileStorageService {
);
for (const folderId of folderIds) {
- const cursorRequest = index.openCursor(
- IDBKeyRange.only(folderId as string),
- );
+ const cursorRequest = index.openCursor(IDBKeyRange.only(folderId));
cursorRequest.onerror = () => reject(cursorRequest.error);
cursorRequest.onsuccess = (event) => {
const cursor = (event.target as IDBRequest)
@@ -1058,11 +1056,11 @@ class FileStorageService {
// share a lineage, so one leaf's delete must not strip another's history.
const keep = new Set<string>();
for (const stub of stubs) {
- if (doomed.has(stub.id as string)) continue;
+ if (doomed.has(stub.id)) continue;
let cursor = stub.parentFileId as string | undefined;
while (cursor && !keep.has(cursor)) {
keep.add(cursor);
- cursor = byId.get(cursor)?.parentFileId as string | undefined;
+ cursor = byId.get(cursor)?.parentFileId;
}
}
@@ -1074,7 +1072,7 @@ class FileStorageService {
doomed.add(cursor);
orphans.push(cursor as FileId);
}
- cursor = byId.get(cursor)?.parentFileId as string | undefined;
+ cursor = byId.get(cursor)?.parentFileId;
}
}
return orphans;
diff --git a/frontend/editor/src/core/services/fileSyncService.ts b/frontend/editor/src/core/services/fileSyncService.ts
index 5cdf1e85d4..c34bbafa97 100644
--- a/frontend/editor/src/core/services/fileSyncService.ts
+++ b/frontend/editor/src/core/services/fileSyncService.ts
@@ -483,8 +483,8 @@ export async function materializeServerStubs(
skipUploadTracking: true,
});
if (ingested.length === 0) continue;
- const primary = ingested[ingested.length - 1]!;
- const newId = primary.fileId as FileId;
+ const primary = ingested[ingested.length - 1];
+ const newId = primary.fileId;
const remoteUpdates = {
// The ingest above made a new local file, which starts in no folder. Without
// carrying membership across, materialising a file to open it moves it to the
@@ -512,7 +512,7 @@ export async function materializeServerStubs(
if (failed.length > 0) {
// Single summarized toast - far less noisy than per-stub alerts but
// still surfaces what would otherwise be a silent drop from the grid.
- const first = failed[0]!;
+ const first = failed[0];
const bodyText =
failed.length === 1
? `Couldn't open "${first.name}"${first.status ? ` (HTTP ${first.status})` : ""}.`
diff --git a/frontend/editor/src/core/services/indexedDBManager.migration.test.ts b/frontend/editor/src/core/services/indexedDBManager.migration.test.ts
index bc3addcb07..e11b838575 100644
--- a/frontend/editor/src/core/services/indexedDBManager.migration.test.ts
+++ b/frontend/editor/src/core/services/indexedDBManager.migration.test.ts
@@ -267,7 +267,7 @@ describe("IndexedDB migration (FILES store)", () => {
const rows = (await readAllFiles()) as Array<Record<string, unknown>>;
expect(rows).toHaveLength(1);
- const row = rows[0]!;
+ const row = rows[0];
// Existing v3 fields should be unchanged
expect(row.isLeaf).toBe(true);
@@ -360,7 +360,7 @@ describe("IndexedDB migration (FILES store)", () => {
const rows = (await readAllFiles()) as Array<Record<string, unknown>>;
expect(rows).toHaveLength(1);
- expect(rows[0]!.folderId).toBeNull();
+ expect(rows[0].folderId).toBeNull();
});
test("SaaS v6 database is force-deleted (data lost, schema reset to v9)", async () => {
diff --git a/frontend/editor/src/core/services/pdfiumInit.test.ts b/frontend/editor/src/core/services/pdfiumInit.test.ts
index 315c39a662..3dbe08ac0e 100644
--- a/frontend/editor/src/core/services/pdfiumInit.test.ts
+++ b/frontend/editor/src/core/services/pdfiumInit.test.ts
@@ -9,7 +9,7 @@ import { describe, expect, test, vi } from "vitest";
const init = vi.hoisted(() => vi.fn());
vi.mock("@embedpdf/pdfium", () => ({ init }));
-const wasmModule = vi.hoisted(() => ({}) as WebAssembly.Module);
+const wasmModule = vi.hoisted<WebAssembly.Module>(() => ({}));
vi.mock("@app/services/wasmPrecompiler", () => ({
pdfiumWasmModulePromise: Promise.resolve(wasmModule),
startEagerWasmCompilation: () => {},
@@ -33,14 +33,9 @@ async function loadService() {
describe("pdfium bootstrap", () => {
test("rejects when instantiating the pre-compiled module fails", async () => {
const failure = new Error("LinkError: import mismatch");
- vi.spyOn(WebAssembly, "instantiate").mockRejectedValue(failure as never);
+ vi.spyOn(WebAssembly, "instantiate").mockRejectedValue(failure);
init.mockImplementation((overrides: Record<string, never>) =>
- emscriptenInit(
- overrides.instantiateWasm as unknown as (
- imports: object,
- ok: () => void,
- ) => void,
- ),
+ emscriptenInit(overrides.instantiateWasm),
);
const { getPdfiumModule } = await loadService();
@@ -52,7 +47,7 @@ describe("pdfium bootstrap", () => {
test("a failed load isn't cached, so the next call retries", async () => {
const instantiate = vi
.spyOn(WebAssembly, "instantiate")
- .mockRejectedValueOnce(new Error("transient") as never)
+ .mockRejectedValueOnce(new Error("transient"))
.mockResolvedValue({} as never);
const ready = { PDFiumExt_Init: () => {} };
init.mockImplementation(
diff --git a/frontend/editor/src/core/services/postLoginRedirect.test.ts b/frontend/editor/src/core/services/postLoginRedirect.test.ts
index 9f1687f392..c1240a7669 100644
--- a/frontend/editor/src/core/services/postLoginRedirect.test.ts
+++ b/frontend/editor/src/core/services/postLoginRedirect.test.ts
@@ -16,7 +16,7 @@ describe("isSafePostLoginRedirect (core base)", () => {
expect(isSafePostLoginRedirect(null)).toBe(false);
expect(isSafePostLoginRedirect(undefined)).toBe(false);
expect(isSafePostLoginRedirect("")).toBe(false);
- expect(isSafePostLoginRedirect(42 as unknown)).toBe(false);
+ expect(isSafePostLoginRedirect(42)).toBe(false);
});
it("rejects off-origin and protocol-relative forms", () => {
diff --git a/frontend/editor/src/core/services/preferencesService.ts b/frontend/editor/src/core/services/preferencesService.ts
index eafb9d1eda..b68cf3a645 100644
--- a/frontend/editor/src/core/services/preferencesService.ts
+++ b/frontend/editor/src/core/services/preferencesService.ts
@@ -71,7 +71,7 @@ class PreferencesService {
if (stored) {
const preferences = JSON.parse(stored) as Partial<UserPreferences>;
if (key in preferences && preferences[key] !== undefined) {
- return preferences[key]!;
+ return preferences[key];
}
}
} catch (error) {
@@ -79,7 +79,7 @@ class PreferencesService {
}
// Use server defaults if available, otherwise use hardcoded defaults
if (key in this.serverDefaults && this.serverDefaults[key] !== undefined) {
- return this.serverDefaults[key]!;
+ return this.serverDefaults[key];
}
return DEFAULT_PREFERENCES[key];
}
diff --git a/frontend/editor/src/core/services/serverStorageBundle.ts b/frontend/editor/src/core/services/serverStorageBundle.ts
index ce9862246c..e132200626 100644
--- a/frontend/editor/src/core/services/serverStorageBundle.ts
+++ b/frontend/editor/src/core/services/serverStorageBundle.ts
@@ -124,7 +124,7 @@ export async function buildSharePackage(stubs: StirlingFileStub[]): Promise<{
const entries: ShareBundleEntry[] = [];
for (const stub of stubs) {
- const file = await fileStorage.getStirlingFile(stub.id as FileId);
+ const file = await fileStorage.getStirlingFile(stub.id);
if (!file) {
throw new Error(`Missing file data for ${stub.name || stub.id}`);
}
diff --git a/frontend/editor/src/core/services/serverStorageUpload.ts b/frontend/editor/src/core/services/serverStorageUpload.ts
index 3c88bc0582..7f2fe9c0bb 100644
--- a/frontend/editor/src/core/services/serverStorageUpload.ts
+++ b/frontend/editor/src/core/services/serverStorageUpload.ts
@@ -102,8 +102,8 @@ export async function uploadHistoryChains(
leafStubs.push(finalStub);
}
for (const stub of chain) {
- if (!seenIds.has(stub.id as FileId)) {
- seenIds.add(stub.id as FileId);
+ if (!seenIds.has(stub.id)) {
+ seenIds.add(stub.id);
combinedChain.push(stub);
}
}
diff --git a/frontend/editor/src/core/services/workbenchSession.ts b/frontend/editor/src/core/services/workbenchSession.ts
index 8783f35386..a37584b903 100644
--- a/frontend/editor/src/core/services/workbenchSession.ts
+++ b/frontend/editor/src/core/services/workbenchSession.ts
@@ -25,7 +25,7 @@ export interface WorkbenchSession {
/** A file's stable identity across versions - what the session records. */
export function originalIdOf(stub: StirlingFileStub): string {
- return stub.originalFileId || (stub.id as string);
+ return stub.originalFileId || stub.id;
}
export function readWorkbenchSession(): WorkbenchSession | null {
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-combined-features.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-combined-features.spec.ts
index 499b13ea66..419fb0e187 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-combined-features.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-combined-features.spec.ts
@@ -86,7 +86,7 @@ async function runText(
const r = (window as unknown as EditorTestWindow).__editor_store.doc
.page(pageIdx)
.runs.find((x) => x.id === id);
- return r ? (r.text as string) : "(gone)";
+ return r ? r.text : "(gone)";
},
{ pageIdx, id },
);
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-cropbox.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-cropbox.spec.ts
index 7f1509df1a..55b98e4ff8 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-cropbox.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-cropbox.spec.ts
@@ -66,7 +66,7 @@ async function load(
boundsX: r?.bounds.x,
display: pg.display,
};
- }) as Promise<Probe>;
+ });
}
test("control fixture (CropBox==MediaBox) yields an identity transform", async ({
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-cross-font-charcode.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-cross-font-charcode.spec.ts
index 36b011fb2e..f60a08475d 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-cross-font-charcode.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-cross-font-charcode.spec.ts
@@ -61,12 +61,12 @@ test("editor sends the run's font name to encode-charcodes", async ({
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, "s");
- }, id as string);
+ }, id);
await page.waitForTimeout(1500);
expect(bodies.length, "endpoint was called").toBeGreaterThan(0);
const named = bodies.filter(
- (b) => typeof b.fontName === "string" && (b.fontName as string).length > 0,
+ (b) => typeof b.fontName === "string" && b.fontName.length > 0,
);
expect(
named.length,
@@ -79,8 +79,7 @@ test("editor sends the run's font name to encode-charcodes", async ({
// "ABCDEF+Family" subset as bare "Family".
const hashed = bodies.filter(
(b) =>
- typeof b.fontSha256 === "string" &&
- /^[0-9a-f]{64}$/.test(b.fontSha256 as string),
+ typeof b.fontSha256 === "string" && /^[0-9a-f]{64}$/.test(b.fontSha256),
);
expect(
hashed.length,
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-double-edit.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-double-edit.spec.ts
index d562c4ceb2..fc31602dcf 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-double-edit.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-double-edit.spec.ts
@@ -159,22 +159,19 @@ test.describe("PDF text editor - a second edit is as safe as the first", () => {
});
await page.waitForTimeout(1800);
- const loadedColour = (await page.evaluate(COLOURED_PIXELS)) as number;
+ const loadedColour = await page.evaluate(COLOURED_PIXELS);
for (const pass of [1, 2]) {
- const run = (await page.evaluate(FIRST_RUN)) as {
- id: string;
- text: string;
- } | null;
+ const run = await page.evaluate(FIRST_RUN);
expect(
run,
`${c.name}: no editable run before pass ${pass}`,
).not.toBeNull();
await appendChar(page, run!.id, String(pass));
- const beforeSave = (await page.evaluate(PAGE_TEXT)) as string;
+ const beforeSave = await page.evaluate(PAGE_TEXT);
await saveAndReopen(page, `${c.name.replace(/\W+/g, "-")}-${pass}`);
- const afterReopen = (await page.evaluate(PAGE_TEXT)) as string;
+ const afterReopen = await page.evaluate(PAGE_TEXT);
expect(
strip(afterReopen).length,
@@ -191,7 +188,7 @@ test.describe("PDF text editor - a second edit is as safe as the first", () => {
// Colour artwork (a gradient, a pattern) must not drain away. The
// second pass is the one that historically loses a background.
if (loadedColour > 1000) {
- const now = (await page.evaluate(COLOURED_PIXELS)) as number;
+ const now = await page.evaluate(COLOURED_PIXELS);
expect(
now / loadedColour,
`${c.name}: pass ${pass} lost the page's colour artwork`,
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-fix-mixed-fontsize.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-fix-mixed-fontsize.spec.ts
index 25fe7b7b7a..b7841fd906 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-fix-mixed-fontsize.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-fix-mixed-fontsize.spec.ts
@@ -73,7 +73,7 @@ async function runsOnPage0(page: Page): Promise<RunInfo[]> {
});
}
return out;
- }) as Promise<RunInfo[]>;
+ });
}
interface Clip {
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-focus-after-edit.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-focus-after-edit.spec.ts
index 79b82bfa86..c97b096bd9 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-focus-after-edit.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-focus-after-edit.spec.ts
@@ -91,7 +91,7 @@ function runText(page: Page, id: string): Promise<string> {
const r = (window as unknown as EditorTestWindow).__editor_store.doc
.page(1)
.runs.find((x) => x.id === rid);
- return r ? (r.text as string) : "(gone)";
+ return r ? r.text : "(gone)";
}, id);
}
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts
index 25621e5c55..9652349689 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts
@@ -191,8 +191,8 @@ async function glyphs(
return {
boundsRight: r.bounds.x + r.bounds.width,
pageWidth: pg.width,
- fontId: r.fontId as string,
- text: (r.text as string) ?? "",
+ fontId: r.fontId,
+ text: r.text ?? "",
maxGap,
hasYdieresis: hasY,
};
@@ -311,7 +311,7 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
(rid: string) =>
(window as unknown as EditorTestWindow).__editor_store.doc
.page(1)
- .runs.find((x) => x.id === rid)!.text as string,
+ .runs.find((x) => x.id === rid)!.text,
id,
);
await replaceAll(page, id, cur.replace(/^Comprehensive/, ""));
@@ -331,7 +331,7 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
(rid: string) =>
(window as unknown as EditorTestWindow).__editor_store.doc
.page(1)
- .runs.find((x) => x.id === rid)!.text as string,
+ .runs.find((x) => x.id === rid)!.text,
id,
);
// drop the 'h' from "Comprehensive" -> the word should read "Compreensive"
@@ -386,7 +386,7 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
(rid: string) =>
(window as unknown as EditorTestWindow).__editor_store.doc
.page(1)
- .runs.find((x) => x.id === rid)!.text as string,
+ .runs.find((x) => x.id === rid)!.text,
id,
);
await replaceAll(
@@ -414,7 +414,7 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
const x = (window as unknown as EditorTestWindow).__editor_store.doc
.page(1)
.runs.find((y) => y.id === r);
- return x ? (x.text as string) : "(gone)";
+ return x ? x.text : "(gone)";
}, id);
await caretEndInsert(page, id, " UNIQ");
await blur(page, id);
@@ -462,7 +462,7 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
(rid: string) =>
(window as unknown as EditorTestWindow).__editor_store.doc
.page(1)
- .runs.find((x) => x.id === rid)!.text as string,
+ .runs.find((x) => x.id === rid)!.text,
id,
);
await caretEndInsert(page, id, "\n");
@@ -478,9 +478,9 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
() =>
page.evaluate(
(rid: string) =>
- ((window as unknown as EditorTestWindow).__editor_store.doc
+ (window as unknown as EditorTestWindow).__editor_store.doc
.page(1)
- .runs.find((x) => x.id === rid)?.text ?? null) as string | null,
+ .runs.find((x) => x.id === rid)?.text ?? null,
id,
),
{ timeout: 6000, message: "one undo should fully revert Enter+type" },
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-model-sync.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-model-sync.spec.ts
index 4866980b48..85c87810fc 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-model-sync.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-model-sync.spec.ts
@@ -64,7 +64,7 @@ test.describe("PDF text editor - identity-preserving pdfium re-read", () => {
const before = await page.evaluate(RUN_IDS);
expect(before.length).toBeGreaterThan(0);
- const result = (await page.evaluate(RESYNC)) as SyncResult | null;
+ const result = await page.evaluate(RESYNC);
expect(result, "resyncPage should return a result").not.toBeNull();
// Every live run must be claimed by exactly one re-read run.
expect(result!.matched).toBe(before.length);
@@ -100,7 +100,7 @@ test.describe("PDF text editor - identity-preserving pdfium re-read", () => {
}, tid);
await page.waitForTimeout(300);
- const result = (await page.evaluate(RESYNC)) as SyncResult | null;
+ const result = await page.evaluate(RESYNC);
expect(result).not.toBeNull();
// The edit replaces objects, so pointer matching is what has to hold up.
expect(result!.unmatched).toBe(0);
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-mushroom-scramble.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-mushroom-scramble.spec.ts
index 2659f1ca95..f9186a4335 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-mushroom-scramble.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-mushroom-scramble.spec.ts
@@ -43,10 +43,10 @@ test("mid-line paragraph edit does not scramble unchanged words (cold backend, n
pg.runs.find((x) => (x.paragraphLineSlots?.length ?? 0) > 1) ??
pg.runs[0];
return {
- id: r?.id as string,
- fontSubset: r?.fontSubset as boolean,
+ id: r?.id,
+ fontSubset: r?.fontSubset,
lineCount: r?.paragraphLineSlots?.length ?? 0,
- firstLine: (r?.text ?? "").split("\n")[0] as string,
+ firstLine: (r?.text ?? "").split("\n")[0],
};
});
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-paragraphs.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-paragraphs.spec.ts
index 8d9bbdcdc3..ab74b4635d 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-paragraphs.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-paragraphs.spec.ts
@@ -362,7 +362,7 @@ test.describe("PDF text editor - paragraph editing battery", () => {
const baseNew = firstBaselineOfWord(info, "NEWLINEWORD");
expect(baseNew !== null, `NEW word missing: ${info.text}`).toBe(true);
if (baseProc !== null) {
- expect(baseNew!).toBeLessThan(baseProc! - 1);
+ expect(baseNew!).toBeLessThan(baseProc - 1);
}
});
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-pattern-fill.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-pattern-fill.spec.ts
index f58402d221..fd194f9437 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-pattern-fill.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-pattern-fill.spec.ts
@@ -39,7 +39,7 @@ test("a pattern colour space fill survives regeneration", async ({ page }) => {
const buf = m.FPDFBitmap_GetBuffer(bmp);
const stride = m.FPDFBitmap_GetStride(bmp);
const heap = new Uint8Array(
- (m.pdfium.wasmExports as any).memory.buffer,
+ m.pdfium.wasmExports.memory.buffer,
buf,
stride * h,
);
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-reported-issues.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-reported-issues.spec.ts
index 46c34115ae..915d9cd6b5 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-reported-issues.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-reported-issues.spec.ts
@@ -71,7 +71,7 @@ async function runText(
const r = (window as unknown as EditorTestWindow).__editor_store.doc
.page(pageIdx)
.runs.find((x) => x.id === id);
- return r ? (r.text as string) : "(gone)";
+ return r ? r.text : "(gone)";
},
{ pageIdx, id },
);
@@ -368,11 +368,10 @@ test.describe("PDF text editor - reported issue: character insertion + font inte
() => ((window as unknown as EditorTestWindow).__charcode_events = []),
);
await appendViaOverlay(page, id, "S");
- const outcomes = await page.evaluate(
- () =>
- ((window as unknown as EditorTestWindow).__charcode_events ?? []).map(
- (e) => `${e.strategy}:${e.outcome}`,
- ) as string[],
+ const outcomes = await page.evaluate(() =>
+ ((window as unknown as EditorTestWindow).__charcode_events ?? []).map(
+ (e) => `${e.strategy}:${e.outcome}`,
+ ),
);
expect(
outcomes,
@@ -395,11 +394,10 @@ test.describe("PDF text editor - reported issue: character insertion + font inte
[]) as unknown as void,
);
await appendViaOverlay(page, id, "S");
- const outcomes = await page.evaluate(
- () =>
- ((window as unknown as EditorTestWindow).__charcode_events ?? []).map(
- (e) => e.outcome,
- ) as string[],
+ const outcomes = await page.evaluate(() =>
+ ((window as unknown as EditorTestWindow).__charcode_events ?? []).map(
+ (e) => e.outcome,
+ ),
);
// At least one emit event fired for the edit.
expect(outcomes.length).toBeGreaterThan(0);
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-signed-save.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-signed-save.spec.ts
index f2025db120..63754fc771 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-signed-save.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-signed-save.spec.ts
@@ -58,7 +58,7 @@ test.describe("PDF text editor - signed save stays signed", () => {
expect(saved).not.toBeNull();
const before = fs.readFileSync(SIGNED);
- const after = fs.readFileSync(saved!);
+ const after = fs.readFileSync(saved);
expect(
after.length,
@@ -110,7 +110,7 @@ test.describe("PDF text editor - signed save stays signed", () => {
const saved = await download.path();
const before = fs.readFileSync(SIGNED);
- const after = fs.readFileSync(saved!);
+ const after = fs.readFileSync(saved);
expect(
after.equals(before),
"an untouched document must come back exactly as it went in",
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts
index 7cba5fd28d..99180e588e 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts
@@ -82,14 +82,14 @@ async function appendSaveReopen(
sel.addRange(range);
document.execCommand("insertText", false, " " + txt);
},
- { rid: id as string, txt: text },
+ { rid: id, txt: text },
);
await page.waitForTimeout(200);
await page.evaluate((rid: string) => {
document
.querySelector<HTMLElement>(`[data-testid="pdf-editor-run-${rid}"]`)
?.blur();
- }, id as string);
+ }, id);
await page.waitForTimeout(1000);
// Save, then reopen the produced bytes.
@@ -112,7 +112,7 @@ async function appendSaveReopen(
.runs.map((r) => r.text)
.join("");
});
- return { reopened, errs, runId: id as string };
+ return { reopened, errs, runId: id };
}
for (const { name, text } of COVERED) {
@@ -197,21 +197,21 @@ for (const { name, text } of RTL_SAMPLES) {
sel.addRange(range);
document.execCommand("insertText", false, " " + txt);
},
- { rid: id as string, txt: text },
+ { rid: id, txt: text },
);
await page.waitForTimeout(200);
await page.evaluate((rid: string) => {
document
.querySelector<HTMLElement>(`[data-testid="pdf-editor-run-${rid}"]`)
?.blur();
- }, id as string);
+ }, id);
await page.waitForTimeout(1000);
// (a) model text carries the inserted RTL string.
const model = await page.evaluate((rid: string) => {
const s = (window as unknown as EditorTestWindow).__editor_store;
return s.doc.page(0).runs.find((r) => r.id === rid)?.text ?? "";
- }, id as string);
+ }, id);
expect(model).toContain(text);
// (b) the edited run stays within page bounds after the edit.
@@ -220,7 +220,7 @@ for (const { name, text } of RTL_SAMPLES) {
const pg = s.doc.page(0);
const r = pg.runs.find((x) => x.id === rid)!;
return { boundsRight: r.bounds.x + r.bounds.width, pageWidth: pg.width };
- }, id as string);
+ }, id);
expect(
fits.boundsRight,
"RTL run must not extend past the page width",
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-images.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-images.spec.ts
index 8ce81db2cb..b14d3a1553 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-images.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-images.spec.ts
@@ -67,7 +67,7 @@ async function inkStats(
`[data-testid="pdf-editor-page-${idx}"]`,
);
if (!pageEl) return { error: `no page ${idx}` } as const;
- const canvas = pageEl.querySelector("canvas") as HTMLCanvasElement | null;
+ const canvas = pageEl.querySelector("canvas");
if (!canvas || !canvas.width || !canvas.height)
return { error: "page canvas has no bitmap" } as const;
const cb = canvas.getBoundingClientRect();
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-rotation.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-rotation.spec.ts
index ca9000a326..16e4776462 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-rotation.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-rotation.spec.ts
@@ -264,7 +264,7 @@ async function appendToRun(
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
- document.execCommand("insertText", false, txt as string);
+ document.execCommand("insertText", false, txt);
},
[runId, text] as const,
);
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-roundtrip.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-roundtrip.spec.ts
index 232f23e94b..bffc7196bd 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-roundtrip.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-roundtrip.spec.ts
@@ -77,7 +77,7 @@ const SCAN_FN = (idx: number): Scan | { err: string } => {
};
async function scan(page: Page, idx = 0): Promise<Scan> {
- const s = (await page.evaluate(SCAN_FN, idx)) as Scan | { err: string };
+ const s = await page.evaluate(SCAN_FN, idx);
if ("err" in s) throw new Error(`scan(page ${idx}) failed: ${s.err}`);
return s;
}
@@ -90,7 +90,7 @@ async function settled(page: Page, idx = 0, tries = 60): Promise<Scan> {
let prev = -1;
let stable = 0;
for (let i = 0; i < tries; i++) {
- const ink = (await page.evaluate((j: number) => {
+ const ink = await page.evaluate((j: number) => {
const el = document.querySelector<HTMLElement>(
`[data-testid="pdf-editor-page-${j}"]`,
);
@@ -105,7 +105,7 @@ async function settled(page: Page, idx = 0, tries = 60): Promise<Scan> {
for (let k = 0; k < d.length; k += 4)
if (d[k] < 160 && d[k + 1] < 160) n++;
return n;
- }, idx)) as number;
+ }, idx);
if (ink > 0 && ink === prev) {
stable++;
if (stable >= 2) return scan(page, idx);
diff --git a/frontend/editor/src/core/tools/annotate/useAnnotationSelection.ts b/frontend/editor/src/core/tools/annotate/useAnnotationSelection.ts
index 4e2c6b7422..1d410991cd 100644
--- a/frontend/editor/src/core/tools/annotate/useAnnotationSelection.ts
+++ b/frontend/editor/src/core/tools/annotate/useAnnotationSelection.ts
@@ -171,12 +171,8 @@ export function useAnnotationSelection({
}
if (type === 3) {
const background =
- (annObject?.backgroundColor as string | undefined) ||
- (annObject?.fillColor as string | undefined) ||
- undefined;
- const textColor =
- (annObject?.textColor as string | undefined) ||
- (annObject?.color as string | undefined);
+ annObject?.backgroundColor || annObject?.fillColor || undefined;
+ const textColor = annObject?.textColor || annObject?.color;
if (textColor) {
setTextColor(textColor);
}
@@ -236,14 +232,10 @@ export function useAnnotationSelection({
}
if ([4, 5, 6, 7, 8].includes(type)) {
- const stroke =
- (annObject?.strokeColor as string | undefined) ??
- (annObject?.color as string | undefined);
+ const stroke = annObject?.strokeColor ?? annObject?.color;
if (stroke) setShapeStrokeColor(stroke);
if ([5, 6, 7].includes(type)) {
- const fill =
- (annObject?.color as string | undefined) ??
- (annObject?.fillColor as string | undefined);
+ const fill = annObject?.color ?? annObject?.fillColor;
if (fill) setShapeFillColor(fill);
}
const opacity =
diff --git a/frontend/editor/src/core/tools/formFill/FormFill.tsx b/frontend/editor/src/core/tools/formFill/FormFill.tsx
index 4dbc5685ac..69be33bc8a 100644
--- a/frontend/editor/src/core/tools/formFill/FormFill.tsx
+++ b/frontend/editor/src/core/tools/formFill/FormFill.tsx
@@ -485,7 +485,7 @@ const FormFill = (_props: BaseToolProps) => {
<div className={styles.modeTabs}>
<SegmentedControl
value={mode}
- onChange={(val) => requestMode(val as FormMode)}
+ onChange={(val) => requestMode(val)}
options={MODE_TABS.map((tab) => ({
value: tab.id,
label: (
@@ -503,14 +503,10 @@ const FormFill = (_props: BaseToolProps) => {
</div>
{/* ---- Create mode ---- */}
- {mode === "create" && (
- <FormFieldCreatePanel currentFile={currentFile as File | Blob | null} />
- )}
+ {mode === "create" && <FormFieldCreatePanel currentFile={currentFile} />}
{/* ---- Modify mode ---- */}
- {mode === "modify" && (
- <FormFieldModifyPanel currentFile={currentFile as File | Blob | null} />
- )}
+ {mode === "modify" && <FormFieldModifyPanel currentFile={currentFile} />}
{/* ---- Fill Form content ---- */}
{mode === "fill" && (
diff --git a/frontend/editor/src/core/tools/formFill/FormFillContext.tsx b/frontend/editor/src/core/tools/formFill/FormFillContext.tsx
index 8bccb51400..0df56c4bb5 100644
--- a/frontend/editor/src/core/tools/formFill/FormFillContext.tsx
+++ b/frontend/editor/src/core/tools/formFill/FormFillContext.tsx
@@ -64,6 +64,12 @@ export interface PendingField extends NewFieldDefinition {
type Listener = () => void;
+interface StagedEdits {
+ pending: PendingField[];
+ modified: Record<string, ModifyFieldDefinition>;
+ deleted: string[];
+}
+
/**
* External store that holds form values outside of React state.
*
@@ -411,18 +417,12 @@ export function FormFillProvider({
// Undo covers the staged edits, which is what the user has been doing here; the applied
// document keeps its own version history elsewhere.
- const undoStackRef = useRef<
- {
- pending: PendingField[];
- modified: Record<string, ModifyFieldDefinition>;
- deleted: string[];
- }[]
- >([]);
+ const undoStackRef = useRef<StagedEdits[]>([]);
const [canUndo, setCanUndo] = useState(false);
- const liveEditsRef = useRef({
- pending: [] as PendingField[],
- modified: {} as Record<string, ModifyFieldDefinition>,
- deleted: [] as string[],
+ const liveEditsRef = useRef<StagedEdits>({
+ pending: [],
+ modified: {},
+ deleted: [],
});
const rememberForUndo = useCallback(() => {
@@ -784,7 +784,7 @@ export function FormFillProvider({
field.options ?? (needsOptions ? ["Option 1", "Option 2"] : undefined);
setPendingFields((prev) => [
...prev,
- { ...field, name: defaultName, options, id } as PendingField,
+ { ...field, name: defaultName, options, id },
]);
return id;
},
diff --git a/frontend/editor/src/core/tools/formFill/useFieldShortcuts.ts b/frontend/editor/src/core/tools/formFill/useFieldShortcuts.ts
index 2e5dd8420d..7c78444152 100644
--- a/frontend/editor/src/core/tools/formFill/useFieldShortcuts.ts
+++ b/frontend/editor/src/core/tools/formFill/useFieldShortcuts.ts
@@ -9,10 +9,7 @@ import {
pendingIdFrom,
pendingSelectionName,
} from "@app/tools/formFill/pendingSelection";
-import type {
- CreatableFieldType,
- NewFieldDefinition,
-} from "@app/tools/formFill/types";
+import type { NewFieldDefinition } from "@app/tools/formFill/types";
/** Enough offset that the copy is visibly its own field rather than hiding the original. */
const PASTE_OFFSET_PT = 12;
@@ -91,7 +88,7 @@ export function useFieldShortcuts() {
if (!field || !widget) return;
clipboardRef.current = {
name: field.name,
- type: field.type as CreatableFieldType,
+ type: field.type,
pageIndex: widget.pageIndex,
x: widget.x,
y: widget.y,
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/commandRollback.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/commandRollback.test.ts
index c496a8ea05..b541d9df33 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/commandRollback.test.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/commandRollback.test.ts
@@ -27,7 +27,7 @@ function tracked(
if (fail?.revert) throw new Error(`${name} revert blew up`);
log.push(`-${name}`);
},
- } as unknown as Command;
+ };
}
describe("CompositeCommand rollback", () => {
@@ -150,11 +150,10 @@ describe("HistoryStack forward-apply failures", () => {
it("a failed execute does not coalesce the next edit into it", () => {
const h = new HistoryStack();
const log: string[] = [];
- const keyed = (name: string, fail?: boolean): Command =>
- ({
- ...tracked(name, log, fail ? { apply: true } : undefined),
- coalesceKey: () => "same",
- }) as unknown as Command;
+ const keyed = (name: string, fail?: boolean): Command => ({
+ ...tracked(name, log, fail ? { apply: true } : undefined),
+ coalesceKey: () => "same",
+ });
h.execute(keyed("a"), doc);
try {
h.execute(keyed("b", true), doc);
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/editorDirtyState.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/editorDirtyState.test.ts
index 27e1947abc..3fe0da7bbd 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/editorDirtyState.test.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/editorDirtyState.test.ts
@@ -4,7 +4,7 @@ import type { Command } from "@app/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
function makeCmd(type = "test"): Command {
- return { type, apply: vi.fn(), revert: vi.fn() } as unknown as Command;
+ return { type, apply: vi.fn(), revert: vi.fn() };
}
function makeKeyedCmd(key: string): Command {
@@ -13,7 +13,7 @@ function makeKeyedCmd(key: string): Command {
apply: vi.fn(),
revert: vi.fn(),
coalesceKey: () => key,
- } as unknown as Command;
+ };
}
function makeDoc(): EditorDocument {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/externalImageEdit.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/externalImageEdit.test.ts
index c513458477..b61d995b1a 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/externalImageEdit.test.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/externalImageEdit.test.ts
@@ -54,7 +54,7 @@ function fakeHandle() {
bytes.buffer.slice(
bytes.byteOffset,
bytes.byteOffset + bytes.byteLength,
- ) as ArrayBuffer,
+ ),
};
},
};
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/historyFailure.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/historyFailure.test.ts
index 20cb12ec5e..b291a00480 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/historyFailure.test.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/historyFailure.test.ts
@@ -17,7 +17,7 @@ function cmd(opts: { failRevert?: boolean; failApply?: boolean }): Command {
revert: () => {
if (opts.failRevert) throw new Error("revert blew up");
},
- } as unknown as Command;
+ };
}
describe("HistoryStack failure handling", () => {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/spellcheck.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/spellcheck.test.ts
index 302923a436..41bf16b2c6 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/spellcheck.test.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/spellcheck.test.ts
@@ -34,7 +34,7 @@ function throwingStorage(): Storage {
key: boom,
removeItem: boom,
setItem: boom,
- } as unknown as Storage;
+ };
}
beforeEach(() => {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts
index c54b352b1e..1841f3ac76 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts
@@ -10,7 +10,7 @@ function makeCmd(overrides: Partial<Command> = {}): Command {
apply: vi.fn(),
revert: vi.fn(),
...overrides,
- } as unknown as Command;
+ };
}
function makeDoc(): EditorDocument {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/SetColourCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/SetColourCommand.ts
index 8d1e3309d4..f1fab978b8 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/SetColourCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/SetColourCommand.ts
@@ -90,10 +90,7 @@ function readObjFill(
m: import("@embedpdf/pdfium").WrappedPdfiumModule,
objPtr: number,
): RGBA | null {
- const exports = m.pdfium.wasmExports as unknown as {
- malloc: (n: number) => number;
- free: (p: number) => void;
- };
+ const exports = m.pdfium.wasmExports;
const r = exports.malloc(4);
const g = exports.malloc(4);
const b = exports.malloc(4);
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts
index 9c69dc47ed..4a45d23f3b 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts
@@ -175,10 +175,7 @@ function readMemberInk(
} catch {
/* keep the run-level value */
}
- const exports = m.pdfium.wasmExports as unknown as {
- malloc: (n: number) => number;
- free: (p: number) => void;
- };
+ const exports = m.pdfium.wasmExports;
const r = exports.malloc(4);
const g = exports.malloc(4);
const b = exports.malloc(4);
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts
index 7e1cd1b865..dcbca07c3a 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts
@@ -1038,7 +1038,7 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
const ptrs: number[] = [];
let cursor = opts.x;
for (const pc of perChar) {
- const ptr = m2.FPDFPageObj_CreateTextObj!(
+ const ptr = m2.FPDFPageObj_CreateTextObj(
opts.doc.docPtr,
pc.font,
size,
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx
index 3a0167b50d..129cfdd870 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx
@@ -225,9 +225,7 @@ export function PageView({
if (!onPageClick) return;
// Convert from CSS pixel coords (origin upper-left) into PDF
// page-space coords (origin lower-left, points).
- const rect = (
- e.currentTarget as HTMLDivElement
- ).getBoundingClientRect();
+ const rect = e.currentTarget.getBoundingClientRect();
const cssX = e.clientX - rect.left;
const cssY = e.clientY - rect.top;
// CSS px -> display-PDF.
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/TextRunOverlay.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
index ee16ddf884..d83fb45444 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
@@ -774,15 +774,13 @@ export function TextRunOverlay({
// which reads back as a line the user never typed. Seat it in the
// block it sits beside before the input applies.
const sel = window.getSelection();
- if (sel)
- normalizeContainerCaret(e.currentTarget as HTMLDivElement, sel);
+ if (sel) normalizeContainerCaret(e.currentTarget, sel);
}}
onPaste={(e) => {
// Paste as PLAIN TEXT.
e.preventDefault();
const sel = window.getSelection();
- if (sel)
- normalizeContainerCaret(e.currentTarget as HTMLDivElement, sel);
+ if (sel) normalizeContainerCaret(e.currentTarget, sel);
const text = e.clipboardData?.getData("text/plain");
if (text) document.execCommand("insertText", false, text);
}}
@@ -792,11 +790,7 @@ export function TextRunOverlay({
e.stopPropagation();
// Locked runs are inert: no select, no drag, no edit.
if (run.locked) return;
- const zone = edgeZoneAt(
- e.currentTarget as HTMLDivElement,
- e.clientX,
- e.clientY,
- );
+ const zone = edgeZoneAt(e.currentTarget, e.clientX, e.clientY);
// Ctrl+drag still moves from anywhere inside, so existing muscle
// memory keeps working; grabbing the frame is the discoverable path.
@@ -806,7 +800,7 @@ export function TextRunOverlay({
dragOriginRef.current = { x: e.clientX, y: e.clientY };
setDragging(true);
setDragOffset({ x: 0, y: 0 });
- (e.currentTarget as HTMLDivElement).blur();
+ e.currentTarget.blur();
// Pointer events (mouse/pen/touch) with a global capture so the
// drag keeps tracking even if the cursor leaves the overlay.
const onPointerMove = (ev: PointerEvent) => {
@@ -852,14 +846,14 @@ export function TextRunOverlay({
return;
}
pointerFocusRef.current = true;
- (e.currentTarget as HTMLDivElement).focus({ preventScroll: true });
+ e.currentTarget.focus({ preventScroll: true });
onSelect(false);
}}
onFocus={(e) => {
setFocused(true);
setTouched(false);
- setMaskColor(readMaskColor(e.currentTarget as HTMLDivElement));
- const el = e.currentTarget as HTMLDivElement;
+ setMaskColor(readMaskColor(e.currentTarget));
+ const el = e.currentTarget;
// Remember the text at focus so blur can tell if the user edited it.
focusTextRef.current = readOverlayText(el);
const fromPointer = pointerFocusRef.current;
@@ -899,7 +893,7 @@ export function TextRunOverlay({
// left. Once focus is genuinely outside the run, its selection goes
// with it.
{
- const el = e.currentTarget as HTMLDivElement;
+ const el = e.currentTarget;
const sel = window.getSelection();
if (
sel &&
@@ -913,7 +907,7 @@ export function TextRunOverlay({
// Wrap mode: when the just-edited content overflows the locked box
// width.
if (!wantWrap || !onWrap) return;
- const el = e.currentTarget as HTMLDivElement;
+ const el = e.currentTarget;
const domText = readOverlayText(el);
if (domText === focusTextRef.current) return; // not edited
const widest = measureMaxLineWidth(domText, font);
@@ -942,7 +936,7 @@ export function TextRunOverlay({
onCompositionEnd={(e) => {
composingRef.current = false;
// Commit the composed string once, like onInput's non-IME path.
- const el = e.currentTarget as HTMLDivElement;
+ const el = e.currentTarget;
onEdit(readOverlayText(el).replace(/\u00A0/g, " "));
}}
onInput={(e) => {
@@ -950,9 +944,8 @@ export function TextRunOverlay({
setEditTick((n) => n + 1);
editedAtRevisionRef.current = pageRevision ?? -1;
// Skip intermediate IME steps; compositionend commits the result.
- if (composingRef.current || (e.nativeEvent as InputEvent).isComposing)
- return;
- const el = e.currentTarget as HTMLDivElement;
+ if (composingRef.current || e.nativeEvent.isComposing) return;
+ const el = e.currentTarget;
// Re-fit the token the user just typed into. Its painted width is the
// PDF's advance for the ORIGINAL string, so leaving it alone lays the
// new text out at the browser's own advances and the caret drifts off
@@ -974,9 +967,7 @@ export function TextRunOverlay({
onPointerMove={(e) => {
// Only while idle: mid-drag the cursor is owned by the gesture.
if (run.locked || dragging) return;
- setEdgeZone(
- edgeZoneAt(e.currentTarget as HTMLDivElement, e.clientX, e.clientY),
- );
+ setEdgeZone(edgeZoneAt(e.currentTarget, e.clientX, e.clientY));
}}
style={{
left,
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/model/DisplayTransform.ts b/frontend/editor/src/core/tools/pdfTextEditor/model/DisplayTransform.ts
index 1435cb0b12..63b573f701 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/model/DisplayTransform.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/model/DisplayTransform.ts
@@ -322,10 +322,7 @@ function readBox(
mod: CropBoxModule,
pagePtr: number,
): PageBox | null {
- const exports = m.pdfium.wasmExports as unknown as {
- malloc: (n: number) => number;
- free: (p: number) => void;
- };
+ const exports = m.pdfium.wasmExports;
const buf = exports.malloc(16);
if (!buf) return null;
try {
diff --git a/frontend/editor/src/core/types/fileContext.ts b/frontend/editor/src/core/types/fileContext.ts
index 262a69cbb4..371d25a3fa 100644
--- a/frontend/editor/src/core/types/fileContext.ts
+++ b/frontend/editor/src/core/types/fileContext.ts
@@ -225,7 +225,7 @@ export function extractFileIds(files: StirlingFile[]): FileId[] {
// Extract regular File objects from StirlingFile array
export function extractFiles(files: StirlingFile[]): File[] {
- return files as File[];
+ return files;
}
// Check if an object is a File or StirlingFile (replaces instanceof File checks)
diff --git a/frontend/editor/src/core/types/folder.ts b/frontend/editor/src/core/types/folder.ts
index 5ac464ed6f..bcc5c457ab 100644
--- a/frontend/editor/src/core/types/folder.ts
+++ b/frontend/editor/src/core/types/folder.ts
@@ -141,5 +141,5 @@ export function pickFolderColor(seed: string): FolderPaletteColor {
hash = (hash * 31 + seed.charCodeAt(i)) | 0;
}
const idx = Math.abs(hash) % FOLDER_COLOR_PALETTE.length;
- return FOLDER_COLOR_PALETTE[idx]!;
+ return FOLDER_COLOR_PALETTE[idx];
}
diff --git a/frontend/editor/src/core/utils/duplicateFile.test.ts b/frontend/editor/src/core/utils/duplicateFile.test.ts
index 88c7cce686..c8d1ccc6b8 100644
--- a/frontend/editor/src/core/utils/duplicateFile.test.ts
+++ b/frontend/editor/src/core/utils/duplicateFile.test.ts
@@ -36,7 +36,7 @@ const asStirlingFile = (name: string): StirlingFile =>
Object.assign(new File(["%PDF-1.7"], name, { type: "application/pdf" }), {
fileId: "new-id" as FileId,
quickKey: "k",
- }) as StirlingFile;
+ });
type AddFilesOptions = {
selectFiles?: boolean;
diff --git a/frontend/editor/src/core/utils/fileHistoryUtils.ts b/frontend/editor/src/core/utils/fileHistoryUtils.ts
index 9bf9215de8..af01b794e6 100644
--- a/frontend/editor/src/core/utils/fileHistoryUtils.ts
+++ b/frontend/editor/src/core/utils/fileHistoryUtils.ts
@@ -63,7 +63,7 @@ export function groupFilesByOriginal(
}
// Check for infinite loops before moving to next
- if (nextFile && lineagePath.some((file) => file.id === nextFile!.id)) {
+ if (nextFile && lineagePath.some((file) => file.id === nextFile.id)) {
break;
}
diff --git a/frontend/editor/src/core/utils/getDropzoneFiles.ts b/frontend/editor/src/core/utils/getDropzoneFiles.ts
index 5137d4f294..1ed8a6e1bd 100644
--- a/frontend/editor/src/core/utils/getDropzoneFiles.ts
+++ b/frontend/editor/src/core/utils/getDropzoneFiles.ts
@@ -84,7 +84,7 @@ export async function getDropzoneFiles(
}
if ("target" in event && event.target && "files" in event.target) {
- return Array.from((event.target as HTMLInputElement).files ?? []);
+ return Array.from(event.target.files ?? []);
}
return [];
}
diff --git a/frontend/editor/src/core/utils/homePageNavigation.test.ts b/frontend/editor/src/core/utils/homePageNavigation.test.ts
index 862e48c3ae..1d0a14364f 100644
--- a/frontend/editor/src/core/utils/homePageNavigation.test.ts
+++ b/frontend/editor/src/core/utils/homePageNavigation.test.ts
@@ -1,143 +1,85 @@
import { describe, expect, it } from "vitest";
import { getStartupNavigationAction } from "@app/utils/homePageNavigation";
-import type { WorkbenchType } from "@app/types/workbench";
describe("getStartupNavigationAction", () => {
it("returns viewer + active index for 0->1 transition when not in fileEditor", () => {
- expect(
- getStartupNavigationAction(0, 1, null, "viewer" as WorkbenchType),
- ).toEqual({
+ expect(getStartupNavigationAction(0, 1, null, "viewer")).toEqual({
workbench: "viewer",
activeFileIndex: 0,
});
- expect(
- getStartupNavigationAction(0, 1, null, "pageEditor" as WorkbenchType),
- ).toEqual({
+ expect(getStartupNavigationAction(0, 1, null, "pageEditor")).toEqual({
workbench: "viewer",
activeFileIndex: 0,
});
});
it("returns fileEditor for 0->2+ transition when not in fileEditor", () => {
- expect(
- getStartupNavigationAction(0, 2, null, "viewer" as WorkbenchType),
- ).toEqual({
+ expect(getStartupNavigationAction(0, 2, null, "viewer")).toEqual({
workbench: "fileEditor",
});
});
it("does not force navigation for pdfTextEditor or multiTool", () => {
expect(
- getStartupNavigationAction(
- 0,
- 1,
- "pdfTextEditor",
- "viewer" as WorkbenchType,
- ),
+ getStartupNavigationAction(0, 1, "pdfTextEditor", "viewer"),
).toBeNull();
expect(
- getStartupNavigationAction(
- 0,
- 3,
- "pdfTextEditor",
- "viewer" as WorkbenchType,
- ),
+ getStartupNavigationAction(0, 3, "pdfTextEditor", "viewer"),
).toBeNull();
expect(
- getStartupNavigationAction(
- 0,
- 1,
- "multiTool",
- "pageEditor" as WorkbenchType,
- ),
+ getStartupNavigationAction(0, 1, "multiTool", "pageEditor"),
).toBeNull();
expect(
- getStartupNavigationAction(
- 0,
- 3,
- "multiTool",
- "pageEditor" as WorkbenchType,
- ),
+ getStartupNavigationAction(0, 3, "multiTool", "pageEditor"),
).toBeNull();
});
it("does not navigate when file count decreases", () => {
- expect(
- getStartupNavigationAction(2, 1, null, "viewer" as WorkbenchType),
- ).toBeNull();
- expect(
- getStartupNavigationAction(3, 1, null, "fileEditor" as WorkbenchType),
- ).toBeNull();
+ expect(getStartupNavigationAction(2, 1, null, "viewer")).toBeNull();
+ expect(getStartupNavigationAction(3, 1, null, "fileEditor")).toBeNull();
});
it("navigates to last file when already in viewer and files are added", () => {
- expect(
- getStartupNavigationAction(1, 2, null, "viewer" as WorkbenchType),
- ).toEqual({
+ expect(getStartupNavigationAction(1, 2, null, "viewer")).toEqual({
workbench: "viewer",
activeFileIndex: 1,
});
- expect(
- getStartupNavigationAction(3, 5, null, "viewer" as WorkbenchType),
- ).toEqual({
+ expect(getStartupNavigationAction(3, 5, null, "viewer")).toEqual({
workbench: "viewer",
activeFileIndex: 4,
});
});
it("does not navigate when adding files in non-viewer workbenches", () => {
- expect(
- getStartupNavigationAction(1, 2, null, "fileEditor" as WorkbenchType),
- ).toBeNull();
- expect(
- getStartupNavigationAction(3, 4, null, "fileEditor" as WorkbenchType),
- ).toBeNull();
- expect(
- getStartupNavigationAction(1, 3, null, "pageEditor" as WorkbenchType),
- ).toBeNull();
+ expect(getStartupNavigationAction(1, 2, null, "fileEditor")).toBeNull();
+ expect(getStartupNavigationAction(3, 4, null, "fileEditor")).toBeNull();
+ expect(getStartupNavigationAction(1, 3, null, "pageEditor")).toBeNull();
});
it("handles all workbench types consistently for 0→N transitions", () => {
// 0→1 always goes to viewer regardless of current workbench (since default is viewer)
- expect(
- getStartupNavigationAction(0, 1, null, "viewer" as WorkbenchType),
- ).toEqual({
+ expect(getStartupNavigationAction(0, 1, null, "viewer")).toEqual({
workbench: "viewer",
activeFileIndex: 0,
});
- expect(
- getStartupNavigationAction(0, 1, null, "fileEditor" as WorkbenchType),
- ).toEqual({
+ expect(getStartupNavigationAction(0, 1, null, "fileEditor")).toEqual({
workbench: "viewer",
activeFileIndex: 0,
});
- expect(
- getStartupNavigationAction(0, 1, null, "pageEditor" as WorkbenchType),
- ).toEqual({
+ expect(getStartupNavigationAction(0, 1, null, "pageEditor")).toEqual({
workbench: "viewer",
activeFileIndex: 0,
});
- expect(
- getStartupNavigationAction(
- 0,
- 1,
- null,
- "custom:formFill" as WorkbenchType,
- ),
- ).toEqual({
+ expect(getStartupNavigationAction(0, 1, null, "custom:formFill")).toEqual({
workbench: "viewer",
activeFileIndex: 0,
});
// 0→N (N>1) always goes to fileEditor
- expect(
- getStartupNavigationAction(0, 3, null, "viewer" as WorkbenchType),
- ).toEqual({
+ expect(getStartupNavigationAction(0, 3, null, "viewer")).toEqual({
workbench: "fileEditor",
});
- expect(
- getStartupNavigationAction(0, 3, null, "custom:myTool" as WorkbenchType),
- ).toEqual({
+ expect(getStartupNavigationAction(0, 3, null, "custom:myTool")).toEqual({
workbench: "fileEditor",
});
});
diff --git a/frontend/editor/src/core/utils/measurementUtils.ts b/frontend/editor/src/core/utils/measurementUtils.ts
index e35645fb2b..d73785d191 100644
--- a/frontend/editor/src/core/utils/measurementUtils.ts
+++ b/frontend/editor/src/core/utils/measurementUtils.ts
@@ -296,8 +296,8 @@ export function validateMeasurement(obj: unknown): obj is Measurement {
}
// Reject cross-page measurements
- const start = m.start as PagePoint;
- const end = m.end as PagePoint;
+ const start = m.start;
+ const end = m.end;
if (start.pageIndex !== end.pageIndex) {
return false;
}
diff --git a/frontend/editor/src/core/utils/patchDomForTranslators.ts b/frontend/editor/src/core/utils/patchDomForTranslators.ts
index 7efa285935..b3f9f539aa 100644
--- a/frontend/editor/src/core/utils/patchDomForTranslators.ts
+++ b/frontend/editor/src/core/utils/patchDomForTranslators.ts
@@ -41,7 +41,7 @@ function applyDomPatch(trigger: string): void {
): T {
if (child.parentNode !== this) return child;
return originalRemoveChild.call(this, child) as T;
- } as typeof Node.prototype.removeChild;
+ };
const originalInsertBefore = Node.prototype.insertBefore;
Node.prototype.insertBefore = function patchedInsertBefore<T extends Node>(
@@ -51,7 +51,7 @@ function applyDomPatch(trigger: string): void {
): T {
if (referenceNode && referenceNode.parentNode !== this) return newNode;
return originalInsertBefore.call(this, newNode, referenceNode) as T;
- } as typeof Node.prototype.insertBefore;
+ };
}
export function armTranslatorDetector(): void {
diff --git a/frontend/editor/src/core/utils/settingsPendingHelper.ts b/frontend/editor/src/core/utils/settingsPendingHelper.ts
index 26c4ed2a5c..c9e2444f16 100644
--- a/frontend/editor/src/core/utils/settingsPendingHelper.ts
+++ b/frontend/editor/src/core/utils/settingsPendingHelper.ts
@@ -29,7 +29,7 @@ export function mergePendingSettings<T extends SettingsWithPending>(
if (!settings || !settings._pending) {
// No pending changes, return as-is (without _pending property)
const { _pending, ...rest } = settings || {};
- return rest as Omit<T, "_pending">;
+ return rest;
}
// Deep merge pending changes
diff --git a/frontend/editor/src/core/utils/signatureFlattening.ts b/frontend/editor/src/core/utils/signatureFlattening.ts
index ec24ffb3cb..6c79fc3461 100644
--- a/frontend/editor/src/core/utils/signatureFlattening.ts
+++ b/frontend/editor/src/core/utils/signatureFlattening.ts
@@ -174,10 +174,7 @@ export async function flattenSignatures(
const fileStub = selectors.getStirlingFileStub(allFileIds[fileIndex]);
const fileObject = selectors.getFile(allFileIds[fileIndex]);
if (fileStub && fileObject) {
- currentFile = createStirlingFile(
- fileObject,
- allFileIds[fileIndex] as FileId,
- );
+ currentFile = createStirlingFile(fileObject, allFileIds[fileIndex]);
}
}
}
@@ -202,7 +199,7 @@ export async function flattenSignatures(
allAnnotations,
getImageData,
);
- signedFile = new File([resultBytes as BlobPart], currentFile.name, {
+ signedFile = new File([resultBytes], currentFile.name, {
type: "application/pdf",
});
} catch (renderError) {
diff --git a/frontend/editor/src/core/utils/toolOperationLabel.test.ts b/frontend/editor/src/core/utils/toolOperationLabel.test.ts
index 9b21f6e65f..8183fa9cc1 100644
--- a/frontend/editor/src/core/utils/toolOperationLabel.test.ts
+++ b/frontend/editor/src/core/utils/toolOperationLabel.test.ts
@@ -7,8 +7,11 @@ import type { ToolOperation } from "@app/types/file";
const t = ((key: string, fallback?: string) =>
key === "home.automate.title" ? "Automate" : (fallback ?? key)) as TFunction;
-const op = (over: Partial<ToolOperation>): ToolOperation =>
- ({ toolId: "automate", timestamp: 0, ...over }) as ToolOperation;
+const op = (over: Partial<ToolOperation>): ToolOperation => ({
+ toolId: "automate",
+ timestamp: 0,
+ ...over,
+});
describe("toolOperationLabel", () => {
it("prefers the operation's own label", () => {
diff --git a/frontend/editor/src/core/utils/toolResponseProcessor.ts b/frontend/editor/src/core/utils/toolResponseProcessor.ts
index 0b569215bc..97f40fb48a 100644
--- a/frontend/editor/src/core/utils/toolResponseProcessor.ts
+++ b/frontend/editor/src/core/utils/toolResponseProcessor.ts
@@ -22,7 +22,7 @@ export async function processResponse(
): Promise<File[]> {
if (responseHandler) {
const out = await responseHandler(blob, originalFiles);
- return Array.isArray(out) ? out : [out as unknown as File];
+ return Array.isArray(out) ? out : [out];
}
// Check if we should use the backend-provided filename from headers
diff --git a/frontend/editor/src/core/utils/toolSearch.ts b/frontend/editor/src/core/utils/toolSearch.ts
index 1a543974a3..34857e132c 100644
--- a/frontend/editor/src/core/utils/toolSearch.ts
+++ b/frontend/editor/src/core/utils/toolSearch.ts
@@ -119,10 +119,10 @@ export function filterToolRegistryByQuery(
ordered.push({ item: [id, tool], matchedText });
};
- for (const { id, tool } of exactName) push(id as ToolId, tool, tool.name);
- for (const { id, tool, text } of exactSyn) push(id as ToolId, tool, text);
- for (const { id, tool, text } of fuzzyName) push(id as ToolId, tool, text);
- for (const { id, tool, text } of fuzzySyn) push(id as ToolId, tool, text);
+ for (const { id, tool } of exactName) push(id, tool, tool.name);
+ for (const { id, tool, text } of exactSyn) push(id, tool, text);
+ for (const { id, tool, text } of fuzzyName) push(id, tool, text);
+ for (const { id, tool, text } of fuzzySyn) push(id, tool, text);
if (ordered.length > 0) return ordered;
diff --git a/frontend/editor/src/core/utils/toolSynonyms.ts b/frontend/editor/src/core/utils/toolSynonyms.ts
index fbfd2afca3..04ca47ae08 100644
--- a/frontend/editor/src/core/utils/toolSynonyms.ts
+++ b/frontend/editor/src/core/utils/toolSynonyms.ts
@@ -5,7 +5,7 @@ export const getSynonyms = (t: TFunction, toolId: string): string[] => {
try {
const candidateKeys = [`home.${toolId}.tags`, `${toolId}.tags`];
const tags = candidateKeys
- .map((key) => ({ key, value: t(key) as unknown as string }))
+ .map((key) => ({ key, value: t(key) }))
.find(({ key, value }) => value && value !== key)?.value;
if (!tags) return [];
diff --git a/frontend/editor/src/desktop/contexts/file/diskResyncFanOut.test.ts b/frontend/editor/src/desktop/contexts/file/diskResyncFanOut.test.ts
index 47d4c0a09f..ca74b3460f 100644
--- a/frontend/editor/src/desktop/contexts/file/diskResyncFanOut.test.ts
+++ b/frontend/editor/src/desktop/contexts/file/diskResyncFanOut.test.ts
@@ -39,13 +39,13 @@ function stub(id: string, path?: string): StirlingFileStub {
createdAt: 1,
quickKey: `report.pdf|1|${id}`,
versionNumber: 1,
- originalFileId: id as FileId,
+ originalFileId: id,
toolHistory: [],
isLeaf: true,
localFilePath: path,
diskSyncedSize: 1,
diskSyncedModifiedMs: 1,
- } as StirlingFileStub;
+ };
}
function harness(stubs: StirlingFileStub[]) {
@@ -69,7 +69,7 @@ function harness(stubs: StirlingFileStub[]) {
run: (paths: string[]) =>
reconcileOpenFilesAt(
paths,
- stateRef as never,
+ stateRef,
{ current: new Map<FileId, File>() },
lifecycleManager as never,
),
diff --git a/frontend/editor/src/desktop/contexts/file/diskVersionHistoryHydration.test.ts b/frontend/editor/src/desktop/contexts/file/diskVersionHistoryHydration.test.ts
index 68c179fc3b..0886d3673e 100644
--- a/frontend/editor/src/desktop/contexts/file/diskVersionHistoryHydration.test.ts
+++ b/frontend/editor/src/desktop/contexts/file/diskVersionHistoryHydration.test.ts
@@ -38,21 +38,20 @@ const PATH = "C:/docs/report.pdf";
const V1_BYTES = "%PDF-v1";
const SAVED_CHILD_BYTES = "%PDF-v2-on-disk";
-const versionStub = (isLeaf: boolean): StirlingFileStub =>
- ({
- id: "v1" as FileId,
- name: "report.pdf",
- type: "application/pdf",
- size: V1_BYTES.length,
- lastModified: 1_000,
- isLeaf,
- originalFileId: "v1",
- versionNumber: 1,
- localFilePath: PATH,
- // Stamped when v1 was the live file, so it predates the child's write.
- diskSyncedSize: V1_BYTES.length,
- diskSyncedModifiedMs: 1_000,
- }) as StirlingFileStub;
+const versionStub = (isLeaf: boolean): StirlingFileStub => ({
+ id: "v1" as FileId,
+ name: "report.pdf",
+ type: "application/pdf",
+ size: V1_BYTES.length,
+ lastModified: 1_000,
+ isLeaf,
+ originalFileId: "v1",
+ versionNumber: 1,
+ localFilePath: PATH,
+ // Stamped when v1 was the live file, so it predates the child's write.
+ diskSyncedSize: V1_BYTES.length,
+ diskSyncedModifiedMs: 1_000,
+});
beforeEach(() => {
vi.clearAllMocks();
diff --git a/frontend/editor/src/desktop/services/diskFileSync.test.ts b/frontend/editor/src/desktop/services/diskFileSync.test.ts
index 2fd9efdb1d..4fdd4efb35 100644
--- a/frontend/editor/src/desktop/services/diskFileSync.test.ts
+++ b/frontend/editor/src/desktop/services/diskFileSync.test.ts
@@ -1,27 +1,19 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { StirlingFileStub } from "@app/types/fileContext";
import type { FileId } from "@app/types/file";
+import type { DiskFileState } from "@app/services/desktopFileLink";
// The seam is a module-level const, so each behaviour is exercised by re-importing
// the module under a fresh mock rather than by mutating a flag.
-const diskState = vi.hoisted(
- () =>
- ({
- supported: true,
- state: { availability: "present", size: 100, modifiedMs: 5000 },
- bytes: new Uint8Array([1, 2, 3]).buffer as ArrayBuffer | null,
- }) as {
- supported: boolean;
- state:
- | { availability: "present"; size: number; modifiedMs: number }
- | { availability: "gone" }
- | {
- availability: "unavailable";
- reason: "permission" | "offline" | "unknown";
- };
- bytes: ArrayBuffer | null;
- },
-);
+const diskState = vi.hoisted<{
+ supported: boolean;
+ state: DiskFileState;
+ bytes: ArrayBuffer | null;
+}>(() => ({
+ supported: true,
+ state: { availability: "present", size: 100, modifiedMs: 5000 },
+ bytes: new Uint8Array([1, 2, 3]).buffer,
+}));
vi.mock("@app/services/desktopFileLink", () => ({
get desktopFileLinkingSupported() {
@@ -86,7 +78,7 @@ function stub(overrides: Partial<StirlingFileStub> = {}): StirlingFileStub {
diskSyncedSize: 100,
diskSyncedModifiedMs: 5000,
...overrides,
- } as StirlingFileStub;
+ };
}
beforeEach(() => {
diff --git a/frontend/editor/src/desktop/services/localProcessingFolders.test.ts b/frontend/editor/src/desktop/services/localProcessingFolders.test.ts
index 2e72d5b3d7..c84d0fd08a 100644
--- a/frontend/editor/src/desktop/services/localProcessingFolders.test.ts
+++ b/frontend/editor/src/desktop/services/localProcessingFolders.test.ts
@@ -17,7 +17,7 @@ const mocks = vi.hoisted(() => ({
name: "a.pdf",
sizeBytes: 10,
lastModified: 1,
- } as DiskFileEntry,
+ },
submit: vi.fn(),
wait: vi.fn(),
download: vi.fn(),
diff --git a/frontend/editor/src/desktop/services/pruneMissingRecentFiles.test.ts b/frontend/editor/src/desktop/services/pruneMissingRecentFiles.test.ts
index 7396295dff..134e38a4d9 100644
--- a/frontend/editor/src/desktop/services/pruneMissingRecentFiles.test.ts
+++ b/frontend/editor/src/desktop/services/pruneMissingRecentFiles.test.ts
@@ -1,7 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { StirlingFileStub } from "@app/types/fileContext";
import type { FileId } from "@app/types/file";
-import type { ToolId } from "@app/types/toolId";
const disk = vi.hoisted(() => ({
supported: true,
@@ -47,7 +46,7 @@ function stub(overrides: Partial<StirlingFileStub> = {}): StirlingFileStub {
versionNumber: 1,
toolHistory: [],
...overrides,
- } as StirlingFileStub;
+ };
}
beforeEach(() => {
@@ -96,7 +95,7 @@ describe("pruneMissingRecentFiles", () => {
id: "edited" as FileId,
localFilePath: "C:/docs/gone.pdf",
versionNumber: 3,
- toolHistory: [{ toolId: "split" as ToolId, timestamp: 1 }],
+ toolHistory: [{ toolId: "split", timestamp: 1 }],
}),
];
const result = await pruneMissingRecentFiles(stubs);
diff --git a/frontend/editor/src/portal-saas/hooks/useFleetStatsAccess.test.ts b/frontend/editor/src/portal-saas/hooks/useFleetStatsAccess.test.ts
index de69ed041a..c93d34019f 100644
--- a/frontend/editor/src/portal-saas/hooks/useFleetStatsAccess.test.ts
+++ b/frontend/editor/src/portal-saas/hooks/useFleetStatsAccess.test.ts
@@ -2,12 +2,20 @@ import { renderHook } from "@testing-library/react";
import { beforeEach, expect, it, vi } from "vitest";
import { useFleetStatsAccess } from "@portal/hooks/useFleetStatsAccess";
-const state = vi.hoisted(() => ({
+const state = vi.hoisted<{
+ auth: {
+ loading: boolean;
+ error: Error | null;
+ session: object | null;
+ user: { id: string } | null;
+ isAnonymous: boolean;
+ };
+}>(() => ({
auth: {
loading: false,
- error: null as Error | null,
- session: {} as object | null,
- user: { id: "member" } as { id: string } | null,
+ error: null,
+ session: {},
+ user: { id: "member" },
isAnonymous: false,
},
}));
diff --git a/frontend/editor/src/portal/api/policies.ts b/frontend/editor/src/portal/api/policies.ts
index 5a9729b885..754d8beb38 100644
--- a/frontend/editor/src/portal/api/policies.ts
+++ b/frontend/editor/src/portal/api/policies.ts
@@ -19,12 +19,7 @@ import {
} from "@app/policies/operations";
import { HttpError } from "@portal/api/http";
import type { Policy } from "@portal/api/pipelines";
-import type {
- PolicyRunView,
- WireOutputOptions,
- WirePipelineStep,
- WirePolicy,
-} from "@app/policies/types";
+import type { PolicyRunView, WirePolicy } from "@app/policies/types";
export type { PolicyRunView, WirePolicy } from "@app/policies/types";
@@ -123,7 +118,7 @@ export function parseSimplePolicy(
const canonical = config.defaultOperations.map((op) => op.toolId);
const toolIds: PolicyToolId[] = [];
for (const step of policy.steps) {
- const parsed = policyStepFromWire(step as WirePipelineStep);
+ const parsed = policyStepFromWire(step);
if (!parsed || !canonical.includes(parsed.toolId)) return null;
toolIds.push(parsed.toolId);
}
@@ -138,11 +133,11 @@ export function parseSimplePolicy(
inputs: policy.inputs ?? [],
outputIds: policy.outputIds ?? [],
routingRules: policy.routingRules ?? [],
- steps: policy.steps as WirePipelineStep[],
+ steps: policy.steps,
// The options bag is untyped on the pipeline record; the codec reads it defensively.
output: {
type: "inline",
- options: (policy.output?.options ?? {}) as Partial<WireOutputOptions>,
+ options: policy.output?.options ?? {},
},
editor: policy.editor,
};
diff --git a/frontend/editor/src/portal/components/failures/failureActionCells.ts b/frontend/editor/src/portal/components/failures/failureActionCells.ts
index 15ee890143..ffe45a312d 100644
--- a/frontend/editor/src/portal/components/failures/failureActionCells.ts
+++ b/frontend/editor/src/portal/components/failures/failureActionCells.ts
@@ -83,7 +83,7 @@ export function buildFailureActionCells({
});
}
if (diagnostics.length > 0) {
- diagnostics[0]!.dividerBefore = menu.length > 0;
+ diagnostics[0].dividerBefore = menu.length > 0;
menu.push(...diagnostics);
}
diff --git a/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsx b/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsx
index bd4ca4a9df..4c11317640 100644
--- a/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsx
+++ b/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsx
@@ -15,10 +15,7 @@ import {
import { PolicyExternalApiConfig } from "@portal/components/policies/PolicyExternalApiConfig";
import { isIntegrationStep } from "@portal/components/pipelines/integrationStep";
-import {
- isIngestStep,
- type IngestStepParams,
-} from "@portal/components/pipelines/docparseStep";
+import { isIngestStep } from "@portal/components/pipelines/docparseStep";
import { IngestStepConfig } from "@portal/components/pipelines/IngestStepConfig";
import type { ExternalApiStepParams } from "@portal/components/policies/stepOperations";
import "@portal/components/pipelines/PipelineStepSettings.css";
@@ -105,7 +102,7 @@ export function PipelineStepSettings({
return (
<IngestStepConfig
editorInput={editorInput}
- parameters={step.params as unknown as IngestStepParams}
+ parameters={step.params}
onChange={(params) => onChange(params as never)}
/>
);
diff --git a/frontend/editor/src/portal/components/users/UsersDirectory.tsx b/frontend/editor/src/portal/components/users/UsersDirectory.tsx
index 639ec9b5f7..222fac7247 100644
--- a/frontend/editor/src/portal/components/users/UsersDirectory.tsx
+++ b/frontend/editor/src/portal/components/users/UsersDirectory.tsx
@@ -89,27 +89,20 @@ export function UsersDirectory({
showGuests = false,
}: UsersDirectoryProps) {
const { t } = useTranslation();
- const roleOptions = useMemo(
- () => [
- ...(capabilities.adminRole
- ? [
- {
- value: "admin" as RoleId,
- label: t("users.role.admin", "Admin"),
- },
- ]
- : []),
- {
- value: "team_owner" as RoleId,
- label: t("users.role.teamOwner", "Team Lead"),
- },
- { value: "member" as RoleId, label: t("users.role.member", "Member") },
- ...(showGuests
- ? [{ value: "guest" as RoleId, label: t("users.role.guest", "Guest") }]
- : []),
- ],
- [capabilities.adminRole, showGuests, t],
- );
+ const roleOptions = useMemo(() => {
+ const options: { value: RoleId; label: string }[] = [];
+ if (capabilities.adminRole) {
+ options.push({ value: "admin", label: t("users.role.admin", "Admin") });
+ }
+ options.push(
+ { value: "team_owner", label: t("users.role.teamOwner", "Team Lead") },
+ { value: "member", label: t("users.role.member", "Member") },
+ );
+ if (showGuests) {
+ options.push({ value: "guest", label: t("users.role.guest", "Guest") });
+ }
+ return options;
+ }, [capabilities.adminRole, showGuests, t]);
// The one structural filter, replacing per-team sections: at a hundred people
// those were ten headings to scroll past, not a shape.
diff --git a/frontend/editor/src/portal/hooks/useAccountLinkOwner.test.ts b/frontend/editor/src/portal/hooks/useAccountLinkOwner.test.ts
index a35cc054be..def60eef89 100644
--- a/frontend/editor/src/portal/hooks/useAccountLinkOwner.test.ts
+++ b/frontend/editor/src/portal/hooks/useAccountLinkOwner.test.ts
@@ -1,11 +1,12 @@
import { renderHook } from "@testing-library/react";
import { beforeEach, expect, it, vi } from "vitest";
+import type { AuthContextValue, AuthUser } from "@app/auth";
-const auth = vi.hoisted(() => ({
- isAdmin: true,
- loading: false,
- user: { orgOwner: true as boolean | undefined },
-}));
+const auth = vi.hoisted<
+ Pick<AuthContextValue, "isAdmin" | "loading"> & {
+ user: Pick<AuthUser, "orgOwner">;
+ }
+>(() => ({ isAdmin: true, loading: false, user: { orgOwner: true } }));
vi.mock("@app/auth", () => ({ useAuth: () => auth }));
import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";
diff --git a/frontend/editor/src/portal/queries/fleetStats.test.tsx b/frontend/editor/src/portal/queries/fleetStats.test.tsx
index 682a5c0f22..bde7450695 100644
--- a/frontend/editor/src/portal/queries/fleetStats.test.tsx
+++ b/frontend/editor/src/portal/queries/fleetStats.test.tsx
@@ -1,16 +1,26 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";
import { useFleetStats } from "@portal/queries/infrastructure";
import { fetchFleetStats } from "@portal/api/fleetStats";
-const state = vi.hoisted(() => ({
+const state = vi.hoisted<{
+ auth: {
+ loading: boolean;
+ error: Error | null;
+ session: object | null;
+ user: { id: string } | null;
+ isAnonymous: boolean;
+ isAdmin: boolean;
+ };
+ json: Mock;
+}>(() => ({
auth: {
loading: false,
- error: null as Error | null,
- session: {} as object | null,
- user: { id: "admin" } as { id: string } | null,
+ error: null,
+ session: {},
+ user: { id: "admin" },
isAdmin: true,
isAnonymous: false,
},
diff --git a/frontend/editor/src/portal/views/ConnectCallback.test.tsx b/frontend/editor/src/portal/views/ConnectCallback.test.tsx
index 272ea30f1e..0182a48f28 100644
--- a/frontend/editor/src/portal/views/ConnectCallback.test.tsx
+++ b/frontend/editor/src/portal/views/ConnectCallback.test.tsx
@@ -338,7 +338,7 @@ describe("account-link callback", () => {
await waitFor(() => expect(lastOutcome()?.state).toBe("retry"));
await act(async () => {
- await lastOutcome()!.reclaim!();
+ await lastOutcome().reclaim!();
});
// Re-claims rather than opening a new handshake, which would spend a leader's approval.
@@ -409,7 +409,7 @@ describe("account-link callback", () => {
renderFlow();
await waitFor(() => expect(lastOutcome()?.state).toBe("retry"));
await act(async () => {
- await lastOutcome()!.reclaim!();
+ await lastOutcome().reclaim!();
});
await waitFor(() => expect(lastOutcome()?.sessionRestored).toBe(true));
expect(completeConnect).toHaveBeenCalledTimes(1);
diff --git a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx b/frontend/editor/src/portal/views/PipelineBuilder.test.tsx
index ad71473627..c17e29bb54 100644
--- a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx
+++ b/frontend/editor/src/portal/views/PipelineBuilder.test.tsx
@@ -1176,7 +1176,7 @@ describe("PipelineBuilder", () => {
steps: [
{ operation: "/api/v1/misc/compress-pdf", parameters: {} },
{ operation: "/api/v1/misc/extract-images", parameters: {} },
- ] as unknown as Policy["steps"],
+ ],
};
}
diff --git a/frontend/editor/src/portal/views/Review.stories.tsx b/frontend/editor/src/portal/views/Review.stories.tsx
index b6769c003c..ed4b4f9d76 100644
--- a/frontend/editor/src/portal/views/Review.stories.tsx
+++ b/frontend/editor/src/portal/views/Review.stories.tsx
@@ -38,7 +38,7 @@ export const ViewingError: Story = {
play: async ({ canvas, userEvent }) => {
await canvas.findAllByText("Password-protected document");
await userEvent.click(
- (await canvas.findAllByRole("button", { name: "More options" }))[0]!,
+ (await canvas.findAllByRole("button", { name: "More options" }))[0],
);
await userEvent.click(
await screen.findByRole("menuitem", { name: "View error" }),
diff --git a/frontend/editor/src/proprietary/auth/configureSpringAuth.ts b/frontend/editor/src/proprietary/auth/configureSpringAuth.ts
index b480d0ab41..9a1b65d9a1 100644
--- a/frontend/editor/src/proprietary/auth/configureSpringAuth.ts
+++ b/frontend/editor/src/proprietary/auth/configureSpringAuth.ts
@@ -29,6 +29,7 @@ configureSpringAuth({
// which is API-compatible with axios but not nominally an AxiosInstance -
// matches the existing `as unknown as AxiosInstance` bridge in
// desktop/services/apiClient.ts. Harmless no-op for the web (axios) build.
+ // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- apiClient is not an AxiosInstance in the desktop build
http: apiClient as unknown as AxiosInstance,
basePath: BASE_PATH,
platform: {
diff --git a/frontend/editor/src/proprietary/billing/ComparePlansModal.test.tsx b/frontend/editor/src/proprietary/billing/ComparePlansModal.test.tsx
index 0601a5b16c..43cc2f7aa3 100644
--- a/frontend/editor/src/proprietary/billing/ComparePlansModal.test.tsx
+++ b/frontend/editor/src/proprietary/billing/ComparePlansModal.test.tsx
@@ -43,7 +43,7 @@ it("quotes the figures it was given rather than a fixed number", () => {
it.each([null, 0])(
"describes the allowance in words when the host reports %s",
(allowance) => {
- open({ freeUserLimit: null, freeAllowance: allowance as number | null });
+ open({ freeUserLimit: null, freeAllowance: allowance });
expect(screen.getByText("A monthly credit allowance")).toBeInTheDocument();
expect(screen.getByText("A small team")).toBeInTheDocument();
},
diff --git a/frontend/editor/src/proprietary/components/policies/classificationLocalPass.ts b/frontend/editor/src/proprietary/components/policies/classificationLocalPass.ts
index 127e758662..702b9f5799 100644
--- a/frontend/editor/src/proprietary/components/policies/classificationLocalPass.ts
+++ b/frontend/editor/src/proprietary/components/policies/classificationLocalPass.ts
@@ -111,7 +111,7 @@ async function classifyStub(
recordRunStart({
runId,
policyKey: CLASSIFICATION_POLICY_KEY,
- fileId: fileId as string,
+ fileId: fileId,
fileName,
fileSize,
target: "local",
@@ -153,7 +153,7 @@ async function classifyStub(
updateRun(runId, {
status: "COMPLETED",
imported: true,
- outputFileIds: [fileId as string],
+ outputFileIds: [fileId],
});
return { labels, confidence: result.confidence, meter };
} catch (err) {
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts
index b3eccff768..3d90f3cec4 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts
@@ -844,7 +844,7 @@ async function importOutputs(
// Mark the outputs handled BEFORE adding them (belt-and-suspenders session
// guard on top of derivedFromTool) so the auto-run never enforces the policy
// on its own output — that would version endlessly in a loop.
- for (const s of categorized) markHandled(s.id as string);
+ for (const s of categorized) markHandled(s.id);
deliveredIds = categorized.map((s) => s.id as string);
if (ctx.parentStub) {
// Input is in the active workspace: version it in place, silently — the
@@ -875,7 +875,7 @@ async function importOutputs(
derivedFromTool: true,
});
// Belt-and-suspenders session guard on top of derivedFromTool.
- for (const f of added) markHandled(f.fileId as string);
+ for (const f of added) markHandled(f.fileId);
deliveredIds = added.map((f) => f.fileId as string);
// Mark each new-file output as tool-derived (the versioned path gets this from the
// CONSUME_FILES reducer; the addFiles path doesn't). This is the real loop guard: the dispatch
diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/audit/AuditEventsTable.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/audit/AuditEventsTable.tsx
index c08577cd78..97f0eb7139 100644
--- a/frontend/editor/src/proprietary/components/shared/config/configSections/audit/AuditEventsTable.tsx
+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/audit/AuditEventsTable.tsx
@@ -407,10 +407,7 @@ const AuditEventsTable: React.FC<AuditEventsTableProps> = ({
let author = "";
let fileHash = "";
if (event.details && typeof event.details === "object") {
- const details = event.details as Record<
- string,
- unknown
- >;
+ const details = event.details;
const files = details.files;
if (Array.isArray(files) && files.length > 0) {
const firstFile = files[0] as Record<string, unknown>;
diff --git a/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts b/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts
index a479e193ed..01ee333bcb 100644
--- a/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts
+++ b/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts
@@ -158,12 +158,12 @@ export function useProcessingFolders(): ProcessingFoldersApi {
[recordFor],
);
- const enabledFolderIds = useMemo(() => {
+ const enabledFolderIds = useMemo<ReadonlySet<string>>(() => {
const ids = new Set<string>();
for (const record of current) {
if (record.enabled && record.folderId) ids.add(record.folderId);
}
- return ids as ReadonlySet<string>;
+ return ids;
}, [current]);
const anyEnabled = useMemo(
diff --git a/frontend/editor/src/proprietary/policies/codec.ts b/frontend/editor/src/proprietary/policies/codec.ts
index acbfce601f..66f3403b93 100644
--- a/frontend/editor/src/proprietary/policies/codec.ts
+++ b/frontend/editor/src/proprietary/policies/codec.ts
@@ -110,9 +110,7 @@ export function fromWirePolicy(policy: WirePolicy): PolicyDecodedState {
const policyKey = str(raw.categoryId);
// Selection = display metadata ∪ bound inputs, so policies saved before
// inputs were emitted (sources only in options) still round-trip complete.
- const optionSources = Array.isArray(raw.sources)
- ? (raw.sources as string[])
- : [];
+ const optionSources = Array.isArray(raw.sources) ? raw.sources : [];
const inputs = policy.inputs ?? [];
const sources = [
...new Set([...optionSources, ...inputs.map((i) => i.sourceId)]),
diff --git a/frontend/editor/src/proprietary/services/heuristic/heuristicRules.lint.test.ts b/frontend/editor/src/proprietary/services/heuristic/heuristicRules.lint.test.ts
index 286d9c91df..a76bf973fe 100644
--- a/frontend/editor/src/proprietary/services/heuristic/heuristicRules.lint.test.ts
+++ b/frontend/editor/src/proprietary/services/heuristic/heuristicRules.lint.test.ts
@@ -89,7 +89,7 @@ let core: RuleFile;
const packs = new Map<string, RuleFile>();
beforeAll(async () => {
- core = (await loadCoreRules()) as RuleFile;
+ core = await loadCoreRules();
for (const [language, load] of Object.entries(LANGUAGE_PACKS)) {
const mod = (await load()) as { default?: RuleFile };
packs.set(language, mod.default ?? (mod as RuleFile));
diff --git a/frontend/editor/src/proprietary/services/policyExport.test.ts b/frontend/editor/src/proprietary/services/policyExport.test.ts
index 69d0528c05..3ae0994c1e 100644
--- a/frontend/editor/src/proprietary/services/policyExport.test.ts
+++ b/frontend/editor/src/proprietary/services/policyExport.test.ts
@@ -58,23 +58,22 @@ const { recordRunStart } =
await import("@app/components/policies/policyRunStore");
/** An active export-time policy as the local store holds it. */
-const exportPolicy = (over: Partial<PolicyState>): PolicyState =>
- ({
- configured: true,
- enabled: true,
- backendId: "backend-1",
- firstOperation: "/api/v1/misc/compress-pdf",
- sources: [],
- runsOnEditor: false,
- scopeTypes: [],
- reviewerEmail: "",
- fieldValues: {},
- outputMode: "new_version",
- outputName: "",
- runOn: "export",
- isDefault: false,
- ...over,
- }) as PolicyState;
+const exportPolicy = (over: Partial<PolicyState>): PolicyState => ({
+ configured: true,
+ enabled: true,
+ backendId: "backend-1",
+ firstOperation: "/api/v1/misc/compress-pdf",
+ sources: [],
+ runsOnEditor: false,
+ scopeTypes: [],
+ reviewerEmail: "",
+ fieldValues: {},
+ outputMode: "new_version",
+ outputName: "",
+ runOn: "export",
+ isDefault: false,
+ ...over,
+});
const pdf = () =>
new File(["%PDF-1.4"], "doc.pdf", { type: "application/pdf" });
@@ -287,7 +286,7 @@ describe("export-time policy selection", () => {
runsOnEditor: true,
backendId: "backend-editor",
}),
- } as unknown as PoliciesByKey);
+ });
const enforcement = enforceExportPolicies([pdf()], ["file-1"]);
await vi.runAllTimersAsync();
@@ -308,7 +307,7 @@ describe("export-time policy selection", () => {
runsOnEditor: false,
backendId: "backend-swept",
}),
- } as unknown as PoliciesByKey);
+ });
const enforcement = enforceExportPolicies([pdf()], ["file-1"]);
await vi.runAllTimersAsync();
@@ -325,7 +324,7 @@ describe("export-time policy selection", () => {
runsOnEditor: true,
backendId: "backend-security",
}),
- } as unknown as PoliciesByKey);
+ });
const enforcement = enforceExportPolicies([pdf()], ["file-1"]);
await vi.runAllTimersAsync();
@@ -351,7 +350,7 @@ describe("export-time policy selection", () => {
backendId: "backend-first",
order: 0,
}),
- } as unknown as PoliciesByKey);
+ });
const enforcement = enforceExportPolicies([pdf()], ["file-1"]);
await vi.runAllTimersAsync();
diff --git a/frontend/editor/src/proprietary/services/policyStorage.ts b/frontend/editor/src/proprietary/services/policyStorage.ts
index b4731f0609..94fd048d4a 100644
--- a/frontend/editor/src/proprietary/services/policyStorage.ts
+++ b/frontend/editor/src/proprietary/services/policyStorage.ts
@@ -96,7 +96,7 @@ export function loadPolicies(): PoliciesByKey {
// Builder pipelines key by their own id, so the walk above misses them. Carried through as
// stored: a tile's defaults would mark them built-in and put them on the editor uninvited.
for (const [key, state] of Object.entries(parsed)) {
- if (!out[key] && state) out[key] = state as PolicyState;
+ if (!out[key] && state) out[key] = state;
}
// Cached endpoints can come from a different frontend version.
for (const state of Object.values(out)) {
diff --git a/frontend/editor/vite.config.ts b/frontend/editor/vite.config.ts
index 8b97e85298..5ce9b25408 100644
--- a/frontend/editor/vite.config.ts
+++ b/frontend/editor/vite.config.ts
@@ -251,7 +251,7 @@ export default defineConfig(async ({ mode, command }) => {
const flavor = (process.env.STIRLING_FLAVOR ?? "").toLowerCase();
const flavorMode: BuildMode | null =
flavor === "core" || flavor === "proprietary" || flavor === "saas"
- ? (flavor as BuildMode)
+ ? flavor
: null;
const effectiveMode: BuildMode =
explicitMode ??
diff --git a/frontend/oxlint.config.ts b/frontend/oxlint.config.ts
index 8e6d50d237..336d1affaa 100644
--- a/frontend/oxlint.config.ts
+++ b/frontend/oxlint.config.ts
@@ -74,6 +74,9 @@ const modernGlobals: OxlintGlobals = {
export default defineConfig({
plugins: ["typescript", "import"],
+ options: {
+ typeAware: true,
+ },
categories: {
correctness: "off",
},
@@ -188,6 +191,7 @@ export default defineConfig({
"typescript/no-non-null-asserted-optional-chain": "error",
"typescript/no-require-imports": "error",
"typescript/no-this-alias": "error",
+ "typescript/no-unnecessary-type-assertion": "error",
"typescript/no-unnecessary-type-constraint": "error",
"typescript/no-unsafe-declaration-merging": "error",
"typescript/no-unsafe-function-type": "error",
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 8eadce82b0..655a14ae91 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -124,6 +124,7 @@
"msw-storybook-addon": "^2.0.7",
"oxfmt": "^0.62.0",
"oxlint": "^1.77.0",
+ "oxlint-tsgolint": "^7.0.2002",
"postcss": "^8.5.12",
"postcss-cli": "^11.0.1",
"postcss-preset-mantine": "^1.18.0",
@@ -3230,6 +3231,90 @@
"node": "^20.19.0 || >=22.12.0"
}
},
+ "node_modules/@oxlint-tsgolint/darwin-arm64": {
+ "version": "7.0.2002",
+ "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/darwin-arm64/-/darwin-arm64-7.0.2002.tgz",
+ "integrity": "sha512-E3yYb/tI+5M3SqGgKwrwUD0nmjA2FMGD1xFbma46qi8Y7+nPTlGY6bZk/hqxijc9Vda/tdtUxQ2d5zGIEX9qlg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@oxlint-tsgolint/darwin-x64": {
+ "version": "7.0.2002",
+ "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/darwin-x64/-/darwin-x64-7.0.2002.tgz",
+ "integrity": "sha512-qEaMySdvzs8faaJwMO4dFtPFCa+degFCz+HbkFQ0REcIJqJ16KmC0smt30FAI9TeEHCoAtz6sU/6acJvi4uaxg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@oxlint-tsgolint/linux-arm64": {
+ "version": "7.0.2002",
+ "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/linux-arm64/-/linux-arm64-7.0.2002.tgz",
+ "integrity": "sha512-bqPObCNIR6tDQSc0Xn9Nu7EfWRXFB+qFzADRl/q6YA8zT9YUg3pGUbmicV2hV91uLpiot74so9ocGjx35SaX6w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxlint-tsgolint/linux-x64": {
+ "version": "7.0.2002",
+ "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/linux-x64/-/linux-x64-7.0.2002.tgz",
+ "integrity": "sha512-E5CcRALAYdiQMbdYjEqlLOiYuEdt21RtXiyxIoD8bfypdfkpWppacijKOR4i0DtLXFRVwCGQggZBWk5bOIpU1A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxlint-tsgolint/win32-arm64": {
+ "version": "7.0.2002",
+ "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/win32-arm64/-/win32-arm64-7.0.2002.tgz",
+ "integrity": "sha512-L+ul0ZFDiz/ZmTwCQ1J/qS7S6s45ktiaFqb+ZIzx+1sSdtdRxm8/H0+p4VDQYrCKBFzKNb6VjUlm48bNEe3BUg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@oxlint-tsgolint/win32-x64": {
+ "version": "7.0.2002",
+ "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/win32-x64/-/win32-x64-7.0.2002.tgz",
+ "integrity": "sha512-zkZeJfo4UmYiCzj77u85eCDpdxOiQiSAsV6j9Pvj5e7Vu5+MvwLtK1xmVutE77tJmUJ3eBOSXHR6WgY4AwHHGQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
"node_modules/@oxlint/binding-android-arm-eabi": {
"version": "1.77.0",
"resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.77.0.tgz",
@@ -13366,6 +13451,24 @@
}
}
},
+ "node_modules/oxlint-tsgolint": {
+ "version": "7.0.2002",
+ "resolved": "https://registry.npmjs.org/oxlint-tsgolint/-/oxlint-tsgolint-7.0.2002.tgz",
+ "integrity": "sha512-rQAj2RAQM57nCwTd3PhtnAkREGW2StqI47tzudNlJF8WwGommM7rVpeP4O1O8/ZiuDZ9f2GnTESzLHGTluwkvQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "tsgolint": "bin/tsgolint.js"
+ },
+ "optionalDependencies": {
+ "@oxlint-tsgolint/darwin-arm64": "7.0.2002",
+ "@oxlint-tsgolint/darwin-x64": "7.0.2002",
+ "@oxlint-tsgolint/linux-arm64": "7.0.2002",
+ "@oxlint-tsgolint/linux-x64": "7.0.2002",
+ "@oxlint-tsgolint/win32-arm64": "7.0.2002",
+ "@oxlint-tsgolint/win32-x64": "7.0.2002"
+ }
+ },
"node_modules/p-map": {
"version": "7.0.4",
"resolved": "https://registry.npmjs.org/p-map/-/p-map-7.0.4.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index 34018f77e0..a8faa69167 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -146,6 +146,7 @@
"msw-storybook-addon": "^2.0.7",
"oxfmt": "^0.62.0",
"oxlint": "^1.77.0",
+ "oxlint-tsgolint": "^7.0.2002",
"postcss": "^8.5.12",
"postcss-cli": "^11.0.1",
"postcss-preset-mantine": "^1.18.0",