import { join } from "../deno_ral/path.ts";
import * as ld from "../core/lodash.ts";
import { safeExistsSync } from "../core/path.ts";
import { readInputTargetIndex } from "./project-index.ts";
import { fileExecutionEngine } from "../execute/engine.ts";
import { ProjectContext, SidebarItem } from "./types.ts";
export type SidebarContext = {
counter: number;
};
export const sidebarContext = (): SidebarContext => {
return { counter: 0 };
};
export function normalizeSidebarItem(
projectDir: string,
item: SidebarItem,
context: { counter: number },
): SidebarItem {
item = ld.cloneDeep(item);
if (typeof item === "string") {
if (safeExistsSync(join(projectDir, item))) {
item = {
href: item,
};
} else {
item = {
text: item,
};
}
} else {
resolveHrefAttribute(item);
const section = item.section;
if (section) {
context.counter = context.counter + 1;
const sectionPath = join(projectDir, section);
if (safeExistsSync(sectionPath) && Deno.statSync(sectionPath).isFile) {
item.href = section;
} else {
item.text = section;
}
item.sectionId = `${kQuartoSidebarPrefix}${context.counter}`;
delete item.section;
item.contents = item.contents || [];
}
if (item.contents) {
for (let i = 0; i < item.contents.length; i++) {
item.contents[i] = normalizeSidebarItem(
projectDir,
item.contents[i],
context,
);
}
}
}
return item;
}
const kQuartoSidebarPrefix = "quarto-sidebar-section-";
export function resolveHrefAttribute(
item: { href?: string; file?: string; url?: string },
) {
item.href = item.href || item.file || item.url;
delete item.file;
delete item.url;
}
export async function partitionedMarkdownForInput(
project: ProjectContext,
input: string,
) {
const { index } = readInputTargetIndex(project.dir, input);
if (index) {
return index.markdown;
} else {
const inputPath = join(project.dir, input);
const engine = await fileExecutionEngine(inputPath, undefined, project);
if (engine) {
return await engine.partitionedMarkdown(inputPath);
} else {
return undefined;
}
}
}