Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 3 additions & 26 deletions src/lib/editorFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,11 @@ import { detectEol, normalizeEol } from "utils/eol";
import haptic from "utils/haptic";
import helpers from "utils/helpers";
import loadMimeTypes from "utils/mimeTypes";
import Path from "utils/Path";
import { readRemoteFilePreview } from "utils/remoteFilePreview";
import Url from "utils/Url";
import config from "./config";
import { isInitialPluginLoadComplete } from "./loadPlugins";
import openFolder from "./openFolder";
import recommendModePlugin from "./recommendModePlugin";
import runLazily from "./runLazily";
import saveFile from "./saveFile";
import appSettings from "./settings";
Expand Down Expand Up @@ -304,22 +303,6 @@ function createSessionProxy(state, file) {
});
}

function maybeRecommendLanguageModeExtension(file, modeInfo) {
if (appSettings.value.recommendExtensions === false) return;
if (!isInitialPluginLoadComplete()) return;
if (modeInfo?.name !== "text" || modeInfo.supportsFile(file.filename)) return;
if (helpers.isBinary(file.filename || file.uri)) return;

void import("./languageModeRecommendations").then(
({ default: recommend }) => {
recommend(file, modeInfo);
},
(error) => {
console.warn("Failed to load language mode recommendations.", error);
},
);
}

/**
* @typedef {'run'|'save'|'change'|'focus'|'blur'|'close'|'rename'|'load'|'loadError'|'loadStart'|'loadEnd'|'changeMode'|'changeEncoding'|'changeReadOnly'} FileEvents
*/
Expand Down Expand Up @@ -1604,13 +1587,7 @@ export default class EditorFile {
this.#emit("changemode", event);
if (event.defaultPrevented) return;

if (!mode) {
const ext = Path.extname(this.filename);
const modes = helpers.parseJSON(localStorage.modeassoc);
if (modes?.[ext]) {
mode = modes[ext];
}
}
if (!mode) mode = helpers.getAssociatedMode(this.filename);

let modeInfo = mode ? getMode(mode) : null;
if (!modeInfo) {
Expand All @@ -1632,7 +1609,7 @@ export default class EditorFile {
this.__cmCachedLanguageSignature = null;
}
if (options.recommend !== false) {
maybeRecommendLanguageModeExtension(this, modeInfo);
recommendModePlugin(this.filename, modeInfo);
}

// sets file icon
Expand Down
21 changes: 13 additions & 8 deletions src/lib/languageModeRecommendations.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { getModeForPath } from "cm/modelist";
import notificationManager from "lib/notificationManager";
import { isBinaryFile } from "utils/binaryExtensions";
import Path from "utils/Path";
import Url from "utils/Url";
import config from "./config";
import fileTypeHandler from "./fileTypeHandler";

let instance = null;

Expand Down Expand Up @@ -38,8 +40,13 @@ function hasPlainTextFallback(modeInfo, filename) {
return modeInfo?.name === "text" && !modeInfo.supportsFile(filename);
}

function hasBinaryFileHandler(filename) {
return isBinaryFile(filename) && !!fileTypeHandler.getFileHandler(filename);
}

export function shouldRecommendLanguageModeExtension(filename, modeInfo) {
if (!hasPlainTextFallback(modeInfo, filename)) return false;
if (hasBinaryFileHandler(filename)) return false;

const keyword = getLanguageModeRecommendationSearchKeyword(filename);
if (!keyword) return false;
Expand Down Expand Up @@ -89,10 +96,7 @@ class LanguageModeRecommendations {
return availability;
}

recommend(file, modeInfo) {
if (!file || file.type !== "editor") return;

const filename = file.filename || "";
recommend(filename, modeInfo) {
if (!shouldRecommendLanguageModeExtension(filename, modeInfo)) return;

const keyword = getLanguageModeRecommendationSearchKeyword(filename);
Expand All @@ -119,8 +123,9 @@ class LanguageModeRecommendations {

async showRecommendation(keyword, filename) {
const hasPlugins = await this.getPluginAvailability(keyword);
// If a plugin registered the mode while the lookup was pending, suppress
// this stale recommendation and leave the keyword eligible for future checks.
// If a plugin registered the mode or a file handler while the lookup was
// pending, suppress this stale recommendation and leave the keyword
// eligible for future checks.
if (
!shouldRecommendLanguageModeExtension(filename, getModeForPath(filename))
) {
Expand Down Expand Up @@ -165,6 +170,6 @@ function getLanguageModeRecommendations() {
return instance;
}

export default function recommendLanguageModeExtension(file, modeInfo) {
getLanguageModeRecommendations().recommend(file, modeInfo);
export default function recommendLanguageModeExtension(filename, modeInfo) {
getLanguageModeRecommendations().recommend(filename, modeInfo);
}
7 changes: 7 additions & 0 deletions src/lib/loadPlugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const PLUGIN_LOAD_TIMEOUT = 15000;
const PLUGIN_DISABLE_TIMEOUT = 60000;
let pluginDisabledUpdateQueue = Promise.resolve();
let initialPluginLoadComplete = false;
const initialPluginLoadWaiters = [];
/** Plugins still loading in the background after PLUGIN_LOAD_TIMEOUT. */
const SLOW_PLUGIN_LOADS = new Set();
let handlerHistoryPending = false;
Expand Down Expand Up @@ -126,6 +127,7 @@ export default async function loadPlugins(loadOnlyTheme = false) {
} finally {
if (!loadOnlyTheme) {
initialPluginLoadComplete = true;
for (const resolve of initialPluginLoadWaiters.splice(0)) resolve();
}
}
}
Expand All @@ -134,6 +136,11 @@ export function isInitialPluginLoadComplete() {
return initialPluginLoadComplete;
}

export function waitForInitialPluginLoad() {
if (initialPluginLoadComplete) return Promise.resolve();
return new Promise((resolve) => initialPluginLoadWaiters.push(resolve));
}

export async function loadPluginWithTimeout(pluginId, justInstalled = false) {
const pluginState = { settled: false };
const pluginLoadPromise = loadPlugin(pluginId, justInstalled)
Expand Down
6 changes: 6 additions & 0 deletions src/lib/openFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import EditorFile from "./editorFile";
import { promoteSessionPersistence } from "./fileSessionPersistence";
import fileTypeHandler from "./fileTypeHandler";
import recents from "./recents";
import recommendModePlugin from "./recommendModePlugin";
import appSettings from "./settings";

/** Documents opened from other apps that only a plugin handler can show. */
Expand Down Expand Up @@ -170,6 +171,7 @@ export default async function openFile(file, options = {}) {
const needsDocumentHandler =
options.external && EXTERNAL_DOCUMENT_PATTERN.test(name);
if (needsDocumentHandler && !customHandler) {
recommendModePlugin(name);
throw Object.assign(new Error("Document handler unavailable"), {
code: "DOCUMENT_HANDLER_UNAVAILABLE",
filename: name,
Expand Down Expand Up @@ -470,6 +472,10 @@ export default async function openFile(file, options = {}) {
return;
}

if (helpers.isBinary(name) || helpers.isBinary(uri)) {
recommendModePlugin(name);
}

// Else open a new file
// Checks for valid file
if (fileInfo.length * 0.000001 > settings.maxFileSize) {
Expand Down
32 changes: 32 additions & 0 deletions src/lib/recommendModePlugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { getMode, getModeForPath } from "cm/modelist";
import helpers from "utils/helpers";
import {
isInitialPluginLoadComplete,
waitForInitialPluginLoad,
} from "./loadPlugins";
import appSettings from "./settings";

export default async function recommendModePlugin(filename, modeInfo) {
try {
if (!isInitialPluginLoadComplete()) {
// Editor tabs are checked again by setMode once plugins load.
if (modeInfo) return;
await waitForInitialPluginLoad();
Comment thread
deadlyjack marked this conversation as resolved.
Resolved
}
if (appSettings.value.recommendExtensions === false) return;

const { default: recommend } = await import(
"./languageModeRecommendations"
);
recommend(filename, modeInfo ?? getFileMode(filename));
} catch (error) {
console.error("Failed to recommend a language mode plugin.", error);
}
}

function getFileMode(filename) {
const associatedMode = helpers.getAssociatedMode(filename);
return (
(associatedMode && getMode(associatedMode)) || getModeForPath(filename)
);
}
7 changes: 7 additions & 0 deletions src/utils/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,13 @@ export default {
return null;
}
},
/**
* Mode the user chose for files with this file's extension
* @param {string} filename
*/
getAssociatedMode(filename) {
return this.parseJSON(localStorage.modeassoc)?.[path.extname(filename)];
},
/**
* Checks whether given type is directory or not
* @param {'dir'|'directory'|'folder'} type
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/fileSaveEvents.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ function setup() {
"utils/Path",
"utils/remoteFilePreview",
"utils/Url",
"./loadPlugins",
"./openFolder",
"./runLazily",
"cm/editorReadOnly",
Expand All @@ -52,6 +51,7 @@ function setup() {
{
...defaults,
"utils/haptic": vi.fn(),
"./recommendModePlugin": vi.fn(),
"components/sidebar": { hide: vi.fn() },
"@codemirror/state": { EditorState, EditorSelection },
"cm/editorUtils": { getDocText: (doc) => doc.toString() },
Expand Down
41 changes: 37 additions & 4 deletions tests/unit/languageModeRecommendations.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
import "cm/supportedModes";
import { getModeForPath } from "cm/modelist";
import fileTypeHandler from "lib/fileTypeHandler";
import recommendLanguageModeExtension from "lib/languageModeRecommendations";
import notificationManager from "lib/notificationManager";

Expand All @@ -19,10 +20,7 @@ globalThis.strings = {
};

function recommend(filename) {
recommendLanguageModeExtension(
{ type: "editor", filename },
getModeForPath(filename),
);
recommendLanguageModeExtension(filename, getModeForPath(filename));
}

describe("language mode recommendations", () => {
Expand Down Expand Up @@ -63,6 +61,41 @@ describe("language mode recommendations", () => {
});
});

it("recommends a plugin for binary documents without a handler", async () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => [{ id: "documents" }],
});

recommend("report.pdf");

await vi.waitFor(() => {
expect(notificationManager.pushNotification).toHaveBeenCalledOnce();
});
});

it("stays silent when a handler registers while the lookup is pending", async () => {
let respond;
globalThis.fetch = vi.fn(
() =>
new Promise((resolve) => {
respond = resolve;
}),
);

recommend("slides.pptx");
await vi.waitFor(() => expect(globalThis.fetch).toHaveBeenCalled());
fileTypeHandler.registerFileHandler("late-documents", {
extensions: ["pptx"],
handleFile: async () => {},
});
respond({ ok: true, json: async () => [{ id: "documents" }] });
await new Promise((resolve) => setTimeout(resolve, 0));
fileTypeHandler.unregisterFileHandler("late-documents");

expect(notificationManager.pushNotification).not.toHaveBeenCalled();
});

it.each([
["network errors", () => Promise.reject(new Error("offline"))],
["server errors", () => Promise.resolve({ ok: false, status: 503 })],
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/openFileCancellation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ describe("openFile cancellation", () => {
let titleLoader;
let loaderVisible;
let languageLoads;
let recommendModePlugin;

beforeEach(() => {
controller = new AbortController();
Expand All @@ -59,6 +60,7 @@ describe("openFile cancellation", () => {
decode = vi.fn().mockResolvedValue("target text");
detectEncoding = vi.fn().mockResolvedValue("UTF-8");
handler = { getFileHandler: vi.fn() };
recommendModePlugin = vi.fn();
recents = { addFile: vi.fn() };
createEditor = vi.fn(function (name, options) {
manager.activeFile = { name, ...options };
Expand Down Expand Up @@ -89,6 +91,7 @@ describe("openFile cancellation", () => {
"./fileSessionPersistence": { promoteSessionPersistence: vi.fn() },
"./fileTypeHandler": { default: handler },
"./recents": { default: recents },
"./recommendModePlugin": { default: recommendModePlugin },
"./settings": {
default: { value: { maxFileSize: 10, defaultFileEncoding: "auto" } },
},
Expand Down Expand Up @@ -149,6 +152,9 @@ describe("openFile cancellation", () => {
await expect(
openFile("content://provider/42", { external: true }),
).rejects.toMatchObject({ code: "DOCUMENT_HANDLER_UNAVAILABLE" });
expect(recommendModePlugin).toHaveBeenCalledWith(
`Document.${extension.toUpperCase()}`,
);
expect(readFile).not.toHaveBeenCalled();
expect(createEditor).not.toHaveBeenCalled();
expect(loaderVisible).toBe(false);
Expand Down Expand Up @@ -214,6 +220,15 @@ describe("openFile cancellation", () => {
expect(loaderVisible).toBe(false);
});

it("recommends a mode plugin for binary files before rejecting their size", async () => {
stat.mockResolvedValue({ name: "archive.zip", length: 50_000_000 });
await expect(
openFile("content://provider/archive", { external: true }),
).rejects.toThrow("File too large");
expect(recommendModePlugin).toHaveBeenCalledWith("archive.zip");
expect(readFile).not.toHaveBeenCalled();
});

it.each([
["README", "text/plain"],
["Makefile", undefined],
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/pluginFileRestoration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ function setup() {
"utils/eol": { detectEol, getEolSeparator, normalizeEol },
"utils/helpers": helpers,
"./config": { DEFAULT_FILE_SESSION: "default" },
"./loadPlugins": { isInitialPluginLoadComplete: () => false },
"./recommendModePlugin": vi.fn(),
"./settings": settings,
"./saveFile": saveFile,
},
Expand Down
Loading