Official
files
Built-in files UI (JavaScript UI plugin).
The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/files@0.2.6
Permissions in 0.2.6
Files
controller.ts8.1 KB
// Scoped file-panel effects: host reads and the divergence/tabs client.
// A layer owns one state instance for both registered views.
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
import { App, Host, Notify, Services } from "divergence/effect";
import type { EffectClient } from "divergence/effect";
import type { AppState, ViewHandle } from "divergence";
import { makeFolders } from "./folders.ts";
import { initialState } from "./panel.ts";
import type { FilesState } from "./panel.ts";
import type { Tabs } from "../tabs/contract.ts";
import { makeWatch } from "./watch.ts";
const same = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((name, at) => name === b[at]);
// The open file follows the visible tab while the tabs plugin runs: its row
// is selected and its folders open. One episode per provider: the previous
// follow ends when the provider goes.
const followTabs = Effect.fn("Files.followTabs")(function* (
state: FilesState,
redraw: () => void,
reveal: (path: string) => Effect.Effect<void>,
) {
const services = yield* Services;
const scope = yield* Effect.scope;
yield* services.when<typeof Tabs>("divergence/tabs").pipe(
Stream.runForEach((option) =>
Effect.gen(function* () {
if (state.follow) {
yield* Fiber.interrupt(state.follow);
state.follow = undefined;
}
if (Option.isNone(option)) {
state.tabs = undefined;
return;
}
const client: EffectClient<typeof Tabs> = option.value;
state.tabs = client;
// A file of another workspace is not this tree's, though its path may be.
const shown = (tab: { kind: string; path: string; workspaceId?: string } | null) =>
Effect.suspend(() => {
const ours = tab?.workspaceId === undefined || tab.workspaceId === state.workspaceId;
state.activePath = tab?.kind === "file" && ours ? tab.path : null;
redraw();
return state.activePath
? Effect.forkIn(reveal(state.activePath), scope, { startImmediately: true })
: Effect.void;
});
state.follow = yield* Effect.forkIn(client.on("activeChanged").pipe(Stream.runForEach(shown)), scope, {
startImmediately: true,
});
yield* client.active({}).pipe(
Effect.tap(shown),
// A provider that goes away mid-read leaves the last selection,
// and the failure is logged.
Effect.ignore({ log: "Warn", message: "Could not read the active tab" }),
);
}),
),
Effect.forkIn(scope, { startImmediately: true }),
);
});
const makeFiles = Effect.fn("Files.make")(function* () {
const host = yield* Host;
const app = yield* App;
const notify = yield* Notify;
const scope = yield* Effect.scope;
const state = initialState();
const views: ViewHandle[] = [];
const redraw = () => {
for (const view of views) view.update();
};
const warn = (error: { message: string }) => notify.warning(`Files unavailable: ${error.message}`);
// One folder's names. A host before `path` answers every path without
// `folders`: the panel then draws that whole list instead.
const list = Effect.fn("Files.list")(function* (workspaceId: string, folder: string) {
const result = yield* host.call("host/fs.search", { workspaceId, limit: 100000, depth: 1, path: folder });
if (state.workspaceId !== workspaceId) return;
if (result.folders) {
if (state.failed.has(folder)) state.failed = new Set([...state.failed].filter((id) => id !== folder));
// A folder listed again as it was draws nothing new.
const was = state.listing[folder];
if (was && same(was.files, result.paths) && same(was.folders, result.folders)) return;
state.listing = { ...state.listing, [folder]: { files: result.paths, folders: result.folders } };
} else state.all = result.paths;
redraw();
});
// A folder that cannot be listed says so in its row, besides the notice.
const listed = (workspaceId: string, folder: string) =>
list(workspaceId, folder).pipe(
Effect.catchTag(["HostCallFailed", "NeedsReview", "PermissionNotGranted"], (error) =>
Effect.suspend(() => {
if (state.workspaceId === workspaceId && !state.listing[folder]) {
state.failed = new Set([...state.failed, folder]);
redraw();
}
return warn(error);
}),
),
);
const folders = makeFolders(state, listed, redraw);
const watch = yield* makeWatch(state, (workspaceId, touched): Effect.Effect<void> =>
touched === null ? refresh(workspaceId) : Effect.forEach(touched, (folder) => listed(workspaceId, folder), { discard: true }),
);
// Lists the top, every folder listed before and every open folder, at
// once. A new workspace starts from its top and the folders open in it.
const refresh = Effect.fn("Files.refresh")(function* (workspaceId: string) {
if (workspaceId !== state.workspaceId) {
state.workspaceId = workspaceId;
state.listing = {};
state.failed = new Set();
state.all = null;
state.results = [];
state.resultsFor = null;
yield* Effect.forkIn(watch(workspaceId), scope, { startImmediately: true });
// A query typed before the switch searches the new workspace.
if (state.query.trim()) yield* Effect.forkIn(search(workspaceId, state.query), scope, { startImmediately: true });
}
const listed = Object.keys(state.listing);
const all = state.all ? [""] : [...new Set(["", ...listed, ...folders.openIn(workspaceId)])];
yield* Effect.forEach(all, (folder) => list(workspaceId, folder), { concurrency: "unbounded", discard: true }).pipe(Effect.catchTag(["HostCallFailed", "NeedsReview", "PermissionNotGranted"], warn));
});
// The host searches every path; a reply for an older query is dropped.
const search = Effect.fn("Files.search")(function* (workspaceId: string, query: string) {
const q = query.trim();
if (!q) return;
const result = yield* host
.call("host/fs.search", { workspaceId, query: q, limit: 500 })
.pipe(
Effect.catchTag(["HostCallFailed", "NeedsReview", "PermissionNotGranted"], (error) =>
Effect.as(warn(error), null),
),
);
if (!result || state.workspaceId !== workspaceId || state.query.trim() !== q) return;
state.results = result.paths;
state.resultsFor = q;
redraw();
});
const followApp = Effect.fn("Files.followApp")(function* (next: AppState) {
if (next.workspaceId && next.workspaceId !== state.workspaceId) yield* refresh(next.workspaceId);
});
const openFile = Effect.fn("Files.openFile")(function* (workspaceId: string, path: string) {
const client = state.tabs;
// Without the tabs plugin there is no detail pane; the shared request
// the baseline wrote would have had no reader either.
if (!client) return;
// The file the user picked takes the keyboard. Left on the list, it
// kept the rail's fly-out open after the pointer had gone.
yield* client.open({ kind: "file", workspaceId, path, focus: true }).pipe(
// A call that loses its provider on the way behaves like no reader,
// and the failure is logged.
Effect.ignore({ log: "Warn", message: "Could not open the file in a tab" }),
);
});
const toggle = Effect.fn("Files.toggle")((next: AppState) =>
app.update({
shared: {
rightPanel: next.shared?.rightPanel === "files" ? null : "files",
},
}),
);
yield* followTabs(state, redraw, folders.reveal);
return {
state,
views,
refresh,
setOpen: folders.setOpen,
collapseAll: folders.collapseAll,
search,
followApp,
openFile,
toggle,
close: app.update({ shared: { rightPanel: null } }),
};
});
export class Files extends Context.Service<Files, Effect.Success<ReturnType<typeof makeFiles>>>()("files/Files") {
static readonly layer = Layer.effect(Files, makeFiles());
}
No comments yet.