prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
import { App, TFolder, parseLinktext } from "obsidian"; import { DendronVault, VaultConfig } from "./vault"; import { getFolderFile } from "../utils"; import { RefTarget, parseRefSubpath } from "./ref"; import { parsePath } from "../path"; const DENDRON_URI_START = "dendron://"; export class DendronWorkspace { vaultList: DendronVault[] = []; constructor(public app: App) {} changeVault(vaultList: VaultConfig[]) { this.vaultList = vaultList.map((config) => { return ( this.vaultList.find( (vault) => vault.config.name === config.name && vault.config.path === config.path ) ?? new DendronVault(this.app, config) ); }); for (const vault of this.vaultList) { vault.init(); } } findVaultByParent(parent: TFolder | null): DendronVault | undefined { return this.vaultList.find((vault) => vault.folder === parent); } findVaultByParentPath(path: string): DendronVault | undefined { const file = getFolderFile(this.app.vault, path); return file instanceof TFolder ? this.findVaultByParent(file) : undefined; } resolveRef(sourcePath: string, link: string): RefTarget | null { if (link.startsWith(DENDRON_URI_START)) { const [vaultName, rest] = link.slice(DENDRON_URI_START.length).split("/", 2) as ( | string | undefined )[]; const { path, subpath } = rest ? parseLinktext(rest) : { path: undefined, subpath: undefined, }; const vault = this.vaultList.find(({ config }) => config.name === vaultName); return { type: "maybe-note", vaultName: vaultName ?? "", vault, note: path ? vault?.tree?.getFromFileName(path) : undefined, path: path ?? "", subpath: subpath ? parseRefSubpath(subpath) : undefined, }; } const { dir: vaultDir
} = parsePath(sourcePath);
const vault = this.findVaultByParentPath(vaultDir); if (!vault) return null; const { path, subpath } = parseLinktext(link); const target = this.app.metadataCache.getFirstLinkpathDest(path, sourcePath); if (target && target.extension !== "md") return { type: "file", file: target, }; const note = vault.tree.getFromFileName(path); return { type: "maybe-note", vaultName: vault.config.name, vault: vault, note, path, subpath: parseRefSubpath(subpath.slice(1) ?? ""), }; } }
src/engine/workspace.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/engine/note.test.ts", "retrieved_chunk": " const { basename, name, extension } = parsePath(path);\n return {\n basename,\n extension,\n name,\n parent: null,\n path: path,\n stat: null as unknown as Stat,\n vault: null as unknown as Vault,\n };", "score": 0.8116909861564636 }, { "filename": "src/settings.ts", "retrieved_chunk": " autoGenerateFrontmatter: boolean;\n autoReveal: boolean;\n customResolver: boolean;\n}\nexport const DEFAULT_SETTINGS: DendronTreePluginSettings = {\n vaultList: [\n {\n name: \"root\",\n path: \"/\",\n },", "score": 0.8045928478240967 }, { "filename": "src/main.ts", "retrieved_chunk": " async migrateSettings() {\n function pathToVaultConfig(path: string) {\n const { name } = parsePath(path);\n if (name.length === 0)\n return {\n name: \"root\",\n path: \"/\",\n };\n let processed = path;\n if (processed.endsWith(\"/\")) processed = processed.slice(0, -1);", "score": 0.800615668296814 }, { "filename": "src/custom-resolver/link-open.ts", "retrieved_chunk": " return originalBoundedFunction(linktext, sourcePath, newLeaf, openViewState);\n let file = target.note?.file;\n if (!file) {\n if (target.vaultName === \"\") {\n new Notice(\"Vault name is unspecified in link.\");\n return;\n } else if (!target.vault) {\n new Notice(`Vault ${target.vaultName} is not found.`);\n return;\n } else if (target.path === \"\") {", "score": 0.7985959053039551 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 0.7832306623458862 } ]
typescript
} = parsePath(sourcePath);
import { Menu, Plugin, TAbstractFile, TFile, addIcon } from "obsidian"; import { DendronView, VIEW_TYPE_DENDRON } from "./view"; import { activeFile, dendronVaultList } from "./store"; import { LookupModal } from "./modal/lookup"; import { dendronActivityBarIcon, dendronActivityBarName } from "./icons"; import { DEFAULT_SETTINGS, DendronTreePluginSettings, DendronTreeSettingTab } from "./settings"; import { parsePath } from "./path"; import { DendronWorkspace } from "./engine/workspace"; import { CustomResolver } from "./custom-resolver"; export default class DendronTreePlugin extends Plugin { settings: DendronTreePluginSettings; workspace: DendronWorkspace = new DendronWorkspace(this.app); customResolver?: CustomResolver; async onload() { await this.loadSettings(); await this.migrateSettings(); addIcon(dendronActivityBarName, dendronActivityBarIcon); this.addCommand({ id: "dendron-lookup", name: "Lookup Note", callback: () => { new LookupModal(this.app, this.workspace).open(); }, }); this.addSettingTab(new DendronTreeSettingTab(this.app, this)); this.registerView(VIEW_TYPE_DENDRON, (leaf) => new DendronView(leaf, this)); this.addRibbonIcon(dendronActivityBarName, "Open Dendron Tree", () => { this.activateView(); }); this.app.workspace.onLayoutReady(() => { this.onRootFolderChanged(); this.registerEvent(this.app.vault.on("create", this.onCreateFile)); this.registerEvent(this.app.vault.on("delete", this.onDeleteFile)); this.registerEvent(this.app.vault.on("rename", this.onRenameFile)); this.registerEvent(this.app.metadataCache.on("resolve", this.onResolveMetadata)); this.registerEvent(this.app.workspace.on("file-open", this.onOpenFile, this)); this.registerEvent(this.app.workspace.on("file-menu", this.onFileMenu)); }); this.configureCustomResolver(); } async migrateSettings() { function pathToVaultConfig(path: string) { const { name } = parsePath(path); if (name.length === 0) return { name: "root", path: "/", }; let processed = path; if (processed.endsWith("/")) processed = processed.slice(0, -1); if (processed.startsWith("/") && processed.length > 1) processed = processed.slice(1); return { name, path: processed, }; } if (this.settings.vaultPath) { this.settings.vaultList = [pathToVaultConfig(this.settings.vaultPath)]; this.settings.vaultPath = undefined; await this.saveSettings(); } if (this.settings.vaultList.length > 0 && typeof this.settings.vaultList[0] === "string") { this.settings.vaultList = (this.settings.vaultList as unknown as string[]).map((path) => pathToVaultConfig(path) ); await this.saveSettings(); } } onunload() {} onRootFolderChanged() { this.workspace.changeVault(this.settings.vaultList); this.updateNoteStore(); } configureCustomResolver() { if (this.settings.customResolver && !this.customResolver) { this.customResolver = new CustomResolver(this, this.workspace); this.addChild(this.customResolver); } else if (!this.settings.customResolver && this.customResolver) { this.removeChild(this.customResolver); this.customResolver = undefined; } } updateNoteStore() { dendronVaultList.set(this.workspace.vaultList); } onCreateFile = async (file: TAbstractFile) => { const vault = this.workspace.findVaultByParent(file.parent); if (vault && vault.onFileCreated(file)) { if (this.settings.autoGenerateFrontmatter && file instanceof TFile && file.stat.size === 0) await vault.generateFronmatter(file); this.updateNoteStore(); } }; onDeleteFile = (file: TAbstractFile) => { // file.parent is null when file is deleted const parsed = parsePath(file.path); const vault = this.workspace.findVaultByParentPath(parsed.dir); if (vault && vault.onFileDeleted(parsed)) { this.updateNoteStore(); } }; onRenameFile = (file: TAbstractFile, oldPath: string) => { const oldParsed = parsePath(oldPath); const oldVault = this.workspace.findVaultByParentPath(oldParsed.dir); let update = false; if (oldVault) { update = oldVault.onFileDeleted(oldParsed); } const newVault = this.workspace.findVaultByParent(file.parent); if (newVault) { update = newVault.onFileCreated(file) || update; } if (update) this.updateNoteStore(); }; onOpenFile(file: TFile | null) { activeFile.set(file); if (file && this.settings.autoReveal) this.revealFile(file); } onFileMenu = (menu: Menu, file: TAbstractFile) => { if (!(file instanceof TFile)) return; menu.addItem((item) => { item .setIcon(dendronActivityBarName) .setTitle("Reveal in Dendron Tree") .onClick(() => this.revealFile(file)); }); }; onResolveMetadata = (file: TFile) => { const vault = this.workspace.findVaultByParent(file.parent); if (vault && vault.onMetadataChanged(file)) { this.updateNoteStore(); } }; revealFile(file: TFile) { const vault = this.workspace.findVaultByParent(file.parent); if (!vault) return; const note = vault.tree.getFromFileName(file.basename); if (!note) return; for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON)) { if (!(leaf.view instanceof DendronView)) continue; leaf
.view.component.focusTo(vault, note);
} } async activateView() { const leafs = this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON); if (leafs.length == 0) { const leaf = this.app.workspace.getLeftLeaf(false); await leaf.setViewState({ type: VIEW_TYPE_DENDRON, active: true, }); this.app.workspace.revealLeaf(leaf); } else { leafs.forEach((leaf) => this.app.workspace.revealLeaf(leaf)); } } async loadSettings() { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); } async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 0.8425846099853516 }, { "filename": "src/engine/workspace.ts", "retrieved_chunk": " }\n findVaultByParent(parent: TFolder | null): DendronVault | undefined {\n return this.vaultList.find((vault) => vault.folder === parent);\n }\n findVaultByParentPath(path: string): DendronVault | undefined {\n const file = getFolderFile(this.app.vault, path);\n return file instanceof TFolder ? this.findVaultByParent(file) : undefined;\n }\n resolveRef(sourcePath: string, link: string): RefTarget | null {\n if (link.startsWith(DENDRON_URI_START)) {", "score": 0.7955800294876099 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " }\n init() {\n if (this.isIniatialized) return;\n this.tree = new NoteTree();\n const root = getFolderFile(this.app.vault, this.config.path);\n if (!(root instanceof TFolder)) {\n new InvalidRootModal(this).open();\n return;\n }\n this.folder = root;", "score": 0.7903357744216919 }, { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " content.setText(`\"${target.path}\" is not created yet. Click to create.`);\n this.containerEl.onclick = () => {\n vault.createNote(path).then((file) => openFile(app, file));\n };\n }\n}\nexport function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) {\n if (!target.note || !target.note.file) {\n return new UnresolvedRefRenderChild(app, container, target);\n } else {", "score": 0.7842778563499451 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " }\n addFile(file: TFile, sort = false) {\n const titlecase = isUseTitleCase(file.basename);\n const path = NoteTree.getPathFromFileName(file.basename);\n let currentNote: Note = this.root;\n if (!NoteTree.isRootPath(path))\n for (const name of path) {\n let note: Note | undefined = currentNote.findChildren(name);\n if (!note) {\n note = new Note(name, titlecase);", "score": 0.7784425020217896 } ]
typescript
.view.component.focusTo(vault, note);
import { Component, MarkdownPreviewRenderer, PagePreviewPlugin, Plugin, Workspace } from "obsidian"; import { DendronWorkspace } from "../engine/workspace"; import { createLinkHoverHandler } from "./link-hover"; import { ViewPlugin } from "@codemirror/view"; import { RefLivePlugin } from "./ref-live"; import { createRefMarkdownProcessor } from "./ref-markdown-processor"; import { createLinkOpenHandler } from "./link-open"; import { LinkLivePlugin } from "./link-live"; import { createLinkMarkdownProcessor } from "./link-markdown-processor"; import { LinkRefClickbale } from "./link-ref-clickbale"; export class CustomResolver extends Component { pagePreviewPlugin?: PagePreviewPlugin; originalLinkHover: PagePreviewPlugin["onLinkHover"]; originalOpenLinkText: Workspace["openLinkText"]; refPostProcessor = createRefMarkdownProcessor(this.plugin.app, this.workspace); linkPostProcessor = createLinkMarkdownProcessor(this.plugin.app, this.workspace); refEditorExtenstion = ViewPlugin.define((v) => { return new RefLivePlugin(this.plugin.app, this.workspace); }); linkEditorExtenstion = ViewPlugin.define( (view) => { return new LinkLivePlugin(this.plugin.app, this.workspace, view); }, { decorations: (value) => value.decorations, } ); linkRefClickbaleExtension = ViewPlugin.define((v) => { return new LinkRefClickbale(v); }); constructor(public plugin: Plugin, public workspace: DendronWorkspace) { super(); } onload(): void { this.plugin.app.workspace.onLayoutReady(() => { this.plugin.app.workspace.registerEditorExtension(this.refEditorExtenstion); this.plugin.app.workspace.registerEditorExtension(this.linkEditorExtenstion); this.plugin.app.workspace.registerEditorExtension(this.linkRefClickbaleExtension); this.pagePreviewPlugin = this.plugin.app.internalPlugins.getEnabledPluginById("page-preview"); if (!this.pagePreviewPlugin) return; this.originalLinkHover = this.pagePreviewPlugin.onLinkHover;
this.pagePreviewPlugin.onLinkHover = createLinkHoverHandler( this.plugin.app, this.workspace, this.originalLinkHover.bind(this.pagePreviewPlugin) );
}); MarkdownPreviewRenderer.registerPostProcessor(this.refPostProcessor); MarkdownPreviewRenderer.registerPostProcessor(this.linkPostProcessor); this.originalOpenLinkText = this.plugin.app.workspace.openLinkText; this.plugin.app.workspace.openLinkText = createLinkOpenHandler( this.workspace, this.originalOpenLinkText.bind(this.plugin.app.workspace) ); } onunload(): void { this.plugin.app.workspace.openLinkText = this.originalOpenLinkText; MarkdownPreviewRenderer.unregisterPostProcessor(this.linkPostProcessor); MarkdownPreviewRenderer.unregisterPostProcessor(this.refPostProcessor); this.plugin.app.workspace.unregisterEditorExtension(this.linkRefClickbaleExtension); this.plugin.app.workspace.unregisterEditorExtension(this.linkEditorExtenstion); this.plugin.app.workspace.unregisterEditorExtension(this.refEditorExtenstion); if (!this.pagePreviewPlugin) return; this.pagePreviewPlugin.onLinkHover = this.originalLinkHover; } }
src/custom-resolver/index.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/main.ts", "retrieved_chunk": " this.onRootFolderChanged();\n this.registerEvent(this.app.vault.on(\"create\", this.onCreateFile));\n this.registerEvent(this.app.vault.on(\"delete\", this.onDeleteFile));\n this.registerEvent(this.app.vault.on(\"rename\", this.onRenameFile));\n this.registerEvent(this.app.metadataCache.on(\"resolve\", this.onResolveMetadata));\n this.registerEvent(this.app.workspace.on(\"file-open\", this.onOpenFile, this));\n this.registerEvent(this.app.workspace.on(\"file-menu\", this.onFileMenu));\n });\n this.configureCustomResolver();\n }", "score": 0.740196943283081 }, { "filename": "src/custom-resolver/link-ref-clickbale.ts", "retrieved_chunk": " if (editor && editor.getClickableTokenAt) {\n this.getClickableTokenAtOrig = editor.getClickableTokenAt;\n editor.getClickableTokenAt = LinkRefClickbale.createClickableTokenAtWrapper(\n this.getClickableTokenAtOrig\n );\n }\n }\n destroy(): void {\n if (this.getClickableTokenAtOrig) {\n const editor = this.view.state.field(editorInfoField).editor;", "score": 0.7124083638191223 }, { "filename": "src/main.ts", "retrieved_chunk": " this.workspace.changeVault(this.settings.vaultList);\n this.updateNoteStore();\n }\n configureCustomResolver() {\n if (this.settings.customResolver && !this.customResolver) {\n this.customResolver = new CustomResolver(this, this.workspace);\n this.addChild(this.customResolver);\n } else if (!this.settings.customResolver && this.customResolver) {\n this.removeChild(this.customResolver);\n this.customResolver = undefined;", "score": 0.6954302191734314 }, { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " ) as unknown as HTMLButtonElement;\n buttonComponent.setIcon(\"lucide-link\").setTooltip(\"Open link\");\n buttonComponent.buttonEl.onclick = () => {\n const openState: OpenViewState = {};\n if (this.ref.subpath) {\n openState.eState = {\n subpath: anchorToLinkSubpath(\n this.ref.subpath.start,\n this.app.metadataCache.getFileCache(this.file)?.headings\n ),", "score": 0.6909433007240295 }, { "filename": "src/settings.ts", "retrieved_chunk": " this.plugin.settings.autoGenerateFrontmatter = value;\n await this.plugin.saveSettings();\n });\n });\n new Setting(containerEl)\n .setName(\"Auto Reveal\")\n .setDesc(\"Automatically reveal active file in Dendron Tree\")\n .addToggle((toggle) => {\n toggle.setValue(this.plugin.settings.autoReveal).onChange(async (value) => {\n this.plugin.settings.autoReveal = value;", "score": 0.6842287182807922 } ]
typescript
this.pagePreviewPlugin.onLinkHover = createLinkHoverHandler( this.plugin.app, this.workspace, this.originalLinkHover.bind(this.pagePreviewPlugin) );
import { App, Notice, PluginSettingTab, Setting } from "obsidian"; import DendronTreePlugin from "./main"; import { VaultConfig } from "./engine/vault"; import { AddVaultModal } from "./modal/add-vault"; export interface DendronTreePluginSettings { /** * @deprecated use vaultList */ vaultPath?: string; vaultList: VaultConfig[]; autoGenerateFrontmatter: boolean; autoReveal: boolean; customResolver: boolean; } export const DEFAULT_SETTINGS: DendronTreePluginSettings = { vaultList: [ { name: "root", path: "/", }, ], autoGenerateFrontmatter: true, autoReveal: true, customResolver: false, }; export class DendronTreeSettingTab extends PluginSettingTab { plugin: DendronTreePlugin; constructor(app: App, plugin: DendronTreePlugin) { super(app, plugin); this.plugin = plugin; } display(): void { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h2", { text: "Dendron Tree Settting" }); new Setting(containerEl) .setName("Auto Generate Front Matter") .setDesc("Generate front matter for new file even if file is created outside of Dendron tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoGenerateFrontmatter).onChange(async (value) => { this.plugin.settings.autoGenerateFrontmatter = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Auto Reveal") .setDesc("Automatically reveal active file in Dendron Tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoReveal).onChange(async (value) => { this.plugin.settings.autoReveal = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Custom Resolver") .setDesc( "Use custom resolver to resolve ref/embed and link. (Please reopen editor after change this setting)" ) .addToggle((toggle) => { toggle.setValue(this.plugin.settings.customResolver).onChange(async (value) => { this.plugin.settings.customResolver = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl).setName("Vault List").setHeading(); for (const vault of this.plugin.settings.vaultList) { new Setting(containerEl) .setName(vault.name) .setDesc(`Folder: ${vault.path}`) .addButton((btn) => { btn.setButtonText("Remove").onClick(async () => { this.plugin.settings.vaultList.remove(vault); await this.plugin.saveSettings(); this.display(); }); }); } new Setting(containerEl).addButton((btn) => { btn.setButtonText("Add Vault").onClick(() => { new AddVaultModal(this
.app, (config) => {
const list = this.plugin.settings.vaultList; const nameLowecase = config.name.toLowerCase(); if (list.find(({ name }) => name.toLowerCase() === nameLowecase)) { new Notice("Vault with same name already exist"); return false; } if (list.find(({ path }) => path === config.path)) { new Notice("Vault with same path already exist"); return false; } list.push(config); this.plugin.saveSettings().then(() => this.display()); return true; }).open(); }); }); } hide() { super.hide(); this.plugin.onRootFolderChanged(); this.plugin.configureCustomResolver(); } }
src/settings.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/invalid-root.ts", "retrieved_chunk": " });\n new Setting(this.contentEl).addButton((button) => {\n button\n .setButtonText(\"Create\")\n .setCta()\n .onClick(async () => {\n await this.dendronVault.createRootFolder();\n this.dendronVault.init();\n this.close();\n });", "score": 0.8815308809280396 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " )\n this.nameText.setValue(this.generateName(newFolder));\n this.folder = newFolder;\n });\n });\n new Setting(this.contentEl).setName(\"Vault Name\").addText((text) => {\n this.nameText = text;\n });\n new Setting(this.contentEl).addButton((btn) => {\n btn", "score": 0.8548528552055359 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " await doCreate(this.workspace.vaultList[0]);\n } else {\n new SelectVaultModal(this.app, this.workspace, doCreate).open();\n }\n }\n}", "score": 0.8176596164703369 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " return name;\n }\n onOpen(): void {\n new Setting(this.contentEl).setHeading().setName(\"Add Vault\");\n new Setting(this.contentEl).setName(\"Vault Path\").addText((text) => {\n new FolderSuggester(this.app, text.inputEl, (newFolder) => {\n const currentName = this.nameText.getValue();\n if (\n currentName.length === 0 ||\n (this.folder && currentName === this.generateName(this.folder))", "score": 0.8110578060150146 }, { "filename": "src/main.ts", "retrieved_chunk": " menu.addItem((item) => {\n item\n .setIcon(dendronActivityBarName)\n .setTitle(\"Reveal in Dendron Tree\")\n .onClick(() => this.revealFile(file));\n });\n };\n onResolveMetadata = (file: TFile) => {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (vault && vault.onMetadataChanged(file)) {", "score": 0.7938699722290039 } ]
typescript
.app, (config) => {
import { Menu, Plugin, TAbstractFile, TFile, addIcon } from "obsidian"; import { DendronView, VIEW_TYPE_DENDRON } from "./view"; import { activeFile, dendronVaultList } from "./store"; import { LookupModal } from "./modal/lookup"; import { dendronActivityBarIcon, dendronActivityBarName } from "./icons"; import { DEFAULT_SETTINGS, DendronTreePluginSettings, DendronTreeSettingTab } from "./settings"; import { parsePath } from "./path"; import { DendronWorkspace } from "./engine/workspace"; import { CustomResolver } from "./custom-resolver"; export default class DendronTreePlugin extends Plugin { settings: DendronTreePluginSettings; workspace: DendronWorkspace = new DendronWorkspace(this.app); customResolver?: CustomResolver; async onload() { await this.loadSettings(); await this.migrateSettings(); addIcon(dendronActivityBarName, dendronActivityBarIcon); this.addCommand({ id: "dendron-lookup", name: "Lookup Note", callback: () => { new LookupModal(this.app, this.workspace).open(); }, }); this.addSettingTab(new DendronTreeSettingTab(this.app, this)); this.registerView(VIEW_TYPE_DENDRON, (leaf) => new DendronView(leaf, this)); this.addRibbonIcon(dendronActivityBarName, "Open Dendron Tree", () => { this.activateView(); }); this.app.workspace.onLayoutReady(() => { this.onRootFolderChanged(); this.registerEvent(this.app.vault.on("create", this.onCreateFile)); this.registerEvent(this.app.vault.on("delete", this.onDeleteFile)); this.registerEvent(this.app.vault.on("rename", this.onRenameFile)); this.registerEvent(this.app.metadataCache.on("resolve", this.onResolveMetadata)); this.registerEvent(this.app.workspace.on("file-open", this.onOpenFile, this)); this.registerEvent(this.app.workspace.on("file-menu", this.onFileMenu)); }); this.configureCustomResolver(); } async migrateSettings() { function pathToVaultConfig(path: string) { const { name } = parsePath(path); if (name.length === 0) return { name: "root", path: "/", }; let processed = path; if (processed.endsWith("/")) processed = processed.slice(0, -1); if (processed.startsWith("/") && processed.length > 1) processed = processed.slice(1); return { name, path: processed, }; } if (this.settings.vaultPath) { this.settings.vaultList = [pathToVaultConfig(this.settings.vaultPath)]; this.settings.vaultPath = undefined; await this.saveSettings(); } if (this.settings.vaultList.length > 0 && typeof this.settings.vaultList[0] === "string") { this.settings.vaultList = (this.settings.vaultList as unknown as string[]).map((path) => pathToVaultConfig(path) ); await this.saveSettings(); } } onunload() {} onRootFolderChanged() { this.workspace.changeVault(this.settings.vaultList); this.updateNoteStore(); } configureCustomResolver() { if (this.settings.customResolver && !this.customResolver) { this.customResolver = new CustomResolver(this, this.workspace); this.addChild(this.customResolver); } else if (!this.settings.customResolver && this.customResolver) { this.removeChild(this.customResolver); this.customResolver = undefined; } } updateNoteStore() { dendronVaultList.set(this.workspace.vaultList); } onCreateFile = async (file: TAbstractFile) => { const vault = this.workspace.findVaultByParent(file.parent); if (vault && vault.onFileCreated(file)) { if (this.settings.autoGenerateFrontmatter && file instanceof TFile && file.stat.size === 0) await vault.generateFronmatter(file); this.updateNoteStore(); } }; onDeleteFile = (file: TAbstractFile) => { // file.parent is null when file is deleted const parsed = parsePath(file.path); const vault = this.workspace.findVaultByParentPath(parsed.dir); if (vault && vault.onFileDeleted(parsed)) { this.updateNoteStore(); } }; onRenameFile = (file: TAbstractFile, oldPath: string) => { const oldParsed = parsePath(oldPath); const oldVault = this.workspace.findVaultByParentPath(oldParsed.dir); let update = false; if (oldVault) { update = oldVault.onFileDeleted(oldParsed); } const newVault = this.workspace.findVaultByParent(file.parent); if (newVault) { update = newVault.onFileCreated(file) || update; } if (update) this.updateNoteStore(); }; onOpenFile(file: TFile | null) { activeFile.set(file); if (file && this.settings.autoReveal) this.revealFile(file); } onFileMenu = (menu: Menu, file: TAbstractFile) => { if (!(file instanceof TFile)) return; menu.addItem((item) => { item .setIcon(dendronActivityBarName) .setTitle("Reveal in Dendron Tree") .onClick(() => this.revealFile(file)); }); }; onResolveMetadata = (file: TFile) => { const vault = this.workspace.findVaultByParent(file.parent); if (vault && vault.onMetadataChanged(file)) { this.updateNoteStore(); } }; revealFile(file: TFile) { const vault = this.workspace.findVaultByParent(file.parent); if (!vault) return; const note = vault.tree.getFromFileName(file.basename); if (!note) return; for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON)) { if (!(leaf.view instanceof DendronView)) continue; leaf.view.component.focusTo(vault, note); } } async activateView() { const leafs = this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON); if (leafs.length == 0) { const leaf = this.app.workspace.getLeftLeaf(false); await leaf.setViewState({ type: VIEW_TYPE_DENDRON, active: true, }); this.app.workspace.revealLeaf(leaf); } else { leafs.forEach((leaf) => this.app.workspace.revealLeaf(leaf)); } } async loadSettings() { this
.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
} async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/settings.ts", "retrieved_chunk": " list.push(config);\n this.plugin.saveSettings().then(() => this.display());\n return true;\n }).open();\n });\n });\n }\n hide() {\n super.hide();\n this.plugin.onRootFolderChanged();", "score": 0.7748672962188721 }, { "filename": "src/settings.ts", "retrieved_chunk": " this.plugin.settings.autoGenerateFrontmatter = value;\n await this.plugin.saveSettings();\n });\n });\n new Setting(containerEl)\n .setName(\"Auto Reveal\")\n .setDesc(\"Automatically reveal active file in Dendron Tree\")\n .addToggle((toggle) => {\n toggle.setValue(this.plugin.settings.autoReveal).onChange(async (value) => {\n this.plugin.settings.autoReveal = value;", "score": 0.7664018869400024 }, { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " onload(): void {\n super.onload();\n this.registerEvent(\n this.app.metadataCache.on(\"changed\", async (file, data) => {\n if (file === this.file) {\n this.loadFile();\n }\n })\n );\n }", "score": 0.7636268138885498 }, { "filename": "src/settings.ts", "retrieved_chunk": " btn.setButtonText(\"Remove\").onClick(async () => {\n this.plugin.settings.vaultList.remove(vault);\n await this.plugin.saveSettings();\n this.display();\n });\n });\n }\n new Setting(containerEl).addButton((btn) => {\n btn.setButtonText(\"Add Vault\").onClick(() => {\n new AddVaultModal(this.app, (config) => {", "score": 0.7544548511505127 }, { "filename": "src/settings.ts", "retrieved_chunk": " this.plugin.settings.customResolver = value;\n await this.plugin.saveSettings();\n });\n });\n new Setting(containerEl).setName(\"Vault List\").setHeading();\n for (const vault of this.plugin.settings.vaultList) {\n new Setting(containerEl)\n .setName(vault.name)\n .setDesc(`Folder: ${vault.path}`)\n .addButton((btn) => {", "score": 0.7519611120223999 } ]
typescript
.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
import { Menu, Plugin, TAbstractFile, TFile, addIcon } from "obsidian"; import { DendronView, VIEW_TYPE_DENDRON } from "./view"; import { activeFile, dendronVaultList } from "./store"; import { LookupModal } from "./modal/lookup"; import { dendronActivityBarIcon, dendronActivityBarName } from "./icons"; import { DEFAULT_SETTINGS, DendronTreePluginSettings, DendronTreeSettingTab } from "./settings"; import { parsePath } from "./path"; import { DendronWorkspace } from "./engine/workspace"; import { CustomResolver } from "./custom-resolver"; export default class DendronTreePlugin extends Plugin { settings: DendronTreePluginSettings; workspace: DendronWorkspace = new DendronWorkspace(this.app); customResolver?: CustomResolver; async onload() { await this.loadSettings(); await this.migrateSettings(); addIcon(dendronActivityBarName, dendronActivityBarIcon); this.addCommand({ id: "dendron-lookup", name: "Lookup Note", callback: () => { new LookupModal(this.app, this.workspace).open(); }, }); this.addSettingTab(new DendronTreeSettingTab(this.app, this)); this.registerView(VIEW_TYPE_DENDRON, (leaf) => new DendronView(leaf, this)); this.addRibbonIcon(dendronActivityBarName, "Open Dendron Tree", () => { this.activateView(); }); this.app.workspace.onLayoutReady(() => { this.onRootFolderChanged(); this.registerEvent(this.app.vault.on("create", this.onCreateFile)); this.registerEvent(this.app.vault.on("delete", this.onDeleteFile)); this.registerEvent(this.app.vault.on("rename", this.onRenameFile)); this.registerEvent(this.app.metadataCache.on("resolve", this.onResolveMetadata)); this.registerEvent(this.app.workspace.on("file-open", this.onOpenFile, this)); this.registerEvent(this.app.workspace.on("file-menu", this.onFileMenu)); }); this.configureCustomResolver(); } async migrateSettings() { function pathToVaultConfig(path: string) {
const { name } = parsePath(path);
if (name.length === 0) return { name: "root", path: "/", }; let processed = path; if (processed.endsWith("/")) processed = processed.slice(0, -1); if (processed.startsWith("/") && processed.length > 1) processed = processed.slice(1); return { name, path: processed, }; } if (this.settings.vaultPath) { this.settings.vaultList = [pathToVaultConfig(this.settings.vaultPath)]; this.settings.vaultPath = undefined; await this.saveSettings(); } if (this.settings.vaultList.length > 0 && typeof this.settings.vaultList[0] === "string") { this.settings.vaultList = (this.settings.vaultList as unknown as string[]).map((path) => pathToVaultConfig(path) ); await this.saveSettings(); } } onunload() {} onRootFolderChanged() { this.workspace.changeVault(this.settings.vaultList); this.updateNoteStore(); } configureCustomResolver() { if (this.settings.customResolver && !this.customResolver) { this.customResolver = new CustomResolver(this, this.workspace); this.addChild(this.customResolver); } else if (!this.settings.customResolver && this.customResolver) { this.removeChild(this.customResolver); this.customResolver = undefined; } } updateNoteStore() { dendronVaultList.set(this.workspace.vaultList); } onCreateFile = async (file: TAbstractFile) => { const vault = this.workspace.findVaultByParent(file.parent); if (vault && vault.onFileCreated(file)) { if (this.settings.autoGenerateFrontmatter && file instanceof TFile && file.stat.size === 0) await vault.generateFronmatter(file); this.updateNoteStore(); } }; onDeleteFile = (file: TAbstractFile) => { // file.parent is null when file is deleted const parsed = parsePath(file.path); const vault = this.workspace.findVaultByParentPath(parsed.dir); if (vault && vault.onFileDeleted(parsed)) { this.updateNoteStore(); } }; onRenameFile = (file: TAbstractFile, oldPath: string) => { const oldParsed = parsePath(oldPath); const oldVault = this.workspace.findVaultByParentPath(oldParsed.dir); let update = false; if (oldVault) { update = oldVault.onFileDeleted(oldParsed); } const newVault = this.workspace.findVaultByParent(file.parent); if (newVault) { update = newVault.onFileCreated(file) || update; } if (update) this.updateNoteStore(); }; onOpenFile(file: TFile | null) { activeFile.set(file); if (file && this.settings.autoReveal) this.revealFile(file); } onFileMenu = (menu: Menu, file: TAbstractFile) => { if (!(file instanceof TFile)) return; menu.addItem((item) => { item .setIcon(dendronActivityBarName) .setTitle("Reveal in Dendron Tree") .onClick(() => this.revealFile(file)); }); }; onResolveMetadata = (file: TFile) => { const vault = this.workspace.findVaultByParent(file.parent); if (vault && vault.onMetadataChanged(file)) { this.updateNoteStore(); } }; revealFile(file: TFile) { const vault = this.workspace.findVaultByParent(file.parent); if (!vault) return; const note = vault.tree.getFromFileName(file.basename); if (!note) return; for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON)) { if (!(leaf.view instanceof DendronView)) continue; leaf.view.component.focusTo(vault, note); } } async activateView() { const leafs = this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON); if (leafs.length == 0) { const leaf = this.app.workspace.getLeftLeaf(false); await leaf.setViewState({ type: VIEW_TYPE_DENDRON, active: true, }); this.app.workspace.revealLeaf(leaf); } else { leafs.forEach((leaf) => this.app.workspace.revealLeaf(leaf)); } } async loadSettings() { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); } async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/custom-resolver/index.ts", "retrieved_chunk": " constructor(public plugin: Plugin, public workspace: DendronWorkspace) {\n super();\n }\n onload(): void {\n this.plugin.app.workspace.onLayoutReady(() => {\n this.plugin.app.workspace.registerEditorExtension(this.refEditorExtenstion);\n this.plugin.app.workspace.registerEditorExtension(this.linkEditorExtenstion);\n this.plugin.app.workspace.registerEditorExtension(this.linkRefClickbaleExtension);\n this.pagePreviewPlugin = this.plugin.app.internalPlugins.getEnabledPluginById(\"page-preview\");\n if (!this.pagePreviewPlugin) return;", "score": 0.7552188634872437 }, { "filename": "src/settings.ts", "retrieved_chunk": " btn.setButtonText(\"Remove\").onClick(async () => {\n this.plugin.settings.vaultList.remove(vault);\n await this.plugin.saveSettings();\n this.display();\n });\n });\n }\n new Setting(containerEl).addButton((btn) => {\n btn.setButtonText(\"Add Vault\").onClick(() => {\n new AddVaultModal(this.app, (config) => {", "score": 0.7488937377929688 }, { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " onload(): void {\n super.onload();\n this.registerEvent(\n this.app.metadataCache.on(\"changed\", async (file, data) => {\n if (file === this.file) {\n this.loadFile();\n }\n })\n );\n }", "score": 0.7393367290496826 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " for (const child of root.children)\n if (child instanceof TFile && this.isNote(child.extension))\n this.tree.addFile(child).syncMetadata(this.resolveMetadata(child));\n this.tree.sort();\n this.isIniatialized = true;\n }\n async createRootFolder() {\n return await this.app.vault.createFolder(this.config.path);\n }\n async createNote(baseName: string) {", "score": 0.7373360395431519 }, { "filename": "src/settings.ts", "retrieved_chunk": " this.plugin.settings.customResolver = value;\n await this.plugin.saveSettings();\n });\n });\n new Setting(containerEl).setName(\"Vault List\").setHeading();\n for (const vault of this.plugin.settings.vaultList) {\n new Setting(containerEl)\n .setName(vault.name)\n .setDesc(`Folder: ${vault.path}`)\n .addButton((btn) => {", "score": 0.7373006939888 } ]
typescript
const { name } = parsePath(path);
import { App, Notice, PluginSettingTab, Setting } from "obsidian"; import DendronTreePlugin from "./main"; import { VaultConfig } from "./engine/vault"; import { AddVaultModal } from "./modal/add-vault"; export interface DendronTreePluginSettings { /** * @deprecated use vaultList */ vaultPath?: string; vaultList: VaultConfig[]; autoGenerateFrontmatter: boolean; autoReveal: boolean; customResolver: boolean; } export const DEFAULT_SETTINGS: DendronTreePluginSettings = { vaultList: [ { name: "root", path: "/", }, ], autoGenerateFrontmatter: true, autoReveal: true, customResolver: false, }; export class DendronTreeSettingTab extends PluginSettingTab { plugin: DendronTreePlugin; constructor(app: App, plugin: DendronTreePlugin) { super(app, plugin); this.plugin = plugin; } display(): void { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h2", { text: "Dendron Tree Settting" }); new Setting(containerEl) .setName("Auto Generate Front Matter") .setDesc("Generate front matter for new file even if file is created outside of Dendron tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoGenerateFrontmatter).onChange(async (value) => { this.plugin.settings.autoGenerateFrontmatter = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Auto Reveal") .setDesc("Automatically reveal active file in Dendron Tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoReveal).onChange(async (value) => { this.plugin.settings.autoReveal = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Custom Resolver") .setDesc( "Use custom resolver to resolve ref/embed and link. (Please reopen editor after change this setting)" ) .addToggle((toggle) => { toggle.setValue(this.plugin.settings.customResolver).onChange(async (value) => { this.plugin.settings.customResolver = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl).setName("Vault List").setHeading(); for (const vault of this.plugin.settings.vaultList) { new Setting(containerEl) .setName(vault.name) .setDesc(`Folder: ${vault.path}`) .addButton((btn) => { btn.setButtonText("Remove").onClick(async () => { this.plugin.settings.vaultList.remove(vault); await this.plugin.saveSettings(); this.display(); }); }); } new Setting(containerEl).addButton((btn) => { btn.setButtonText("Add Vault").onClick(() => { new AddVaultModal(this.app, (config) => { const list = this.plugin.settings.vaultList; const nameLowecase = config.name.toLowerCase();
if (list.find(({ name }) => name.toLowerCase() === nameLowecase)) {
new Notice("Vault with same name already exist"); return false; } if (list.find(({ path }) => path === config.path)) { new Notice("Vault with same path already exist"); return false; } list.push(config); this.plugin.saveSettings().then(() => this.display()); return true; }).open(); }); }); } hide() { super.hide(); this.plugin.onRootFolderChanged(); this.plugin.configureCustomResolver(); } }
src/settings.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " return name;\n }\n onOpen(): void {\n new Setting(this.contentEl).setHeading().setName(\"Add Vault\");\n new Setting(this.contentEl).setName(\"Vault Path\").addText((text) => {\n new FolderSuggester(this.app, text.inputEl, (newFolder) => {\n const currentName = this.nameText.getValue();\n if (\n currentName.length === 0 ||\n (this.folder && currentName === this.generateName(this.folder))", "score": 0.8445751667022705 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " .setCta()\n .setButtonText(\"Add Text\")\n .onClick(() => {\n const name = this.nameText.getValue();\n if (!this.folder || name.trim().length === 0) {\n new Notice(\"Please specify Vault Path and Vault Name\");\n return;\n }\n if (\n this.onSubmit({", "score": 0.8364614248275757 }, { "filename": "src/modal/invalid-root.ts", "retrieved_chunk": " });\n new Setting(this.contentEl).addButton((button) => {\n button\n .setButtonText(\"Create\")\n .setCta()\n .onClick(async () => {\n await this.dendronVault.createRootFolder();\n this.dendronVault.init();\n this.close();\n });", "score": 0.828825831413269 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " )\n this.nameText.setValue(this.generateName(newFolder));\n this.folder = newFolder;\n });\n });\n new Setting(this.contentEl).setName(\"Vault Name\").addText((text) => {\n this.nameText = text;\n });\n new Setting(this.contentEl).addButton((btn) => {\n btn", "score": 0.8254209160804749 }, { "filename": "src/main.ts", "retrieved_chunk": " menu.addItem((item) => {\n item\n .setIcon(dendronActivityBarName)\n .setTitle(\"Reveal in Dendron Tree\")\n .onClick(() => this.revealFile(file));\n });\n };\n onResolveMetadata = (file: TFile) => {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (vault && vault.onMetadataChanged(file)) {", "score": 0.808326780796051 } ]
typescript
if (list.find(({ name }) => name.toLowerCase() === nameLowecase)) {
import { EditorView, PluginValue, ViewUpdate } from "@codemirror/view"; import { App, Component, editorLivePreviewField } from "obsidian"; import { NoteRefRenderChild, createRefRenderer } from "./ref-render"; import { DendronWorkspace } from "../engine/workspace"; interface InternalEmbedWidget { end: number; href: string; sourcePath: string; start: string; title: string; children: Component[]; containerEl: HTMLElement; hacked?: boolean; initDOM(): HTMLElement; addChild(c: Component): void; applyTitle(container: HTMLElement, title: string): void; } export class RefLivePlugin implements PluginValue { constructor(public app: App, public workspace: DendronWorkspace) {} update(update: ViewUpdate) { if (!update.state.field(editorLivePreviewField)) { return; } update.view.state.facet(EditorView.decorations).forEach((d) => { if (typeof d !== "function") { const iter = d.iter(); while (iter.value) { const widget = iter.value.spec.widget; if (widget && widget.href && widget.sourcePath && widget.title) { const internalWidget = widget as InternalEmbedWidget; this.hack(internalWidget); } iter.next(); } } }); } hack(widget: InternalEmbedWidget) { if (widget.hacked) { return; } widget.hacked = true; const target = this.workspace.resolveRef(widget.sourcePath, widget.href); if (!target || target.type !== "maybe-note") return; const loadComponent = (widget: InternalEmbedWidget) => {
const renderer = createRefRenderer(target, this.app, widget.containerEl);
if (renderer instanceof NoteRefRenderChild) renderer.loadFile(); widget.addChild(renderer); }; widget.initDOM = function (this: InternalEmbedWidget) { this.containerEl = createDiv("internal-embed"); loadComponent(this); return this.containerEl; }; widget.applyTitle = function ( this: InternalEmbedWidget, container: HTMLElement, title: string ) { this.title = title; }; if (widget.containerEl) { console.log("Workaround"); widget.children[0].unload(); widget.children.pop(); loadComponent(widget); } } }
src/custom-resolver/ref-live.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/custom-resolver/ref-markdown-processor.ts", "retrieved_chunk": " embeddedItems.forEach((el) => {\n const link = el.getAttribute(\"src\");\n if (!link) return;\n const target = workspace.resolveRef(context.sourcePath, link);\n if (!target || target.type !== \"maybe-note\") return;\n const renderer = createRefRenderer(target, app, el as HTMLElement);\n if (renderer instanceof NoteRefRenderChild) promises.push(renderer.loadFile());\n context.addChild(renderer);\n });\n return Promise.all(promises);", "score": 0.857369601726532 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " widget.updateTitle();\n this.widgets.splice(lastWidgetIndex, 1);\n return widget;\n }\n return new LinkWidget(this.app, this.workspace, sourcePath, link.href, link.title);\n }\n buildDecorations(view: EditorView): DecorationSet {\n if (!view.state.field(editorLivePreviewField)) {\n return Decoration.none;\n }", "score": 0.811875581741333 }, { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " content.setText(`\"${target.path}\" is not created yet. Click to create.`);\n this.containerEl.onclick = () => {\n vault.createNote(path).then((file) => openFile(app, file));\n };\n }\n}\nexport function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) {\n if (!target.note || !target.note.file) {\n return new UnresolvedRefRenderChild(app, container, target);\n } else {", "score": 0.8107233047485352 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " if (found) break;\n }\n }\n getWidget(link: LinkData, sourcePath: string) {\n const lastWidgetIndex = this.widgets.findIndex(\n (widget) => widget.href === link.href && widget.sourcePath === sourcePath\n );\n if (lastWidgetIndex >= 0) {\n const widget = this.widgets[lastWidgetIndex];\n widget.title = link.title;", "score": 0.8013375401496887 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " this.app.workspace.openLinkText(this.href, this.sourcePath);\n });\n }\n updateTitle() {\n this.containerEl.children[0].setText(\n renderLinkTitle(this.app, this.workspace, this.href, this.title, this.sourcePath)\n );\n }\n toDOM(view: EditorView): HTMLElement {\n if (!this.containerEl) this.initDOM();", "score": 0.7920998334884644 } ]
typescript
const renderer = createRefRenderer(target, this.app, widget.containerEl);
import { App, Notice, PluginSettingTab, Setting } from "obsidian"; import DendronTreePlugin from "./main"; import { VaultConfig } from "./engine/vault"; import { AddVaultModal } from "./modal/add-vault"; export interface DendronTreePluginSettings { /** * @deprecated use vaultList */ vaultPath?: string; vaultList: VaultConfig[]; autoGenerateFrontmatter: boolean; autoReveal: boolean; customResolver: boolean; } export const DEFAULT_SETTINGS: DendronTreePluginSettings = { vaultList: [ { name: "root", path: "/", }, ], autoGenerateFrontmatter: true, autoReveal: true, customResolver: false, }; export class DendronTreeSettingTab extends PluginSettingTab { plugin: DendronTreePlugin; constructor(app: App, plugin: DendronTreePlugin) { super(app, plugin); this.plugin = plugin; } display(): void { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h2", { text: "Dendron Tree Settting" }); new Setting(containerEl) .setName("Auto Generate Front Matter") .setDesc("Generate front matter for new file even if file is created outside of Dendron tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoGenerateFrontmatter).onChange(async (value) => { this.plugin.settings.autoGenerateFrontmatter = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Auto Reveal") .setDesc("Automatically reveal active file in Dendron Tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoReveal).onChange(async (value) => { this.plugin.settings.autoReveal = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Custom Resolver") .setDesc( "Use custom resolver to resolve ref/embed and link. (Please reopen editor after change this setting)" ) .addToggle((toggle) => { toggle.setValue(this.plugin.settings.customResolver).onChange(async (value) => { this.plugin.settings.customResolver = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl).setName("Vault List").setHeading(); for (const vault of this.plugin.settings.vaultList) { new Setting(containerEl) .setName(vault.name) .setDesc(`Folder: ${vault.path}`) .addButton((btn) => { btn.setButtonText("Remove").onClick(async () => { this.plugin.settings.vaultList.remove(vault); await this.plugin.saveSettings(); this.display(); }); }); } new Setting(containerEl).addButton((btn) => { btn.setButtonText("Add Vault").onClick(() => { new
AddVaultModal(this.app, (config) => {
const list = this.plugin.settings.vaultList; const nameLowecase = config.name.toLowerCase(); if (list.find(({ name }) => name.toLowerCase() === nameLowecase)) { new Notice("Vault with same name already exist"); return false; } if (list.find(({ path }) => path === config.path)) { new Notice("Vault with same path already exist"); return false; } list.push(config); this.plugin.saveSettings().then(() => this.display()); return true; }).open(); }); }); } hide() { super.hide(); this.plugin.onRootFolderChanged(); this.plugin.configureCustomResolver(); } }
src/settings.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/invalid-root.ts", "retrieved_chunk": " });\n new Setting(this.contentEl).addButton((button) => {\n button\n .setButtonText(\"Create\")\n .setCta()\n .onClick(async () => {\n await this.dendronVault.createRootFolder();\n this.dendronVault.init();\n this.close();\n });", "score": 0.8814990520477295 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " )\n this.nameText.setValue(this.generateName(newFolder));\n this.folder = newFolder;\n });\n });\n new Setting(this.contentEl).setName(\"Vault Name\").addText((text) => {\n this.nameText = text;\n });\n new Setting(this.contentEl).addButton((btn) => {\n btn", "score": 0.8562177419662476 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " await doCreate(this.workspace.vaultList[0]);\n } else {\n new SelectVaultModal(this.app, this.workspace, doCreate).open();\n }\n }\n}", "score": 0.8159254193305969 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " return name;\n }\n onOpen(): void {\n new Setting(this.contentEl).setHeading().setName(\"Add Vault\");\n new Setting(this.contentEl).setName(\"Vault Path\").addText((text) => {\n new FolderSuggester(this.app, text.inputEl, (newFolder) => {\n const currentName = this.nameText.getValue();\n if (\n currentName.length === 0 ||\n (this.folder && currentName === this.generateName(this.folder))", "score": 0.8088521957397461 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " .setCta()\n .setButtonText(\"Add Text\")\n .onClick(() => {\n const name = this.nameText.getValue();\n if (!this.folder || name.trim().length === 0) {\n new Notice(\"Please specify Vault Path and Vault Name\");\n return;\n }\n if (\n this.onSubmit({", "score": 0.7914694547653198 } ]
typescript
AddVaultModal(this.app, (config) => {
import { App, Notice, PluginSettingTab, Setting } from "obsidian"; import DendronTreePlugin from "./main"; import { VaultConfig } from "./engine/vault"; import { AddVaultModal } from "./modal/add-vault"; export interface DendronTreePluginSettings { /** * @deprecated use vaultList */ vaultPath?: string; vaultList: VaultConfig[]; autoGenerateFrontmatter: boolean; autoReveal: boolean; customResolver: boolean; } export const DEFAULT_SETTINGS: DendronTreePluginSettings = { vaultList: [ { name: "root", path: "/", }, ], autoGenerateFrontmatter: true, autoReveal: true, customResolver: false, }; export class DendronTreeSettingTab extends PluginSettingTab { plugin: DendronTreePlugin; constructor(app: App, plugin: DendronTreePlugin) { super(app, plugin); this.plugin = plugin; } display(): void { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h2", { text: "Dendron Tree Settting" }); new Setting(containerEl) .setName("Auto Generate Front Matter") .setDesc("Generate front matter for new file even if file is created outside of Dendron tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoGenerateFrontmatter).onChange(async (value) => { this.plugin.settings.autoGenerateFrontmatter = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Auto Reveal") .setDesc("Automatically reveal active file in Dendron Tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoReveal).onChange(async (value) => { this.plugin.settings.autoReveal = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Custom Resolver") .setDesc( "Use custom resolver to resolve ref/embed and link. (Please reopen editor after change this setting)" ) .addToggle((toggle) => { toggle.setValue(this.plugin.settings.customResolver).onChange(async (value) => { this.plugin.settings.customResolver = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl).setName("Vault List").setHeading(); for (const vault of this.plugin.settings.vaultList) { new Setting(containerEl) .setName(vault.name) .setDesc(`Folder: ${vault.path}`) .addButton((btn) => { btn.setButtonText("Remove").onClick(async () => { this.plugin.settings.vaultList.remove(vault); await this.plugin.saveSettings(); this.display(); }); }); } new Setting(containerEl).addButton((btn) => { btn.setButtonText("Add Vault").onClick(() => { new AddVaultModal(this.app, (config) => { const list = this.plugin.settings.vaultList; const nameLowecase = config.name.toLowerCase(); if (list.find(({ name }) => name.toLowerCase() === nameLowecase)) { new Notice("Vault with same name already exist"); return false; } if (list
.find(({ path }) => path === config.path)) {
new Notice("Vault with same path already exist"); return false; } list.push(config); this.plugin.saveSettings().then(() => this.display()); return true; }).open(); }); }); } hide() { super.hide(); this.plugin.onRootFolderChanged(); this.plugin.configureCustomResolver(); } }
src/settings.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " .setCta()\n .setButtonText(\"Add Text\")\n .onClick(() => {\n const name = this.nameText.getValue();\n if (!this.folder || name.trim().length === 0) {\n new Notice(\"Please specify Vault Path and Vault Name\");\n return;\n }\n if (\n this.onSubmit({", "score": 0.8686385750770569 }, { "filename": "src/engine/workspace.ts", "retrieved_chunk": " this.vaultList = vaultList.map((config) => {\n return (\n this.vaultList.find(\n (vault) => vault.config.name === config.name && vault.config.path === config.path\n ) ?? new DendronVault(this.app, config)\n );\n });\n for (const vault of this.vaultList) {\n vault.init();\n }", "score": 0.8396132588386536 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 0.8213456273078918 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " return name;\n }\n onOpen(): void {\n new Setting(this.contentEl).setHeading().setName(\"Add Vault\");\n new Setting(this.contentEl).setName(\"Vault Path\").addText((text) => {\n new FolderSuggester(this.app, text.inputEl, (newFolder) => {\n const currentName = this.nameText.getValue();\n if (\n currentName.length === 0 ||\n (this.folder && currentName === this.generateName(this.folder))", "score": 0.8126714825630188 }, { "filename": "src/modal/select-vault.ts", "retrieved_chunk": " }\n getSuggestions(query: string): DendronVault[] | Promise<DendronVault[]> {\n const queryLowercase = query.toLowerCase();\n return this.workspace.vaultList.filter(\n (value) =>\n value.config.path.toLowerCase().contains(queryLowercase) ||\n value.config.name.toLowerCase().contains(queryLowercase)\n );\n }\n renderSuggestion(value: DendronVault, el: HTMLElement) {", "score": 0.811887264251709 } ]
typescript
.find(({ path }) => path === config.path)) {
import type { Stat, TFile, Vault } from "obsidian"; import { Note, NoteTree, generateNoteTitle, isUseTitleCase } from "./note"; import { parsePath } from "../path"; describe("note title", () => { it("use title case when file name is lowercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("aku.cinta.kamu-milikku.md"))).toBe( "Kamu Milikku" ); }); it("use file name when note name contain uppercase", () => { expect(generateNoteTitle("Kamu-Milikku", isUseTitleCase("aku.cinta.Kamu-Milikku.md"))).toBe( "Kamu-Milikku" ); }); it("use file name when file name contain uppercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("Aku.cinta.kamu-milikku.md"))).toBe( "kamu-milikku" ); }); }); describe("note class", () => { it("append and remove child work", () => { const child = new Note("lala", true); expect(child.parent).toBeUndefined(); const parent = new Note("apa", true); expect(parent.children).toEqual([]); parent.appendChild(child); expect(child.parent).toBe(parent); expect(parent.children).toEqual([child]); parent.removeChildren(child); expect(child.parent).toBeUndefined(); expect(parent.children).toEqual([]); }); it("append child must throw if child already has parent", () => { const origParent = new Note("root", true); const parent = new Note("root2", true); const child = new Note("child", true); origParent.appendChild(child); expect(() => parent.appendChild(child)).toThrowError("has parent"); }); it("find children work", () => { const parent = new Note("parent", true); const child1 = new Note("child1", true); const child2 = new Note("child2", true); const child3 = new Note("child3", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.findChildren("child1")).toBe(child1); expect(parent.findChildren("child2")).toBe(child2); expect(parent.findChildren("child3")).toBe(child3); expect(parent.findChildren("child4")).toBeUndefined(); }); it("non-recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("gajak", true); const child2 = new Note("lumba", true); const child3 = new Note("biawak", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.children).toEqual([child1, child2, child3]); parent.sortChildren(false); expect(parent.children).toEqual([child3, child1, child2]); }); it("recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("lumba", true); const child2 = new Note("galak", true); const grandchild1 = new Note("lupa", true); const grandchild2 = new Note("apa", true); const grandchild3 = new Note("abu", true); const grandchild4 = new Note("lagi", true); parent.appendChild(child1); child1.appendChild(grandchild1); child1.appendChild(grandchild2); parent.appendChild(child2); child2.appendChild(grandchild3); child2.appendChild(grandchild4); expect(parent.children).toEqual([child1, child2]); expect(child1.children).toEqual([grandchild1, grandchild2]); expect(child2.children).toEqual([grandchild3, grandchild4]); parent.sortChildren(true); expect(parent.children).toEqual([child2, child1]); expect(child1.children).toEqual([grandchild2, grandchild1]); expect(child2.children).toEqual([grandchild3, grandchild4]); }); it("get path on non-root", () => { const root = new Note("root", true); const ch1 = new Note("parent", true); const ch2 = new Note("parent2", true); const ch3 = new Note("child", true); root.appendChild(ch1); ch1.appendChild(ch2); ch2.appendChild(ch3); expect(ch3.getPath()).toBe("parent.parent2.child"); expect(ch3.getPathNotes()).toEqual([root, ch1, ch2, ch3]); }); it("get path on root", () => { const root = new Note("root", true); expect(root.getPath()).toBe("root"); expect(root.getPathNotes()).toEqual([root]); }); it("use generated title when titlecase true", () => { const note = new Note("aku-cinta", true); expect(note.title).toBe("Aku Cinta"); }); it("use filename as title when titlecase false", () => { const note = new Note("aKu-ciNta", false); expect(note.title).toBe("aKu-ciNta"); }); it("use metadata title when has metadata", () => { const note = new Note("aKu-ciNta", false); note.syncMetadata({ title: "Butuh Kamu", }); expect(note.title).toBe("Butuh Kamu"); }); }); function createTFile(path: string): TFile { const { basename, name, extension } = parsePath(path); return { basename, extension, name, parent: null, path: path, stat: null as unknown as Stat, vault: null as unknown as Vault, }; } describe("tree class", () => { it("add file without sort", () => {
const tree = new NoteTree();
tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.root.children.length).toBe(1); expect(tree.root.children[0].name).toBe("abc"); expect(tree.root.children[0].children.length).toBe(1); expect(tree.root.children[0].children[0].name).toBe("def"); expect(tree.root.children[0].children[0].children.length).toBe(2); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); }); it("add file with sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md"), true); tree.addFile(createTFile("abc.def.ghi.md"), true); tree.addFile(createTFile("abc.def.mno.md"), true); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("get note by file base name", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("abc.def.jkl")?.name).toBe("jkl"); expect(tree.getFromFileName("abc.def.ghi")?.name).toBe("ghi"); expect(tree.getFromFileName("abc.def.mno")).toBeUndefined(); }); it("get note using blank path", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("")).toBeUndefined() }) it("delete note if do not have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")).toBeUndefined(); }); it("do not delete note if have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.addFile(createTFile("abc.def.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")?.name).toBe("abc"); expect(tree.getFromFileName("abc.def")?.name).toBe("def"); }); it("delete note and parent if do not have children and parent file is null", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc")); tree.addFile(createTFile("abc.def.ghi.md")); tree.deleteByFileName("abc.def.ghi"); expect(tree.getFromFileName("abc.def.ghi")).toBeUndefined(); expect(tree.getFromFileName("abc.def")).toBeUndefined(); expect(tree.getFromFileName("abc")?.name).toBe("abc"); }); it("sort note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.def.mno.md")); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); tree.sort(); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("flatten note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.jkl.mno.md")); expect(tree.flatten().map((note) => note.getPath())).toEqual([ "root", "abc", "abc.def", "abc.def.ghi", "abc.jkl", "abc.jkl.mno", ]); }); });
src/engine/note.test.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/settings.ts", "retrieved_chunk": " autoGenerateFrontmatter: boolean;\n autoReveal: boolean;\n customResolver: boolean;\n}\nexport const DEFAULT_SETTINGS: DendronTreePluginSettings = {\n vaultList: [\n {\n name: \"root\",\n path: \"/\",\n },", "score": 0.8475939035415649 }, { "filename": "src/path.ts", "retrieved_chunk": "export interface ParsedPath {\n /**\n * parent directory name (if exist)\n */\n dir: string;\n /**\n * name with extension\n */\n name: string;\n /**", "score": 0.8039563298225403 }, { "filename": "src/engine/workspace.ts", "retrieved_chunk": " const vault = this.vaultList.find(({ config }) => config.name === vaultName);\n return {\n type: \"maybe-note\",\n vaultName: vaultName ?? \"\",\n vault,\n note: path ? vault?.tree?.getFromFileName(path) : undefined,\n path: path ?? \"\",\n subpath: subpath ? parseRefSubpath(subpath) : undefined,\n };\n }", "score": 0.7965319156646729 }, { "filename": "src/engine/ref.ts", "retrieved_chunk": " }\n | {\n type: \"header\";\n name: string;\n lineOffset: number;\n };\nexport interface RefRange {\n start: number;\n startLineOffset: number;\n /* undefined = end of file */", "score": 0.7894867658615112 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " public workspace: DendronWorkspace,\n public sourcePath: string,\n public href: string,\n public title: string | undefined\n ) {\n super();\n }\n initDOM() {\n this.containerEl = createSpan(\n {", "score": 0.7856796383857727 } ]
typescript
const tree = new NoteTree();
import { App, ButtonComponent, MarkdownRenderChild, MarkdownRenderer, MarkdownRendererConstructorType, OpenViewState, TFile, setIcon, } from "obsidian"; import { openFile } from "../utils"; import { MaybeNoteRef, RefRange, getRefContentRange, anchorToLinkSubpath } from "../engine/ref"; import { dendronActivityBarName } from "../icons"; const MarkdownRendererConstructor = MarkdownRenderer as unknown as MarkdownRendererConstructorType; class RefMarkdownRenderer extends MarkdownRendererConstructor { constructor(public parent: NoteRefRenderChild, queed: boolean) { super(parent.app, parent.previewEl, queed); } get file(): TFile { return this.parent.file; } edit(markdown: string) { this.parent.editContent(markdown); } } export class NoteRefRenderChild extends MarkdownRenderChild { previewEl: HTMLElement; renderer: RefMarkdownRenderer; file: TFile; range: RefRange | null; markdown?: string; found = false; constructor( public readonly app: App, public readonly containerEl: HTMLElement, public readonly ref: MaybeNoteRef ) { super(containerEl); if (!ref.note || !ref.note.file) throw Error("NoteRefChild only accept ref with non-blank note and file"); this.file = ref.note.file; this.containerEl.classList.add("dendron-embed", "markdown-embed", "inline-embed", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); this.previewEl = this.containerEl.createDiv("markdown-embed-content"); const buttonComponent = new ButtonComponent(this.containerEl); buttonComponent.buttonEl.remove(); buttonComponent.buttonEl = this.containerEl.createDiv( "markdown-embed-link" ) as unknown as HTMLButtonElement; buttonComponent.setIcon("lucide-link").setTooltip("Open link"); buttonComponent.buttonEl.onclick = () => { const openState: OpenViewState = {}; if (this.ref.subpath) { openState.eState = { subpath: anchorToLinkSubpath( this.ref.subpath.start, this.app.metadataCache.getFileCache(this.file)?.headings ), }; } openFile(this.app, this.ref.note?.file, openState); }; this.renderer = new RefMarkdownRenderer(this, true); this.addChild(this.renderer); } async getContent(): Promise<string> { this.markdown = await this.app.vault.cachedRead(this.file); if (!this.ref.subpath) { this.found = true; return this.markdown; } const metadata = this.app.metadataCache.getFileCache(this.file); if (metadata) {
this.range = getRefContentRange(this.ref.subpath, metadata);
if (this.range) { let currentLineIndex = 0; while (currentLineIndex < this.range.startLineOffset) { if (this.markdown[this.range.start] === "\n") currentLineIndex++; this.range.start++; } this.found = true; return this.markdown.substring(this.range.start, this.range.end); } } this.found = false; return "### Unable to find section " .concat(this.ref.subpath.text, " in ") .concat(this.file.basename); } editContent(target: string) { if (!this.found || !this.markdown) return; let md; if (!this.range) { md = target; } else { const before = this.markdown.substring(0, this.range.start); md = before + target; if (this.range.end) { const after = this.markdown.substring(this.range.end); md += after; } } this.app.vault.modify(this.file, md); } async loadFile() { const content = await this.getContent(); this.renderer.renderer.set(content); } onload(): void { super.onload(); this.registerEvent( this.app.metadataCache.on("changed", async (file, data) => { if (file === this.file) { this.loadFile(); } }) ); } } export class UnresolvedRefRenderChild extends MarkdownRenderChild { constructor(app: App, containerEl: HTMLElement, target: MaybeNoteRef) { super(containerEl); this.containerEl.classList.add("dendron-embed", "file-embed", "mod-empty", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); const content = this.containerEl.createDiv(); const { vaultName, vault, path } = target; if (vaultName === "") { content.setText("Vault name are unspecified in link."); return; } else if (!vault) { content.setText(`Vault ${vaultName} are not found.`); return; } else if (path === "") { content.setText("Note path are unspecified in link."); return; } content.setText(`"${target.path}" is not created yet. Click to create.`); this.containerEl.onclick = () => { vault.createNote(path).then((file) => openFile(app, file)); }; } } export function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) { if (!target.note || !target.note.file) { return new UnresolvedRefRenderChild(app, container, target); } else { return new NoteRefRenderChild(app, container, target); } }
src/custom-resolver/ref-render.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/engine/workspace.ts", "retrieved_chunk": " const { dir: vaultDir } = parsePath(sourcePath);\n const vault = this.findVaultByParentPath(vaultDir);\n if (!vault) return null;\n const { path, subpath } = parseLinktext(link);\n const target = this.app.metadataCache.getFirstLinkpathDest(path, sourcePath);\n if (target && target.extension !== \"md\")\n return {\n type: \"file\",\n file: target,\n };", "score": 0.7709939479827881 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " onFileDeleted(parsed: ParsedPath): boolean {\n if (!this.isNote(parsed.extension)) return false;\n const note = this.tree.deleteByFileName(parsed.basename);\n if (note?.parent) {\n note.syncMetadata(undefined);\n }\n return true;\n }\n}", "score": 0.7614575028419495 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " this.tree.addFile(file, true).syncMetadata(this.resolveMetadata(file));\n return true;\n }\n onMetadataChanged(file: TFile): boolean {\n if (!this.isNote(file.extension)) return false;\n const note = this.tree.getFromFileName(file.basename);\n if (!note) return false;\n note.syncMetadata(this.resolveMetadata(file));\n return true;\n }", "score": 0.7570405602455139 }, { "filename": "src/custom-resolver/link-markdown-processor.ts", "retrieved_chunk": " if (linksEl.length == 0) return;\n const section = ctx.getSectionInfo(el);\n const cache = app.metadataCache.getCache(ctx.sourcePath);\n if (!section || !cache?.links) return;\n const links = cache.links.filter(\n (link) =>\n link.position.start.line >= section.lineStart && link.position.end.line <= section.lineEnd\n );\n if (links.length !== linksEl.length) {\n console.warn(\"Cannot post process link\");", "score": 0.7559142112731934 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " const filePath = `${this.config.path}/${baseName}.md`;\n return await this.app.vault.create(filePath, \"\");\n }\n async generateFronmatter(file: TFile) {\n if (!this.isNote(file.extension)) return;\n const note = this.tree.getFromFileName(file.basename);\n if (!note) return false;\n return await this.app.fileManager.processFrontMatter(file, (fronmatter) => {\n if (!fronmatter.id) fronmatter.id = generateUUID();\n if (!fronmatter.title) fronmatter.title = note.title;", "score": 0.7540720105171204 } ]
typescript
this.range = getRefContentRange(this.ref.subpath, metadata);
import { App, TFolder, parseLinktext } from "obsidian"; import { DendronVault, VaultConfig } from "./vault"; import { getFolderFile } from "../utils"; import { RefTarget, parseRefSubpath } from "./ref"; import { parsePath } from "../path"; const DENDRON_URI_START = "dendron://"; export class DendronWorkspace { vaultList: DendronVault[] = []; constructor(public app: App) {} changeVault(vaultList: VaultConfig[]) { this.vaultList = vaultList.map((config) => { return ( this.vaultList.find( (vault) => vault.config.name === config.name && vault.config.path === config.path ) ?? new DendronVault(this.app, config) ); }); for (const vault of this.vaultList) { vault.init(); } } findVaultByParent(parent: TFolder | null): DendronVault | undefined { return this.vaultList.find((vault) => vault.folder === parent); } findVaultByParentPath(path: string): DendronVault | undefined { const file = getFolderFile(this.app.vault, path); return file instanceof TFolder ? this.findVaultByParent(file) : undefined; } resolveRef(sourcePath: string, link: string): RefTarget | null { if (link.startsWith(DENDRON_URI_START)) { const [vaultName, rest] = link.slice(DENDRON_URI_START.length).split("/", 2) as ( | string | undefined )[]; const { path, subpath } = rest ? parseLinktext(rest) : { path: undefined, subpath: undefined, }; const vault = this.vaultList.find(({ config }) => config.name === vaultName); return { type: "maybe-note", vaultName: vaultName ?? "", vault, note: path ? vault?.tree?.getFromFileName(path) : undefined, path: path ?? "",
subpath: subpath ? parseRefSubpath(subpath) : undefined, };
} const { dir: vaultDir } = parsePath(sourcePath); const vault = this.findVaultByParentPath(vaultDir); if (!vault) return null; const { path, subpath } = parseLinktext(link); const target = this.app.metadataCache.getFirstLinkpathDest(path, sourcePath); if (target && target.extension !== "md") return { type: "file", file: target, }; const note = vault.tree.getFromFileName(path); return { type: "maybe-note", vaultName: vault.config.name, vault: vault, note, path, subpath: parseRefSubpath(subpath.slice(1) ?? ""), }; } }
src/engine/workspace.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/engine/note.test.ts", "retrieved_chunk": " const { basename, name, extension } = parsePath(path);\n return {\n basename,\n extension,\n name,\n parent: null,\n path: path,\n stat: null as unknown as Stat,\n vault: null as unknown as Vault,\n };", "score": 0.8241868019104004 }, { "filename": "src/custom-resolver/link-open.ts", "retrieved_chunk": " return originalBoundedFunction(linktext, sourcePath, newLeaf, openViewState);\n let file = target.note?.file;\n if (!file) {\n if (target.vaultName === \"\") {\n new Notice(\"Vault name is unspecified in link.\");\n return;\n } else if (!target.vault) {\n new Notice(`Vault ${target.vaultName} is not found.`);\n return;\n } else if (target.path === \"\") {", "score": 0.8196184635162354 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 0.8079516887664795 }, { "filename": "src/main.ts", "retrieved_chunk": " async migrateSettings() {\n function pathToVaultConfig(path: string) {\n const { name } = parsePath(path);\n if (name.length === 0)\n return {\n name: \"root\",\n path: \"/\",\n };\n let processed = path;\n if (processed.endsWith(\"/\")) processed = processed.slice(0, -1);", "score": 0.8018417954444885 }, { "filename": "src/settings.ts", "retrieved_chunk": " const list = this.plugin.settings.vaultList;\n const nameLowecase = config.name.toLowerCase();\n if (list.find(({ name }) => name.toLowerCase() === nameLowecase)) {\n new Notice(\"Vault with same name already exist\");\n return false;\n }\n if (list.find(({ path }) => path === config.path)) {\n new Notice(\"Vault with same path already exist\");\n return false;\n }", "score": 0.8002838492393494 } ]
typescript
subpath: subpath ? parseRefSubpath(subpath) : undefined, };
import { App, ButtonComponent, MarkdownRenderChild, MarkdownRenderer, MarkdownRendererConstructorType, OpenViewState, TFile, setIcon, } from "obsidian"; import { openFile } from "../utils"; import { MaybeNoteRef, RefRange, getRefContentRange, anchorToLinkSubpath } from "../engine/ref"; import { dendronActivityBarName } from "../icons"; const MarkdownRendererConstructor = MarkdownRenderer as unknown as MarkdownRendererConstructorType; class RefMarkdownRenderer extends MarkdownRendererConstructor { constructor(public parent: NoteRefRenderChild, queed: boolean) { super(parent.app, parent.previewEl, queed); } get file(): TFile { return this.parent.file; } edit(markdown: string) { this.parent.editContent(markdown); } } export class NoteRefRenderChild extends MarkdownRenderChild { previewEl: HTMLElement; renderer: RefMarkdownRenderer; file: TFile; range: RefRange | null; markdown?: string; found = false; constructor( public readonly app: App, public readonly containerEl: HTMLElement, public readonly ref: MaybeNoteRef ) { super(containerEl); if (!ref.note || !ref.note.file) throw Error("NoteRefChild only accept ref with non-blank note and file"); this.file = ref.note.file; this.containerEl.classList.add("dendron-embed", "markdown-embed", "inline-embed", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); this.previewEl = this.containerEl.createDiv("markdown-embed-content"); const buttonComponent = new ButtonComponent(this.containerEl); buttonComponent.buttonEl.remove(); buttonComponent.buttonEl = this.containerEl.createDiv( "markdown-embed-link" ) as unknown as HTMLButtonElement; buttonComponent.setIcon("lucide-link").setTooltip("Open link"); buttonComponent.buttonEl.onclick = () => { const openState: OpenViewState = {}; if (this.ref.subpath) { openState.eState = { subpath: anchorToLinkSubpath( this.ref.subpath.start, this.app.metadataCache.getFileCache(this.file)?.headings ), }; } openFile(this.app, this.ref.note?.file, openState); }; this.renderer = new RefMarkdownRenderer(this, true); this.addChild(this.renderer); } async getContent(): Promise<string> { this.markdown = await this.app.vault.cachedRead(this.file); if (!this.ref.subpath) { this.found = true; return this.markdown; } const metadata = this.app.metadataCache.getFileCache(this.file); if (metadata) { this.range = getRefContentRange(this.ref.subpath, metadata); if (this.range) { let currentLineIndex = 0; while (currentLineIndex < this.range.startLineOffset) { if (this.markdown[this.range.start] === "\n") currentLineIndex++; this.range.start++; } this.found = true; return this.markdown.substring(this.range.start, this.range.end); } } this.found = false; return "### Unable to find section " .concat(this.ref.subpath.text, " in ") .concat(this.file.basename); } editContent(target: string) { if (!this.found || !this.markdown) return; let md; if (!this.range) { md = target; } else { const before = this.markdown.substring(0, this.range.start); md = before + target; if (this.range.end) { const after = this.markdown.substring(this.range.end); md += after; } } this.app.vault.modify(this.file, md); } async loadFile() { const content = await this.getContent(); this.renderer.renderer.set(content); } onload(): void { super.onload(); this.registerEvent( this.app.metadataCache.on("changed", async (file, data) => { if (file === this.file) { this.loadFile(); } }) ); } } export class UnresolvedRefRenderChild extends MarkdownRenderChild { constructor(app: App, containerEl: HTMLElement, target: MaybeNoteRef) { super(containerEl); this.containerEl.classList.add("dendron-embed", "file-embed", "mod-empty", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); const content = this.containerEl.createDiv(); const { vaultName, vault, path } = target; if (vaultName === "") { content.setText("Vault name are unspecified in link."); return; } else if (!vault) { content.setText(`Vault ${vaultName} are not found.`); return; } else if (path === "") { content.setText("Note path are unspecified in link."); return; } content.setText(`"${target.path}" is not created yet. Click to create.`); this.containerEl.onclick = () => {
vault.createNote(path).then((file) => openFile(app, file));
}; } } export function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) { if (!target.note || !target.note.file) { return new UnresolvedRefRenderChild(app, container, target); } else { return new NoteRefRenderChild(app, container, target); } }
src/custom-resolver/ref-render.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/custom-resolver/link-open.ts", "retrieved_chunk": " return originalBoundedFunction(linktext, sourcePath, newLeaf, openViewState);\n let file = target.note?.file;\n if (!file) {\n if (target.vaultName === \"\") {\n new Notice(\"Vault name is unspecified in link.\");\n return;\n } else if (!target.vault) {\n new Notice(`Vault ${target.vaultName} is not found.`);\n return;\n } else if (target.path === \"\") {", "score": 0.8736719489097595 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 0.8261755704879761 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " .setCta()\n .setButtonText(\"Add Text\")\n .onClick(() => {\n const name = this.nameText.getValue();\n if (!this.folder || name.trim().length === 0) {\n new Notice(\"Please specify Vault Path and Vault Name\");\n return;\n }\n if (\n this.onSubmit({", "score": 0.8234037160873413 }, { "filename": "src/main.ts", "retrieved_chunk": " menu.addItem((item) => {\n item\n .setIcon(dendronActivityBarName)\n .setTitle(\"Reveal in Dendron Tree\")\n .onClick(() => this.revealFile(file));\n });\n };\n onResolveMetadata = (file: TFile) => {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (vault && vault.onMetadataChanged(file)) {", "score": 0.7977348566055298 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " }\n init() {\n if (this.isIniatialized) return;\n this.tree = new NoteTree();\n const root = getFolderFile(this.app.vault, this.config.path);\n if (!(root instanceof TFolder)) {\n new InvalidRootModal(this).open();\n return;\n }\n this.folder = root;", "score": 0.797551155090332 } ]
typescript
vault.createNote(path).then((file) => openFile(app, file));
import { App, SuggestModal, getIcon } from "obsidian"; import { Note } from "../engine/note"; import { openFile } from "../utils"; import { DendronVault } from "../engine/vault"; import { SelectVaultModal } from "./select-vault"; import { DendronWorkspace } from "../engine/workspace"; interface LookupItem { note: Note; vault: DendronVault; } export class LookupModal extends SuggestModal<LookupItem | null> { constructor(app: App, private workspace: DendronWorkspace, private initialQuery: string = "") { super(app); } onOpen(): void { super.onOpen(); if (this.initialQuery.length > 0) { this.inputEl.value = this.initialQuery; this.inputEl.dispatchEvent(new Event("input")); } } getSuggestions(query: string): (LookupItem | null)[] { const queryLowercase = query.toLowerCase(); const result: (LookupItem | null)[] = []; let foundExact = true; for (const vault of this.workspace.vaultList) { let currentFoundExact = false; for (const note of vault.tree.flatten()) { const path = note.getPath(); const item: LookupItem = { note, vault, }; if (path === queryLowercase) { currentFoundExact = true; result.unshift(item); continue; } if ( note.title.toLowerCase().includes(queryLowercase) || note.name.includes(queryLowercase) || path.includes(queryLowercase) ) result.push(item); } foundExact = foundExact && currentFoundExact; } if (!foundExact && queryLowercase.trim().length > 0) result.unshift(null); return result; } renderSuggestion(item: LookupItem | null, el: HTMLElement) { el.classList.add("mod-complex"); el.createEl("div", { cls: "suggestion-content" }, (el) => {
el.createEl("div", { text: item?.note.title ?? "Create New", cls: "suggestion-title" });
el.createEl("small", { text: item ? item.note.getPath() + (this.workspace.vaultList.length > 1 ? ` (${item.vault.config.name})` : "") : "Note does not exist", cls: "suggestion-content", }); }); if (!item || !item.note.file) el.createEl("div", { cls: "suggestion-aux" }, (el) => { el.append(getIcon("plus")!); }); } async onChooseSuggestion(item: LookupItem | null, evt: MouseEvent | KeyboardEvent) { if (item && item.note.file) { openFile(this.app, item.note.file); return; } const path = item ? item.note.getPath() : this.inputEl.value; const doCreate = async (vault: DendronVault) => { const file = await vault.createNote(path); return openFile(vault.app, file); }; if (item?.vault) { await doCreate(item.vault); } else if (this.workspace.vaultList.length == 1) { await doCreate(this.workspace.vaultList[0]); } else { new SelectVaultModal(this.app, this.workspace, doCreate).open(); } } }
src/modal/lookup.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " }\n renderSuggestion(value: TFolder, el: HTMLElement): void {\n el.createDiv({\n text: value.path,\n });\n }\n selectSuggestion(value: TFolder, evt: MouseEvent | KeyboardEvent): void {\n this.inputEl.value = value.path;\n this.close();\n this.onSelected(value);", "score": 0.797134280204773 }, { "filename": "src/modal/select-vault.ts", "retrieved_chunk": " el.createEl(\"div\", { text: value.config.name });\n el.createEl(\"small\", {\n text: value.config.path,\n });\n }\n onChooseSuggestion(item: DendronVault, evt: MouseEvent | KeyboardEvent) {\n this.onSelected(item);\n }\n}", "score": 0.7927186489105225 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " cls: \"cm-hmd-internal-link\",\n },\n (el) => {\n el.createSpan({\n cls: \"cm-underline\",\n });\n }\n );\n this.updateTitle();\n this.containerEl.addEventListener(\"click\", () => {", "score": 0.7888755798339844 }, { "filename": "src/settings.ts", "retrieved_chunk": " }\n display(): void {\n const { containerEl } = this;\n containerEl.empty();\n containerEl.createEl(\"h2\", { text: \"Dendron Tree Settting\" });\n new Setting(containerEl)\n .setName(\"Auto Generate Front Matter\")\n .setDesc(\"Generate front matter for new file even if file is created outside of Dendron tree\")\n .addToggle((toggle) => {\n toggle.setValue(this.plugin.settings.autoGenerateFrontmatter).onChange(async (value) => {", "score": 0.7726352214813232 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " inputEl.addEventListener(\"focus\", this.onInputChange);\n inputEl.addEventListener(\"blur\", () => this.close());\n this.suggestEl.on(\"mousedown\", \".suggestion-item\", (e) => e.preventDefault());\n this.suggestEl.classList.add(\"dendron-folder-suggest\");\n }\n onInputChange = () => {\n const suggestionList = this.getSuggestions(this.inputEl.value);\n if (suggestionList.length === 0) {\n this.close();\n return;", "score": 0.7585247755050659 } ]
typescript
el.createEl("div", { text: item?.note.title ?? "Create New", cls: "suggestion-title" });
import type { Stat, TFile, Vault } from "obsidian"; import { Note, NoteTree, generateNoteTitle, isUseTitleCase } from "./note"; import { parsePath } from "../path"; describe("note title", () => { it("use title case when file name is lowercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("aku.cinta.kamu-milikku.md"))).toBe( "Kamu Milikku" ); }); it("use file name when note name contain uppercase", () => { expect(generateNoteTitle("Kamu-Milikku", isUseTitleCase("aku.cinta.Kamu-Milikku.md"))).toBe( "Kamu-Milikku" ); }); it("use file name when file name contain uppercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("Aku.cinta.kamu-milikku.md"))).toBe( "kamu-milikku" ); }); }); describe("note class", () => { it("append and remove child work", () => { const child = new Note("lala", true); expect(child.parent).toBeUndefined(); const parent = new Note("apa", true); expect(parent.children).toEqual([]); parent.appendChild(child); expect(child.parent).toBe(parent); expect(parent.children).toEqual([child]); parent.removeChildren(child); expect(child.parent).toBeUndefined(); expect(parent.children).toEqual([]); }); it("append child must throw if child already has parent", () => { const origParent = new Note("root", true); const parent = new Note("root2", true); const child = new Note("child", true); origParent.appendChild(child); expect(() => parent.appendChild(child)).toThrowError("has parent"); }); it("find children work", () => { const parent = new Note("parent", true); const child1 = new Note("child1", true); const child2 = new Note("child2", true); const child3 = new Note("child3", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.findChildren("child1")).toBe(child1); expect(parent.findChildren("child2")).toBe(child2); expect(parent.findChildren("child3")).toBe(child3); expect(parent.findChildren("child4")).toBeUndefined(); }); it("non-recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("gajak", true); const child2 = new Note("lumba", true); const child3 = new Note("biawak", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.children).toEqual([child1, child2, child3]); parent.sortChildren(false); expect(parent.children).toEqual([child3, child1, child2]); }); it("recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("lumba", true); const child2 = new Note("galak", true); const grandchild1 = new Note("lupa", true); const grandchild2 = new Note("apa", true); const grandchild3 = new Note("abu", true); const grandchild4 = new Note("lagi", true); parent.appendChild(child1); child1.appendChild(grandchild1); child1.appendChild(grandchild2); parent.appendChild(child2); child2.appendChild(grandchild3); child2.appendChild(grandchild4); expect(parent.children).toEqual([child1, child2]); expect(child1.children).toEqual([grandchild1, grandchild2]); expect(child2.children).toEqual([grandchild3, grandchild4]); parent.sortChildren(true); expect(parent.children).toEqual([child2, child1]); expect(child1.children).toEqual([grandchild2, grandchild1]); expect(child2.children).toEqual([grandchild3, grandchild4]); }); it("get path on non-root", () => { const root = new Note("root", true); const ch1 = new Note("parent", true); const ch2 = new Note("parent2", true); const ch3 = new Note("child", true); root.appendChild(ch1); ch1.appendChild(ch2); ch2.appendChild(ch3); expect(ch3.getPath()).toBe("parent.parent2.child");
expect(ch3.getPathNotes()).toEqual([root, ch1, ch2, ch3]);
}); it("get path on root", () => { const root = new Note("root", true); expect(root.getPath()).toBe("root"); expect(root.getPathNotes()).toEqual([root]); }); it("use generated title when titlecase true", () => { const note = new Note("aku-cinta", true); expect(note.title).toBe("Aku Cinta"); }); it("use filename as title when titlecase false", () => { const note = new Note("aKu-ciNta", false); expect(note.title).toBe("aKu-ciNta"); }); it("use metadata title when has metadata", () => { const note = new Note("aKu-ciNta", false); note.syncMetadata({ title: "Butuh Kamu", }); expect(note.title).toBe("Butuh Kamu"); }); }); function createTFile(path: string): TFile { const { basename, name, extension } = parsePath(path); return { basename, extension, name, parent: null, path: path, stat: null as unknown as Stat, vault: null as unknown as Vault, }; } describe("tree class", () => { it("add file without sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.root.children.length).toBe(1); expect(tree.root.children[0].name).toBe("abc"); expect(tree.root.children[0].children.length).toBe(1); expect(tree.root.children[0].children[0].name).toBe("def"); expect(tree.root.children[0].children[0].children.length).toBe(2); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); }); it("add file with sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md"), true); tree.addFile(createTFile("abc.def.ghi.md"), true); tree.addFile(createTFile("abc.def.mno.md"), true); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("get note by file base name", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("abc.def.jkl")?.name).toBe("jkl"); expect(tree.getFromFileName("abc.def.ghi")?.name).toBe("ghi"); expect(tree.getFromFileName("abc.def.mno")).toBeUndefined(); }); it("get note using blank path", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("")).toBeUndefined() }) it("delete note if do not have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")).toBeUndefined(); }); it("do not delete note if have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.addFile(createTFile("abc.def.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")?.name).toBe("abc"); expect(tree.getFromFileName("abc.def")?.name).toBe("def"); }); it("delete note and parent if do not have children and parent file is null", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc")); tree.addFile(createTFile("abc.def.ghi.md")); tree.deleteByFileName("abc.def.ghi"); expect(tree.getFromFileName("abc.def.ghi")).toBeUndefined(); expect(tree.getFromFileName("abc.def")).toBeUndefined(); expect(tree.getFromFileName("abc")?.name).toBe("abc"); }); it("sort note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.def.mno.md")); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); tree.sort(); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("flatten note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.jkl.mno.md")); expect(tree.flatten().map((note) => note.getPath())).toEqual([ "root", "abc", "abc.def", "abc.def.ghi", "abc.jkl", "abc.jkl.mno", ]); }); });
src/engine/note.test.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/engine/note.ts", "retrieved_chunk": " if (rescursive) this.children.forEach((child) => child.sortChildren(rescursive));\n }\n getPath(original = false) {\n const component: string[] = [];\n const notes = this.getPathNotes();\n if (notes.length === 1) return original ? notes[0].originalName : notes[0].name;\n for (const note of notes) {\n if (!note.parent && note.name === \"root\") continue;\n component.push(original ? note.originalName : note.name);\n }", "score": 0.6900724768638611 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " constructor(private originalName: string, private titlecase: boolean) {\n this.name = originalName.toLowerCase();\n this.syncMetadata(undefined);\n }\n appendChild(note: Note) {\n if (note.parent) throw Error(\"Note has parent\");\n note.parent = this;\n this.children.push(note);\n }\n removeChildren(note: Note) {", "score": 0.6841742992401123 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " const note = this.getFromFileName(name);\n if (!note) return;\n note.file = undefined;\n if (note.children.length == 0) {\n let currentNote: Note | undefined = note;\n while (\n currentNote &&\n currentNote.parent &&\n !currentNote.file &&\n currentNote.children.length == 0", "score": 0.6639408469200134 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " note.parent = undefined;\n const index = this.children.indexOf(note);\n this.children.splice(index, 1);\n }\n findChildren(name: string) {\n const lower = name.toLowerCase();\n return this.children.find((note) => note.name == lower);\n }\n sortChildren(rescursive: boolean) {\n this.children.sort((a, b) => a.name.localeCompare(b.name));", "score": 0.6550799012184143 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " currentNote.appendChild(note);\n if (sort) currentNote.sortChildren(false);\n }\n currentNote = note;\n }\n currentNote.file = file;\n return currentNote;\n }\n getFromFileName(name: string) {\n const path = NoteTree.getPathFromFileName(name);", "score": 0.650578498840332 } ]
typescript
expect(ch3.getPathNotes()).toEqual([root, ch1, ch2, ch3]);
import { App, ButtonComponent, MarkdownRenderChild, MarkdownRenderer, MarkdownRendererConstructorType, OpenViewState, TFile, setIcon, } from "obsidian"; import { openFile } from "../utils"; import { MaybeNoteRef, RefRange, getRefContentRange, anchorToLinkSubpath } from "../engine/ref"; import { dendronActivityBarName } from "../icons"; const MarkdownRendererConstructor = MarkdownRenderer as unknown as MarkdownRendererConstructorType; class RefMarkdownRenderer extends MarkdownRendererConstructor { constructor(public parent: NoteRefRenderChild, queed: boolean) { super(parent.app, parent.previewEl, queed); } get file(): TFile { return this.parent.file; } edit(markdown: string) { this.parent.editContent(markdown); } } export class NoteRefRenderChild extends MarkdownRenderChild { previewEl: HTMLElement; renderer: RefMarkdownRenderer; file: TFile; range: RefRange | null; markdown?: string; found = false; constructor( public readonly app: App, public readonly containerEl: HTMLElement, public readonly ref: MaybeNoteRef ) { super(containerEl);
if (!ref.note || !ref.note.file) throw Error("NoteRefChild only accept ref with non-blank note and file");
this.file = ref.note.file; this.containerEl.classList.add("dendron-embed", "markdown-embed", "inline-embed", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); this.previewEl = this.containerEl.createDiv("markdown-embed-content"); const buttonComponent = new ButtonComponent(this.containerEl); buttonComponent.buttonEl.remove(); buttonComponent.buttonEl = this.containerEl.createDiv( "markdown-embed-link" ) as unknown as HTMLButtonElement; buttonComponent.setIcon("lucide-link").setTooltip("Open link"); buttonComponent.buttonEl.onclick = () => { const openState: OpenViewState = {}; if (this.ref.subpath) { openState.eState = { subpath: anchorToLinkSubpath( this.ref.subpath.start, this.app.metadataCache.getFileCache(this.file)?.headings ), }; } openFile(this.app, this.ref.note?.file, openState); }; this.renderer = new RefMarkdownRenderer(this, true); this.addChild(this.renderer); } async getContent(): Promise<string> { this.markdown = await this.app.vault.cachedRead(this.file); if (!this.ref.subpath) { this.found = true; return this.markdown; } const metadata = this.app.metadataCache.getFileCache(this.file); if (metadata) { this.range = getRefContentRange(this.ref.subpath, metadata); if (this.range) { let currentLineIndex = 0; while (currentLineIndex < this.range.startLineOffset) { if (this.markdown[this.range.start] === "\n") currentLineIndex++; this.range.start++; } this.found = true; return this.markdown.substring(this.range.start, this.range.end); } } this.found = false; return "### Unable to find section " .concat(this.ref.subpath.text, " in ") .concat(this.file.basename); } editContent(target: string) { if (!this.found || !this.markdown) return; let md; if (!this.range) { md = target; } else { const before = this.markdown.substring(0, this.range.start); md = before + target; if (this.range.end) { const after = this.markdown.substring(this.range.end); md += after; } } this.app.vault.modify(this.file, md); } async loadFile() { const content = await this.getContent(); this.renderer.renderer.set(content); } onload(): void { super.onload(); this.registerEvent( this.app.metadataCache.on("changed", async (file, data) => { if (file === this.file) { this.loadFile(); } }) ); } } export class UnresolvedRefRenderChild extends MarkdownRenderChild { constructor(app: App, containerEl: HTMLElement, target: MaybeNoteRef) { super(containerEl); this.containerEl.classList.add("dendron-embed", "file-embed", "mod-empty", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); const content = this.containerEl.createDiv(); const { vaultName, vault, path } = target; if (vaultName === "") { content.setText("Vault name are unspecified in link."); return; } else if (!vault) { content.setText(`Vault ${vaultName} are not found.`); return; } else if (path === "") { content.setText("Note path are unspecified in link."); return; } content.setText(`"${target.path}" is not created yet. Click to create.`); this.containerEl.onclick = () => { vault.createNote(path).then((file) => openFile(app, file)); }; } } export function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) { if (!target.note || !target.note.file) { return new UnresolvedRefRenderChild(app, container, target); } else { return new NoteRefRenderChild(app, container, target); } }
src/custom-resolver/ref-render.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " public workspace: DendronWorkspace,\n public sourcePath: string,\n public href: string,\n public title: string | undefined\n ) {\n super();\n }\n initDOM() {\n this.containerEl = createSpan(\n {", "score": 0.8218722939491272 }, { "filename": "src/custom-resolver/ref-live.ts", "retrieved_chunk": " children: Component[];\n containerEl: HTMLElement;\n hacked?: boolean;\n initDOM(): HTMLElement;\n addChild(c: Component): void;\n applyTitle(container: HTMLElement, title: string): void;\n}\nexport class RefLivePlugin implements PluginValue {\n constructor(public app: App, public workspace: DendronWorkspace) {}\n update(update: ViewUpdate) {", "score": 0.7933114767074585 }, { "filename": "src/obsidian-ex.d.ts", "retrieved_chunk": " onLinkHover(\n parent: HoverParent,\n tergetEl: HTMLElement,\n link: string,\n sourcePath: string,\n state: EditorState\n );\n }\n interface InternalPlugins {\n \"page-preview\": PagePreviewPlugin;", "score": 0.7903519868850708 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " });\n });\n if (!item || !item.note.file)\n el.createEl(\"div\", { cls: \"suggestion-aux\" }, (el) => {\n el.append(getIcon(\"plus\")!);\n });\n }\n async onChooseSuggestion(item: LookupItem | null, evt: MouseEvent | KeyboardEvent) {\n if (item && item.note.file) {\n openFile(this.app, item.note.file);", "score": 0.787539005279541 }, { "filename": "src/engine/ref.ts", "retrieved_chunk": " subpath?: RefSubpath;\n}\nexport interface FileRef {\n type: \"file\";\n file: TFile;\n}\nexport type RefTarget = MaybeNoteRef | FileRef;\nexport type RefAnchor =\n | {\n type: \"begin\";", "score": 0.7823711633682251 } ]
typescript
if (!ref.note || !ref.note.file) throw Error("NoteRefChild only accept ref with non-blank note and file");
import { EditorView, PluginValue, ViewUpdate } from "@codemirror/view"; import { App, Component, editorLivePreviewField } from "obsidian"; import { NoteRefRenderChild, createRefRenderer } from "./ref-render"; import { DendronWorkspace } from "../engine/workspace"; interface InternalEmbedWidget { end: number; href: string; sourcePath: string; start: string; title: string; children: Component[]; containerEl: HTMLElement; hacked?: boolean; initDOM(): HTMLElement; addChild(c: Component): void; applyTitle(container: HTMLElement, title: string): void; } export class RefLivePlugin implements PluginValue { constructor(public app: App, public workspace: DendronWorkspace) {} update(update: ViewUpdate) { if (!update.state.field(editorLivePreviewField)) { return; } update.view.state.facet(EditorView.decorations).forEach((d) => { if (typeof d !== "function") { const iter = d.iter(); while (iter.value) { const widget = iter.value.spec.widget; if (widget && widget.href && widget.sourcePath && widget.title) { const internalWidget = widget as InternalEmbedWidget; this.hack(internalWidget); } iter.next(); } } }); } hack(widget: InternalEmbedWidget) { if (widget.hacked) { return; } widget.hacked = true; const target = this.workspace.resolveRef(widget.sourcePath, widget.href); if (!target || target.type !== "maybe-note") return; const loadComponent = (widget: InternalEmbedWidget) => { const renderer = createRefRenderer(target, this.app, widget.containerEl);
if (renderer instanceof NoteRefRenderChild) renderer.loadFile();
widget.addChild(renderer); }; widget.initDOM = function (this: InternalEmbedWidget) { this.containerEl = createDiv("internal-embed"); loadComponent(this); return this.containerEl; }; widget.applyTitle = function ( this: InternalEmbedWidget, container: HTMLElement, title: string ) { this.title = title; }; if (widget.containerEl) { console.log("Workaround"); widget.children[0].unload(); widget.children.pop(); loadComponent(widget); } } }
src/custom-resolver/ref-live.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/custom-resolver/ref-markdown-processor.ts", "retrieved_chunk": " embeddedItems.forEach((el) => {\n const link = el.getAttribute(\"src\");\n if (!link) return;\n const target = workspace.resolveRef(context.sourcePath, link);\n if (!target || target.type !== \"maybe-note\") return;\n const renderer = createRefRenderer(target, app, el as HTMLElement);\n if (renderer instanceof NoteRefRenderChild) promises.push(renderer.loadFile());\n context.addChild(renderer);\n });\n return Promise.all(promises);", "score": 0.8891457915306091 }, { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " content.setText(`\"${target.path}\" is not created yet. Click to create.`);\n this.containerEl.onclick = () => {\n vault.createNote(path).then((file) => openFile(app, file));\n };\n }\n}\nexport function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) {\n if (!target.note || !target.note.file) {\n return new UnresolvedRefRenderChild(app, container, target);\n } else {", "score": 0.8512030839920044 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " widget.updateTitle();\n this.widgets.splice(lastWidgetIndex, 1);\n return widget;\n }\n return new LinkWidget(this.app, this.workspace, sourcePath, link.href, link.title);\n }\n buildDecorations(view: EditorView): DecorationSet {\n if (!view.state.field(editorLivePreviewField)) {\n return Decoration.none;\n }", "score": 0.8249452114105225 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " if (found) break;\n }\n }\n getWidget(link: LinkData, sourcePath: string) {\n const lastWidgetIndex = this.widgets.findIndex(\n (widget) => widget.href === link.href && widget.sourcePath === sourcePath\n );\n if (lastWidgetIndex >= 0) {\n const widget = this.widgets[lastWidgetIndex];\n widget.title = link.title;", "score": 0.8154348134994507 }, { "filename": "src/custom-resolver/link-hover.ts", "retrieved_chunk": " setTimeout(async () => {\n if (popOver.state === PopoverState.Hidden) return;\n const container = popOver.hoverEl.createDiv();\n const component = createRefRenderer(ref, app, container);\n popOver.addChild(component);\n if (component instanceof NoteRefRenderChild) await component.loadFile();\n if (popOver.state === PopoverState.Shown) popOver.position();\n }, 100);\n }\n };", "score": 0.8044321537017822 } ]
typescript
if (renderer instanceof NoteRefRenderChild) renderer.loadFile();
import { Component, MarkdownPreviewRenderer, PagePreviewPlugin, Plugin, Workspace } from "obsidian"; import { DendronWorkspace } from "../engine/workspace"; import { createLinkHoverHandler } from "./link-hover"; import { ViewPlugin } from "@codemirror/view"; import { RefLivePlugin } from "./ref-live"; import { createRefMarkdownProcessor } from "./ref-markdown-processor"; import { createLinkOpenHandler } from "./link-open"; import { LinkLivePlugin } from "./link-live"; import { createLinkMarkdownProcessor } from "./link-markdown-processor"; import { LinkRefClickbale } from "./link-ref-clickbale"; export class CustomResolver extends Component { pagePreviewPlugin?: PagePreviewPlugin; originalLinkHover: PagePreviewPlugin["onLinkHover"]; originalOpenLinkText: Workspace["openLinkText"]; refPostProcessor = createRefMarkdownProcessor(this.plugin.app, this.workspace); linkPostProcessor = createLinkMarkdownProcessor(this.plugin.app, this.workspace); refEditorExtenstion = ViewPlugin.define((v) => { return new RefLivePlugin(this.plugin.app, this.workspace); }); linkEditorExtenstion = ViewPlugin.define( (view) => { return new LinkLivePlugin(this.plugin.app, this.workspace, view); }, { decorations: (value) => value.decorations, } ); linkRefClickbaleExtension = ViewPlugin.define((v) => { return new LinkRefClickbale(v); }); constructor(public plugin: Plugin, public workspace: DendronWorkspace) { super(); } onload(): void { this.plugin.app.workspace.onLayoutReady(() => { this.plugin.app.workspace.registerEditorExtension(this.refEditorExtenstion); this.plugin.app.workspace.registerEditorExtension(this.linkEditorExtenstion); this.plugin.app.workspace.registerEditorExtension(this.linkRefClickbaleExtension); this.pagePreviewPlugin = this.plugin.app.internalPlugins.getEnabledPluginById("page-preview"); if (!this.pagePreviewPlugin) return; this.originalLinkHover = this.pagePreviewPlugin.onLinkHover; this.pagePreviewPlugin.onLinkHover = createLinkHoverHandler( this.plugin.app, this.workspace, this.originalLinkHover.bind(this.pagePreviewPlugin) ); }); MarkdownPreviewRenderer.registerPostProcessor(this.refPostProcessor); MarkdownPreviewRenderer.registerPostProcessor(this.linkPostProcessor); this.originalOpenLinkText = this.plugin.app.workspace.openLinkText; this.plugin.
app.workspace.openLinkText = createLinkOpenHandler( this.workspace, this.originalOpenLinkText.bind(this.plugin.app.workspace) );
} onunload(): void { this.plugin.app.workspace.openLinkText = this.originalOpenLinkText; MarkdownPreviewRenderer.unregisterPostProcessor(this.linkPostProcessor); MarkdownPreviewRenderer.unregisterPostProcessor(this.refPostProcessor); this.plugin.app.workspace.unregisterEditorExtension(this.linkRefClickbaleExtension); this.plugin.app.workspace.unregisterEditorExtension(this.linkEditorExtenstion); this.plugin.app.workspace.unregisterEditorExtension(this.refEditorExtenstion); if (!this.pagePreviewPlugin) return; this.pagePreviewPlugin.onLinkHover = this.originalLinkHover; } }
src/custom-resolver/index.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " ) as unknown as HTMLButtonElement;\n buttonComponent.setIcon(\"lucide-link\").setTooltip(\"Open link\");\n buttonComponent.buttonEl.onclick = () => {\n const openState: OpenViewState = {};\n if (this.ref.subpath) {\n openState.eState = {\n subpath: anchorToLinkSubpath(\n this.ref.subpath.start,\n this.app.metadataCache.getFileCache(this.file)?.headings\n ),", "score": 0.7322204113006592 }, { "filename": "src/main.ts", "retrieved_chunk": " this.onRootFolderChanged();\n this.registerEvent(this.app.vault.on(\"create\", this.onCreateFile));\n this.registerEvent(this.app.vault.on(\"delete\", this.onDeleteFile));\n this.registerEvent(this.app.vault.on(\"rename\", this.onRenameFile));\n this.registerEvent(this.app.metadataCache.on(\"resolve\", this.onResolveMetadata));\n this.registerEvent(this.app.workspace.on(\"file-open\", this.onOpenFile, this));\n this.registerEvent(this.app.workspace.on(\"file-menu\", this.onFileMenu));\n });\n this.configureCustomResolver();\n }", "score": 0.7256354093551636 }, { "filename": "src/custom-resolver/link-ref-clickbale.ts", "retrieved_chunk": " if (editor && editor.getClickableTokenAt) {\n this.getClickableTokenAtOrig = editor.getClickableTokenAt;\n editor.getClickableTokenAt = LinkRefClickbale.createClickableTokenAtWrapper(\n this.getClickableTokenAtOrig\n );\n }\n }\n destroy(): void {\n if (this.getClickableTokenAtOrig) {\n const editor = this.view.state.field(editorInfoField).editor;", "score": 0.7162636518478394 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " this.app.workspace.openLinkText(this.href, this.sourcePath);\n });\n }\n updateTitle() {\n this.containerEl.children[0].setText(\n renderLinkTitle(this.app, this.workspace, this.href, this.title, this.sourcePath)\n );\n }\n toDOM(view: EditorView): HTMLElement {\n if (!this.containerEl) this.initDOM();", "score": 0.7019718885421753 }, { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " };\n }\n openFile(this.app, this.ref.note?.file, openState);\n };\n this.renderer = new RefMarkdownRenderer(this, true);\n this.addChild(this.renderer);\n }\n async getContent(): Promise<string> {\n this.markdown = await this.app.vault.cachedRead(this.file);\n if (!this.ref.subpath) {", "score": 0.6696290373802185 } ]
typescript
app.workspace.openLinkText = createLinkOpenHandler( this.workspace, this.originalOpenLinkText.bind(this.plugin.app.workspace) );
import { Menu, Plugin, TAbstractFile, TFile, addIcon } from "obsidian"; import { DendronView, VIEW_TYPE_DENDRON } from "./view"; import { activeFile, dendronVaultList } from "./store"; import { LookupModal } from "./modal/lookup"; import { dendronActivityBarIcon, dendronActivityBarName } from "./icons"; import { DEFAULT_SETTINGS, DendronTreePluginSettings, DendronTreeSettingTab } from "./settings"; import { parsePath } from "./path"; import { DendronWorkspace } from "./engine/workspace"; import { CustomResolver } from "./custom-resolver"; export default class DendronTreePlugin extends Plugin { settings: DendronTreePluginSettings; workspace: DendronWorkspace = new DendronWorkspace(this.app); customResolver?: CustomResolver; async onload() { await this.loadSettings(); await this.migrateSettings(); addIcon(dendronActivityBarName, dendronActivityBarIcon); this.addCommand({ id: "dendron-lookup", name: "Lookup Note", callback: () => { new LookupModal(this.app, this.workspace).open(); }, }); this.addSettingTab(new DendronTreeSettingTab(this.app, this)); this.registerView(VIEW_TYPE_DENDRON, (leaf) => new DendronView(leaf, this)); this.addRibbonIcon(dendronActivityBarName, "Open Dendron Tree", () => { this.activateView(); }); this.app.workspace.onLayoutReady(() => { this.onRootFolderChanged(); this.registerEvent(this.app.vault.on("create", this.onCreateFile)); this.registerEvent(this.app.vault.on("delete", this.onDeleteFile)); this.registerEvent(this.app.vault.on("rename", this.onRenameFile)); this.registerEvent(this.app.metadataCache.on("resolve", this.onResolveMetadata)); this.registerEvent(this.app.workspace.on("file-open", this.onOpenFile, this)); this.registerEvent(this.app.workspace.on("file-menu", this.onFileMenu)); }); this.configureCustomResolver(); } async migrateSettings() { function pathToVaultConfig(path: string) { const { name } = parsePath(path); if (name.length === 0) return { name: "root", path: "/", }; let processed = path; if (processed.endsWith("/")) processed = processed.slice(0, -1); if (processed.startsWith("/") && processed.length > 1) processed = processed.slice(1); return { name, path: processed, }; } if (this.settings.vaultPath) { this.settings.vaultList = [pathToVaultConfig(this.settings.vaultPath)]; this.settings.vaultPath = undefined; await this.saveSettings(); } if (this.settings.vaultList.length > 0 && typeof this.settings.vaultList[0] === "string") { this.settings.vaultList = (this.settings.vaultList as unknown as string[]).map((path) => pathToVaultConfig(path) ); await this.saveSettings(); } } onunload() {} onRootFolderChanged() { this.workspace.changeVault(this.settings.vaultList); this.updateNoteStore(); } configureCustomResolver() { if (this.settings.customResolver && !this.customResolver) { this.customResolver = new CustomResolver(this, this.workspace); this.addChild(this.customResolver); } else if (!this.settings.customResolver && this.customResolver) { this.removeChild(this.customResolver); this.customResolver = undefined; } } updateNoteStore() { dendronVaultList.set(this.workspace.vaultList); } onCreateFile = async (file: TAbstractFile) => { const vault = this.workspace.findVaultByParent(file.parent); if (vault && vault.onFileCreated(file)) { if (this.settings.autoGenerateFrontmatter && file instanceof TFile && file.stat.size === 0) await vault.generateFronmatter(file); this.updateNoteStore(); } }; onDeleteFile = (file: TAbstractFile) => { // file.parent is null when file is deleted const parsed = parsePath(file.path); const vault = this.workspace.findVaultByParentPath(parsed.dir); if (vault && vault.onFileDeleted(parsed)) { this.updateNoteStore(); } }; onRenameFile = (file: TAbstractFile, oldPath: string) => { const oldParsed = parsePath(oldPath); const oldVault = this.workspace.findVaultByParentPath(oldParsed.dir); let update = false; if (oldVault) { update = oldVault.onFileDeleted(oldParsed); } const newVault = this.workspace.findVaultByParent(file.parent); if (newVault) { update = newVault.onFileCreated(file) || update; } if (update) this.updateNoteStore(); }; onOpenFile(file: TFile | null) {
activeFile.set(file);
if (file && this.settings.autoReveal) this.revealFile(file); } onFileMenu = (menu: Menu, file: TAbstractFile) => { if (!(file instanceof TFile)) return; menu.addItem((item) => { item .setIcon(dendronActivityBarName) .setTitle("Reveal in Dendron Tree") .onClick(() => this.revealFile(file)); }); }; onResolveMetadata = (file: TFile) => { const vault = this.workspace.findVaultByParent(file.parent); if (vault && vault.onMetadataChanged(file)) { this.updateNoteStore(); } }; revealFile(file: TFile) { const vault = this.workspace.findVaultByParent(file.parent); if (!vault) return; const note = vault.tree.getFromFileName(file.basename); if (!note) return; for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON)) { if (!(leaf.view instanceof DendronView)) continue; leaf.view.component.focusTo(vault, note); } } async activateView() { const leafs = this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON); if (leafs.length == 0) { const leaf = this.app.workspace.getLeftLeaf(false); await leaf.setViewState({ type: VIEW_TYPE_DENDRON, active: true, }); this.app.workspace.revealLeaf(leaf); } else { leafs.forEach((leaf) => this.app.workspace.revealLeaf(leaf)); } } async loadSettings() { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); } async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 0.815076470375061 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " this.tree.addFile(file, true).syncMetadata(this.resolveMetadata(file));\n return true;\n }\n onMetadataChanged(file: TFile): boolean {\n if (!this.isNote(file.extension)) return false;\n const note = this.tree.getFromFileName(file.basename);\n if (!note) return false;\n note.syncMetadata(this.resolveMetadata(file));\n return true;\n }", "score": 0.8044512271881104 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " for (const child of root.children)\n if (child instanceof TFile && this.isNote(child.extension))\n this.tree.addFile(child).syncMetadata(this.resolveMetadata(child));\n this.tree.sort();\n this.isIniatialized = true;\n }\n async createRootFolder() {\n return await this.app.vault.createFolder(this.config.path);\n }\n async createNote(baseName: string) {", "score": 0.7868186831474304 }, { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " content.setText(`\"${target.path}\" is not created yet. Click to create.`);\n this.containerEl.onclick = () => {\n vault.createNote(path).then((file) => openFile(app, file));\n };\n }\n}\nexport function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) {\n if (!target.note || !target.note.file) {\n return new UnresolvedRefRenderChild(app, container, target);\n } else {", "score": 0.7593975067138672 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " }\n init() {\n if (this.isIniatialized) return;\n this.tree = new NoteTree();\n const root = getFolderFile(this.app.vault, this.config.path);\n if (!(root instanceof TFolder)) {\n new InvalidRootModal(this).open();\n return;\n }\n this.folder = root;", "score": 0.754796028137207 } ]
typescript
activeFile.set(file);
import { App, TAbstractFile, TFile, TFolder } from "obsidian"; import { NoteMetadata, NoteTree } from "./note"; import { InvalidRootModal } from "../modal/invalid-root"; import { generateUUID, getFolderFile } from "../utils"; import { ParsedPath } from "../path"; export interface VaultConfig { path: string; name: string; } export class DendronVault { folder: TFolder; tree: NoteTree; isIniatialized = false; constructor(public app: App, public config: VaultConfig) {} private resolveMetadata(file: TFile): NoteMetadata | undefined { const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter; if (!frontmatter) return undefined; return { title: frontmatter["title"], }; } init() { if (this.isIniatialized) return; this.tree = new NoteTree(); const root = getFolderFile(this.app.vault, this.config.path); if (!(root instanceof TFolder)) { new InvalidRootModal(this).open(); return; } this.folder = root; for (const child of root.children) if (child instanceof TFile && this.isNote(child.extension)) this.tree.addFile(child).syncMetadata(this.resolveMetadata(child)); this.tree.sort(); this.isIniatialized = true; } async createRootFolder() { return await this.app.vault.createFolder(this.config.path); } async createNote(baseName: string) { const filePath = `${this.config.path}/${baseName}.md`; return await this.app.vault.create(filePath, ""); } async generateFronmatter(file: TFile) { if (!this.isNote(file.extension)) return; const note = this.tree.getFromFileName(file.basename); if (!note) return false; return await this.app.fileManager.processFrontMatter(file, (fronmatter) => { if (!fronmatter.id) fronmatter.id = generateUUID(); if (!fronmatter.title) fronmatter.title = note.title; if (fronmatter.desc === undefined) fronmatter.desc = ""; if (!fronmatter.created) fronmatter.created = file.stat.ctime; if (!fronmatter.updated) fronmatter.updated = file.stat.mtime; }); } isNote(extension: string) { return extension === "md"; } onFileCreated(file: TAbstractFile): boolean { if (!(file instanceof TFile) || !this.isNote(file.extension)) return false; this.tree.addFile(file, true).syncMetadata(this.resolveMetadata(file)); return true; } onMetadataChanged(file: TFile): boolean { if (!this.isNote(file.extension)) return false; const note = this.tree.getFromFileName(file.basename); if (!note) return false; note.syncMetadata(this.resolveMetadata(file)); return true; } onFileDeleted(parsed: ParsedPath): boolean { if (!this.isNote(parsed.extension)) return false;
const note = this.tree.deleteByFileName(parsed.basename);
if (note?.parent) { note.syncMetadata(undefined); } return true; } }
src/engine/vault.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/engine/note.ts", "retrieved_chunk": " }\n addFile(file: TFile, sort = false) {\n const titlecase = isUseTitleCase(file.basename);\n const path = NoteTree.getPathFromFileName(file.basename);\n let currentNote: Note = this.root;\n if (!NoteTree.isRootPath(path))\n for (const name of path) {\n let note: Note | undefined = currentNote.findChildren(name);\n if (!note) {\n note = new Note(name, titlecase);", "score": 0.8188101053237915 }, { "filename": "src/main.ts", "retrieved_chunk": " this.updateNoteStore();\n }\n };\n revealFile(file: TFile) {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (!vault) return;\n const note = vault.tree.getFromFileName(file.basename);\n if (!note) return;\n for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON)) {\n if (!(leaf.view instanceof DendronView)) continue;", "score": 0.8101806044578552 }, { "filename": "src/main.ts", "retrieved_chunk": " this.updateNoteStore();\n }\n };\n onDeleteFile = (file: TAbstractFile) => {\n // file.parent is null when file is deleted\n const parsed = parsePath(file.path);\n const vault = this.workspace.findVaultByParentPath(parsed.dir);\n if (vault && vault.onFileDeleted(parsed)) {\n this.updateNoteStore();\n }", "score": 0.8086493015289307 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " if (NoteTree.isRootPath(path)) return this.root;\n let currentNote: Note = this.root;\n for (const name of path) {\n const found = currentNote.findChildren(name);\n if (!found) return undefined;\n currentNote = found;\n }\n return currentNote;\n }\n deleteByFileName(name: string) {", "score": 0.8079401254653931 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " currentNote.appendChild(note);\n if (sort) currentNote.sortChildren(false);\n }\n currentNote = note;\n }\n currentNote.file = file;\n return currentNote;\n }\n getFromFileName(name: string) {\n const path = NoteTree.getPathFromFileName(name);", "score": 0.7926537394523621 } ]
typescript
const note = this.tree.deleteByFileName(parsed.basename);
import { App, ButtonComponent, MarkdownRenderChild, MarkdownRenderer, MarkdownRendererConstructorType, OpenViewState, TFile, setIcon, } from "obsidian"; import { openFile } from "../utils"; import { MaybeNoteRef, RefRange, getRefContentRange, anchorToLinkSubpath } from "../engine/ref"; import { dendronActivityBarName } from "../icons"; const MarkdownRendererConstructor = MarkdownRenderer as unknown as MarkdownRendererConstructorType; class RefMarkdownRenderer extends MarkdownRendererConstructor { constructor(public parent: NoteRefRenderChild, queed: boolean) { super(parent.app, parent.previewEl, queed); } get file(): TFile { return this.parent.file; } edit(markdown: string) { this.parent.editContent(markdown); } } export class NoteRefRenderChild extends MarkdownRenderChild { previewEl: HTMLElement; renderer: RefMarkdownRenderer; file: TFile; range: RefRange | null; markdown?: string; found = false; constructor( public readonly app: App, public readonly containerEl: HTMLElement, public readonly ref: MaybeNoteRef ) { super(containerEl); if (!ref.note || !ref.note.file) throw Error("NoteRefChild only accept ref with non-blank note and file"); this.file = ref.note.file; this.containerEl.classList.add("dendron-embed", "markdown-embed", "inline-embed", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); this.previewEl = this.containerEl.createDiv("markdown-embed-content"); const buttonComponent = new ButtonComponent(this.containerEl); buttonComponent.buttonEl.remove(); buttonComponent.buttonEl = this.containerEl.createDiv( "markdown-embed-link" ) as unknown as HTMLButtonElement; buttonComponent.setIcon("lucide-link").setTooltip("Open link"); buttonComponent.buttonEl.onclick = () => { const openState: OpenViewState = {}; if (this.ref.subpath) { openState.eState = { subpath: anchorToLinkSubpath( this.ref.subpath.start, this.app.metadataCache.getFileCache(this.file)?.headings ), }; } openFile(this.app, this.ref.note?.file, openState); }; this.renderer = new RefMarkdownRenderer(this, true); this.addChild(this.renderer); } async getContent(): Promise<string> { this.markdown = await this.app.vault.cachedRead(this.file); if (!this.ref.subpath) { this.found = true; return this.markdown; } const metadata = this.app.metadataCache.getFileCache(this.file); if (metadata) { this.range = getRefContentRange(this.ref.subpath, metadata); if (this.range) { let currentLineIndex = 0;
while (currentLineIndex < this.range.startLineOffset) {
if (this.markdown[this.range.start] === "\n") currentLineIndex++; this.range.start++; } this.found = true; return this.markdown.substring(this.range.start, this.range.end); } } this.found = false; return "### Unable to find section " .concat(this.ref.subpath.text, " in ") .concat(this.file.basename); } editContent(target: string) { if (!this.found || !this.markdown) return; let md; if (!this.range) { md = target; } else { const before = this.markdown.substring(0, this.range.start); md = before + target; if (this.range.end) { const after = this.markdown.substring(this.range.end); md += after; } } this.app.vault.modify(this.file, md); } async loadFile() { const content = await this.getContent(); this.renderer.renderer.set(content); } onload(): void { super.onload(); this.registerEvent( this.app.metadataCache.on("changed", async (file, data) => { if (file === this.file) { this.loadFile(); } }) ); } } export class UnresolvedRefRenderChild extends MarkdownRenderChild { constructor(app: App, containerEl: HTMLElement, target: MaybeNoteRef) { super(containerEl); this.containerEl.classList.add("dendron-embed", "file-embed", "mod-empty", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); const content = this.containerEl.createDiv(); const { vaultName, vault, path } = target; if (vaultName === "") { content.setText("Vault name are unspecified in link."); return; } else if (!vault) { content.setText(`Vault ${vaultName} are not found.`); return; } else if (path === "") { content.setText("Note path are unspecified in link."); return; } content.setText(`"${target.path}" is not created yet. Click to create.`); this.containerEl.onclick = () => { vault.createNote(path).then((file) => openFile(app, file)); }; } } export function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) { if (!target.note || !target.note.file) { return new UnresolvedRefRenderChild(app, container, target); } else { return new NoteRefRenderChild(app, container, target); } }
src/custom-resolver/ref-render.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/custom-resolver/link-markdown-processor.ts", "retrieved_chunk": " if (linksEl.length == 0) return;\n const section = ctx.getSectionInfo(el);\n const cache = app.metadataCache.getCache(ctx.sourcePath);\n if (!section || !cache?.links) return;\n const links = cache.links.filter(\n (link) =>\n link.position.start.line >= section.lineStart && link.position.end.line <= section.lineEnd\n );\n if (links.length !== linksEl.length) {\n console.warn(\"Cannot post process link\");", "score": 0.8311755657196045 }, { "filename": "src/engine/ref.ts", "retrieved_chunk": " range.end = position.end.offset;\n } else if (start.type === \"header\") {\n if (!metadata.headings) return null;\n const { index: startHeadingIndex, heading: startHeading } = findHeadingByGithubSlug(\n metadata.headings,\n start.name\n );\n if (!startHeading) return null;\n range.start = startHeading.position.start.offset;\n range.startLineOffset = start.lineOffset;", "score": 0.8253241777420044 }, { "filename": "src/engine/ref.ts", "retrieved_chunk": " };\n}\nexport function getRefContentRange(subpath: RefSubpath, metadata: CachedMetadata): RefRange | null {\n const range: RefRange = {\n start: 0,\n startLineOffset: 0,\n end: undefined,\n };\n const { start, end } = subpath;\n if (start.type === \"begin\") {", "score": 0.817988932132721 }, { "filename": "src/engine/ref.ts", "retrieved_chunk": " if (!end) return range;\n if (end.type === \"begin\") {\n return null;\n } else if (end.type === \"end\") {\n range.end = undefined;\n } else if (end.type === \"header\") {\n if (!metadata.headings) return null;\n const { heading } = findHeadingByGithubSlug(metadata.headings, end.name);\n if (!heading) return null;\n range.end = heading?.position.end.offset;", "score": 0.793766438961029 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " const iter = decor.iter();\n let found = false;\n while (iter.value) {\n if ((iter.value as any).isReplace) {\n const link = links.find(({ start }) => start === iter.from);\n if (link) {\n found = true;\n link.showSource = false;\n if (link.hasAlias) {\n iter.next(); // skip before pipe", "score": 0.7818160653114319 } ]
typescript
while (currentLineIndex < this.range.startLineOffset) {
import { App, TAbstractFile, TFile, TFolder } from "obsidian"; import { NoteMetadata, NoteTree } from "./note"; import { InvalidRootModal } from "../modal/invalid-root"; import { generateUUID, getFolderFile } from "../utils"; import { ParsedPath } from "../path"; export interface VaultConfig { path: string; name: string; } export class DendronVault { folder: TFolder; tree: NoteTree; isIniatialized = false; constructor(public app: App, public config: VaultConfig) {} private resolveMetadata(file: TFile): NoteMetadata | undefined { const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter; if (!frontmatter) return undefined; return { title: frontmatter["title"], }; } init() { if (this.isIniatialized) return; this.tree = new NoteTree(); const root = getFolderFile(this.app.vault, this.config.path); if (!(root instanceof TFolder)) { new InvalidRootModal(this).open(); return; } this.folder = root; for (const child of root.children) if (child instanceof TFile && this.isNote(child.extension)) this.tree.addFile(child).syncMetadata(this.resolveMetadata(child)); this.tree.sort(); this.isIniatialized = true; } async createRootFolder() { return await this.app.vault.createFolder(this.config.path); } async createNote(baseName: string) { const filePath = `${this.config.path}/${baseName}.md`; return await this.app.vault.create(filePath, ""); } async generateFronmatter(file: TFile) { if (!this.isNote(file.extension)) return; const note = this.tree.getFromFileName(file.basename); if (!note) return false; return await this.app.fileManager.processFrontMatter(file, (fronmatter) => { if (!fronmatter.id) fronmatter.id = generateUUID(); if (!fronmatter.title) fronmatter.title = note.title; if (fronmatter.desc === undefined) fronmatter.desc = ""; if (!fronmatter.created) fronmatter.created = file.stat.ctime; if (!fronmatter.updated) fronmatter.updated = file.stat.mtime; }); } isNote(extension: string) { return extension === "md"; } onFileCreated(file: TAbstractFile): boolean { if (!(file instanceof TFile) || !this.isNote(file.extension)) return false; this.tree.addFile(file, true).syncMetadata(this.resolveMetadata(file)); return true; } onMetadataChanged(file: TFile): boolean { if (!this.isNote(file.extension)) return false; const note = this.tree.getFromFileName(file.basename); if (!note) return false; note.syncMetadata(this.resolveMetadata(file)); return true; } onFileDeleted
(parsed: ParsedPath): boolean {
if (!this.isNote(parsed.extension)) return false; const note = this.tree.deleteByFileName(parsed.basename); if (note?.parent) { note.syncMetadata(undefined); } return true; } }
src/engine/vault.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/main.ts", "retrieved_chunk": " this.updateNoteStore();\n }\n };\n onDeleteFile = (file: TAbstractFile) => {\n // file.parent is null when file is deleted\n const parsed = parsePath(file.path);\n const vault = this.workspace.findVaultByParentPath(parsed.dir);\n if (vault && vault.onFileDeleted(parsed)) {\n this.updateNoteStore();\n }", "score": 0.8208931088447571 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " }\n addFile(file: TFile, sort = false) {\n const titlecase = isUseTitleCase(file.basename);\n const path = NoteTree.getPathFromFileName(file.basename);\n let currentNote: Note = this.root;\n if (!NoteTree.isRootPath(path))\n for (const name of path) {\n let note: Note | undefined = currentNote.findChildren(name);\n if (!note) {\n note = new Note(name, titlecase);", "score": 0.8132150173187256 }, { "filename": "src/main.ts", "retrieved_chunk": " this.updateNoteStore();\n }\n };\n revealFile(file: TFile) {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (!vault) return;\n const note = vault.tree.getFromFileName(file.basename);\n if (!note) return;\n for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON)) {\n if (!(leaf.view instanceof DendronView)) continue;", "score": 0.8097848296165466 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " if (NoteTree.isRootPath(path)) return this.root;\n let currentNote: Note = this.root;\n for (const name of path) {\n const found = currentNote.findChildren(name);\n if (!found) return undefined;\n currentNote = found;\n }\n return currentNote;\n }\n deleteByFileName(name: string) {", "score": 0.7981973886489868 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " currentNote.appendChild(note);\n if (sort) currentNote.sortChildren(false);\n }\n currentNote = note;\n }\n currentNote.file = file;\n return currentNote;\n }\n getFromFileName(name: string) {\n const path = NoteTree.getPathFromFileName(name);", "score": 0.7962328791618347 } ]
typescript
(parsed: ParsedPath): boolean {
import { EditorView, PluginValue, ViewUpdate } from "@codemirror/view"; import { App, Component, editorLivePreviewField } from "obsidian"; import { NoteRefRenderChild, createRefRenderer } from "./ref-render"; import { DendronWorkspace } from "../engine/workspace"; interface InternalEmbedWidget { end: number; href: string; sourcePath: string; start: string; title: string; children: Component[]; containerEl: HTMLElement; hacked?: boolean; initDOM(): HTMLElement; addChild(c: Component): void; applyTitle(container: HTMLElement, title: string): void; } export class RefLivePlugin implements PluginValue { constructor(public app: App, public workspace: DendronWorkspace) {} update(update: ViewUpdate) { if (!update.state.field(editorLivePreviewField)) { return; } update.view.state.facet(EditorView.decorations).forEach((d) => { if (typeof d !== "function") { const iter = d.iter(); while (iter.value) { const widget = iter.value.spec.widget; if (widget && widget.href && widget.sourcePath && widget.title) { const internalWidget = widget as InternalEmbedWidget; this.hack(internalWidget); } iter.next(); } } }); } hack(widget: InternalEmbedWidget) { if (widget.hacked) { return; } widget.hacked = true; const target = this.workspace.resolveRef(widget.sourcePath, widget.href); if (!target || target.type !== "maybe-note") return; const loadComponent = (widget: InternalEmbedWidget) => { const renderer =
createRefRenderer(target, this.app, widget.containerEl);
if (renderer instanceof NoteRefRenderChild) renderer.loadFile(); widget.addChild(renderer); }; widget.initDOM = function (this: InternalEmbedWidget) { this.containerEl = createDiv("internal-embed"); loadComponent(this); return this.containerEl; }; widget.applyTitle = function ( this: InternalEmbedWidget, container: HTMLElement, title: string ) { this.title = title; }; if (widget.containerEl) { console.log("Workaround"); widget.children[0].unload(); widget.children.pop(); loadComponent(widget); } } }
src/custom-resolver/ref-live.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/custom-resolver/ref-markdown-processor.ts", "retrieved_chunk": " embeddedItems.forEach((el) => {\n const link = el.getAttribute(\"src\");\n if (!link) return;\n const target = workspace.resolveRef(context.sourcePath, link);\n if (!target || target.type !== \"maybe-note\") return;\n const renderer = createRefRenderer(target, app, el as HTMLElement);\n if (renderer instanceof NoteRefRenderChild) promises.push(renderer.loadFile());\n context.addChild(renderer);\n });\n return Promise.all(promises);", "score": 0.8695917129516602 }, { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " content.setText(`\"${target.path}\" is not created yet. Click to create.`);\n this.containerEl.onclick = () => {\n vault.createNote(path).then((file) => openFile(app, file));\n };\n }\n}\nexport function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) {\n if (!target.note || !target.note.file) {\n return new UnresolvedRefRenderChild(app, container, target);\n } else {", "score": 0.8294126987457275 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " widget.updateTitle();\n this.widgets.splice(lastWidgetIndex, 1);\n return widget;\n }\n return new LinkWidget(this.app, this.workspace, sourcePath, link.href, link.title);\n }\n buildDecorations(view: EditorView): DecorationSet {\n if (!view.state.field(editorLivePreviewField)) {\n return Decoration.none;\n }", "score": 0.8270449638366699 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " if (found) break;\n }\n }\n getWidget(link: LinkData, sourcePath: string) {\n const lastWidgetIndex = this.widgets.findIndex(\n (widget) => widget.href === link.href && widget.sourcePath === sourcePath\n );\n if (lastWidgetIndex >= 0) {\n const widget = this.widgets[lastWidgetIndex];\n widget.title = link.title;", "score": 0.8169300556182861 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " this.app.workspace.openLinkText(this.href, this.sourcePath);\n });\n }\n updateTitle() {\n this.containerEl.children[0].setText(\n renderLinkTitle(this.app, this.workspace, this.href, this.title, this.sourcePath)\n );\n }\n toDOM(view: EditorView): HTMLElement {\n if (!this.containerEl) this.initDOM();", "score": 0.7963556051254272 } ]
typescript
createRefRenderer(target, this.app, widget.containerEl);
import { App, ButtonComponent, MarkdownRenderChild, MarkdownRenderer, MarkdownRendererConstructorType, OpenViewState, TFile, setIcon, } from "obsidian"; import { openFile } from "../utils"; import { MaybeNoteRef, RefRange, getRefContentRange, anchorToLinkSubpath } from "../engine/ref"; import { dendronActivityBarName } from "../icons"; const MarkdownRendererConstructor = MarkdownRenderer as unknown as MarkdownRendererConstructorType; class RefMarkdownRenderer extends MarkdownRendererConstructor { constructor(public parent: NoteRefRenderChild, queed: boolean) { super(parent.app, parent.previewEl, queed); } get file(): TFile { return this.parent.file; } edit(markdown: string) { this.parent.editContent(markdown); } } export class NoteRefRenderChild extends MarkdownRenderChild { previewEl: HTMLElement; renderer: RefMarkdownRenderer; file: TFile; range: RefRange | null; markdown?: string; found = false; constructor( public readonly app: App, public readonly containerEl: HTMLElement, public readonly ref: MaybeNoteRef ) { super(containerEl); if (!ref.note || !ref.note.file) throw Error("NoteRefChild only accept ref with non-blank note and file"); this.file = ref.note.file; this.containerEl.classList.add("dendron-embed", "markdown-embed", "inline-embed", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); this.previewEl = this.containerEl.createDiv("markdown-embed-content"); const buttonComponent = new ButtonComponent(this.containerEl); buttonComponent.buttonEl.remove(); buttonComponent.buttonEl = this.containerEl.createDiv( "markdown-embed-link" ) as unknown as HTMLButtonElement; buttonComponent.setIcon("lucide-link").setTooltip("Open link"); buttonComponent.buttonEl.onclick = () => { const openState: OpenViewState = {}; if (this.ref.subpath) { openState.eState = { subpath: anchorToLinkSubpath( this.ref.subpath.start, this.app.metadataCache.getFileCache(this.file)?.headings ), }; } openFile(this.app, this.ref.note?.file, openState); }; this.renderer = new RefMarkdownRenderer(this, true); this.addChild(this.renderer); } async getContent(): Promise<string> { this.markdown = await this.app.vault.cachedRead(this.file); if (!this.ref.subpath) { this.found = true; return this.markdown; } const metadata = this.app.metadataCache.getFileCache(this.file); if (metadata) { this.range = getRefContentRange(this.ref.subpath, metadata); if (this.range) { let currentLineIndex = 0; while (currentLineIndex < this.range.startLineOffset) { if (this.markdown[this.range.start] === "\n") currentLineIndex++; this.range.start++; } this.found = true; return this.markdown.substring(this.range.start, this.range.end); } } this.found = false; return "### Unable to find section " .concat(this.ref.subpath.text, " in ") .concat(this.file.basename); } editContent(target: string) { if (!this.found || !this.markdown) return; let md; if (!this.range) { md = target; } else { const before = this.markdown.substring(0, this.range.start); md = before + target; if (this.range.end) { const after = this.markdown.substring(this.range.end); md += after; } } this.app.vault.modify(this.file, md); } async loadFile() { const content = await this.getContent(); this.renderer.renderer.set(content); } onload(): void { super.onload(); this.registerEvent( this.app.metadataCache.on("changed", async (file, data) => { if (file === this.file) { this.loadFile(); } }) ); } } export class UnresolvedRefRenderChild extends MarkdownRenderChild { constructor(app: App, containerEl: HTMLElement, target: MaybeNoteRef) { super(containerEl); this.containerEl.classList.add("dendron-embed", "file-embed", "mod-empty", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); const content = this.containerEl.createDiv();
const { vaultName, vault, path } = target;
if (vaultName === "") { content.setText("Vault name are unspecified in link."); return; } else if (!vault) { content.setText(`Vault ${vaultName} are not found.`); return; } else if (path === "") { content.setText("Note path are unspecified in link."); return; } content.setText(`"${target.path}" is not created yet. Click to create.`); this.containerEl.onclick = () => { vault.createNote(path).then((file) => openFile(app, file)); }; } } export function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) { if (!target.note || !target.note.file) { return new UnresolvedRefRenderChild(app, container, target); } else { return new NoteRefRenderChild(app, container, target); } }
src/custom-resolver/ref-render.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/invalid-root.ts", "retrieved_chunk": "import { Modal, Setting } from \"obsidian\";\nimport { DendronVault } from \"../engine/vault\";\nexport class InvalidRootModal extends Modal {\n constructor(private dendronVault: DendronVault) {\n super(dendronVault.app);\n }\n onOpen(): void {\n this.contentEl.createEl(\"h1\", { text: \"Invalid Root\" });\n this.contentEl.createEl(\"p\", {\n text: `\"${this.dendronVault.config.path}\" is not folder. Do you want to create this folder?`,", "score": 0.8380360007286072 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " renderSuggestion(item: LookupItem | null, el: HTMLElement) {\n el.classList.add(\"mod-complex\");\n el.createEl(\"div\", { cls: \"suggestion-content\" }, (el) => {\n el.createEl(\"div\", { text: item?.note.title ?? \"Create New\", cls: \"suggestion-title\" });\n el.createEl(\"small\", {\n text: item\n ? item.note.getPath() +\n (this.workspace.vaultList.length > 1 ? ` (${item.vault.config.name})` : \"\")\n : \"Note does not exist\",\n cls: \"suggestion-content\",", "score": 0.7955948710441589 }, { "filename": "src/settings.ts", "retrieved_chunk": " }\n display(): void {\n const { containerEl } = this;\n containerEl.empty();\n containerEl.createEl(\"h2\", { text: \"Dendron Tree Settting\" });\n new Setting(containerEl)\n .setName(\"Auto Generate Front Matter\")\n .setDesc(\"Generate front matter for new file even if file is created outside of Dendron tree\")\n .addToggle((toggle) => {\n toggle.setValue(this.plugin.settings.autoGenerateFrontmatter).onChange(async (value) => {", "score": 0.7924127578735352 }, { "filename": "src/custom-resolver/ref-live.ts", "retrieved_chunk": " }\n widget.hacked = true;\n const target = this.workspace.resolveRef(widget.sourcePath, widget.href);\n if (!target || target.type !== \"maybe-note\") return;\n const loadComponent = (widget: InternalEmbedWidget) => {\n const renderer = createRefRenderer(target, this.app, widget.containerEl);\n if (renderer instanceof NoteRefRenderChild) renderer.loadFile();\n widget.addChild(renderer);\n };\n widget.initDOM = function (this: InternalEmbedWidget) {", "score": 0.7754829525947571 }, { "filename": "src/main.ts", "retrieved_chunk": " settings: DendronTreePluginSettings;\n workspace: DendronWorkspace = new DendronWorkspace(this.app);\n customResolver?: CustomResolver;\n async onload() {\n await this.loadSettings();\n await this.migrateSettings();\n addIcon(dendronActivityBarName, dendronActivityBarIcon);\n this.addCommand({\n id: \"dendron-lookup\",\n name: \"Lookup Note\",", "score": 0.7699249386787415 } ]
typescript
const { vaultName, vault, path } = target;
import type { Stat, TFile, Vault } from "obsidian"; import { Note, NoteTree, generateNoteTitle, isUseTitleCase } from "./note"; import { parsePath } from "../path"; describe("note title", () => { it("use title case when file name is lowercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("aku.cinta.kamu-milikku.md"))).toBe( "Kamu Milikku" ); }); it("use file name when note name contain uppercase", () => { expect(generateNoteTitle("Kamu-Milikku", isUseTitleCase("aku.cinta.Kamu-Milikku.md"))).toBe( "Kamu-Milikku" ); }); it("use file name when file name contain uppercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("Aku.cinta.kamu-milikku.md"))).toBe( "kamu-milikku" ); }); }); describe("note class", () => { it("append and remove child work", () => { const child = new Note("lala", true); expect(child.parent).toBeUndefined(); const parent = new Note("apa", true); expect(parent.children).toEqual([]); parent.appendChild(child); expect(child.parent).toBe(parent); expect(parent.children).toEqual([child]); parent.removeChildren(child); expect(child.parent).toBeUndefined(); expect(parent.children).toEqual([]); }); it("append child must throw if child already has parent", () => { const origParent = new Note("root", true); const parent = new Note("root2", true); const child = new Note("child", true); origParent.appendChild(child); expect(() => parent.appendChild(child)).toThrowError("has parent"); }); it("find children work", () => { const parent = new Note("parent", true); const child1 = new Note("child1", true); const child2 = new Note("child2", true); const child3 = new Note("child3", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3);
expect(parent.findChildren("child1")).toBe(child1);
expect(parent.findChildren("child2")).toBe(child2); expect(parent.findChildren("child3")).toBe(child3); expect(parent.findChildren("child4")).toBeUndefined(); }); it("non-recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("gajak", true); const child2 = new Note("lumba", true); const child3 = new Note("biawak", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.children).toEqual([child1, child2, child3]); parent.sortChildren(false); expect(parent.children).toEqual([child3, child1, child2]); }); it("recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("lumba", true); const child2 = new Note("galak", true); const grandchild1 = new Note("lupa", true); const grandchild2 = new Note("apa", true); const grandchild3 = new Note("abu", true); const grandchild4 = new Note("lagi", true); parent.appendChild(child1); child1.appendChild(grandchild1); child1.appendChild(grandchild2); parent.appendChild(child2); child2.appendChild(grandchild3); child2.appendChild(grandchild4); expect(parent.children).toEqual([child1, child2]); expect(child1.children).toEqual([grandchild1, grandchild2]); expect(child2.children).toEqual([grandchild3, grandchild4]); parent.sortChildren(true); expect(parent.children).toEqual([child2, child1]); expect(child1.children).toEqual([grandchild2, grandchild1]); expect(child2.children).toEqual([grandchild3, grandchild4]); }); it("get path on non-root", () => { const root = new Note("root", true); const ch1 = new Note("parent", true); const ch2 = new Note("parent2", true); const ch3 = new Note("child", true); root.appendChild(ch1); ch1.appendChild(ch2); ch2.appendChild(ch3); expect(ch3.getPath()).toBe("parent.parent2.child"); expect(ch3.getPathNotes()).toEqual([root, ch1, ch2, ch3]); }); it("get path on root", () => { const root = new Note("root", true); expect(root.getPath()).toBe("root"); expect(root.getPathNotes()).toEqual([root]); }); it("use generated title when titlecase true", () => { const note = new Note("aku-cinta", true); expect(note.title).toBe("Aku Cinta"); }); it("use filename as title when titlecase false", () => { const note = new Note("aKu-ciNta", false); expect(note.title).toBe("aKu-ciNta"); }); it("use metadata title when has metadata", () => { const note = new Note("aKu-ciNta", false); note.syncMetadata({ title: "Butuh Kamu", }); expect(note.title).toBe("Butuh Kamu"); }); }); function createTFile(path: string): TFile { const { basename, name, extension } = parsePath(path); return { basename, extension, name, parent: null, path: path, stat: null as unknown as Stat, vault: null as unknown as Vault, }; } describe("tree class", () => { it("add file without sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.root.children.length).toBe(1); expect(tree.root.children[0].name).toBe("abc"); expect(tree.root.children[0].children.length).toBe(1); expect(tree.root.children[0].children[0].name).toBe("def"); expect(tree.root.children[0].children[0].children.length).toBe(2); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); }); it("add file with sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md"), true); tree.addFile(createTFile("abc.def.ghi.md"), true); tree.addFile(createTFile("abc.def.mno.md"), true); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("get note by file base name", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("abc.def.jkl")?.name).toBe("jkl"); expect(tree.getFromFileName("abc.def.ghi")?.name).toBe("ghi"); expect(tree.getFromFileName("abc.def.mno")).toBeUndefined(); }); it("get note using blank path", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("")).toBeUndefined() }) it("delete note if do not have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")).toBeUndefined(); }); it("do not delete note if have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.addFile(createTFile("abc.def.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")?.name).toBe("abc"); expect(tree.getFromFileName("abc.def")?.name).toBe("def"); }); it("delete note and parent if do not have children and parent file is null", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc")); tree.addFile(createTFile("abc.def.ghi.md")); tree.deleteByFileName("abc.def.ghi"); expect(tree.getFromFileName("abc.def.ghi")).toBeUndefined(); expect(tree.getFromFileName("abc.def")).toBeUndefined(); expect(tree.getFromFileName("abc")?.name).toBe("abc"); }); it("sort note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.def.mno.md")); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); tree.sort(); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("flatten note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.jkl.mno.md")); expect(tree.flatten().map((note) => note.getPath())).toEqual([ "root", "abc", "abc.def", "abc.def.ghi", "abc.jkl", "abc.jkl.mno", ]); }); });
src/engine/note.test.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/engine/note.ts", "retrieved_chunk": " constructor(private originalName: string, private titlecase: boolean) {\n this.name = originalName.toLowerCase();\n this.syncMetadata(undefined);\n }\n appendChild(note: Note) {\n if (note.parent) throw Error(\"Note has parent\");\n note.parent = this;\n this.children.push(note);\n }\n removeChildren(note: Note) {", "score": 0.6970423460006714 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " note.parent = undefined;\n const index = this.children.indexOf(note);\n this.children.splice(index, 1);\n }\n findChildren(name: string) {\n const lower = name.toLowerCase();\n return this.children.find((note) => note.name == lower);\n }\n sortChildren(rescursive: boolean) {\n this.children.sort((a, b) => a.name.localeCompare(b.name));", "score": 0.6753627061843872 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " const note = this.getFromFileName(name);\n if (!note) return;\n note.file = undefined;\n if (note.children.length == 0) {\n let currentNote: Note | undefined = note;\n while (\n currentNote &&\n currentNote.parent &&\n !currentNote.file &&\n currentNote.children.length == 0", "score": 0.6533491015434265 }, { "filename": "src/path.test.ts", "retrieved_chunk": "import { parsePath } from \"./path\";\ndescribe(\"parse path\", () => {\n it(\"parse path with 2 component\", () => {\n expect(parsePath(\"abc/ll.md\")).toStrictEqual({\n dir: \"abc\",\n name: \"ll.md\",\n basename: \"ll\",\n extension: \"md\",\n });\n });", "score": 0.6486020684242249 }, { "filename": "src/custom-resolver/ref-markdown-processor.ts", "retrieved_chunk": " embeddedItems.forEach((el) => {\n const link = el.getAttribute(\"src\");\n if (!link) return;\n const target = workspace.resolveRef(context.sourcePath, link);\n if (!target || target.type !== \"maybe-note\") return;\n const renderer = createRefRenderer(target, app, el as HTMLElement);\n if (renderer instanceof NoteRefRenderChild) promises.push(renderer.loadFile());\n context.addChild(renderer);\n });\n return Promise.all(promises);", "score": 0.6436376571655273 } ]
typescript
expect(parent.findChildren("child1")).toBe(child1);
import { App, TFolder, parseLinktext } from "obsidian"; import { DendronVault, VaultConfig } from "./vault"; import { getFolderFile } from "../utils"; import { RefTarget, parseRefSubpath } from "./ref"; import { parsePath } from "../path"; const DENDRON_URI_START = "dendron://"; export class DendronWorkspace { vaultList: DendronVault[] = []; constructor(public app: App) {} changeVault(vaultList: VaultConfig[]) { this.vaultList = vaultList.map((config) => { return ( this.vaultList.find( (vault) => vault.config.name === config.name && vault.config.path === config.path ) ?? new DendronVault(this.app, config) ); }); for (const vault of this.vaultList) { vault.init(); } } findVaultByParent(parent: TFolder | null): DendronVault | undefined { return this.vaultList.find((vault) => vault.folder === parent); } findVaultByParentPath(path: string): DendronVault | undefined { const file = getFolderFile(this.app.vault, path); return file instanceof TFolder ? this.findVaultByParent(file) : undefined; } resolveRef(sourcePath: string, link: string): RefTarget | null { if (link.startsWith(DENDRON_URI_START)) { const [vaultName, rest] = link.slice(DENDRON_URI_START.length).split("/", 2) as ( | string | undefined )[]; const { path, subpath } = rest ? parseLinktext(rest) : { path: undefined, subpath: undefined, }; const vault = this.vaultList.find(({ config }) => config.name === vaultName); return { type: "maybe-note", vaultName: vaultName ?? "", vault, note: path ? vault?.tree?.getFromFileName(path) : undefined, path: path ?? "", subpath: subpath ? parseRefSubpath(subpath) : undefined, }; }
const { dir: vaultDir } = parsePath(sourcePath);
const vault = this.findVaultByParentPath(vaultDir); if (!vault) return null; const { path, subpath } = parseLinktext(link); const target = this.app.metadataCache.getFirstLinkpathDest(path, sourcePath); if (target && target.extension !== "md") return { type: "file", file: target, }; const note = vault.tree.getFromFileName(path); return { type: "maybe-note", vaultName: vault.config.name, vault: vault, note, path, subpath: parseRefSubpath(subpath.slice(1) ?? ""), }; } }
src/engine/workspace.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/engine/note.test.ts", "retrieved_chunk": " const { basename, name, extension } = parsePath(path);\n return {\n basename,\n extension,\n name,\n parent: null,\n path: path,\n stat: null as unknown as Stat,\n vault: null as unknown as Vault,\n };", "score": 0.8188959360122681 }, { "filename": "src/custom-resolver/link-open.ts", "retrieved_chunk": " return originalBoundedFunction(linktext, sourcePath, newLeaf, openViewState);\n let file = target.note?.file;\n if (!file) {\n if (target.vaultName === \"\") {\n new Notice(\"Vault name is unspecified in link.\");\n return;\n } else if (!target.vault) {\n new Notice(`Vault ${target.vaultName} is not found.`);\n return;\n } else if (target.path === \"\") {", "score": 0.8065333366394043 }, { "filename": "src/settings.ts", "retrieved_chunk": " autoGenerateFrontmatter: boolean;\n autoReveal: boolean;\n customResolver: boolean;\n}\nexport const DEFAULT_SETTINGS: DendronTreePluginSettings = {\n vaultList: [\n {\n name: \"root\",\n path: \"/\",\n },", "score": 0.7978621125221252 }, { "filename": "src/main.ts", "retrieved_chunk": " async migrateSettings() {\n function pathToVaultConfig(path: string) {\n const { name } = parsePath(path);\n if (name.length === 0)\n return {\n name: \"root\",\n path: \"/\",\n };\n let processed = path;\n if (processed.endsWith(\"/\")) processed = processed.slice(0, -1);", "score": 0.7956932187080383 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 0.7833077907562256 } ]
typescript
const { dir: vaultDir } = parsePath(sourcePath);
import { App, ButtonComponent, MarkdownRenderChild, MarkdownRenderer, MarkdownRendererConstructorType, OpenViewState, TFile, setIcon, } from "obsidian"; import { openFile } from "../utils"; import { MaybeNoteRef, RefRange, getRefContentRange, anchorToLinkSubpath } from "../engine/ref"; import { dendronActivityBarName } from "../icons"; const MarkdownRendererConstructor = MarkdownRenderer as unknown as MarkdownRendererConstructorType; class RefMarkdownRenderer extends MarkdownRendererConstructor { constructor(public parent: NoteRefRenderChild, queed: boolean) { super(parent.app, parent.previewEl, queed); } get file(): TFile { return this.parent.file; } edit(markdown: string) { this.parent.editContent(markdown); } } export class NoteRefRenderChild extends MarkdownRenderChild { previewEl: HTMLElement; renderer: RefMarkdownRenderer; file: TFile; range: RefRange | null; markdown?: string; found = false; constructor( public readonly app: App, public readonly containerEl: HTMLElement, public readonly ref: MaybeNoteRef ) { super(containerEl); if (!ref.note || !ref.note.file) throw Error("NoteRefChild only accept ref with non-blank note and file"); this.file = ref.note.file; this.containerEl.classList.add("dendron-embed", "markdown-embed", "inline-embed", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); this.previewEl = this.containerEl.createDiv("markdown-embed-content"); const buttonComponent = new ButtonComponent(this.containerEl); buttonComponent.buttonEl.remove(); buttonComponent.buttonEl = this.containerEl.createDiv( "markdown-embed-link" ) as unknown as HTMLButtonElement; buttonComponent.setIcon("lucide-link").setTooltip("Open link"); buttonComponent.buttonEl.onclick = () => { const openState: OpenViewState = {}; if (this.ref.subpath) { openState.eState = { subpath: anchorToLinkSubpath( this.ref.subpath.start, this.app.metadataCache.getFileCache(this.file)?.headings ), }; } openFile(this.app, this.ref.note?.file, openState); }; this.renderer = new RefMarkdownRenderer(this, true); this.addChild(this.renderer); } async getContent(): Promise<string> { this.markdown = await this.app.vault.cachedRead(this.file); if (!this.ref.subpath) { this.found = true; return this.markdown; } const metadata = this.app.metadataCache.getFileCache(this.file); if (metadata) { this.range = getRefContentRange(this.ref.subpath, metadata); if (this.range) { let currentLineIndex = 0; while (currentLineIndex < this.range.startLineOffset) { if (this.markdown[
this.range.start] === "\n") currentLineIndex++;
this.range.start++; } this.found = true; return this.markdown.substring(this.range.start, this.range.end); } } this.found = false; return "### Unable to find section " .concat(this.ref.subpath.text, " in ") .concat(this.file.basename); } editContent(target: string) { if (!this.found || !this.markdown) return; let md; if (!this.range) { md = target; } else { const before = this.markdown.substring(0, this.range.start); md = before + target; if (this.range.end) { const after = this.markdown.substring(this.range.end); md += after; } } this.app.vault.modify(this.file, md); } async loadFile() { const content = await this.getContent(); this.renderer.renderer.set(content); } onload(): void { super.onload(); this.registerEvent( this.app.metadataCache.on("changed", async (file, data) => { if (file === this.file) { this.loadFile(); } }) ); } } export class UnresolvedRefRenderChild extends MarkdownRenderChild { constructor(app: App, containerEl: HTMLElement, target: MaybeNoteRef) { super(containerEl); this.containerEl.classList.add("dendron-embed", "file-embed", "mod-empty", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); const content = this.containerEl.createDiv(); const { vaultName, vault, path } = target; if (vaultName === "") { content.setText("Vault name are unspecified in link."); return; } else if (!vault) { content.setText(`Vault ${vaultName} are not found.`); return; } else if (path === "") { content.setText("Note path are unspecified in link."); return; } content.setText(`"${target.path}" is not created yet. Click to create.`); this.containerEl.onclick = () => { vault.createNote(path).then((file) => openFile(app, file)); }; } } export function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) { if (!target.note || !target.note.file) { return new UnresolvedRefRenderChild(app, container, target); } else { return new NoteRefRenderChild(app, container, target); } }
src/custom-resolver/ref-render.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/custom-resolver/link-markdown-processor.ts", "retrieved_chunk": " if (linksEl.length == 0) return;\n const section = ctx.getSectionInfo(el);\n const cache = app.metadataCache.getCache(ctx.sourcePath);\n if (!section || !cache?.links) return;\n const links = cache.links.filter(\n (link) =>\n link.position.start.line >= section.lineStart && link.position.end.line <= section.lineEnd\n );\n if (links.length !== linksEl.length) {\n console.warn(\"Cannot post process link\");", "score": 0.8331525325775146 }, { "filename": "src/engine/ref.ts", "retrieved_chunk": " range.end = position.end.offset;\n } else if (start.type === \"header\") {\n if (!metadata.headings) return null;\n const { index: startHeadingIndex, heading: startHeading } = findHeadingByGithubSlug(\n metadata.headings,\n start.name\n );\n if (!startHeading) return null;\n range.start = startHeading.position.start.offset;\n range.startLineOffset = start.lineOffset;", "score": 0.8173102736473083 }, { "filename": "src/engine/ref.ts", "retrieved_chunk": " };\n}\nexport function getRefContentRange(subpath: RefSubpath, metadata: CachedMetadata): RefRange | null {\n const range: RefRange = {\n start: 0,\n startLineOffset: 0,\n end: undefined,\n };\n const { start, end } = subpath;\n if (start.type === \"begin\") {", "score": 0.8028399348258972 }, { "filename": "src/engine/ref.ts", "retrieved_chunk": " if (!end) return range;\n if (end.type === \"begin\") {\n return null;\n } else if (end.type === \"end\") {\n range.end = undefined;\n } else if (end.type === \"header\") {\n if (!metadata.headings) return null;\n const { heading } = findHeadingByGithubSlug(metadata.headings, end.name);\n if (!heading) return null;\n range.end = heading?.position.end.offset;", "score": 0.7779654264450073 }, { "filename": "src/engine/ref.ts", "retrieved_chunk": " let endHeading: HeadingCache | undefined;\n if (end && end.type === \"wildcard\") {\n endHeading = metadata.headings?.[startHeadingIndex + 1];\n } else {\n endHeading = metadata.headings?.find(\n ({ level }, index) => index > startHeadingIndex && level <= startHeading.level\n );\n }\n range.end = endHeading?.position.start.offset;\n }", "score": 0.771000862121582 } ]
typescript
this.range.start] === "\n") currentLineIndex++;
import { App, TFolder, parseLinktext } from "obsidian"; import { DendronVault, VaultConfig } from "./vault"; import { getFolderFile } from "../utils"; import { RefTarget, parseRefSubpath } from "./ref"; import { parsePath } from "../path"; const DENDRON_URI_START = "dendron://"; export class DendronWorkspace { vaultList: DendronVault[] = []; constructor(public app: App) {} changeVault(vaultList: VaultConfig[]) { this.vaultList = vaultList.map((config) => { return ( this.vaultList.find( (vault) => vault.config.name === config.name && vault.config.path === config.path ) ?? new DendronVault(this.app, config) ); }); for (const vault of this.vaultList) { vault.init(); } } findVaultByParent(parent: TFolder | null): DendronVault | undefined { return this.vaultList.find((vault) => vault.folder === parent); } findVaultByParentPath(path: string): DendronVault | undefined { const file = getFolderFile(this.app.vault, path); return file instanceof TFolder ? this.findVaultByParent(file) : undefined; } resolveRef(sourcePath: string, link: string): RefTarget | null { if (link.startsWith(DENDRON_URI_START)) { const [vaultName, rest] = link.slice(DENDRON_URI_START.length).split("/", 2) as ( | string | undefined )[]; const { path, subpath } = rest ? parseLinktext(rest) : { path: undefined, subpath: undefined, }; const vault = this.vaultList.find(({ config }) => config.name === vaultName); return { type: "maybe-note", vaultName: vaultName ?? "", vault, note: path ? vault?.tree?.getFromFileName(path) : undefined, path: path ?? "", subpath: subpath
? parseRefSubpath(subpath) : undefined, };
} const { dir: vaultDir } = parsePath(sourcePath); const vault = this.findVaultByParentPath(vaultDir); if (!vault) return null; const { path, subpath } = parseLinktext(link); const target = this.app.metadataCache.getFirstLinkpathDest(path, sourcePath); if (target && target.extension !== "md") return { type: "file", file: target, }; const note = vault.tree.getFromFileName(path); return { type: "maybe-note", vaultName: vault.config.name, vault: vault, note, path, subpath: parseRefSubpath(subpath.slice(1) ?? ""), }; } }
src/engine/workspace.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/engine/note.test.ts", "retrieved_chunk": " const { basename, name, extension } = parsePath(path);\n return {\n basename,\n extension,\n name,\n parent: null,\n path: path,\n stat: null as unknown as Stat,\n vault: null as unknown as Vault,\n };", "score": 0.8304281234741211 }, { "filename": "src/custom-resolver/link-open.ts", "retrieved_chunk": " return originalBoundedFunction(linktext, sourcePath, newLeaf, openViewState);\n let file = target.note?.file;\n if (!file) {\n if (target.vaultName === \"\") {\n new Notice(\"Vault name is unspecified in link.\");\n return;\n } else if (!target.vault) {\n new Notice(`Vault ${target.vaultName} is not found.`);\n return;\n } else if (target.path === \"\") {", "score": 0.8201085329055786 }, { "filename": "src/settings.ts", "retrieved_chunk": " const list = this.plugin.settings.vaultList;\n const nameLowecase = config.name.toLowerCase();\n if (list.find(({ name }) => name.toLowerCase() === nameLowecase)) {\n new Notice(\"Vault with same name already exist\");\n return false;\n }\n if (list.find(({ path }) => path === config.path)) {\n new Notice(\"Vault with same path already exist\");\n return false;\n }", "score": 0.7954133749008179 }, { "filename": "src/main.ts", "retrieved_chunk": " if (processed.startsWith(\"/\") && processed.length > 1) processed = processed.slice(1);\n return {\n name,\n path: processed,\n };\n }\n if (this.settings.vaultPath) {\n this.settings.vaultList = [pathToVaultConfig(this.settings.vaultPath)];\n this.settings.vaultPath = undefined;\n await this.saveSettings();", "score": 0.7935329079627991 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 0.7906693816184998 } ]
typescript
? parseRefSubpath(subpath) : undefined, };
import { App, SuggestModal, getIcon } from "obsidian"; import { Note } from "../engine/note"; import { openFile } from "../utils"; import { DendronVault } from "../engine/vault"; import { SelectVaultModal } from "./select-vault"; import { DendronWorkspace } from "../engine/workspace"; interface LookupItem { note: Note; vault: DendronVault; } export class LookupModal extends SuggestModal<LookupItem | null> { constructor(app: App, private workspace: DendronWorkspace, private initialQuery: string = "") { super(app); } onOpen(): void { super.onOpen(); if (this.initialQuery.length > 0) { this.inputEl.value = this.initialQuery; this.inputEl.dispatchEvent(new Event("input")); } } getSuggestions(query: string): (LookupItem | null)[] { const queryLowercase = query.toLowerCase(); const result: (LookupItem | null)[] = []; let foundExact = true; for (const vault of this.workspace.vaultList) { let currentFoundExact = false; for (const note of vault.tree.flatten()) { const path = note.getPath(); const item: LookupItem = { note, vault, }; if (path === queryLowercase) { currentFoundExact = true; result.unshift(item); continue; } if ( note.title.toLowerCase().includes(queryLowercase) || note.name.includes(queryLowercase) || path.includes(queryLowercase) ) result.push(item); } foundExact = foundExact && currentFoundExact; } if (!foundExact && queryLowercase.trim().length > 0) result.unshift(null); return result; } renderSuggestion(item: LookupItem | null, el: HTMLElement) { el.classList.add("mod-complex"); el.createEl("div", { cls: "suggestion-content" }, (el) => { el.createEl("div", { text: item?.note.title ?? "Create New", cls: "suggestion-title" }); el.createEl("small", { text: item ? item.note.getPath() + (this.workspace.vaultList.length > 1 ? ` (${item.vault.config.name})` : "") : "Note does not exist", cls: "suggestion-content", }); }); if (!item || !item.note.file) el.createEl("div", { cls: "suggestion-aux" }, (el) => { el.append(getIcon("plus")!); }); } async onChooseSuggestion(item: LookupItem | null, evt: MouseEvent | KeyboardEvent) { if (item && item.note.file) { openFile(this.app, item.note.file); return; } const path = item ? item.note.getPath() : this.inputEl.value; const doCreate = async (vault: DendronVault) => { const file = await vault.createNote(path);
return openFile(vault.app, file);
}; if (item?.vault) { await doCreate(item.vault); } else if (this.workspace.vaultList.length == 1) { await doCreate(this.workspace.vaultList[0]); } else { new SelectVaultModal(this.app, this.workspace, doCreate).open(); } } }
src/modal/lookup.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " content.setText(`\"${target.path}\" is not created yet. Click to create.`);\n this.containerEl.onclick = () => {\n vault.createNote(path).then((file) => openFile(app, file));\n };\n }\n}\nexport function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) {\n if (!target.note || !target.note.file) {\n return new UnresolvedRefRenderChild(app, container, target);\n } else {", "score": 0.8654217720031738 }, { "filename": "src/main.ts", "retrieved_chunk": " menu.addItem((item) => {\n item\n .setIcon(dendronActivityBarName)\n .setTitle(\"Reveal in Dendron Tree\")\n .onClick(() => this.revealFile(file));\n });\n };\n onResolveMetadata = (file: TFile) => {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (vault && vault.onMetadataChanged(file)) {", "score": 0.8422306776046753 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " }\n renderSuggestion(value: TFolder, el: HTMLElement): void {\n el.createDiv({\n text: value.path,\n });\n }\n selectSuggestion(value: TFolder, evt: MouseEvent | KeyboardEvent): void {\n this.inputEl.value = value.path;\n this.close();\n this.onSelected(value);", "score": 0.8420483469963074 }, { "filename": "src/main.ts", "retrieved_chunk": " update = newVault.onFileCreated(file) || update;\n }\n if (update) this.updateNoteStore();\n };\n onOpenFile(file: TFile | null) {\n activeFile.set(file);\n if (file && this.settings.autoReveal) this.revealFile(file);\n }\n onFileMenu = (menu: Menu, file: TAbstractFile) => {\n if (!(file instanceof TFile)) return;", "score": 0.8301801681518555 }, { "filename": "src/main.ts", "retrieved_chunk": " this.updateNoteStore();\n }\n };\n onDeleteFile = (file: TAbstractFile) => {\n // file.parent is null when file is deleted\n const parsed = parsePath(file.path);\n const vault = this.workspace.findVaultByParentPath(parsed.dir);\n if (vault && vault.onFileDeleted(parsed)) {\n this.updateNoteStore();\n }", "score": 0.8244851231575012 } ]
typescript
return openFile(vault.app, file);
import type { Stat, TFile, Vault } from "obsidian"; import { Note, NoteTree, generateNoteTitle, isUseTitleCase } from "./note"; import { parsePath } from "../path"; describe("note title", () => { it("use title case when file name is lowercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("aku.cinta.kamu-milikku.md"))).toBe( "Kamu Milikku" ); }); it("use file name when note name contain uppercase", () => { expect(generateNoteTitle("Kamu-Milikku", isUseTitleCase("aku.cinta.Kamu-Milikku.md"))).toBe( "Kamu-Milikku" ); }); it("use file name when file name contain uppercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("Aku.cinta.kamu-milikku.md"))).toBe( "kamu-milikku" ); }); }); describe("note class", () => { it("append and remove child work", () => { const child = new Note("lala", true); expect(child.parent).toBeUndefined(); const parent = new Note("apa", true); expect(parent.children).toEqual([]); parent.appendChild(child); expect(child.parent).toBe(parent); expect(parent.children).toEqual([child]); parent.removeChildren(child); expect(child.parent).toBeUndefined(); expect(parent.children).toEqual([]); }); it("append child must throw if child already has parent", () => { const origParent = new Note("root", true); const parent = new Note("root2", true); const child = new Note("child", true); origParent.appendChild(child); expect(() => parent.appendChild(child)).toThrowError("has parent"); }); it("find children work", () => { const parent = new Note("parent", true); const child1 = new Note("child1", true); const child2 = new Note("child2", true); const child3 = new Note("child3", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.findChildren("child1")).toBe(child1); expect(parent.findChildren("child2")).toBe(child2); expect(parent.findChildren("child3")).toBe(child3); expect(parent.findChildren("child4")).toBeUndefined(); }); it("non-recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("gajak", true); const child2 = new Note("lumba", true); const child3 = new Note("biawak", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.children).toEqual([child1, child2, child3]); parent.sortChildren(false); expect(parent.children).toEqual([child3, child1, child2]); }); it("recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("lumba", true); const child2 = new Note("galak", true); const grandchild1 = new Note("lupa", true); const grandchild2 = new Note("apa", true); const grandchild3 = new Note("abu", true); const grandchild4 = new Note("lagi", true); parent.appendChild(child1); child1.appendChild(grandchild1); child1.appendChild(grandchild2); parent.appendChild(child2); child2.appendChild(grandchild3); child2.appendChild(grandchild4); expect(parent.children).toEqual([child1, child2]); expect(child1.children).toEqual([grandchild1, grandchild2]); expect(child2.children).toEqual([grandchild3, grandchild4]); parent.sortChildren(true); expect(parent.children).toEqual([child2, child1]); expect(child1.children).toEqual([grandchild2, grandchild1]); expect(child2.children).toEqual([grandchild3, grandchild4]); }); it("get path on non-root", () => { const root = new Note("root", true); const ch1 = new Note("parent", true); const ch2 = new Note("parent2", true); const ch3 = new Note("child", true); root.appendChild(ch1); ch1.appendChild(ch2); ch2.appendChild(ch3); expect(ch3.getPath()).toBe("parent.parent2.child"); expect(ch3.getPathNotes()).toEqual([root, ch1, ch2, ch3]); }); it("get path on root", () => { const root = new Note("root", true); expect(root.getPath()).toBe("root"); expect(root.getPathNotes()).toEqual([root]); }); it("use generated title when titlecase true", () => { const note = new Note("aku-cinta", true); expect(note.title).toBe("Aku Cinta"); }); it("use filename as title when titlecase false", () => { const note = new Note("aKu-ciNta", false); expect(note.title).toBe("aKu-ciNta"); }); it("use metadata title when has metadata", () => { const note = new Note("aKu-ciNta", false); note.syncMetadata({ title: "Butuh Kamu", }); expect(note.title).toBe("Butuh Kamu"); }); }); function createTFile(path: string): TFile { const { basename, name, extension } = parsePath(path); return { basename, extension, name, parent: null, path: path, stat: null as unknown as Stat, vault: null as unknown as Vault, }; } describe("tree class", () => { it("add file without sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.root.children.length).toBe(1); expect(tree.root.children[0].name).toBe("abc"); expect(tree.root.children[0].children.length).toBe(1); expect(tree.root.children[0].children[0].name).toBe("def"); expect(tree.root.children[0].children[0].children.length).toBe(2); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); }); it("add file with sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md"), true); tree.addFile(createTFile("abc.def.ghi.md"), true); tree.addFile(createTFile("abc.def.mno.md"), true); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("get note by file base name", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md"));
expect(tree.getFromFileName("abc.def.jkl")?.name).toBe("jkl");
expect(tree.getFromFileName("abc.def.ghi")?.name).toBe("ghi"); expect(tree.getFromFileName("abc.def.mno")).toBeUndefined(); }); it("get note using blank path", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("")).toBeUndefined() }) it("delete note if do not have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")).toBeUndefined(); }); it("do not delete note if have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.addFile(createTFile("abc.def.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")?.name).toBe("abc"); expect(tree.getFromFileName("abc.def")?.name).toBe("def"); }); it("delete note and parent if do not have children and parent file is null", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc")); tree.addFile(createTFile("abc.def.ghi.md")); tree.deleteByFileName("abc.def.ghi"); expect(tree.getFromFileName("abc.def.ghi")).toBeUndefined(); expect(tree.getFromFileName("abc.def")).toBeUndefined(); expect(tree.getFromFileName("abc")?.name).toBe("abc"); }); it("sort note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.def.mno.md")); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); tree.sort(); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("flatten note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.jkl.mno.md")); expect(tree.flatten().map((note) => note.getPath())).toEqual([ "root", "abc", "abc.def", "abc.def.ghi", "abc.jkl", "abc.jkl.mno", ]); }); });
src/engine/note.test.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/path.test.ts", "retrieved_chunk": " dir: \"\",\n name: \"baca.buku.md\",\n basename: \"baca.buku\",\n extension: \"md\",\n });\n });\n it(\"parse path with multiple component\", () => {\n expect(parsePath(\"baca/buku/dirumah/pacar.md\")).toStrictEqual({\n dir: \"baca/buku/dirumah\",\n name: \"pacar.md\",", "score": 0.5964031219482422 }, { "filename": "src/custom-resolver/link-render.ts", "retrieved_chunk": " return title;\n }\n const ref = workspace.resolveRef(sourcePath, href);\n if (!ref || ref.type !== \"maybe-note\" || !ref.note?.file) {\n return href;\n }\n const fileTitle = app.metadataCache.getFileCache(ref.note.file)?.frontmatter?.[\"title\"];\n return fileTitle ?? href;\n}", "score": 0.5501394867897034 }, { "filename": "src/main.ts", "retrieved_chunk": " this.onRootFolderChanged();\n this.registerEvent(this.app.vault.on(\"create\", this.onCreateFile));\n this.registerEvent(this.app.vault.on(\"delete\", this.onDeleteFile));\n this.registerEvent(this.app.vault.on(\"rename\", this.onRenameFile));\n this.registerEvent(this.app.metadataCache.on(\"resolve\", this.onResolveMetadata));\n this.registerEvent(this.app.workspace.on(\"file-open\", this.onOpenFile, this));\n this.registerEvent(this.app.workspace.on(\"file-menu\", this.onFileMenu));\n });\n this.configureCustomResolver();\n }", "score": 0.5361451506614685 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " for (const child of root.children)\n if (child instanceof TFile && this.isNote(child.extension))\n this.tree.addFile(child).syncMetadata(this.resolveMetadata(child));\n this.tree.sort();\n this.isIniatialized = true;\n }\n async createRootFolder() {\n return await this.app.vault.createFolder(this.config.path);\n }\n async createNote(baseName: string) {", "score": 0.5315123796463013 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " )\n this.nameText.setValue(this.generateName(newFolder));\n this.folder = newFolder;\n });\n });\n new Setting(this.contentEl).setName(\"Vault Name\").addText((text) => {\n this.nameText = text;\n });\n new Setting(this.contentEl).addButton((btn) => {\n btn", "score": 0.5185044407844543 } ]
typescript
expect(tree.getFromFileName("abc.def.jkl")?.name).toBe("jkl");
import { App, ButtonComponent, MarkdownRenderChild, MarkdownRenderer, MarkdownRendererConstructorType, OpenViewState, TFile, setIcon, } from "obsidian"; import { openFile } from "../utils"; import { MaybeNoteRef, RefRange, getRefContentRange, anchorToLinkSubpath } from "../engine/ref"; import { dendronActivityBarName } from "../icons"; const MarkdownRendererConstructor = MarkdownRenderer as unknown as MarkdownRendererConstructorType; class RefMarkdownRenderer extends MarkdownRendererConstructor { constructor(public parent: NoteRefRenderChild, queed: boolean) { super(parent.app, parent.previewEl, queed); } get file(): TFile { return this.parent.file; } edit(markdown: string) { this.parent.editContent(markdown); } } export class NoteRefRenderChild extends MarkdownRenderChild { previewEl: HTMLElement; renderer: RefMarkdownRenderer; file: TFile; range: RefRange | null; markdown?: string; found = false; constructor( public readonly app: App, public readonly containerEl: HTMLElement, public readonly ref: MaybeNoteRef ) { super(containerEl); if (!ref.note || !ref.note.file) throw Error("NoteRefChild only accept ref with non-blank note and file"); this.file = ref.note.file; this.containerEl.classList.add("dendron-embed", "markdown-embed", "inline-embed", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); this.previewEl = this.containerEl.createDiv("markdown-embed-content"); const buttonComponent = new ButtonComponent(this.containerEl); buttonComponent.buttonEl.remove(); buttonComponent.buttonEl = this.containerEl.createDiv( "markdown-embed-link" ) as unknown as HTMLButtonElement; buttonComponent.setIcon("lucide-link").setTooltip("Open link"); buttonComponent.buttonEl.onclick = () => { const openState: OpenViewState = {}; if (this.ref.subpath) { openState.eState = {
subpath: anchorToLinkSubpath( this.ref.subpath.start, this.app.metadataCache.getFileCache(this.file)?.headings ), };
} openFile(this.app, this.ref.note?.file, openState); }; this.renderer = new RefMarkdownRenderer(this, true); this.addChild(this.renderer); } async getContent(): Promise<string> { this.markdown = await this.app.vault.cachedRead(this.file); if (!this.ref.subpath) { this.found = true; return this.markdown; } const metadata = this.app.metadataCache.getFileCache(this.file); if (metadata) { this.range = getRefContentRange(this.ref.subpath, metadata); if (this.range) { let currentLineIndex = 0; while (currentLineIndex < this.range.startLineOffset) { if (this.markdown[this.range.start] === "\n") currentLineIndex++; this.range.start++; } this.found = true; return this.markdown.substring(this.range.start, this.range.end); } } this.found = false; return "### Unable to find section " .concat(this.ref.subpath.text, " in ") .concat(this.file.basename); } editContent(target: string) { if (!this.found || !this.markdown) return; let md; if (!this.range) { md = target; } else { const before = this.markdown.substring(0, this.range.start); md = before + target; if (this.range.end) { const after = this.markdown.substring(this.range.end); md += after; } } this.app.vault.modify(this.file, md); } async loadFile() { const content = await this.getContent(); this.renderer.renderer.set(content); } onload(): void { super.onload(); this.registerEvent( this.app.metadataCache.on("changed", async (file, data) => { if (file === this.file) { this.loadFile(); } }) ); } } export class UnresolvedRefRenderChild extends MarkdownRenderChild { constructor(app: App, containerEl: HTMLElement, target: MaybeNoteRef) { super(containerEl); this.containerEl.classList.add("dendron-embed", "file-embed", "mod-empty", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); const content = this.containerEl.createDiv(); const { vaultName, vault, path } = target; if (vaultName === "") { content.setText("Vault name are unspecified in link."); return; } else if (!vault) { content.setText(`Vault ${vaultName} are not found.`); return; } else if (path === "") { content.setText("Note path are unspecified in link."); return; } content.setText(`"${target.path}" is not created yet. Click to create.`); this.containerEl.onclick = () => { vault.createNote(path).then((file) => openFile(app, file)); }; } } export function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) { if (!target.note || !target.note.file) { return new UnresolvedRefRenderChild(app, container, target); } else { return new NoteRefRenderChild(app, container, target); } }
src/custom-resolver/ref-render.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/custom-resolver/link-open.ts", "retrieved_chunk": " new Notice(\"Note path is unspecified in link.\");\n return;\n }\n file = await target.vault.createNote(target.path);\n }\n let newLink = file.path;\n if (target.subpath)\n newLink += anchorToLinkSubpath(\n target.subpath.start,\n app.metadataCache.getFileCache(file)?.headings", "score": 0.802000880241394 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " this.app.workspace.openLinkText(this.href, this.sourcePath);\n });\n }\n updateTitle() {\n this.containerEl.children[0].setText(\n renderLinkTitle(this.app, this.workspace, this.href, this.title, this.sourcePath)\n );\n }\n toDOM(view: EditorView): HTMLElement {\n if (!this.containerEl) this.initDOM();", "score": 0.7990977764129639 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " });\n });\n if (!item || !item.note.file)\n el.createEl(\"div\", { cls: \"suggestion-aux\" }, (el) => {\n el.append(getIcon(\"plus\")!);\n });\n }\n async onChooseSuggestion(item: LookupItem | null, evt: MouseEvent | KeyboardEvent) {\n if (item && item.note.file) {\n openFile(this.app, item.note.file);", "score": 0.7651311159133911 }, { "filename": "src/modal/invalid-root.ts", "retrieved_chunk": " });\n new Setting(this.contentEl).addButton((button) => {\n button\n .setButtonText(\"Create\")\n .setCta()\n .onClick(async () => {\n await this.dendronVault.createRootFolder();\n this.dendronVault.init();\n this.close();\n });", "score": 0.7633477449417114 }, { "filename": "src/settings.ts", "retrieved_chunk": " this.plugin.settings.autoGenerateFrontmatter = value;\n await this.plugin.saveSettings();\n });\n });\n new Setting(containerEl)\n .setName(\"Auto Reveal\")\n .setDesc(\"Automatically reveal active file in Dendron Tree\")\n .addToggle((toggle) => {\n toggle.setValue(this.plugin.settings.autoReveal).onChange(async (value) => {\n this.plugin.settings.autoReveal = value;", "score": 0.7582141160964966 } ]
typescript
subpath: anchorToLinkSubpath( this.ref.subpath.start, this.app.metadataCache.getFileCache(this.file)?.headings ), };
import type { Stat, TFile, Vault } from "obsidian"; import { Note, NoteTree, generateNoteTitle, isUseTitleCase } from "./note"; import { parsePath } from "../path"; describe("note title", () => { it("use title case when file name is lowercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("aku.cinta.kamu-milikku.md"))).toBe( "Kamu Milikku" ); }); it("use file name when note name contain uppercase", () => { expect(generateNoteTitle("Kamu-Milikku", isUseTitleCase("aku.cinta.Kamu-Milikku.md"))).toBe( "Kamu-Milikku" ); }); it("use file name when file name contain uppercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("Aku.cinta.kamu-milikku.md"))).toBe( "kamu-milikku" ); }); }); describe("note class", () => { it("append and remove child work", () => { const child = new Note("lala", true); expect(child.parent).toBeUndefined(); const parent = new Note("apa", true); expect(parent.children).toEqual([]); parent.appendChild(child); expect(child.parent).toBe(parent); expect(parent.children).toEqual([child]); parent.removeChildren(child); expect(child.parent).toBeUndefined(); expect(parent.children).toEqual([]); }); it("append child must throw if child already has parent", () => { const origParent = new Note("root", true); const parent = new Note("root2", true); const child = new Note("child", true); origParent.appendChild(child); expect(() => parent.appendChild(child)).toThrowError("has parent"); }); it("find children work", () => { const parent = new Note("parent", true); const child1 = new Note("child1", true); const child2 = new Note("child2", true); const child3 = new Note("child3", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.findChildren("child1")).toBe(child1); expect(parent.findChildren("child2")).toBe(child2); expect(parent.findChildren("child3")).toBe(child3); expect(parent.findChildren("child4")).toBeUndefined(); }); it("non-recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("gajak", true); const child2 = new Note("lumba", true); const child3 = new Note("biawak", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.children).toEqual([child1, child2, child3]); parent.sortChildren(false); expect(parent.children).toEqual([child3, child1, child2]); }); it("recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("lumba", true); const child2 = new Note("galak", true); const grandchild1 = new Note("lupa", true); const grandchild2 = new Note("apa", true); const grandchild3 = new Note("abu", true); const grandchild4 = new Note("lagi", true); parent.appendChild(child1); child1.appendChild(grandchild1); child1.appendChild(grandchild2); parent.appendChild(child2); child2.appendChild(grandchild3); child2.appendChild(grandchild4); expect(parent.children).toEqual([child1, child2]); expect(child1.children).toEqual([grandchild1, grandchild2]); expect(child2.children).toEqual([grandchild3, grandchild4]); parent.sortChildren(true); expect(parent.children).toEqual([child2, child1]); expect(child1.children).toEqual([grandchild2, grandchild1]); expect(child2.children).toEqual([grandchild3, grandchild4]); }); it("get path on non-root", () => { const root = new Note("root", true); const ch1 = new Note("parent", true); const ch2 = new Note("parent2", true); const ch3 = new Note("child", true); root.appendChild(ch1); ch1.appendChild(ch2); ch2.appendChild(ch3); expect(ch3.getPath()).toBe("parent.parent2.child"); expect(ch3.getPathNotes()).toEqual([root, ch1, ch2, ch3]); }); it("get path on root", () => { const root = new Note("root", true); expect(root.getPath()).toBe("root"); expect(root.getPathNotes()).toEqual([root]); }); it("use generated title when titlecase true", () => { const note = new Note("aku-cinta", true); expect(note.title).toBe("Aku Cinta"); }); it("use filename as title when titlecase false", () => { const note = new Note("aKu-ciNta", false); expect(note.title).toBe("aKu-ciNta"); }); it("use metadata title when has metadata", () => { const note = new Note("aKu-ciNta", false); note.syncMetadata({ title: "Butuh Kamu", }); expect(note.title).toBe("Butuh Kamu"); }); }); function createTFile(path: string): TFile { const { basename, name, extension } = parsePath(path); return { basename, extension, name, parent: null, path: path, stat: null as unknown as Stat, vault: null as unknown as Vault, }; } describe("tree class", () => { it("add file without sort", () => { const tree = new NoteTree(); tree
.addFile(createTFile("abc.def.jkl.md"));
tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.root.children.length).toBe(1); expect(tree.root.children[0].name).toBe("abc"); expect(tree.root.children[0].children.length).toBe(1); expect(tree.root.children[0].children[0].name).toBe("def"); expect(tree.root.children[0].children[0].children.length).toBe(2); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); }); it("add file with sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md"), true); tree.addFile(createTFile("abc.def.ghi.md"), true); tree.addFile(createTFile("abc.def.mno.md"), true); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("get note by file base name", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("abc.def.jkl")?.name).toBe("jkl"); expect(tree.getFromFileName("abc.def.ghi")?.name).toBe("ghi"); expect(tree.getFromFileName("abc.def.mno")).toBeUndefined(); }); it("get note using blank path", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("")).toBeUndefined() }) it("delete note if do not have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")).toBeUndefined(); }); it("do not delete note if have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.addFile(createTFile("abc.def.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")?.name).toBe("abc"); expect(tree.getFromFileName("abc.def")?.name).toBe("def"); }); it("delete note and parent if do not have children and parent file is null", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc")); tree.addFile(createTFile("abc.def.ghi.md")); tree.deleteByFileName("abc.def.ghi"); expect(tree.getFromFileName("abc.def.ghi")).toBeUndefined(); expect(tree.getFromFileName("abc.def")).toBeUndefined(); expect(tree.getFromFileName("abc")?.name).toBe("abc"); }); it("sort note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.def.mno.md")); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); tree.sort(); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("flatten note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.jkl.mno.md")); expect(tree.flatten().map((note) => note.getPath())).toEqual([ "root", "abc", "abc.def", "abc.def.ghi", "abc.jkl", "abc.jkl.mno", ]); }); });
src/engine/note.test.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/path.test.ts", "retrieved_chunk": "import { parsePath } from \"./path\";\ndescribe(\"parse path\", () => {\n it(\"parse path with 2 component\", () => {\n expect(parsePath(\"abc/ll.md\")).toStrictEqual({\n dir: \"abc\",\n name: \"ll.md\",\n basename: \"ll\",\n extension: \"md\",\n });\n });", "score": 0.7859193086624146 }, { "filename": "src/settings.ts", "retrieved_chunk": " autoGenerateFrontmatter: boolean;\n autoReveal: boolean;\n customResolver: boolean;\n}\nexport const DEFAULT_SETTINGS: DendronTreePluginSettings = {\n vaultList: [\n {\n name: \"root\",\n path: \"/\",\n },", "score": 0.7837870121002197 }, { "filename": "src/path.test.ts", "retrieved_chunk": " basename: \"pacar\",\n extension: \"md\",\n });\n });\n it(\"parse windows path\", () => {\n expect(parsePath(\"abc\\\\ll.md\")).toStrictEqual({\n dir: \"abc\",\n name: \"ll.md\",\n basename: \"ll\",\n extension: \"md\",", "score": 0.7676464319229126 }, { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " markdown?: string;\n found = false;\n constructor(\n public readonly app: App,\n public readonly containerEl: HTMLElement,\n public readonly ref: MaybeNoteRef\n ) {\n super(containerEl);\n if (!ref.note || !ref.note.file)\n throw Error(\"NoteRefChild only accept ref with non-blank note and file\");", "score": 0.7585947513580322 }, { "filename": "src/path.test.ts", "retrieved_chunk": " it(\"parse path with 1 component\", () => {\n expect(parsePath(\"hugo.md\")).toStrictEqual({\n dir: \"\",\n name: \"hugo.md\",\n basename: \"hugo\",\n extension: \"md\",\n });\n });\n it(\"parse path with name contain multiple dot\", () => {\n expect(parsePath(\"baca.buku.md\")).toStrictEqual({", "score": 0.756862998008728 } ]
typescript
.addFile(createTFile("abc.def.jkl.md"));
import { App, ButtonComponent, MarkdownRenderChild, MarkdownRenderer, MarkdownRendererConstructorType, OpenViewState, TFile, setIcon, } from "obsidian"; import { openFile } from "../utils"; import { MaybeNoteRef, RefRange, getRefContentRange, anchorToLinkSubpath } from "../engine/ref"; import { dendronActivityBarName } from "../icons"; const MarkdownRendererConstructor = MarkdownRenderer as unknown as MarkdownRendererConstructorType; class RefMarkdownRenderer extends MarkdownRendererConstructor { constructor(public parent: NoteRefRenderChild, queed: boolean) { super(parent.app, parent.previewEl, queed); } get file(): TFile { return this.parent.file; } edit(markdown: string) { this.parent.editContent(markdown); } } export class NoteRefRenderChild extends MarkdownRenderChild { previewEl: HTMLElement; renderer: RefMarkdownRenderer; file: TFile; range: RefRange | null; markdown?: string; found = false; constructor( public readonly app: App, public readonly containerEl: HTMLElement, public readonly ref: MaybeNoteRef ) { super(containerEl); if (!ref.note || !ref.note.file) throw Error("NoteRefChild only accept ref with non-blank note and file"); this.file = ref.note.file; this.containerEl.classList.add("dendron-embed", "markdown-embed", "inline-embed", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); this.previewEl = this.containerEl.createDiv("markdown-embed-content"); const buttonComponent = new ButtonComponent(this.containerEl); buttonComponent.buttonEl.remove(); buttonComponent.buttonEl = this.containerEl.createDiv( "markdown-embed-link" ) as unknown as HTMLButtonElement; buttonComponent.setIcon("lucide-link").setTooltip("Open link"); buttonComponent.buttonEl.onclick = () => { const openState: OpenViewState = {}; if (this.ref.subpath) { openState.eState = { subpath: anchorToLinkSubpath( this.ref.subpath.start, this.app.metadataCache.getFileCache(this.file)?.headings ), }; } openFile(this.app, this.ref.note?.file, openState); }; this.renderer = new RefMarkdownRenderer(this, true); this.addChild(this.renderer); } async getContent(): Promise<string> { this.markdown = await this.app.vault.cachedRead(this.file); if (!this.ref.subpath) { this.found = true; return this.markdown; } const metadata = this.app.metadataCache.getFileCache(this.file); if (metadata) { this.range = getRefContentRange(this.ref.subpath, metadata); if (this.range) { let currentLineIndex = 0; while (currentLineIndex < this.range.startLineOffset) { if (this.markdown[this.range.start] === "\n") currentLineIndex++; this.range.start++; } this.found = true; return this.markdown.substring(this.range.start, this.range.end); } } this.found = false; return "### Unable to find section " .concat(this.ref.subpath.text, " in ") .concat(this.file.basename); } editContent(target: string) { if (!this.found || !this.markdown) return; let md; if (!this.range) { md = target; } else { const before = this.markdown.substring(0, this.range.start); md = before + target; if (this.range.end) { const after = this.markdown.substring(this.range.end); md += after; } } this.app.vault.modify(this.file, md); } async loadFile() { const content = await this.getContent(); this.renderer.renderer.set(content); } onload(): void { super.onload(); this.registerEvent( this.app.metadataCache.on("changed", async (file, data) => { if (file === this.file) { this.loadFile(); } }) ); } } export class UnresolvedRefRenderChild extends MarkdownRenderChild { constructor(app: App, containerEl: HTMLElement, target: MaybeNoteRef) { super(containerEl); this.containerEl.classList.add("dendron-embed", "file-embed", "mod-empty", "is-loaded"); this.containerEl.setText(""); const icon = this.containerEl.createDiv("dendron-icon"); setIcon(icon, dendronActivityBarName); const content = this.containerEl.createDiv(); const { vaultName, vault, path } = target; if (vaultName === "") { content.setText("Vault name are unspecified in link."); return; } else if (!vault) { content.setText(`Vault ${vaultName} are not found.`); return; } else if (path === "") { content.setText("Note path are unspecified in link."); return; } content.setText(`"${target.path}" is not created yet. Click to create.`); this.containerEl.onclick = () => { vault.createNote(path)
.then((file) => openFile(app, file));
}; } } export function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) { if (!target.note || !target.note.file) { return new UnresolvedRefRenderChild(app, container, target); } else { return new NoteRefRenderChild(app, container, target); } }
src/custom-resolver/ref-render.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/custom-resolver/link-open.ts", "retrieved_chunk": " return originalBoundedFunction(linktext, sourcePath, newLeaf, openViewState);\n let file = target.note?.file;\n if (!file) {\n if (target.vaultName === \"\") {\n new Notice(\"Vault name is unspecified in link.\");\n return;\n } else if (!target.vault) {\n new Notice(`Vault ${target.vaultName} is not found.`);\n return;\n } else if (target.path === \"\") {", "score": 0.8619074821472168 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 0.8239762783050537 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " .setCta()\n .setButtonText(\"Add Text\")\n .onClick(() => {\n const name = this.nameText.getValue();\n if (!this.folder || name.trim().length === 0) {\n new Notice(\"Please specify Vault Path and Vault Name\");\n return;\n }\n if (\n this.onSubmit({", "score": 0.818371057510376 }, { "filename": "src/main.ts", "retrieved_chunk": " menu.addItem((item) => {\n item\n .setIcon(dendronActivityBarName)\n .setTitle(\"Reveal in Dendron Tree\")\n .onClick(() => this.revealFile(file));\n });\n };\n onResolveMetadata = (file: TFile) => {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (vault && vault.onMetadataChanged(file)) {", "score": 0.7965567111968994 }, { "filename": "src/custom-resolver/link-open.ts", "retrieved_chunk": " new Notice(\"Note path is unspecified in link.\");\n return;\n }\n file = await target.vault.createNote(target.path);\n }\n let newLink = file.path;\n if (target.subpath)\n newLink += anchorToLinkSubpath(\n target.subpath.start,\n app.metadataCache.getFileCache(file)?.headings", "score": 0.7939572334289551 } ]
typescript
.then((file) => openFile(app, file));
import type { Stat, TFile, Vault } from "obsidian"; import { Note, NoteTree, generateNoteTitle, isUseTitleCase } from "./note"; import { parsePath } from "../path"; describe("note title", () => { it("use title case when file name is lowercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("aku.cinta.kamu-milikku.md"))).toBe( "Kamu Milikku" ); }); it("use file name when note name contain uppercase", () => { expect(generateNoteTitle("Kamu-Milikku", isUseTitleCase("aku.cinta.Kamu-Milikku.md"))).toBe( "Kamu-Milikku" ); }); it("use file name when file name contain uppercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("Aku.cinta.kamu-milikku.md"))).toBe( "kamu-milikku" ); }); }); describe("note class", () => { it("append and remove child work", () => { const child = new Note("lala", true); expect(child.parent).toBeUndefined(); const parent = new Note("apa", true); expect(parent.children).toEqual([]); parent.appendChild(child); expect(child.parent).toBe(parent); expect(parent.children).toEqual([child]); parent.removeChildren(child); expect(child.parent).toBeUndefined(); expect(parent.children).toEqual([]); }); it("append child must throw if child already has parent", () => { const origParent = new Note("root", true); const parent = new Note("root2", true); const child = new Note("child", true); origParent.appendChild(child); expect(() => parent.appendChild(child)).toThrowError("has parent"); }); it("find children work", () => { const parent = new Note("parent", true); const child1 = new Note("child1", true); const child2 = new Note("child2", true); const child3 = new Note("child3", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.findChildren("child1")).toBe(child1); expect(parent.findChildren("child2")).toBe(child2); expect(parent.findChildren("child3")).toBe(child3); expect(parent.findChildren("child4")).toBeUndefined(); }); it("non-recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("gajak", true); const child2 = new Note("lumba", true); const child3 = new Note("biawak", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.children).toEqual([child1, child2, child3]); parent.sortChildren(false); expect(parent.children).toEqual([child3, child1, child2]); }); it("recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("lumba", true); const child2 = new Note("galak", true); const grandchild1 = new Note("lupa", true); const grandchild2 = new Note("apa", true); const grandchild3 = new Note("abu", true); const grandchild4 = new Note("lagi", true); parent.appendChild(child1); child1.appendChild(grandchild1); child1.appendChild(grandchild2); parent.appendChild(child2); child2.appendChild(grandchild3); child2.appendChild(grandchild4); expect(parent.children).toEqual([child1, child2]); expect(child1.children).toEqual([grandchild1, grandchild2]); expect(child2.children).toEqual([grandchild3, grandchild4]); parent.sortChildren(true); expect(parent.children).toEqual([child2, child1]); expect(child1.children).toEqual([grandchild2, grandchild1]); expect(child2.children).toEqual([grandchild3, grandchild4]); }); it("get path on non-root", () => { const root = new Note("root", true); const ch1 = new Note("parent", true); const ch2 = new Note("parent2", true); const ch3 = new Note("child", true); root.appendChild(ch1); ch1.appendChild(ch2); ch2.appendChild(ch3); expect(ch3.getPath()).toBe("parent.parent2.child"); expect(ch3.getPathNotes()).toEqual([root, ch1, ch2, ch3]); }); it("get path on root", () => { const root = new Note("root", true); expect(root.getPath()).toBe("root"); expect(root.getPathNotes()).toEqual([root]); }); it("use generated title when titlecase true", () => { const note = new Note("aku-cinta", true); expect(note.title).toBe("Aku Cinta"); }); it("use filename as title when titlecase false", () => { const note = new Note("aKu-ciNta", false); expect(note.title).toBe("aKu-ciNta"); }); it("use metadata title when has metadata", () => { const note = new Note("aKu-ciNta", false); note.syncMetadata({ title: "Butuh Kamu", }); expect(note.title).toBe("Butuh Kamu"); }); }); function createTFile(path: string): TFile {
const { basename, name, extension } = parsePath(path);
return { basename, extension, name, parent: null, path: path, stat: null as unknown as Stat, vault: null as unknown as Vault, }; } describe("tree class", () => { it("add file without sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.root.children.length).toBe(1); expect(tree.root.children[0].name).toBe("abc"); expect(tree.root.children[0].children.length).toBe(1); expect(tree.root.children[0].children[0].name).toBe("def"); expect(tree.root.children[0].children[0].children.length).toBe(2); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); }); it("add file with sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md"), true); tree.addFile(createTFile("abc.def.ghi.md"), true); tree.addFile(createTFile("abc.def.mno.md"), true); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("get note by file base name", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("abc.def.jkl")?.name).toBe("jkl"); expect(tree.getFromFileName("abc.def.ghi")?.name).toBe("ghi"); expect(tree.getFromFileName("abc.def.mno")).toBeUndefined(); }); it("get note using blank path", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("")).toBeUndefined() }) it("delete note if do not have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")).toBeUndefined(); }); it("do not delete note if have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.addFile(createTFile("abc.def.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")?.name).toBe("abc"); expect(tree.getFromFileName("abc.def")?.name).toBe("def"); }); it("delete note and parent if do not have children and parent file is null", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc")); tree.addFile(createTFile("abc.def.ghi.md")); tree.deleteByFileName("abc.def.ghi"); expect(tree.getFromFileName("abc.def.ghi")).toBeUndefined(); expect(tree.getFromFileName("abc.def")).toBeUndefined(); expect(tree.getFromFileName("abc")?.name).toBe("abc"); }); it("sort note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.def.mno.md")); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); tree.sort(); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("flatten note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.jkl.mno.md")); expect(tree.flatten().map((note) => note.getPath())).toEqual([ "root", "abc", "abc.def", "abc.def.ghi", "abc.jkl", "abc.jkl.mno", ]); }); });
src/engine/note.test.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/engine/note.ts", "retrieved_chunk": " return notes;\n }\n syncMetadata(metadata: NoteMetadata | undefined) {\n this.title = metadata?.title ?? generateNoteTitle(this.originalName, this.titlecase);\n }\n}\n/**\n * Check whetever generated note title must be title case or not\n * @param baseName file base name\n */", "score": 0.8093512058258057 }, { "filename": "src/path.test.ts", "retrieved_chunk": "import { parsePath } from \"./path\";\ndescribe(\"parse path\", () => {\n it(\"parse path with 2 component\", () => {\n expect(parsePath(\"abc/ll.md\")).toStrictEqual({\n dir: \"abc\",\n name: \"ll.md\",\n basename: \"ll\",\n extension: \"md\",\n });\n });", "score": 0.7978162169456482 }, { "filename": "src/path.test.ts", "retrieved_chunk": " it(\"parse path with 1 component\", () => {\n expect(parsePath(\"hugo.md\")).toStrictEqual({\n dir: \"\",\n name: \"hugo.md\",\n basename: \"hugo\",\n extension: \"md\",\n });\n });\n it(\"parse path with name contain multiple dot\", () => {\n expect(parsePath(\"baca.buku.md\")).toStrictEqual({", "score": 0.7924091219902039 }, { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " content.setText(`\"${target.path}\" is not created yet. Click to create.`);\n this.containerEl.onclick = () => {\n vault.createNote(path).then((file) => openFile(app, file));\n };\n }\n}\nexport function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) {\n if (!target.note || !target.note.file) {\n return new UnresolvedRefRenderChild(app, container, target);\n } else {", "score": 0.7881056070327759 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " folder: TFolder;\n tree: NoteTree;\n isIniatialized = false;\n constructor(public app: App, public config: VaultConfig) {}\n private resolveMetadata(file: TFile): NoteMetadata | undefined {\n const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter;\n if (!frontmatter) return undefined;\n return {\n title: frontmatter[\"title\"],\n };", "score": 0.7852860689163208 } ]
typescript
const { basename, name, extension } = parsePath(path);
import { App, SuggestModal, getIcon } from "obsidian"; import { Note } from "../engine/note"; import { openFile } from "../utils"; import { DendronVault } from "../engine/vault"; import { SelectVaultModal } from "./select-vault"; import { DendronWorkspace } from "../engine/workspace"; interface LookupItem { note: Note; vault: DendronVault; } export class LookupModal extends SuggestModal<LookupItem | null> { constructor(app: App, private workspace: DendronWorkspace, private initialQuery: string = "") { super(app); } onOpen(): void { super.onOpen(); if (this.initialQuery.length > 0) { this.inputEl.value = this.initialQuery; this.inputEl.dispatchEvent(new Event("input")); } } getSuggestions(query: string): (LookupItem | null)[] { const queryLowercase = query.toLowerCase(); const result: (LookupItem | null)[] = []; let foundExact = true; for (const vault of this.workspace.vaultList) { let currentFoundExact = false; for (const note of vault.tree.flatten()) { const path = note.getPath(); const item: LookupItem = { note, vault, }; if (path === queryLowercase) { currentFoundExact = true; result.unshift(item); continue; } if ( note.title.toLowerCase().includes(queryLowercase) || note.name.includes(queryLowercase) || path.includes(queryLowercase) ) result.push(item); } foundExact = foundExact && currentFoundExact; } if (!foundExact && queryLowercase.trim().length > 0) result.unshift(null); return result; } renderSuggestion(item: LookupItem | null, el: HTMLElement) { el.classList.add("mod-complex"); el.createEl("div", { cls: "suggestion-content" }, (el) => { el.createEl("div", { text: item?.note.title ?? "Create New", cls: "suggestion-title" }); el.createEl("small", { text: item ? item.note.getPath() + (this.workspace.vaultList.length > 1 ? ` (${item.vault.config.name})` : "") : "Note does not exist", cls: "suggestion-content", }); }); if (!item || !item.note.file) el.createEl("div", { cls: "suggestion-aux" }, (el) => { el.append(getIcon("plus")!); }); } async onChooseSuggestion(item: LookupItem | null, evt: MouseEvent | KeyboardEvent) { if (item && item.note.file) { openFile(this.app, item.note.file); return; } const path = item ? item.note.getPath() : this.inputEl.value; const doCreate = async (vault: DendronVault) => {
const file = await vault.createNote(path);
return openFile(vault.app, file); }; if (item?.vault) { await doCreate(item.vault); } else if (this.workspace.vaultList.length == 1) { await doCreate(this.workspace.vaultList[0]); } else { new SelectVaultModal(this.app, this.workspace, doCreate).open(); } } }
src/modal/lookup.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " content.setText(`\"${target.path}\" is not created yet. Click to create.`);\n this.containerEl.onclick = () => {\n vault.createNote(path).then((file) => openFile(app, file));\n };\n }\n}\nexport function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) {\n if (!target.note || !target.note.file) {\n return new UnresolvedRefRenderChild(app, container, target);\n } else {", "score": 0.8694091439247131 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " }\n renderSuggestion(value: TFolder, el: HTMLElement): void {\n el.createDiv({\n text: value.path,\n });\n }\n selectSuggestion(value: TFolder, evt: MouseEvent | KeyboardEvent): void {\n this.inputEl.value = value.path;\n this.close();\n this.onSelected(value);", "score": 0.840837836265564 }, { "filename": "src/main.ts", "retrieved_chunk": " menu.addItem((item) => {\n item\n .setIcon(dendronActivityBarName)\n .setTitle(\"Reveal in Dendron Tree\")\n .onClick(() => this.revealFile(file));\n });\n };\n onResolveMetadata = (file: TFile) => {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (vault && vault.onMetadataChanged(file)) {", "score": 0.8389086723327637 }, { "filename": "src/main.ts", "retrieved_chunk": " update = newVault.onFileCreated(file) || update;\n }\n if (update) this.updateNoteStore();\n };\n onOpenFile(file: TFile | null) {\n activeFile.set(file);\n if (file && this.settings.autoReveal) this.revealFile(file);\n }\n onFileMenu = (menu: Menu, file: TAbstractFile) => {\n if (!(file instanceof TFile)) return;", "score": 0.834027886390686 }, { "filename": "src/main.ts", "retrieved_chunk": " this.updateNoteStore();\n }\n };\n onDeleteFile = (file: TAbstractFile) => {\n // file.parent is null when file is deleted\n const parsed = parsePath(file.path);\n const vault = this.workspace.findVaultByParentPath(parsed.dir);\n if (vault && vault.onFileDeleted(parsed)) {\n this.updateNoteStore();\n }", "score": 0.8292284607887268 } ]
typescript
const file = await vault.createNote(path);
import { Menu, Plugin, TAbstractFile, TFile, addIcon } from "obsidian"; import { DendronView, VIEW_TYPE_DENDRON } from "./view"; import { activeFile, dendronVaultList } from "./store"; import { LookupModal } from "./modal/lookup"; import { dendronActivityBarIcon, dendronActivityBarName } from "./icons"; import { DEFAULT_SETTINGS, DendronTreePluginSettings, DendronTreeSettingTab } from "./settings"; import { parsePath } from "./path"; import { DendronWorkspace } from "./engine/workspace"; import { CustomResolver } from "./custom-resolver"; export default class DendronTreePlugin extends Plugin { settings: DendronTreePluginSettings; workspace: DendronWorkspace = new DendronWorkspace(this.app); customResolver?: CustomResolver; async onload() { await this.loadSettings(); await this.migrateSettings(); addIcon(dendronActivityBarName, dendronActivityBarIcon); this.addCommand({ id: "dendron-lookup", name: "Lookup Note", callback: () => { new LookupModal(this.app, this.workspace).open(); }, }); this.addSettingTab(new DendronTreeSettingTab(this.app, this)); this.registerView(VIEW_TYPE_DENDRON, (leaf) => new DendronView(leaf, this)); this.addRibbonIcon(dendronActivityBarName, "Open Dendron Tree", () => { this.activateView(); }); this.app.workspace.onLayoutReady(() => { this.onRootFolderChanged(); this.registerEvent(this.app.vault.on("create", this.onCreateFile)); this.registerEvent(this.app.vault.on("delete", this.onDeleteFile)); this.registerEvent(this.app.vault.on("rename", this.onRenameFile)); this.registerEvent(this.app.metadataCache.on("resolve", this.onResolveMetadata)); this.registerEvent(this.app.workspace.on("file-open", this.onOpenFile, this)); this.registerEvent(this.app.workspace.on("file-menu", this.onFileMenu)); }); this.configureCustomResolver(); } async migrateSettings() { function pathToVaultConfig(path: string) { const { name } = parsePath(path); if (name.length === 0) return { name: "root", path: "/", }; let processed = path; if (processed.endsWith("/")) processed = processed.slice(0, -1); if (processed.startsWith("/") && processed.length > 1) processed = processed.slice(1); return { name, path: processed, }; } if (this.settings.vaultPath) { this.settings.vaultList = [pathToVaultConfig(this.settings.vaultPath)]; this.settings.vaultPath = undefined; await this.saveSettings(); } if (this.settings.vaultList.length > 0 && typeof this.settings.vaultList[0] === "string") { this.settings.vaultList = (this.settings.vaultList as unknown as string[]).map((path) => pathToVaultConfig(path) ); await this.saveSettings(); } } onunload() {} onRootFolderChanged() { this.workspace.changeVault(this.settings.vaultList); this.updateNoteStore(); } configureCustomResolver() { if (this.settings.customResolver && !this.customResolver) { this.customResolver = new CustomResolver(this, this.workspace); this.addChild(this.customResolver); } else if (!this.settings.customResolver && this.customResolver) { this.removeChild(this.customResolver); this.customResolver = undefined; } } updateNoteStore() {
dendronVaultList.set(this.workspace.vaultList);
} onCreateFile = async (file: TAbstractFile) => { const vault = this.workspace.findVaultByParent(file.parent); if (vault && vault.onFileCreated(file)) { if (this.settings.autoGenerateFrontmatter && file instanceof TFile && file.stat.size === 0) await vault.generateFronmatter(file); this.updateNoteStore(); } }; onDeleteFile = (file: TAbstractFile) => { // file.parent is null when file is deleted const parsed = parsePath(file.path); const vault = this.workspace.findVaultByParentPath(parsed.dir); if (vault && vault.onFileDeleted(parsed)) { this.updateNoteStore(); } }; onRenameFile = (file: TAbstractFile, oldPath: string) => { const oldParsed = parsePath(oldPath); const oldVault = this.workspace.findVaultByParentPath(oldParsed.dir); let update = false; if (oldVault) { update = oldVault.onFileDeleted(oldParsed); } const newVault = this.workspace.findVaultByParent(file.parent); if (newVault) { update = newVault.onFileCreated(file) || update; } if (update) this.updateNoteStore(); }; onOpenFile(file: TFile | null) { activeFile.set(file); if (file && this.settings.autoReveal) this.revealFile(file); } onFileMenu = (menu: Menu, file: TAbstractFile) => { if (!(file instanceof TFile)) return; menu.addItem((item) => { item .setIcon(dendronActivityBarName) .setTitle("Reveal in Dendron Tree") .onClick(() => this.revealFile(file)); }); }; onResolveMetadata = (file: TFile) => { const vault = this.workspace.findVaultByParent(file.parent); if (vault && vault.onMetadataChanged(file)) { this.updateNoteStore(); } }; revealFile(file: TFile) { const vault = this.workspace.findVaultByParent(file.parent); if (!vault) return; const note = vault.tree.getFromFileName(file.basename); if (!note) return; for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON)) { if (!(leaf.view instanceof DendronView)) continue; leaf.view.component.focusTo(vault, note); } } async activateView() { const leafs = this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON); if (leafs.length == 0) { const leaf = this.app.workspace.getLeftLeaf(false); await leaf.setViewState({ type: VIEW_TYPE_DENDRON, active: true, }); this.app.workspace.revealLeaf(leaf); } else { leafs.forEach((leaf) => this.app.workspace.revealLeaf(leaf)); } } async loadSettings() { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); } async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 0.7306820154190063 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " for (const child of root.children)\n if (child instanceof TFile && this.isNote(child.extension))\n this.tree.addFile(child).syncMetadata(this.resolveMetadata(child));\n this.tree.sort();\n this.isIniatialized = true;\n }\n async createRootFolder() {\n return await this.app.vault.createFolder(this.config.path);\n }\n async createNote(baseName: string) {", "score": 0.7291173934936523 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " }\n init() {\n if (this.isIniatialized) return;\n this.tree = new NoteTree();\n const root = getFolderFile(this.app.vault, this.config.path);\n if (!(root instanceof TFolder)) {\n new InvalidRootModal(this).open();\n return;\n }\n this.folder = root;", "score": 0.7273731231689453 }, { "filename": "src/custom-resolver/index.ts", "retrieved_chunk": " constructor(public plugin: Plugin, public workspace: DendronWorkspace) {\n super();\n }\n onload(): void {\n this.plugin.app.workspace.onLayoutReady(() => {\n this.plugin.app.workspace.registerEditorExtension(this.refEditorExtenstion);\n this.plugin.app.workspace.registerEditorExtension(this.linkEditorExtenstion);\n this.plugin.app.workspace.registerEditorExtension(this.linkRefClickbaleExtension);\n this.pagePreviewPlugin = this.plugin.app.internalPlugins.getEnabledPluginById(\"page-preview\");\n if (!this.pagePreviewPlugin) return;", "score": 0.711864173412323 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " this.app.workspace.openLinkText(this.href, this.sourcePath);\n });\n }\n updateTitle() {\n this.containerEl.children[0].setText(\n renderLinkTitle(this.app, this.workspace, this.href, this.title, this.sourcePath)\n );\n }\n toDOM(view: EditorView): HTMLElement {\n if (!this.containerEl) this.initDOM();", "score": 0.7084806561470032 } ]
typescript
dendronVaultList.set(this.workspace.vaultList);
import type { Stat, TFile, Vault } from "obsidian"; import { Note, NoteTree, generateNoteTitle, isUseTitleCase } from "./note"; import { parsePath } from "../path"; describe("note title", () => { it("use title case when file name is lowercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("aku.cinta.kamu-milikku.md"))).toBe( "Kamu Milikku" ); }); it("use file name when note name contain uppercase", () => { expect(generateNoteTitle("Kamu-Milikku", isUseTitleCase("aku.cinta.Kamu-Milikku.md"))).toBe( "Kamu-Milikku" ); }); it("use file name when file name contain uppercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("Aku.cinta.kamu-milikku.md"))).toBe( "kamu-milikku" ); }); }); describe("note class", () => { it("append and remove child work", () => { const child = new Note("lala", true); expect(child.parent).toBeUndefined(); const parent = new Note("apa", true); expect(parent.children).toEqual([]); parent.appendChild(child); expect(child.parent).toBe(parent); expect(parent.children).toEqual([child]); parent.removeChildren(child); expect(child.parent).toBeUndefined(); expect(parent.children).toEqual([]); }); it("append child must throw if child already has parent", () => { const origParent = new Note("root", true); const parent = new Note("root2", true); const child = new Note("child", true); origParent.appendChild(child); expect(() => parent.appendChild(child)).toThrowError("has parent"); }); it("find children work", () => { const parent = new Note("parent", true); const child1 = new Note("child1", true); const child2 = new Note("child2", true); const child3 = new Note("child3", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.findChildren("child1")).toBe(child1); expect(parent.findChildren("child2")).toBe(child2); expect(parent.findChildren("child3")).toBe(child3); expect(parent.findChildren("child4")).toBeUndefined(); }); it("non-recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("gajak", true); const child2 = new Note("lumba", true); const child3 = new Note("biawak", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.children).toEqual([child1, child2, child3]);
parent.sortChildren(false);
expect(parent.children).toEqual([child3, child1, child2]); }); it("recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("lumba", true); const child2 = new Note("galak", true); const grandchild1 = new Note("lupa", true); const grandchild2 = new Note("apa", true); const grandchild3 = new Note("abu", true); const grandchild4 = new Note("lagi", true); parent.appendChild(child1); child1.appendChild(grandchild1); child1.appendChild(grandchild2); parent.appendChild(child2); child2.appendChild(grandchild3); child2.appendChild(grandchild4); expect(parent.children).toEqual([child1, child2]); expect(child1.children).toEqual([grandchild1, grandchild2]); expect(child2.children).toEqual([grandchild3, grandchild4]); parent.sortChildren(true); expect(parent.children).toEqual([child2, child1]); expect(child1.children).toEqual([grandchild2, grandchild1]); expect(child2.children).toEqual([grandchild3, grandchild4]); }); it("get path on non-root", () => { const root = new Note("root", true); const ch1 = new Note("parent", true); const ch2 = new Note("parent2", true); const ch3 = new Note("child", true); root.appendChild(ch1); ch1.appendChild(ch2); ch2.appendChild(ch3); expect(ch3.getPath()).toBe("parent.parent2.child"); expect(ch3.getPathNotes()).toEqual([root, ch1, ch2, ch3]); }); it("get path on root", () => { const root = new Note("root", true); expect(root.getPath()).toBe("root"); expect(root.getPathNotes()).toEqual([root]); }); it("use generated title when titlecase true", () => { const note = new Note("aku-cinta", true); expect(note.title).toBe("Aku Cinta"); }); it("use filename as title when titlecase false", () => { const note = new Note("aKu-ciNta", false); expect(note.title).toBe("aKu-ciNta"); }); it("use metadata title when has metadata", () => { const note = new Note("aKu-ciNta", false); note.syncMetadata({ title: "Butuh Kamu", }); expect(note.title).toBe("Butuh Kamu"); }); }); function createTFile(path: string): TFile { const { basename, name, extension } = parsePath(path); return { basename, extension, name, parent: null, path: path, stat: null as unknown as Stat, vault: null as unknown as Vault, }; } describe("tree class", () => { it("add file without sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.root.children.length).toBe(1); expect(tree.root.children[0].name).toBe("abc"); expect(tree.root.children[0].children.length).toBe(1); expect(tree.root.children[0].children[0].name).toBe("def"); expect(tree.root.children[0].children[0].children.length).toBe(2); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); }); it("add file with sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md"), true); tree.addFile(createTFile("abc.def.ghi.md"), true); tree.addFile(createTFile("abc.def.mno.md"), true); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("get note by file base name", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("abc.def.jkl")?.name).toBe("jkl"); expect(tree.getFromFileName("abc.def.ghi")?.name).toBe("ghi"); expect(tree.getFromFileName("abc.def.mno")).toBeUndefined(); }); it("get note using blank path", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("")).toBeUndefined() }) it("delete note if do not have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")).toBeUndefined(); }); it("do not delete note if have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.addFile(createTFile("abc.def.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")?.name).toBe("abc"); expect(tree.getFromFileName("abc.def")?.name).toBe("def"); }); it("delete note and parent if do not have children and parent file is null", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc")); tree.addFile(createTFile("abc.def.ghi.md")); tree.deleteByFileName("abc.def.ghi"); expect(tree.getFromFileName("abc.def.ghi")).toBeUndefined(); expect(tree.getFromFileName("abc.def")).toBeUndefined(); expect(tree.getFromFileName("abc")?.name).toBe("abc"); }); it("sort note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.def.mno.md")); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); tree.sort(); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("flatten note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.jkl.mno.md")); expect(tree.flatten().map((note) => note.getPath())).toEqual([ "root", "abc", "abc.def", "abc.def.ghi", "abc.jkl", "abc.jkl.mno", ]); }); });
src/engine/note.test.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/engine/note.ts", "retrieved_chunk": " note.parent = undefined;\n const index = this.children.indexOf(note);\n this.children.splice(index, 1);\n }\n findChildren(name: string) {\n const lower = name.toLowerCase();\n return this.children.find((note) => note.name == lower);\n }\n sortChildren(rescursive: boolean) {\n this.children.sort((a, b) => a.name.localeCompare(b.name));", "score": 0.7416834235191345 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " constructor(private originalName: string, private titlecase: boolean) {\n this.name = originalName.toLowerCase();\n this.syncMetadata(undefined);\n }\n appendChild(note: Note) {\n if (note.parent) throw Error(\"Note has parent\");\n note.parent = this;\n this.children.push(note);\n }\n removeChildren(note: Note) {", "score": 0.7250113487243652 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " if (rescursive) this.children.forEach((child) => child.sortChildren(rescursive));\n }\n getPath(original = false) {\n const component: string[] = [];\n const notes = this.getPathNotes();\n if (notes.length === 1) return original ? notes[0].originalName : notes[0].name;\n for (const note of notes) {\n if (!note.parent && note.name === \"root\") continue;\n component.push(original ? note.originalName : note.name);\n }", "score": 0.7067752480506897 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " const note = this.getFromFileName(name);\n if (!note) return;\n note.file = undefined;\n if (note.children.length == 0) {\n let currentNote: Note | undefined = note;\n while (\n currentNote &&\n currentNote.parent &&\n !currentNote.file &&\n currentNote.children.length == 0", "score": 0.6801462769508362 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " }\n addFile(file: TFile, sort = false) {\n const titlecase = isUseTitleCase(file.basename);\n const path = NoteTree.getPathFromFileName(file.basename);\n let currentNote: Note = this.root;\n if (!NoteTree.isRootPath(path))\n for (const name of path) {\n let note: Note | undefined = currentNote.findChildren(name);\n if (!note) {\n note = new Note(name, titlecase);", "score": 0.6765280961990356 } ]
typescript
parent.sortChildren(false);
import { App, SuggestModal, getIcon } from "obsidian"; import { Note } from "../engine/note"; import { openFile } from "../utils"; import { DendronVault } from "../engine/vault"; import { SelectVaultModal } from "./select-vault"; import { DendronWorkspace } from "../engine/workspace"; interface LookupItem { note: Note; vault: DendronVault; } export class LookupModal extends SuggestModal<LookupItem | null> { constructor(app: App, private workspace: DendronWorkspace, private initialQuery: string = "") { super(app); } onOpen(): void { super.onOpen(); if (this.initialQuery.length > 0) { this.inputEl.value = this.initialQuery; this.inputEl.dispatchEvent(new Event("input")); } } getSuggestions(query: string): (LookupItem | null)[] { const queryLowercase = query.toLowerCase(); const result: (LookupItem | null)[] = []; let foundExact = true; for (const vault of this.workspace.vaultList) { let currentFoundExact = false; for (const note of vault.tree.flatten()) { const path = note.getPath(); const item: LookupItem = { note, vault, }; if (path === queryLowercase) { currentFoundExact = true; result.unshift(item); continue; } if ( note.title.toLowerCase().includes(queryLowercase) || note.name.includes(queryLowercase) || path.includes(queryLowercase) ) result.push(item); } foundExact = foundExact && currentFoundExact; } if (!foundExact && queryLowercase.trim().length > 0) result.unshift(null); return result; } renderSuggestion(item: LookupItem | null, el: HTMLElement) { el.classList.add("mod-complex"); el.createEl("div", { cls: "suggestion-content" }, (el) => { el.createEl("div", { text: item?.note.title ?? "Create New", cls: "suggestion-title" }); el.createEl("small", { text: item ? item.note.getPath() + (this.workspace.vaultList.length > 1 ? ` (${item.vault.config.name})` : "") : "Note does not exist", cls: "suggestion-content", }); }); if (!item || !item.note.file) el.createEl("div", { cls: "suggestion-aux" }, (el) => { el.append(getIcon("plus")!); }); } async onChooseSuggestion(item: LookupItem | null, evt: MouseEvent | KeyboardEvent) { if (item && item.note.file) { openFile(this.app, item.note.file); return; } const path = item ? item.note.getPath() : this.inputEl.value; const doCreate = async (vault: DendronVault) => { const file = await vault.createNote(path); return openFile(vault.app, file); }; if (item?.vault) { await doCreate(item.vault); } else if (this.workspace.vaultList.length == 1) { await doCreate(this.workspace.vaultList[0]); } else {
new SelectVaultModal(this.app, this.workspace, doCreate).open();
} } }
src/modal/lookup.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/main.ts", "retrieved_chunk": " menu.addItem((item) => {\n item\n .setIcon(dendronActivityBarName)\n .setTitle(\"Reveal in Dendron Tree\")\n .onClick(() => this.revealFile(file));\n });\n };\n onResolveMetadata = (file: TFile) => {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (vault && vault.onMetadataChanged(file)) {", "score": 0.8379160165786743 }, { "filename": "src/main.ts", "retrieved_chunk": " }\n }\n updateNoteStore() {\n dendronVaultList.set(this.workspace.vaultList);\n }\n onCreateFile = async (file: TAbstractFile) => {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (vault && vault.onFileCreated(file)) {\n if (this.settings.autoGenerateFrontmatter && file instanceof TFile && file.stat.size === 0)\n await vault.generateFronmatter(file);", "score": 0.8356966972351074 }, { "filename": "src/main.ts", "retrieved_chunk": " this.updateNoteStore();\n }\n };\n revealFile(file: TFile) {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (!vault) return;\n const note = vault.tree.getFromFileName(file.basename);\n if (!note) return;\n for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON)) {\n if (!(leaf.view instanceof DendronView)) continue;", "score": 0.8270155191421509 }, { "filename": "src/engine/workspace.ts", "retrieved_chunk": " this.vaultList = vaultList.map((config) => {\n return (\n this.vaultList.find(\n (vault) => vault.config.name === config.name && vault.config.path === config.path\n ) ?? new DendronVault(this.app, config)\n );\n });\n for (const vault of this.vaultList) {\n vault.init();\n }", "score": 0.8261711597442627 }, { "filename": "src/main.ts", "retrieved_chunk": " this.updateNoteStore();\n }\n };\n onDeleteFile = (file: TAbstractFile) => {\n // file.parent is null when file is deleted\n const parsed = parsePath(file.path);\n const vault = this.workspace.findVaultByParentPath(parsed.dir);\n if (vault && vault.onFileDeleted(parsed)) {\n this.updateNoteStore();\n }", "score": 0.8144928216934204 } ]
typescript
new SelectVaultModal(this.app, this.workspace, doCreate).open();
import type { Stat, TFile, Vault } from "obsidian"; import { Note, NoteTree, generateNoteTitle, isUseTitleCase } from "./note"; import { parsePath } from "../path"; describe("note title", () => { it("use title case when file name is lowercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("aku.cinta.kamu-milikku.md"))).toBe( "Kamu Milikku" ); }); it("use file name when note name contain uppercase", () => { expect(generateNoteTitle("Kamu-Milikku", isUseTitleCase("aku.cinta.Kamu-Milikku.md"))).toBe( "Kamu-Milikku" ); }); it("use file name when file name contain uppercase", () => { expect(generateNoteTitle("kamu-milikku", isUseTitleCase("Aku.cinta.kamu-milikku.md"))).toBe( "kamu-milikku" ); }); }); describe("note class", () => { it("append and remove child work", () => { const child = new Note("lala", true); expect(child.parent).toBeUndefined(); const parent = new Note("apa", true); expect(parent.children).toEqual([]); parent.appendChild(child); expect(child.parent).toBe(parent); expect(parent.children).toEqual([child]); parent.removeChildren(child); expect(child.parent).toBeUndefined(); expect(parent.children).toEqual([]); }); it("append child must throw if child already has parent", () => { const origParent = new Note("root", true); const parent = new Note("root2", true); const child = new Note("child", true); origParent.appendChild(child); expect(() => parent.appendChild(child)).toThrowError("has parent"); }); it("find children work", () => { const parent = new Note("parent", true); const child1 = new Note("child1", true); const child2 = new Note("child2", true); const child3 = new Note("child3", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.findChildren("child1")).toBe(child1); expect(parent.findChildren("child2")).toBe(child2); expect(parent.findChildren("child3")).toBe(child3); expect(parent.findChildren("child4")).toBeUndefined(); }); it("non-recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("gajak", true); const child2 = new Note("lumba", true); const child3 = new Note("biawak", true); parent.appendChild(child1); parent.appendChild(child2); parent.appendChild(child3); expect(parent.children).toEqual([child1, child2, child3]); parent.sortChildren(false); expect(parent.children).toEqual([child3, child1, child2]); }); it("recursive sort children work", () => { const parent = new Note("parent", true); const child1 = new Note("lumba", true); const child2 = new Note("galak", true); const grandchild1 = new Note("lupa", true); const grandchild2 = new Note("apa", true); const grandchild3 = new Note("abu", true); const grandchild4 = new Note("lagi", true); parent.appendChild(child1); child1.appendChild(grandchild1); child1.appendChild(grandchild2); parent.appendChild(child2); child2.appendChild(grandchild3); child2.appendChild(grandchild4); expect(parent.children).toEqual([child1, child2]); expect(child1.children).toEqual([grandchild1, grandchild2]); expect(child2.children).toEqual([grandchild3, grandchild4]); parent.sortChildren(true); expect(parent.children).toEqual([child2, child1]); expect(child1.children).toEqual([grandchild2, grandchild1]); expect(child2.children).toEqual([grandchild3, grandchild4]); }); it("get path on non-root", () => { const root = new Note("root", true); const ch1 = new Note("parent", true); const ch2 = new Note("parent2", true); const ch3 = new Note("child", true); root.appendChild(ch1); ch1.appendChild(ch2); ch2.appendChild(ch3); expect(ch3.getPath()).toBe("parent.parent2.child"); expect(ch3.getPathNotes()).toEqual([root, ch1, ch2, ch3]); }); it("get path on root", () => { const root = new Note("root", true); expect(root.getPath()).toBe("root"); expect(root.getPathNotes()).toEqual([root]); }); it("use generated title when titlecase true", () => { const note = new Note("aku-cinta", true);
expect(note.title).toBe("Aku Cinta");
}); it("use filename as title when titlecase false", () => { const note = new Note("aKu-ciNta", false); expect(note.title).toBe("aKu-ciNta"); }); it("use metadata title when has metadata", () => { const note = new Note("aKu-ciNta", false); note.syncMetadata({ title: "Butuh Kamu", }); expect(note.title).toBe("Butuh Kamu"); }); }); function createTFile(path: string): TFile { const { basename, name, extension } = parsePath(path); return { basename, extension, name, parent: null, path: path, stat: null as unknown as Stat, vault: null as unknown as Vault, }; } describe("tree class", () => { it("add file without sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.root.children.length).toBe(1); expect(tree.root.children[0].name).toBe("abc"); expect(tree.root.children[0].children.length).toBe(1); expect(tree.root.children[0].children[0].name).toBe("def"); expect(tree.root.children[0].children[0].children.length).toBe(2); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); }); it("add file with sort", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md"), true); tree.addFile(createTFile("abc.def.ghi.md"), true); tree.addFile(createTFile("abc.def.mno.md"), true); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("get note by file base name", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("abc.def.jkl")?.name).toBe("jkl"); expect(tree.getFromFileName("abc.def.ghi")?.name).toBe("ghi"); expect(tree.getFromFileName("abc.def.mno")).toBeUndefined(); }); it("get note using blank path", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); expect(tree.getFromFileName("")).toBeUndefined() }) it("delete note if do not have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")).toBeUndefined(); }); it("do not delete note if have children", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.md")); tree.addFile(createTFile("abc.def.md")); tree.deleteByFileName("abc"); expect(tree.getFromFileName("abc")?.name).toBe("abc"); expect(tree.getFromFileName("abc.def")?.name).toBe("def"); }); it("delete note and parent if do not have children and parent file is null", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc")); tree.addFile(createTFile("abc.def.ghi.md")); tree.deleteByFileName("abc.def.ghi"); expect(tree.getFromFileName("abc.def.ghi")).toBeUndefined(); expect(tree.getFromFileName("abc.def")).toBeUndefined(); expect(tree.getFromFileName("abc")?.name).toBe("abc"); }); it("sort note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.jkl.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.def.mno.md")); expect(tree.root.children[0].children[0].children.length).toBe(3); expect(tree.root.children[0].children[0].children[0].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[1].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); tree.sort(); expect(tree.root.children[0].children[0].children[0].name).toBe("ghi"); expect(tree.root.children[0].children[0].children[1].name).toBe("jkl"); expect(tree.root.children[0].children[0].children[2].name).toBe("mno"); }); it("flatten note", () => { const tree = new NoteTree(); tree.addFile(createTFile("abc.def.md")); tree.addFile(createTFile("abc.def.ghi.md")); tree.addFile(createTFile("abc.jkl.mno.md")); expect(tree.flatten().map((note) => note.getPath())).toEqual([ "root", "abc", "abc.def", "abc.def.ghi", "abc.jkl", "abc.jkl.mno", ]); }); });
src/engine/note.test.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/path.test.ts", "retrieved_chunk": "import { parsePath } from \"./path\";\ndescribe(\"parse path\", () => {\n it(\"parse path with 2 component\", () => {\n expect(parsePath(\"abc/ll.md\")).toStrictEqual({\n dir: \"abc\",\n name: \"ll.md\",\n basename: \"ll\",\n extension: \"md\",\n });\n });", "score": 0.8046467304229736 }, { "filename": "src/path.test.ts", "retrieved_chunk": " it(\"parse path with 1 component\", () => {\n expect(parsePath(\"hugo.md\")).toStrictEqual({\n dir: \"\",\n name: \"hugo.md\",\n basename: \"hugo\",\n extension: \"md\",\n });\n });\n it(\"parse path with name contain multiple dot\", () => {\n expect(parsePath(\"baca.buku.md\")).toStrictEqual({", "score": 0.7962100505828857 }, { "filename": "src/path.test.ts", "retrieved_chunk": " basename: \"pacar\",\n extension: \"md\",\n });\n });\n it(\"parse windows path\", () => {\n expect(parsePath(\"abc\\\\ll.md\")).toStrictEqual({\n dir: \"abc\",\n name: \"ll.md\",\n basename: \"ll\",\n extension: \"md\",", "score": 0.7840675115585327 }, { "filename": "src/path.test.ts", "retrieved_chunk": " dir: \"\",\n name: \"baca.buku.md\",\n basename: \"baca.buku\",\n extension: \"md\",\n });\n });\n it(\"parse path with multiple component\", () => {\n expect(parsePath(\"baca/buku/dirumah/pacar.md\")).toStrictEqual({\n dir: \"baca/buku/dirumah\",\n name: \"pacar.md\",", "score": 0.7152532339096069 }, { "filename": "src/engine/note.ts", "retrieved_chunk": "export class NoteTree {\n root: Note = new Note(\"root\", true);\n sort() {\n this.root.sortChildren(true);\n }\n public static getPathFromFileName(name: string) {\n return name.split(\".\");\n }\n private static isRootPath(path: string[]) {\n return path.length === 1 && path[0] === \"root\";", "score": 0.70711749792099 } ]
typescript
expect(note.title).toBe("Aku Cinta");
import { App, Notice, PluginSettingTab, Setting } from "obsidian"; import DendronTreePlugin from "./main"; import { VaultConfig } from "./engine/vault"; import { AddVaultModal } from "./modal/add-vault"; export interface DendronTreePluginSettings { /** * @deprecated use vaultList */ vaultPath?: string; vaultList: VaultConfig[]; autoGenerateFrontmatter: boolean; autoReveal: boolean; customResolver: boolean; } export const DEFAULT_SETTINGS: DendronTreePluginSettings = { vaultList: [ { name: "root", path: "/", }, ], autoGenerateFrontmatter: true, autoReveal: true, customResolver: false, }; export class DendronTreeSettingTab extends PluginSettingTab { plugin: DendronTreePlugin; constructor(app: App, plugin: DendronTreePlugin) { super(app, plugin); this.plugin = plugin; } display(): void { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h2", { text: "Dendron Tree Settting" }); new Setting(containerEl) .setName("Auto Generate Front Matter") .setDesc("Generate front matter for new file even if file is created outside of Dendron tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoGenerateFrontmatter).onChange(async (value) => { this.plugin.settings.autoGenerateFrontmatter = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Auto Reveal") .setDesc("Automatically reveal active file in Dendron Tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoReveal).onChange(async (value) => { this.plugin.settings.autoReveal = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Custom Resolver") .setDesc( "Use custom resolver to resolve ref/embed and link. (Please reopen editor after change this setting)" ) .addToggle((toggle) => { toggle.setValue(this.plugin.settings.customResolver).onChange(async (value) => { this.plugin.settings.customResolver = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl).setName("Vault List").setHeading(); for (const vault of this.plugin.settings.vaultList) { new Setting(containerEl) .setName(vault.name) .setDesc(`Folder: ${vault.path}`) .addButton((btn) => { btn.setButtonText("Remove").onClick(async () => { this.plugin.settings.vaultList.remove(vault); await this.plugin.saveSettings(); this.display(); }); }); } new Setting(containerEl).addButton((btn) => { btn.setButtonText("Add Vault").onClick(() => {
new AddVaultModal(this.app, (config) => {
const list = this.plugin.settings.vaultList; const nameLowecase = config.name.toLowerCase(); if (list.find(({ name }) => name.toLowerCase() === nameLowecase)) { new Notice("Vault with same name already exist"); return false; } if (list.find(({ path }) => path === config.path)) { new Notice("Vault with same path already exist"); return false; } list.push(config); this.plugin.saveSettings().then(() => this.display()); return true; }).open(); }); }); } hide() { super.hide(); this.plugin.onRootFolderChanged(); this.plugin.configureCustomResolver(); } }
src/settings.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/invalid-root.ts", "retrieved_chunk": " });\n new Setting(this.contentEl).addButton((button) => {\n button\n .setButtonText(\"Create\")\n .setCta()\n .onClick(async () => {\n await this.dendronVault.createRootFolder();\n this.dendronVault.init();\n this.close();\n });", "score": 0.8950753211975098 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " )\n this.nameText.setValue(this.generateName(newFolder));\n this.folder = newFolder;\n });\n });\n new Setting(this.contentEl).setName(\"Vault Name\").addText((text) => {\n this.nameText = text;\n });\n new Setting(this.contentEl).addButton((btn) => {\n btn", "score": 0.8412641286849976 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " return name;\n }\n onOpen(): void {\n new Setting(this.contentEl).setHeading().setName(\"Add Vault\");\n new Setting(this.contentEl).setName(\"Vault Path\").addText((text) => {\n new FolderSuggester(this.app, text.inputEl, (newFolder) => {\n const currentName = this.nameText.getValue();\n if (\n currentName.length === 0 ||\n (this.folder && currentName === this.generateName(this.folder))", "score": 0.8220335245132446 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " .setCta()\n .setButtonText(\"Add Text\")\n .onClick(() => {\n const name = this.nameText.getValue();\n if (!this.folder || name.trim().length === 0) {\n new Notice(\"Please specify Vault Path and Vault Name\");\n return;\n }\n if (\n this.onSubmit({", "score": 0.8078774809837341 }, { "filename": "src/main.ts", "retrieved_chunk": " menu.addItem((item) => {\n item\n .setIcon(dendronActivityBarName)\n .setTitle(\"Reveal in Dendron Tree\")\n .onClick(() => this.revealFile(file));\n });\n };\n onResolveMetadata = (file: TFile) => {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (vault && vault.onMetadataChanged(file)) {", "score": 0.8052403926849365 } ]
typescript
new AddVaultModal(this.app, (config) => {
// Adapted from https://github.com/solidjs/vite-plugin-solid/blob/master/src/index.ts import { readFileSync } from "node:fs"; import type { TransformOptions } from "@babel/core"; import { transformAsync } from "@babel/core"; // @ts-expect-error import ts from "@babel/preset-typescript"; import { createFilter } from "@rollup/pluginutils"; // @ts-expect-error import solid from "babel-preset-solid"; import { mergeAndConcat } from "merge-anything"; import solidRefresh from "solid-refresh/babel"; import { createUnplugin } from "unplugin"; import type { UserConfig } from "vite"; import { crawlFrameworkPkgs } from "vitefu"; import type { Options } from "./types"; import { containsSolidField, getExtension, isJestDomInstalled, normalizeAliases, } from "./utils"; const runtimePublicPath = "/@solid-refresh"; const runtimeFilePath = require.resolve("solid-refresh/dist/solid-refresh.mjs"); const runtimeCode = readFileSync(runtimeFilePath, "utf-8"); export default createUnplugin<Partial<Options> | undefined>( (options = {}, meta) => { const filter = createFilter(options.include, options.exclude); const isVite = meta.framework === "vite"; let needHmr = false; let replaceDev = false; let projectRoot = process.cwd(); return { name: "unplugin-solid", enforce: "pre", vite: { async config(userConfig, { command }) { // We inject the dev mode only if the user explicitely wants it or if we are in dev (serve) mode replaceDev = options.dev === true || (options.dev !== false && command === "serve"); projectRoot = userConfig.root ?? projectRoot; if (!userConfig.resolve) { userConfig.resolve = {}; } userConfig.resolve.alias = normalizeAliases(userConfig.resolve.alias); const solidPkgsConfig = await crawlFrameworkPkgs({ viteUserConfig: userConfig, root: projectRoot || process.cwd(), isBuild: command === "build", isFrameworkPkgByJson(pkgJson) { return containsSolidField(pkgJson.exports || {}); }, }); // fix for bundling dev in production const nestedDeps = replaceDev ? [ "solid-js", "solid-js/web", "solid-js/store", "solid-js/html", "solid-js/h", ] : []; const test = userConfig.mode === "test" ? { test: { globals: true, ...(options.ssr ? {} : { environment: "jsdom" }), transformMode: { [options.ssr ? "ssr" : "web"]: [/\.[jt]sx?$/], }, ...(isJestDomInstalled() ? { setupFiles: [ "node_modules/@testing-library/jest-dom/extend-expect.js", ], } : {}), deps: { registerNodeLoader: true }, ...( userConfig as UserConfig & { test: Record<string, any> } ).test, }, } : {}; return { /** * We only need esbuild on .ts or .js files. .tsx & .jsx files are * handled by us */ esbuild: { include: /\.ts$/ }, resolve: { conditions: [ "solid", ...(isVite && replaceDev ? ["development"] : []), ...(userConfig.mode === "test" && !options.ssr ? ["browser"] : []), ], dedupe: nestedDeps, alias: [ { find: /^solid-refresh$/, replacement: runtimePublicPath }, ], }, optimizeDeps: { include: [...nestedDeps, ...solidPkgsConfig.optimizeDeps.include], exclude: solidPkgsConfig.optimizeDeps.exclude, }, ssr: solidPkgsConfig.ssr, ...test, }; }, configResolved(config) { needHmr = config.command === "serve" && config.mode !== "production" && options.hot !== false; }, resolveId(id) { if (id === runtimePublicPath) { return id; } }, load(id) { if (id === runtimePublicPath) { return runtimeCode; } }, }, async transform(source, id) { const isSsr = !!options.ssr; const currentFileExtension = getExtension(id); const extensionsToWatch = [ ...(
options.extensions ?? []), ".tsx", ".jsx", ];
const allExtensions = extensionsToWatch.map((extension) => // An extension can be a string or a tuple [extension, options] typeof extension === "string" ? extension : extension[0], ); if (!filter(id) || !allExtensions.includes(currentFileExtension)) { return null; } const inNodeModules = /node_modules/.test(id); let solidOptions: { generate: "ssr" | "dom"; hydratable: boolean }; if (options.ssr) { solidOptions = isSsr ? { generate: "ssr", hydratable: true } : { generate: "dom", hydratable: true }; } else { solidOptions = { generate: "dom", hydratable: false }; } id = id.replace(/\?.+$/, ""); const opts: TransformOptions = { babelrc: false, configFile: false, root: projectRoot, filename: id, sourceFileName: id, presets: [[solid, { ...solidOptions, ...(options.solid ?? {}) }]], plugins: isVite && needHmr && !isSsr && !inNodeModules ? [[solidRefresh, { bundler: "vite" }]] : [], sourceMaps: true, // Vite handles sourcemap flattening inputSourceMap: false as any, }; // We need to know if the current file extension has a typescript options tied to it const shouldBeProcessedWithTypescript = extensionsToWatch.some( (extension) => { if (typeof extension === "string") { return extension.includes("tsx"); } const [extensionName, extensionOptions] = extension; if (extensionName !== currentFileExtension) { return false; } return extensionOptions.typescript; }, ); if (shouldBeProcessedWithTypescript) { (opts.presets ??= []).push([ts, options.typescript ?? {}]); } // Default value for babel user options let babelUserOptions: TransformOptions = {}; if (options.babel) { if (typeof options.babel === "function") { const babelOptions = options.babel(source, id, isSsr); babelUserOptions = babelOptions instanceof Promise ? await babelOptions : babelOptions; } else { babelUserOptions = options.babel; } } const babelOptions = mergeAndConcat(babelUserOptions, opts); const { code, map } = (await transformAsync(source, babelOptions))!; return { code: code!, map }; }, }; }, );
src/core/index.ts
so1ve-unplugin-solid-3c0a7e1
[ { "filename": "src/core/utils.ts", "retrieved_chunk": "import { createRequire } from \"node:module\";\nimport type { Alias, AliasOptions } from \"vite\";\nconst require = createRequire(import.meta.url);\nexport function getExtension(filename: string): string {\n const index = filename.lastIndexOf(\".\");\n return index < 0\n ? \"\"\n : filename.slice(Math.max(0, index)).replace(/\\?.+$/, \"\");\n}\nexport function containsSolidField(fields: any) {", "score": 0.7123690843582153 }, { "filename": "src/core/types.ts", "retrieved_chunk": " */\n babel:\n | TransformOptions\n | ((source: string, id: string, ssr: boolean) => TransformOptions)\n | ((source: string, id: string, ssr: boolean) => Promise<TransformOptions>);\n typescript: {\n /**\n * Forcibly enables jsx parsing. Otherwise angle brackets will be treated as\n * typescript's legacy type assertion var foo = <string>bar;. Also, isTSX:\n * true requires allExtensions: true.", "score": 0.7088820934295654 }, { "filename": "src/core/types.ts", "retrieved_chunk": " * vite-plugin-solid.\n *\n * @default undefined\n */\n extensions?: (string | [string, ExtensionOptions])[];\n /**\n * Pass any additional babel transform options. They will be merged with the\n * transformations required by Solid.\n *\n * @default { }", "score": 0.6973733901977539 }, { "filename": "src/core/types.ts", "retrieved_chunk": " * Indicates that every file should be parsed as TS or TSX (depending on the\n * isTSX option).\n *\n * @default false\n */\n allExtensions?: boolean;\n /**\n * Enables compilation of TypeScript namespaces.\n *\n * @default uses the default set by @babel/plugin-transform-typescript.", "score": 0.6854424476623535 }, { "filename": "src/core/utils.ts", "retrieved_chunk": "export const normalizeAliases = (alias: AliasOptions = []): Alias[] =>\n Array.isArray(alias)\n ? alias\n : Object.entries(alias).map(([find, replacement]) => ({\n find,\n replacement,\n }));", "score": 0.6793231964111328 } ]
typescript
options.extensions ?? []), ".tsx", ".jsx", ];
// Adapted from https://github.com/solidjs/vite-plugin-solid/blob/master/src/index.ts import { readFileSync } from "node:fs"; import type { TransformOptions } from "@babel/core"; import { transformAsync } from "@babel/core"; // @ts-expect-error import ts from "@babel/preset-typescript"; import { createFilter } from "@rollup/pluginutils"; // @ts-expect-error import solid from "babel-preset-solid"; import { mergeAndConcat } from "merge-anything"; import solidRefresh from "solid-refresh/babel"; import { createUnplugin } from "unplugin"; import type { UserConfig } from "vite"; import { crawlFrameworkPkgs } from "vitefu"; import type { Options } from "./types"; import { containsSolidField, getExtension, isJestDomInstalled, normalizeAliases, } from "./utils"; const runtimePublicPath = "/@solid-refresh"; const runtimeFilePath = require.resolve("solid-refresh/dist/solid-refresh.mjs"); const runtimeCode = readFileSync(runtimeFilePath, "utf-8"); export default createUnplugin<Partial<Options> | undefined>( (options = {}, meta) => { const filter = createFilter(options.include, options.exclude); const isVite = meta.framework === "vite"; let needHmr = false; let replaceDev = false; let projectRoot = process.cwd(); return { name: "unplugin-solid", enforce: "pre", vite: { async config(userConfig, { command }) { // We inject the dev mode only if the user explicitely wants it or if we are in dev (serve) mode replaceDev = options.dev === true || (options.dev !== false && command === "serve"); projectRoot = userConfig.root ?? projectRoot; if (!userConfig.resolve) { userConfig.resolve = {}; } userConfig.resolve.alias = normalizeAliases(userConfig.resolve.alias); const solidPkgsConfig = await crawlFrameworkPkgs({ viteUserConfig: userConfig, root: projectRoot || process.cwd(), isBuild: command === "build", isFrameworkPkgByJson(pkgJson) { return containsSolidField(pkgJson.exports || {}); }, }); // fix for bundling dev in production const nestedDeps = replaceDev ? [ "solid-js", "solid-js/web", "solid-js/store", "solid-js/html", "solid-js/h", ] : []; const test = userConfig.mode === "test" ? { test: { globals: true, ...(options.ssr ? {} : { environment: "jsdom" }), transformMode: { [options.ssr ? "ssr" : "web"]: [/\.[jt]sx?$/], }, ...(isJestDomInstalled() ? { setupFiles: [ "node_modules/@testing-library/jest-dom/extend-expect.js", ], } : {}), deps: { registerNodeLoader: true }, ...( userConfig as UserConfig & { test: Record<string, any> } ).test, }, } : {}; return { /** * We only need esbuild on .ts or .js files. .tsx & .jsx files are * handled by us */ esbuild: { include: /\.ts$/ }, resolve: { conditions: [ "solid", ...(isVite && replaceDev ? ["development"] : []), ...(userConfig.mode === "test" && !options.ssr ? ["browser"] : []), ], dedupe: nestedDeps, alias: [ { find: /^solid-refresh$/, replacement: runtimePublicPath }, ], }, optimizeDeps: { include: [...nestedDeps, ...solidPkgsConfig.optimizeDeps.include], exclude: solidPkgsConfig.optimizeDeps.exclude, }, ssr: solidPkgsConfig.ssr, ...test, }; }, configResolved(config) { needHmr = config.command === "serve" && config.mode !== "production" && options.hot !== false; }, resolveId(id) { if (id === runtimePublicPath) { return id; } }, load(id) { if (id === runtimePublicPath) { return runtimeCode; } }, }, async transform(source, id) { const isSsr = !!options.ssr; const currentFileExtension = getExtension(id); const extensionsToWatch = [ ...(options.extensions ?? []), ".tsx", ".jsx", ]; const allExtensions = extensionsToWatch.map((extension) => // An extension can be a string or a tuple [extension, options] typeof extension === "string" ? extension : extension[0], ); if (!filter(id) || !allExtensions.includes(currentFileExtension)) { return null; } const inNodeModules = /node_modules/.test(id); let solidOptions: { generate: "ssr" | "dom"; hydratable: boolean }; if (options.ssr) { solidOptions = isSsr ? { generate: "ssr", hydratable: true } : { generate: "dom", hydratable: true }; } else { solidOptions = { generate: "dom", hydratable: false }; } id = id.replace(/\?.+$/, ""); const opts: TransformOptions = { babelrc: false, configFile: false, root: projectRoot, filename: id, sourceFileName: id, presets: [[solid, { ...solidOptions, ...(options.solid ?? {}) }]], plugins: isVite && needHmr && !isSsr && !inNodeModules ? [[solidRefresh, { bundler: "vite" }]] : [], sourceMaps: true, // Vite handles sourcemap flattening inputSourceMap: false as any, }; // We need to know if the current file extension has a typescript options tied to it const shouldBeProcessedWithTypescript = extensionsToWatch.some( (extension) => { if (typeof extension === "string") { return extension.includes("tsx"); } const [extensionName, extensionOptions] = extension; if (extensionName !== currentFileExtension) { return false; } return extensionOptions.typescript; }, ); if (shouldBeProcessedWithTypescript) {
(opts.presets ??= []).push([ts, options.typescript ?? {}]);
} // Default value for babel user options let babelUserOptions: TransformOptions = {}; if (options.babel) { if (typeof options.babel === "function") { const babelOptions = options.babel(source, id, isSsr); babelUserOptions = babelOptions instanceof Promise ? await babelOptions : babelOptions; } else { babelUserOptions = options.babel; } } const babelOptions = mergeAndConcat(babelUserOptions, opts); const { code, map } = (await transformAsync(source, babelOptions))!; return { code: code!, map }; }, }; }, );
src/core/index.ts
so1ve-unplugin-solid-3c0a7e1
[ { "filename": "src/core/types.ts", "retrieved_chunk": " */\n babel:\n | TransformOptions\n | ((source: string, id: string, ssr: boolean) => TransformOptions)\n | ((source: string, id: string, ssr: boolean) => Promise<TransformOptions>);\n typescript: {\n /**\n * Forcibly enables jsx parsing. Otherwise angle brackets will be treated as\n * typescript's legacy type assertion var foo = <string>bar;. Also, isTSX:\n * true requires allExtensions: true.", "score": 0.7521619200706482 }, { "filename": "src/core/utils.ts", "retrieved_chunk": "export const normalizeAliases = (alias: AliasOptions = []): Alias[] =>\n Array.isArray(alias)\n ? alias\n : Object.entries(alias).map(([find, replacement]) => ({\n find,\n replacement,\n }));", "score": 0.7419715523719788 }, { "filename": "src/core/types.ts", "retrieved_chunk": " * vite-plugin-solid.\n *\n * @default undefined\n */\n extensions?: (string | [string, ExtensionOptions])[];\n /**\n * Pass any additional babel transform options. They will be merged with the\n * transformations required by Solid.\n *\n * @default { }", "score": 0.7344591617584229 }, { "filename": "src/core/types.ts", "retrieved_chunk": " * Indicates that every file should be parsed as TS or TSX (depending on the\n * isTSX option).\n *\n * @default false\n */\n allExtensions?: boolean;\n /**\n * Enables compilation of TypeScript namespaces.\n *\n * @default uses the default set by @babel/plugin-transform-typescript.", "score": 0.7238155603408813 }, { "filename": "src/core/types.ts", "retrieved_chunk": "import type { TransformOptions } from \"@babel/core\";\nimport type { FilterPattern } from \"@rollup/pluginutils\";\ninterface ExtensionOptions {\n typescript?: boolean;\n}\nexport interface Options {\n /**\n * A [picomatch](https://github.com/micromatch/picomatch) pattern, or array of\n * patterns, which specifies the files the plugin should operate on.\n */", "score": 0.7088717222213745 } ]
typescript
(opts.presets ??= []).push([ts, options.typescript ?? {}]);
// Adapted from https://github.com/solidjs/vite-plugin-solid/blob/master/src/index.ts import { readFileSync } from "node:fs"; import type { TransformOptions } from "@babel/core"; import { transformAsync } from "@babel/core"; // @ts-expect-error import ts from "@babel/preset-typescript"; import { createFilter } from "@rollup/pluginutils"; // @ts-expect-error import solid from "babel-preset-solid"; import { mergeAndConcat } from "merge-anything"; import solidRefresh from "solid-refresh/babel"; import { createUnplugin } from "unplugin"; import type { UserConfig } from "vite"; import { crawlFrameworkPkgs } from "vitefu"; import type { Options } from "./types"; import { containsSolidField, getExtension, isJestDomInstalled, normalizeAliases, } from "./utils"; const runtimePublicPath = "/@solid-refresh"; const runtimeFilePath = require.resolve("solid-refresh/dist/solid-refresh.mjs"); const runtimeCode = readFileSync(runtimeFilePath, "utf-8"); export default createUnplugin<Partial<Options> | undefined>( (options = {}, meta) => { const filter = createFilter(options.include, options.exclude); const isVite = meta.framework === "vite"; let needHmr = false; let replaceDev = false; let projectRoot = process.cwd(); return { name: "unplugin-solid", enforce: "pre", vite: { async config(userConfig, { command }) { // We inject the dev mode only if the user explicitely wants it or if we are in dev (serve) mode replaceDev = options.dev === true || (options.dev !== false && command === "serve"); projectRoot = userConfig.root ?? projectRoot; if (!userConfig.resolve) { userConfig.resolve = {}; } userConfig.resolve.alias = normalizeAliases(userConfig.resolve.alias); const solidPkgsConfig = await crawlFrameworkPkgs({ viteUserConfig: userConfig, root: projectRoot || process.cwd(), isBuild: command === "build", isFrameworkPkgByJson(pkgJson) { return containsSolidField(pkgJson.exports || {}); }, }); // fix for bundling dev in production const nestedDeps = replaceDev ? [ "solid-js", "solid-js/web", "solid-js/store", "solid-js/html", "solid-js/h", ] : []; const test = userConfig.mode === "test" ? { test: { globals: true, ...(options.ssr ? {} : { environment: "jsdom" }), transformMode: { [options.ssr ? "ssr" : "web"]: [/\.[jt]sx?$/], }, ...(isJestDomInstalled() ? { setupFiles: [ "node_modules/@testing-library/jest-dom/extend-expect.js", ], } : {}), deps: { registerNodeLoader: true }, ...( userConfig as UserConfig & { test: Record<string, any> } ).test, }, } : {}; return { /** * We only need esbuild on .ts or .js files. .tsx & .jsx files are * handled by us */ esbuild: { include: /\.ts$/ }, resolve: { conditions: [ "solid", ...(isVite && replaceDev ? ["development"] : []), ...(userConfig.mode === "test" && !options.ssr ? ["browser"] : []), ], dedupe: nestedDeps, alias: [ { find: /^solid-refresh$/, replacement: runtimePublicPath }, ], }, optimizeDeps: { include: [...nestedDeps, ...solidPkgsConfig.optimizeDeps.include], exclude: solidPkgsConfig.optimizeDeps.exclude, }, ssr: solidPkgsConfig.ssr, ...test, }; }, configResolved(config) { needHmr = config.command === "serve" && config.mode !== "production" &&
options.hot !== false;
}, resolveId(id) { if (id === runtimePublicPath) { return id; } }, load(id) { if (id === runtimePublicPath) { return runtimeCode; } }, }, async transform(source, id) { const isSsr = !!options.ssr; const currentFileExtension = getExtension(id); const extensionsToWatch = [ ...(options.extensions ?? []), ".tsx", ".jsx", ]; const allExtensions = extensionsToWatch.map((extension) => // An extension can be a string or a tuple [extension, options] typeof extension === "string" ? extension : extension[0], ); if (!filter(id) || !allExtensions.includes(currentFileExtension)) { return null; } const inNodeModules = /node_modules/.test(id); let solidOptions: { generate: "ssr" | "dom"; hydratable: boolean }; if (options.ssr) { solidOptions = isSsr ? { generate: "ssr", hydratable: true } : { generate: "dom", hydratable: true }; } else { solidOptions = { generate: "dom", hydratable: false }; } id = id.replace(/\?.+$/, ""); const opts: TransformOptions = { babelrc: false, configFile: false, root: projectRoot, filename: id, sourceFileName: id, presets: [[solid, { ...solidOptions, ...(options.solid ?? {}) }]], plugins: isVite && needHmr && !isSsr && !inNodeModules ? [[solidRefresh, { bundler: "vite" }]] : [], sourceMaps: true, // Vite handles sourcemap flattening inputSourceMap: false as any, }; // We need to know if the current file extension has a typescript options tied to it const shouldBeProcessedWithTypescript = extensionsToWatch.some( (extension) => { if (typeof extension === "string") { return extension.includes("tsx"); } const [extensionName, extensionOptions] = extension; if (extensionName !== currentFileExtension) { return false; } return extensionOptions.typescript; }, ); if (shouldBeProcessedWithTypescript) { (opts.presets ??= []).push([ts, options.typescript ?? {}]); } // Default value for babel user options let babelUserOptions: TransformOptions = {}; if (options.babel) { if (typeof options.babel === "function") { const babelOptions = options.babel(source, id, isSsr); babelUserOptions = babelOptions instanceof Promise ? await babelOptions : babelOptions; } else { babelUserOptions = options.babel; } } const babelOptions = mergeAndConcat(babelUserOptions, opts); const { code, map } = (await transformAsync(source, babelOptions))!; return { code: code!, map }; }, }; }, );
src/core/index.ts
so1ve-unplugin-solid-3c0a7e1
[ { "filename": "src/core/types.ts", "retrieved_chunk": " */\n babel:\n | TransformOptions\n | ((source: string, id: string, ssr: boolean) => TransformOptions)\n | ((source: string, id: string, ssr: boolean) => Promise<TransformOptions>);\n typescript: {\n /**\n * Forcibly enables jsx parsing. Otherwise angle brackets will be treated as\n * typescript's legacy type assertion var foo = <string>bar;. Also, isTSX:\n * true requires allExtensions: true.", "score": 0.7191550135612488 }, { "filename": "src/core/types.ts", "retrieved_chunk": " ssr: boolean;\n /**\n * This will inject HMR runtime in dev mode. Has no effect in prod. If set to\n * `false`, it won't inject the runtime in dev.\n *\n * @default true\n */\n hot: boolean;\n /**\n * This registers additional extensions that should be processed by", "score": 0.7164684534072876 }, { "filename": "src/core/utils.ts", "retrieved_chunk": " return true;\n }\n }\n return false;\n}\nexport function isJestDomInstalled() {\n try {\n // attempt to reference a file that will not throw error because expect is missing\n require(\"@testing-library/jest-dom/dist/utils\");\n return true;", "score": 0.7063515186309814 }, { "filename": "src/core/types.ts", "retrieved_chunk": "import type { TransformOptions } from \"@babel/core\";\nimport type { FilterPattern } from \"@rollup/pluginutils\";\ninterface ExtensionOptions {\n typescript?: boolean;\n}\nexport interface Options {\n /**\n * A [picomatch](https://github.com/micromatch/picomatch) pattern, or array of\n * patterns, which specifies the files the plugin should operate on.\n */", "score": 0.7002294659614563 }, { "filename": "src/core/types.ts", "retrieved_chunk": " * vite-plugin-solid.\n *\n * @default undefined\n */\n extensions?: (string | [string, ExtensionOptions])[];\n /**\n * Pass any additional babel transform options. They will be merged with the\n * transformations required by Solid.\n *\n * @default { }", "score": 0.6982058882713318 } ]
typescript
options.hot !== false;
import { App, Notice, PluginSettingTab, Setting } from "obsidian"; import DendronTreePlugin from "./main"; import { VaultConfig } from "./engine/vault"; import { AddVaultModal } from "./modal/add-vault"; export interface DendronTreePluginSettings { /** * @deprecated use vaultList */ vaultPath?: string; vaultList: VaultConfig[]; autoGenerateFrontmatter: boolean; autoReveal: boolean; customResolver: boolean; } export const DEFAULT_SETTINGS: DendronTreePluginSettings = { vaultList: [ { name: "root", path: "/", }, ], autoGenerateFrontmatter: true, autoReveal: true, customResolver: false, }; export class DendronTreeSettingTab extends PluginSettingTab { plugin: DendronTreePlugin; constructor(app: App, plugin: DendronTreePlugin) { super(app, plugin); this.plugin = plugin; } display(): void { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h2", { text: "Dendron Tree Settting" }); new Setting(containerEl) .setName("Auto Generate Front Matter") .setDesc("Generate front matter for new file even if file is created outside of Dendron tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoGenerateFrontmatter).onChange(async (value) => { this.plugin.settings.autoGenerateFrontmatter = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Auto Reveal") .setDesc("Automatically reveal active file in Dendron Tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoReveal).onChange(async (value) => { this.plugin.settings.autoReveal = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Custom Resolver") .setDesc( "Use custom resolver to resolve ref/embed and link. (Please reopen editor after change this setting)" ) .addToggle((toggle) => { toggle.setValue(this.plugin.settings.customResolver).onChange(async (value) => { this.plugin.settings.customResolver = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl).setName("Vault List").setHeading(); for (const vault of this.plugin.settings.vaultList) { new Setting(containerEl) .setName(vault.name) .setDesc(`Folder: ${vault.path}`) .addButton((btn) => { btn.setButtonText("Remove").onClick(async () => { this.plugin.settings.vaultList.remove(vault); await this.plugin.saveSettings(); this.display(); }); }); } new Setting(containerEl).addButton((btn) => { btn.setButtonText("Add Vault").onClick(() => { new AddVaultModal(this.app, (config) => { const list = this.plugin.settings.vaultList; const nameLowecase = config.name.toLowerCase(); if (list.find(({ name }) => name.toLowerCase() === nameLowecase)) { new Notice("Vault with same name already exist"); return false; }
if (list.find(({ path }) => path === config.path)) {
new Notice("Vault with same path already exist"); return false; } list.push(config); this.plugin.saveSettings().then(() => this.display()); return true; }).open(); }); }); } hide() { super.hide(); this.plugin.onRootFolderChanged(); this.plugin.configureCustomResolver(); } }
src/settings.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " .setCta()\n .setButtonText(\"Add Text\")\n .onClick(() => {\n const name = this.nameText.getValue();\n if (!this.folder || name.trim().length === 0) {\n new Notice(\"Please specify Vault Path and Vault Name\");\n return;\n }\n if (\n this.onSubmit({", "score": 0.8601366281509399 }, { "filename": "src/engine/workspace.ts", "retrieved_chunk": " this.vaultList = vaultList.map((config) => {\n return (\n this.vaultList.find(\n (vault) => vault.config.name === config.name && vault.config.path === config.path\n ) ?? new DendronVault(this.app, config)\n );\n });\n for (const vault of this.vaultList) {\n vault.init();\n }", "score": 0.838246762752533 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 0.8266846537590027 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " return name;\n }\n onOpen(): void {\n new Setting(this.contentEl).setHeading().setName(\"Add Vault\");\n new Setting(this.contentEl).setName(\"Vault Path\").addText((text) => {\n new FolderSuggester(this.app, text.inputEl, (newFolder) => {\n const currentName = this.nameText.getValue();\n if (\n currentName.length === 0 ||\n (this.folder && currentName === this.generateName(this.folder))", "score": 0.8239543437957764 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " bottom: loc.top + this.inputEl.offsetHeight,\n });\n };\n getSuggestions(query: string) {\n const queryLowercase = query.toLowerCase();\n return this.app.vault\n .getAllLoadedFiles()\n .filter(\n (file) => file instanceof TFolder && file.path.toLowerCase().contains(queryLowercase)\n ) as TFolder[];", "score": 0.8046322464942932 } ]
typescript
if (list.find(({ path }) => path === config.path)) {
import { App, Notice, PluginSettingTab, Setting } from "obsidian"; import DendronTreePlugin from "./main"; import { VaultConfig } from "./engine/vault"; import { AddVaultModal } from "./modal/add-vault"; export interface DendronTreePluginSettings { /** * @deprecated use vaultList */ vaultPath?: string; vaultList: VaultConfig[]; autoGenerateFrontmatter: boolean; autoReveal: boolean; customResolver: boolean; } export const DEFAULT_SETTINGS: DendronTreePluginSettings = { vaultList: [ { name: "root", path: "/", }, ], autoGenerateFrontmatter: true, autoReveal: true, customResolver: false, }; export class DendronTreeSettingTab extends PluginSettingTab { plugin: DendronTreePlugin; constructor(app: App, plugin: DendronTreePlugin) { super(app, plugin); this.plugin = plugin; } display(): void { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h2", { text: "Dendron Tree Settting" }); new Setting(containerEl) .setName("Auto Generate Front Matter") .setDesc("Generate front matter for new file even if file is created outside of Dendron tree") .addToggle((toggle) => { toggle.
setValue(this.plugin.settings.autoGenerateFrontmatter).onChange(async (value) => {
this.plugin.settings.autoGenerateFrontmatter = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Auto Reveal") .setDesc("Automatically reveal active file in Dendron Tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoReveal).onChange(async (value) => { this.plugin.settings.autoReveal = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Custom Resolver") .setDesc( "Use custom resolver to resolve ref/embed and link. (Please reopen editor after change this setting)" ) .addToggle((toggle) => { toggle.setValue(this.plugin.settings.customResolver).onChange(async (value) => { this.plugin.settings.customResolver = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl).setName("Vault List").setHeading(); for (const vault of this.plugin.settings.vaultList) { new Setting(containerEl) .setName(vault.name) .setDesc(`Folder: ${vault.path}`) .addButton((btn) => { btn.setButtonText("Remove").onClick(async () => { this.plugin.settings.vaultList.remove(vault); await this.plugin.saveSettings(); this.display(); }); }); } new Setting(containerEl).addButton((btn) => { btn.setButtonText("Add Vault").onClick(() => { new AddVaultModal(this.app, (config) => { const list = this.plugin.settings.vaultList; const nameLowecase = config.name.toLowerCase(); if (list.find(({ name }) => name.toLowerCase() === nameLowecase)) { new Notice("Vault with same name already exist"); return false; } if (list.find(({ path }) => path === config.path)) { new Notice("Vault with same path already exist"); return false; } list.push(config); this.plugin.saveSettings().then(() => this.display()); return true; }).open(); }); }); } hide() { super.hide(); this.plugin.onRootFolderChanged(); this.plugin.configureCustomResolver(); } }
src/settings.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/invalid-root.ts", "retrieved_chunk": " });\n new Setting(this.contentEl).addButton((button) => {\n button\n .setButtonText(\"Create\")\n .setCta()\n .onClick(async () => {\n await this.dendronVault.createRootFolder();\n this.dendronVault.init();\n this.close();\n });", "score": 0.8169822692871094 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " return name;\n }\n onOpen(): void {\n new Setting(this.contentEl).setHeading().setName(\"Add Vault\");\n new Setting(this.contentEl).setName(\"Vault Path\").addText((text) => {\n new FolderSuggester(this.app, text.inputEl, (newFolder) => {\n const currentName = this.nameText.getValue();\n if (\n currentName.length === 0 ||\n (this.folder && currentName === this.generateName(this.folder))", "score": 0.8077552914619446 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " cls: \"cm-hmd-internal-link\",\n },\n (el) => {\n el.createSpan({\n cls: \"cm-underline\",\n });\n }\n );\n this.updateTitle();\n this.containerEl.addEventListener(\"click\", () => {", "score": 0.8053510189056396 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " renderSuggestion(item: LookupItem | null, el: HTMLElement) {\n el.classList.add(\"mod-complex\");\n el.createEl(\"div\", { cls: \"suggestion-content\" }, (el) => {\n el.createEl(\"div\", { text: item?.note.title ?? \"Create New\", cls: \"suggestion-title\" });\n el.createEl(\"small\", {\n text: item\n ? item.note.getPath() +\n (this.workspace.vaultList.length > 1 ? ` (${item.vault.config.name})` : \"\")\n : \"Note does not exist\",\n cls: \"suggestion-content\",", "score": 0.8033896088600159 }, { "filename": "src/main.ts", "retrieved_chunk": " settings: DendronTreePluginSettings;\n workspace: DendronWorkspace = new DendronWorkspace(this.app);\n customResolver?: CustomResolver;\n async onload() {\n await this.loadSettings();\n await this.migrateSettings();\n addIcon(dendronActivityBarName, dendronActivityBarIcon);\n this.addCommand({\n id: \"dendron-lookup\",\n name: \"Lookup Note\",", "score": 0.8021102547645569 } ]
typescript
setValue(this.plugin.settings.autoGenerateFrontmatter).onChange(async (value) => {
import { OpenAIApi, Configuration, ChatCompletionRequestMessage } from 'openai'; import dedent from 'dedent'; import { IncomingMessage } from 'http'; import { KnownError } from './error'; import { streamToIterable } from './stream-to-iterable'; import { detectShell } from './os-detect'; import type { AxiosError } from 'axios'; import { streamToString } from './stream-to-string'; import './replace-all-polyfill'; import i18n from './i18n'; const explainInSecondRequest = true; function getOpenAi(key: string, apiEndpoint: string) { const openAi = new OpenAIApi( new Configuration({ apiKey: key, basePath: apiEndpoint }) ); return openAi; } // Openai outputs markdown format for code blocks. It oftne uses // a github style like: "```bash" const shellCodeStartRegex = /```[^\n]*/gi; export async function getScriptAndInfo({ prompt, key, model, apiEndpoint, }: { prompt: string; key: string; model?: string; apiEndpoint: string; }) { const fullPrompt = getFullPrompt(prompt); const stream = await generateCompletion({ prompt: fullPrompt, number: 1, key, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); const codeBlock = '```'; return { readScript: readData(iterableStream, () => true, shellCodeStartRegex), readInfo: readData( iterableStream, (content) => content.endsWith(codeBlock), shellCodeStartRegex ), }; } export async function generateCompletion({ prompt, number = 1, key, model, apiEndpoint, }: { prompt: string | ChatCompletionRequestMessage[]; number?: number; model?: string; key: string; apiEndpoint: string; }) { const openAi = getOpenAi(key, apiEndpoint); try { const completion = await openAi.createChatCompletion( { model: model || 'gpt-3.5-turbo', messages: Array.isArray(prompt) ? prompt : [{ role: 'user', content: prompt }], n: Math.min(number, 10), stream: true, }, { responseType: 'stream' } ); return completion.data as unknown as IncomingMessage; } catch (err) { const error = err as AxiosError; if (error.code === 'ENOTFOUND') { throw new KnownError( `Error connecting to ${error.request.hostname} (${error.request.syscall}). Are you connected to the internet?` ); } const response = error.response; let message = response?.data as string | object | IncomingMessage; if (response && message instanceof IncomingMessage) { message = await streamToString( response.data as unknown as IncomingMessage ); try { // Handle if the message is JSON. It should be but occasionally will // be HTML, so lets handle both message = JSON.parse(message); } catch (e) { // Ignore } } const messageString = message && JSON.stringify(message, null, 2); if (response?.status === 429) { throw new KnownError( dedent` Request to OpenAI failed with status 429. This is due to incorrect billing setup or excessive quota usage. Please follow this guide to fix it: https://help.openai.com/en/articles/6891831-error-code-429-you-exceeded-your-current-quota-please-check-your-plan-and-billing-details You can activate billing here: https://platform.openai.com/account/billing/overview . Make sure to add a payment method if not under an active grant from OpenAI. Full message from OpenAI: ` + '\n\n' + messageString + '\n' ); } else if (response && message) { throw new KnownError( dedent` Request to OpenAI failed with status ${response?.status}: ` + '\n\n' + messageString + '\n' ); } throw error; } } export async function getExplanation({ script, key, model, apiEndpoint, }: { script: string; key: string; model?: string; apiEndpoint: string; }) { const prompt = getExplanationPrompt(script); const stream = await generateCompletion({ prompt, key, number: 1, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); return { readExplanation: readData(iterableStream, () => true) }; } export async function getRevision({ prompt, code, key, model, apiEndpoint, }: { prompt: string; code: string; key: string; model?: string; apiEndpoint: string; }) { const fullPrompt = getRevisionPrompt(prompt, code); const stream = await generateCompletion({ prompt: fullPrompt, key, number: 1, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); return { readScript: readData(iterableStream, () => true), }; } export const readData = ( iterableStream: AsyncGenerator<string, void>, startSignal: (content: string) => boolean, excluded?: RegExp ) => (writer: (data: string) => void): Promise<string> => new Promise(async (resolve) => { let data = ''; let content = ''; let dataStart = false; let waitUntilNewline = false; for await (const chunk of iterableStream) { const payloads = chunk.toString().split('\n\n'); for (const payload of payloads) { if (payload.includes('[DONE]')) { dataStart = false; resolve(data); return; } if (payload.startsWith('data:')) { content = parseContent(payload); if (!dataStart && content.match(excluded ?? '')) { dataStart = startSignal(content); if (!content.includes('\n')) { waitUntilNewline = true; } if (excluded) break; } if (content && waitUntilNewline) { if (!content.includes('\n')) { continue; } waitUntilNewline = false; } if (dataStart && content) { const contentWithoutExcluded = excluded ? content.replaceAll(excluded, '') : content; data += contentWithoutExcluded; writer(contentWithoutExcluded); } } } } function parseContent(payload: string): string { const data = payload.replaceAll(/(\n)?^data:\s*/g, ''); try { const delta = JSON.parse(data.trim()); return delta.choices?.[0].delta?.content ?? ''; } catch (error) { return `Error with JSON.parse and ${payload}.\n${error}`; } } resolve(data); }); function getExplanationPrompt(script: string) { return dedent` ${explainScript} Please reply in ${i18n.getCurrentLanguagenName()} The script: ${script} `; } function getShellDetails() { const
shellDetails = detectShell();
return dedent` The target shell is ${shellDetails} `; } const shellDetails = getShellDetails(); const explainScript = dedent` Please provide a clear, concise description of the script, using minimal words. Outline the steps in a list format. `; function getOperationSystemDetails() { const os = require('@nexssp/os/legacy'); return os.name(); } const generationDetails = dedent` Only reply with the single line command surrounded by three backticks. It must be able to be directly run in the target shell. Do not include any other text. Make sure the command runs on ${getOperationSystemDetails()} operating system. `; function getFullPrompt(prompt: string) { return dedent` Create a single line command that one can enter in a terminal and run, based on what is specified in the prompt. ${shellDetails} ${generationDetails} ${explainInSecondRequest ? '' : explainScript} The prompt is: ${prompt} `; } function getRevisionPrompt(prompt: string, code: string) { return dedent` Update the following script based on what is asked in the following prompt. The script: ${code} The prompt: ${prompt} ${generationDetails} `; }
src/helpers/completion.ts
BuilderIO-ai-shell-83e73ac
[ { "filename": "src/prompt.ts", "retrieved_chunk": " console.log('');\n console.log(dim('•'));\n if (!silentMode) {\n const infoSpin = p.spinner();\n infoSpin.start(i18n.t(`Getting explanation...`));\n const { readExplanation } = await getExplanation({\n script,\n key,\n model,\n apiEndpoint,", "score": 0.8065179586410522 }, { "filename": "src/prompt.ts", "retrieved_chunk": " });\n}\nasync function getPrompt(prompt?: string) {\n const group = p.group(\n {\n prompt: () =>\n p.text({\n message: i18n.t('What would you like me to do?'),\n placeholder: `${i18n.t('e.g.')} ${sample(examples)}`,\n initialValue: prompt,", "score": 0.7953708171844482 }, { "filename": "src/prompt.ts", "retrieved_chunk": " const emptyScript = script.trim() === '';\n const answer: symbol | (() => any) = await p.select({\n message: emptyScript\n ? i18n.t('Revise this script?')\n : i18n.t('Run this script?'),\n options: [\n ...(emptyScript\n ? []\n : [\n {", "score": 0.7901226878166199 }, { "filename": "src/helpers/config.ts", "retrieved_chunk": " }\n await fs.writeFile(configPath, ini.stringify(config), 'utf8');\n};\nexport const showConfigUI = async () => {\n try {\n const config = await getConfig();\n const choice = (await p.select({\n message: i18n.t('Set config') + ':',\n options: [\n {", "score": 0.7876455783843994 }, { "filename": "src/prompt.ts", "retrieved_chunk": " currentScript: string,\n key: string,\n model: string,\n apiEndpoint: string,\n silentMode?: boolean\n) {\n const revision = await promptForRevision();\n const spin = p.spinner();\n spin.start(i18n.t(`Loading...`));\n const { readScript } = await getRevision({", "score": 0.7814441919326782 } ]
typescript
shellDetails = detectShell();
import { App, Notice, PluginSettingTab, Setting } from "obsidian"; import DendronTreePlugin from "./main"; import { VaultConfig } from "./engine/vault"; import { AddVaultModal } from "./modal/add-vault"; export interface DendronTreePluginSettings { /** * @deprecated use vaultList */ vaultPath?: string; vaultList: VaultConfig[]; autoGenerateFrontmatter: boolean; autoReveal: boolean; customResolver: boolean; } export const DEFAULT_SETTINGS: DendronTreePluginSettings = { vaultList: [ { name: "root", path: "/", }, ], autoGenerateFrontmatter: true, autoReveal: true, customResolver: false, }; export class DendronTreeSettingTab extends PluginSettingTab { plugin: DendronTreePlugin; constructor(app: App, plugin: DendronTreePlugin) { super(app, plugin); this.plugin = plugin; } display(): void { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h2", { text: "Dendron Tree Settting" }); new Setting(containerEl) .setName("Auto Generate Front Matter") .setDesc("Generate front matter for new file even if file is created outside of Dendron tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoGenerateFrontmatter).onChange(async (value) => { this.plugin.settings.autoGenerateFrontmatter = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Auto Reveal") .setDesc("Automatically reveal active file in Dendron Tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoReveal).onChange(async (value) => { this.plugin.settings.autoReveal = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Custom Resolver") .setDesc( "Use custom resolver to resolve ref/embed and link. (Please reopen editor after change this setting)" ) .addToggle((toggle) => { toggle.setValue(this.plugin.settings.customResolver).onChange(async (value) => { this.plugin.settings.customResolver = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl).setName("Vault List").setHeading(); for (const vault of this.plugin.settings.vaultList) { new Setting(containerEl) .setName(vault.name) .setDesc(`Folder: ${vault.path}`) .addButton((btn) => { btn.setButtonText("Remove").onClick(async () => { this.plugin.settings.vaultList.remove(vault); await this.plugin.saveSettings(); this.display(); }); }); } new Setting(containerEl).addButton((btn) => { btn.setButtonText("Add Vault").onClick(() => { new AddVaultModal(this.app, (config) => { const list = this.plugin.settings.vaultList; const nameLowecase = config.name.toLowerCase(); if
(list.find(({ name }) => name.toLowerCase() === nameLowecase)) {
new Notice("Vault with same name already exist"); return false; } if (list.find(({ path }) => path === config.path)) { new Notice("Vault with same path already exist"); return false; } list.push(config); this.plugin.saveSettings().then(() => this.display()); return true; }).open(); }); }); } hide() { super.hide(); this.plugin.onRootFolderChanged(); this.plugin.configureCustomResolver(); } }
src/settings.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " return name;\n }\n onOpen(): void {\n new Setting(this.contentEl).setHeading().setName(\"Add Vault\");\n new Setting(this.contentEl).setName(\"Vault Path\").addText((text) => {\n new FolderSuggester(this.app, text.inputEl, (newFolder) => {\n const currentName = this.nameText.getValue();\n if (\n currentName.length === 0 ||\n (this.folder && currentName === this.generateName(this.folder))", "score": 0.8429040908813477 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " .setCta()\n .setButtonText(\"Add Text\")\n .onClick(() => {\n const name = this.nameText.getValue();\n if (!this.folder || name.trim().length === 0) {\n new Notice(\"Please specify Vault Path and Vault Name\");\n return;\n }\n if (\n this.onSubmit({", "score": 0.8400794863700867 }, { "filename": "src/modal/invalid-root.ts", "retrieved_chunk": " });\n new Setting(this.contentEl).addButton((button) => {\n button\n .setButtonText(\"Create\")\n .setCta()\n .onClick(async () => {\n await this.dendronVault.createRootFolder();\n this.dendronVault.init();\n this.close();\n });", "score": 0.8206119537353516 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 0.816119372844696 }, { "filename": "src/engine/workspace.ts", "retrieved_chunk": " this.vaultList = vaultList.map((config) => {\n return (\n this.vaultList.find(\n (vault) => vault.config.name === config.name && vault.config.path === config.path\n ) ?? new DendronVault(this.app, config)\n );\n });\n for (const vault of this.vaultList) {\n vault.init();\n }", "score": 0.8157886266708374 } ]
typescript
(list.find(({ name }) => name.toLowerCase() === nameLowecase)) {
import { App, Notice, PluginSettingTab, Setting } from "obsidian"; import DendronTreePlugin from "./main"; import { VaultConfig } from "./engine/vault"; import { AddVaultModal } from "./modal/add-vault"; export interface DendronTreePluginSettings { /** * @deprecated use vaultList */ vaultPath?: string; vaultList: VaultConfig[]; autoGenerateFrontmatter: boolean; autoReveal: boolean; customResolver: boolean; } export const DEFAULT_SETTINGS: DendronTreePluginSettings = { vaultList: [ { name: "root", path: "/", }, ], autoGenerateFrontmatter: true, autoReveal: true, customResolver: false, }; export class DendronTreeSettingTab extends PluginSettingTab { plugin: DendronTreePlugin; constructor(app: App, plugin: DendronTreePlugin) { super(app, plugin); this.plugin = plugin; } display(): void { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h2", { text: "Dendron Tree Settting" }); new Setting(containerEl) .setName("Auto Generate Front Matter") .setDesc("Generate front matter for new file even if file is created outside of Dendron tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoGenerateFrontmatter).onChange(async (value) => { this.plugin.settings.autoGenerateFrontmatter = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Auto Reveal") .setDesc("Automatically reveal active file in Dendron Tree") .addToggle((toggle) => { toggle.setValue(this.plugin.settings.autoReveal).onChange(async (value) => { this.plugin.settings.autoReveal = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName("Custom Resolver") .setDesc( "Use custom resolver to resolve ref/embed and link. (Please reopen editor after change this setting)" ) .addToggle((toggle) => { toggle.setValue(this.plugin.settings.customResolver).onChange(async (value) => { this.plugin.settings.customResolver = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl).setName("Vault List").setHeading(); for (const vault of this.plugin.settings.vaultList) { new Setting(containerEl) .setName(vault.name) .setDesc(`Folder: ${vault.path}`) .addButton((btn) => { btn.setButtonText("Remove").onClick(async () => { this.plugin.settings.vaultList.remove(vault); await this.plugin.saveSettings(); this.display(); }); }); } new Setting(containerEl).addButton((btn) => { btn.setButtonText("Add Vault").onClick(() => { new AddVaultModal(this.app
, (config) => {
const list = this.plugin.settings.vaultList; const nameLowecase = config.name.toLowerCase(); if (list.find(({ name }) => name.toLowerCase() === nameLowecase)) { new Notice("Vault with same name already exist"); return false; } if (list.find(({ path }) => path === config.path)) { new Notice("Vault with same path already exist"); return false; } list.push(config); this.plugin.saveSettings().then(() => this.display()); return true; }).open(); }); }); } hide() { super.hide(); this.plugin.onRootFolderChanged(); this.plugin.configureCustomResolver(); } }
src/settings.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/modal/invalid-root.ts", "retrieved_chunk": " });\n new Setting(this.contentEl).addButton((button) => {\n button\n .setButtonText(\"Create\")\n .setCta()\n .onClick(async () => {\n await this.dendronVault.createRootFolder();\n this.dendronVault.init();\n this.close();\n });", "score": 0.8802391886711121 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " )\n this.nameText.setValue(this.generateName(newFolder));\n this.folder = newFolder;\n });\n });\n new Setting(this.contentEl).setName(\"Vault Name\").addText((text) => {\n this.nameText = text;\n });\n new Setting(this.contentEl).addButton((btn) => {\n btn", "score": 0.8547718524932861 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " await doCreate(this.workspace.vaultList[0]);\n } else {\n new SelectVaultModal(this.app, this.workspace, doCreate).open();\n }\n }\n}", "score": 0.8184584379196167 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": " return name;\n }\n onOpen(): void {\n new Setting(this.contentEl).setHeading().setName(\"Add Vault\");\n new Setting(this.contentEl).setName(\"Vault Path\").addText((text) => {\n new FolderSuggester(this.app, text.inputEl, (newFolder) => {\n const currentName = this.nameText.getValue();\n if (\n currentName.length === 0 ||\n (this.folder && currentName === this.generateName(this.folder))", "score": 0.8088614344596863 }, { "filename": "src/main.ts", "retrieved_chunk": " menu.addItem((item) => {\n item\n .setIcon(dendronActivityBarName)\n .setTitle(\"Reveal in Dendron Tree\")\n .onClick(() => this.revealFile(file));\n });\n };\n onResolveMetadata = (file: TFile) => {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (vault && vault.onMetadataChanged(file)) {", "score": 0.7899080514907837 } ]
typescript
, (config) => {
import { OpenAIApi, Configuration, ChatCompletionRequestMessage } from 'openai'; import dedent from 'dedent'; import { IncomingMessage } from 'http'; import { KnownError } from './error'; import { streamToIterable } from './stream-to-iterable'; import { detectShell } from './os-detect'; import type { AxiosError } from 'axios'; import { streamToString } from './stream-to-string'; import './replace-all-polyfill'; import i18n from './i18n'; const explainInSecondRequest = true; function getOpenAi(key: string, apiEndpoint: string) { const openAi = new OpenAIApi( new Configuration({ apiKey: key, basePath: apiEndpoint }) ); return openAi; } // Openai outputs markdown format for code blocks. It oftne uses // a github style like: "```bash" const shellCodeStartRegex = /```[^\n]*/gi; export async function getScriptAndInfo({ prompt, key, model, apiEndpoint, }: { prompt: string; key: string; model?: string; apiEndpoint: string; }) { const fullPrompt = getFullPrompt(prompt); const stream = await generateCompletion({ prompt: fullPrompt, number: 1, key, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); const codeBlock = '```'; return { readScript: readData(iterableStream, () => true, shellCodeStartRegex), readInfo: readData( iterableStream, (content) => content.endsWith(codeBlock), shellCodeStartRegex ), }; } export async function generateCompletion({ prompt, number = 1, key, model, apiEndpoint, }: { prompt: string | ChatCompletionRequestMessage[]; number?: number; model?: string; key: string; apiEndpoint: string; }) { const openAi = getOpenAi(key, apiEndpoint); try { const completion = await openAi.createChatCompletion( { model: model || 'gpt-3.5-turbo', messages: Array.isArray(prompt) ? prompt : [{ role: 'user', content: prompt }], n: Math.min(number, 10), stream: true, }, { responseType: 'stream' } ); return completion.data as unknown as IncomingMessage; } catch (err) { const error = err as AxiosError; if (error.code === 'ENOTFOUND') {
throw new KnownError( `Error connecting to ${error.request.hostname} (${error.request.syscall}). Are you connected to the internet?` );
} const response = error.response; let message = response?.data as string | object | IncomingMessage; if (response && message instanceof IncomingMessage) { message = await streamToString( response.data as unknown as IncomingMessage ); try { // Handle if the message is JSON. It should be but occasionally will // be HTML, so lets handle both message = JSON.parse(message); } catch (e) { // Ignore } } const messageString = message && JSON.stringify(message, null, 2); if (response?.status === 429) { throw new KnownError( dedent` Request to OpenAI failed with status 429. This is due to incorrect billing setup or excessive quota usage. Please follow this guide to fix it: https://help.openai.com/en/articles/6891831-error-code-429-you-exceeded-your-current-quota-please-check-your-plan-and-billing-details You can activate billing here: https://platform.openai.com/account/billing/overview . Make sure to add a payment method if not under an active grant from OpenAI. Full message from OpenAI: ` + '\n\n' + messageString + '\n' ); } else if (response && message) { throw new KnownError( dedent` Request to OpenAI failed with status ${response?.status}: ` + '\n\n' + messageString + '\n' ); } throw error; } } export async function getExplanation({ script, key, model, apiEndpoint, }: { script: string; key: string; model?: string; apiEndpoint: string; }) { const prompt = getExplanationPrompt(script); const stream = await generateCompletion({ prompt, key, number: 1, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); return { readExplanation: readData(iterableStream, () => true) }; } export async function getRevision({ prompt, code, key, model, apiEndpoint, }: { prompt: string; code: string; key: string; model?: string; apiEndpoint: string; }) { const fullPrompt = getRevisionPrompt(prompt, code); const stream = await generateCompletion({ prompt: fullPrompt, key, number: 1, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); return { readScript: readData(iterableStream, () => true), }; } export const readData = ( iterableStream: AsyncGenerator<string, void>, startSignal: (content: string) => boolean, excluded?: RegExp ) => (writer: (data: string) => void): Promise<string> => new Promise(async (resolve) => { let data = ''; let content = ''; let dataStart = false; let waitUntilNewline = false; for await (const chunk of iterableStream) { const payloads = chunk.toString().split('\n\n'); for (const payload of payloads) { if (payload.includes('[DONE]')) { dataStart = false; resolve(data); return; } if (payload.startsWith('data:')) { content = parseContent(payload); if (!dataStart && content.match(excluded ?? '')) { dataStart = startSignal(content); if (!content.includes('\n')) { waitUntilNewline = true; } if (excluded) break; } if (content && waitUntilNewline) { if (!content.includes('\n')) { continue; } waitUntilNewline = false; } if (dataStart && content) { const contentWithoutExcluded = excluded ? content.replaceAll(excluded, '') : content; data += contentWithoutExcluded; writer(contentWithoutExcluded); } } } } function parseContent(payload: string): string { const data = payload.replaceAll(/(\n)?^data:\s*/g, ''); try { const delta = JSON.parse(data.trim()); return delta.choices?.[0].delta?.content ?? ''; } catch (error) { return `Error with JSON.parse and ${payload}.\n${error}`; } } resolve(data); }); function getExplanationPrompt(script: string) { return dedent` ${explainScript} Please reply in ${i18n.getCurrentLanguagenName()} The script: ${script} `; } function getShellDetails() { const shellDetails = detectShell(); return dedent` The target shell is ${shellDetails} `; } const shellDetails = getShellDetails(); const explainScript = dedent` Please provide a clear, concise description of the script, using minimal words. Outline the steps in a list format. `; function getOperationSystemDetails() { const os = require('@nexssp/os/legacy'); return os.name(); } const generationDetails = dedent` Only reply with the single line command surrounded by three backticks. It must be able to be directly run in the target shell. Do not include any other text. Make sure the command runs on ${getOperationSystemDetails()} operating system. `; function getFullPrompt(prompt: string) { return dedent` Create a single line command that one can enter in a terminal and run, based on what is specified in the prompt. ${shellDetails} ${generationDetails} ${explainInSecondRequest ? '' : explainScript} The prompt is: ${prompt} `; } function getRevisionPrompt(prompt: string, code: string) { return dedent` Update the following script based on what is asked in the following prompt. The script: ${code} The prompt: ${prompt} ${generationDetails} `; }
src/helpers/completion.ts
BuilderIO-ai-shell-83e73ac
[ { "filename": "src/helpers/os-detect.ts", "retrieved_chunk": " return path.basename(os.userInfo().shell ?? 'bash');\n } catch (err: unknown) {\n if (err instanceof Error) {\n throw new Error(\n `${i18n.t('Shell detection failed unexpectedly')}: ${err.message}`\n );\n }\n }\n}", "score": 0.8417568206787109 }, { "filename": "src/helpers/config.ts", "retrieved_chunk": " `${i18n.t('Invalid config property')} ${name}: ${message}`\n );\n }\n};\nconst configParsers = {\n OPENAI_KEY(key?: string) {\n if (!key) {\n throw new KnownError(\n `Please set your OpenAI API key via \\`${commandName} config set OPENAI_KEY=<your token>\\`` // TODO: i18n\n );", "score": 0.7886837124824524 }, { "filename": "src/prompt.ts", "retrieved_chunk": "export const parseAssert = (name: string, condition: any, message: string) => {\n if (!condition) {\n throw new KnownError(\n `${i18n.t('Invalid config property')} ${name}: ${message}`\n );\n }\n};", "score": 0.7834357619285583 }, { "filename": "src/commands/config.ts", "retrieved_chunk": " const { mode, keyValue: keyValues } = argv._;\n if (mode === 'ui' || !mode) {\n await showConfigUI();\n return;\n }\n if (!keyValues.length) {\n console.error(\n `${i18n.t('Error')}: ${i18n.t(\n 'Missing required parameter'\n )} \"key=value\"\\n`", "score": 0.7626620531082153 }, { "filename": "src/commands/config.ts", "retrieved_chunk": " throw new KnownError(\n `${i18n.t('Invalid config property')}: ${key}`\n );\n }\n }\n return;\n }\n if (mode === 'set') {\n await setConfigs(\n keyValues.map((keyValue) => keyValue.split('=') as [string, string])", "score": 0.7568998336791992 } ]
typescript
throw new KnownError( `Error connecting to ${error.request.hostname} (${error.request.syscall}). Are you connected to the internet?` );
import { OpenAIApi, Configuration, ChatCompletionRequestMessage } from 'openai'; import dedent from 'dedent'; import { IncomingMessage } from 'http'; import { KnownError } from './error'; import { streamToIterable } from './stream-to-iterable'; import { detectShell } from './os-detect'; import type { AxiosError } from 'axios'; import { streamToString } from './stream-to-string'; import './replace-all-polyfill'; import i18n from './i18n'; const explainInSecondRequest = true; function getOpenAi(key: string, apiEndpoint: string) { const openAi = new OpenAIApi( new Configuration({ apiKey: key, basePath: apiEndpoint }) ); return openAi; } // Openai outputs markdown format for code blocks. It oftne uses // a github style like: "```bash" const shellCodeStartRegex = /```[^\n]*/gi; export async function getScriptAndInfo({ prompt, key, model, apiEndpoint, }: { prompt: string; key: string; model?: string; apiEndpoint: string; }) { const fullPrompt = getFullPrompt(prompt); const stream = await generateCompletion({ prompt: fullPrompt, number: 1, key, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); const codeBlock = '```'; return { readScript: readData(iterableStream, () => true, shellCodeStartRegex), readInfo: readData( iterableStream, (content) => content.endsWith(codeBlock), shellCodeStartRegex ), }; } export async function generateCompletion({ prompt, number = 1, key, model, apiEndpoint, }: { prompt: string | ChatCompletionRequestMessage[]; number?: number; model?: string; key: string; apiEndpoint: string; }) { const openAi = getOpenAi(key, apiEndpoint); try { const completion = await openAi.createChatCompletion( { model: model || 'gpt-3.5-turbo', messages: Array.isArray(prompt) ? prompt : [{ role: 'user', content: prompt }], n: Math.min(number, 10), stream: true, }, { responseType: 'stream' } ); return completion.data as unknown as IncomingMessage; } catch (err) { const error = err as AxiosError; if (error.code === 'ENOTFOUND') { throw new KnownError( `Error connecting to ${error.request.hostname} (${error.request.syscall}). Are you connected to the internet?` ); } const response = error.response; let message = response?.data as string | object | IncomingMessage; if (response && message instanceof IncomingMessage) { message = await streamToString( response.data as unknown as IncomingMessage ); try { // Handle if the message is JSON. It should be but occasionally will // be HTML, so lets handle both message = JSON.parse(message); } catch (e) { // Ignore } } const messageString = message && JSON.stringify(message, null, 2); if (response?.status === 429) { throw new KnownError( dedent` Request to OpenAI failed with status 429. This is due to incorrect billing setup or excessive quota usage. Please follow this guide to fix it: https://help.openai.com/en/articles/6891831-error-code-429-you-exceeded-your-current-quota-please-check-your-plan-and-billing-details You can activate billing here: https://platform.openai.com/account/billing/overview . Make sure to add a payment method if not under an active grant from OpenAI. Full message from OpenAI: ` + '\n\n' + messageString + '\n' ); } else if (response && message) { throw new KnownError( dedent` Request to OpenAI failed with status ${response?.status}: ` + '\n\n' + messageString + '\n' ); } throw error; } } export async function getExplanation({ script, key, model, apiEndpoint, }: { script: string; key: string; model?: string; apiEndpoint: string; }) { const prompt = getExplanationPrompt(script); const stream = await generateCompletion({ prompt, key, number: 1, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); return { readExplanation: readData(iterableStream, () => true) }; } export async function getRevision({ prompt, code, key, model, apiEndpoint, }: { prompt: string; code: string; key: string; model?: string; apiEndpoint: string; }) { const fullPrompt = getRevisionPrompt(prompt, code); const stream = await generateCompletion({ prompt: fullPrompt, key, number: 1, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); return { readScript: readData(iterableStream, () => true), }; } export const readData = ( iterableStream: AsyncGenerator<string, void>, startSignal: (content: string) => boolean, excluded?: RegExp ) => (writer: (data: string) => void): Promise<string> => new Promise(async (resolve) => { let data = ''; let content = ''; let dataStart = false; let waitUntilNewline = false; for await (const chunk of iterableStream) { const payloads = chunk.toString().split('\n\n'); for (const payload of payloads) { if (payload.includes('[DONE]')) { dataStart = false; resolve(data); return; } if (payload.startsWith('data:')) { content = parseContent(payload); if (!dataStart && content.match(excluded ?? '')) { dataStart = startSignal(content); if (!content.includes('\n')) { waitUntilNewline = true; } if (excluded) break; } if (content && waitUntilNewline) { if (!content.includes('\n')) { continue; } waitUntilNewline = false; } if (dataStart && content) { const contentWithoutExcluded = excluded ? content.replaceAll(excluded, '') : content; data += contentWithoutExcluded; writer(contentWithoutExcluded); } } } } function parseContent(payload: string): string { const data = payload.replaceAll(/(\n)?^data:\s*/g, ''); try { const delta = JSON.parse(data.trim()); return delta.choices?.[0].delta?.content ?? ''; } catch (error) { return `Error with JSON.parse and ${payload}.\n${error}`; } } resolve(data); }); function getExplanationPrompt(script: string) { return dedent` ${explainScript}
Please reply in ${i18n.getCurrentLanguagenName()}
The script: ${script} `; } function getShellDetails() { const shellDetails = detectShell(); return dedent` The target shell is ${shellDetails} `; } const shellDetails = getShellDetails(); const explainScript = dedent` Please provide a clear, concise description of the script, using minimal words. Outline the steps in a list format. `; function getOperationSystemDetails() { const os = require('@nexssp/os/legacy'); return os.name(); } const generationDetails = dedent` Only reply with the single line command surrounded by three backticks. It must be able to be directly run in the target shell. Do not include any other text. Make sure the command runs on ${getOperationSystemDetails()} operating system. `; function getFullPrompt(prompt: string) { return dedent` Create a single line command that one can enter in a terminal and run, based on what is specified in the prompt. ${shellDetails} ${generationDetails} ${explainInSecondRequest ? '' : explainScript} The prompt is: ${prompt} `; } function getRevisionPrompt(prompt: string, code: string) { return dedent` Update the following script based on what is asked in the following prompt. The script: ${code} The prompt: ${prompt} ${generationDetails} `; }
src/helpers/completion.ts
BuilderIO-ai-shell-83e73ac
[ { "filename": "src/commands/config.ts", "retrieved_chunk": " );\n return;\n }\n throw new KnownError(`${i18n.t('Invalid mode')}: ${mode}`);\n })().catch((error) => {\n console.error(`\\n${red('✖')} ${error.message}`);\n handleCliError(error);\n process.exit(1);\n });\n }", "score": 0.8023090362548828 }, { "filename": "src/prompt.ts", "retrieved_chunk": " defaultValue: i18n.t('Say hello'),\n validate: (value) => {\n if (!value) return i18n.t('Please enter a prompt.');\n },\n }),\n },\n {\n onCancel: () => {\n p.cancel(i18n.t('Goodbye!'));\n process.exit(0);", "score": 0.7972102165222168 }, { "filename": "src/commands/chat.ts", "retrieved_chunk": " validate: (value) => {\n if (!value) return i18n.t('Please enter a prompt.');\n },\n })) as string;\n if (isCancel(userPrompt) || userPrompt === 'exit') {\n outro(i18n.t('Goodbye!'));\n process.exit(0);\n }\n const infoSpin = spinner();\n infoSpin.start(i18n.t(`THINKING...`));", "score": 0.7867833971977234 }, { "filename": "src/helpers/os-detect.ts", "retrieved_chunk": " return path.basename(os.userInfo().shell ?? 'bash');\n } catch (err: unknown) {\n if (err instanceof Error) {\n throw new Error(\n `${i18n.t('Shell detection failed unexpectedly')}: ${err.message}`\n );\n }\n }\n}", "score": 0.7824866771697998 }, { "filename": "src/cli.ts", "retrieved_chunk": " if (promptText.trim() === 'update') {\n update.callback?.(argv);\n } else {\n prompt({ usePrompt: promptText, silentMode }).catch((error) => {\n console.error(`\\n${red('✖')} ${error.message}`);\n handleCliError(error);\n process.exit(1);\n });\n }\n }", "score": 0.7804970145225525 } ]
typescript
Please reply in ${i18n.getCurrentLanguagenName()}
import { command } from 'cleye'; import { spinner, intro, outro, text, isCancel } from '@clack/prompts'; import { cyan, green } from 'kolorist'; import { generateCompletion, readData } from '../helpers/completion'; import { getConfig } from '../helpers/config'; import { streamToIterable } from '../helpers/stream-to-iterable'; import { ChatCompletionRequestMessage } from 'openai'; import i18n from '../helpers/i18n'; export default command( { name: 'chat', help: { description: 'Start a new chat session to send and receive messages, continue replying until the user chooses to exit.', }, }, async () => { const { OPENAI_KEY: key, OPENAI_API_ENDPOINT: apiEndpoint, MODEL: model, } = await getConfig(); const chatHistory: ChatCompletionRequestMessage[] = []; console.log(''); intro(i18n.t('Starting new conversation')); const prompt = async () => { const msgYou = `${i18n.t('You')}:`; const userPrompt = (await text({ message: `${cyan(msgYou)}`, placeholder: i18n.t(`send a message ('exit' to quit)`), validate: (value) => { if (!value) return i18n.t('Please enter a prompt.'); }, })) as string; if (isCancel(userPrompt) || userPrompt === 'exit') { outro(i18n.t('Goodbye!')); process.exit(0); } const infoSpin = spinner(); infoSpin.start(i18n.t(`THINKING...`)); chatHistory.push({ role: 'user', content: userPrompt, }); const { readResponse } = await getResponse({ prompt: chatHistory, key, model, apiEndpoint, }); infoSpin.stop(`${green('AI Shell:')}`); console.log(''); const fullResponse = await readResponse( process.stdout.write.bind(process.stdout) ); chatHistory.push({ role: 'assistant', content: fullResponse, }); console.log(''); console.log(''); prompt(); }; prompt(); } ); async function getResponse({ prompt, number = 1, key, model, apiEndpoint, }: { prompt: string | ChatCompletionRequestMessage[]; number?: number; model?: string; key: string; apiEndpoint: string; }) { const stream = await generateCompletion({ prompt, key, model, number, apiEndpoint, }); const iterableStream = streamToIterable(stream); return {
readResponse: readData(iterableStream, () => true) };
}
src/commands/chat.ts
BuilderIO-ai-shell-83e73ac
[ { "filename": "src/helpers/completion.ts", "retrieved_chunk": " prompt: fullPrompt,\n key,\n number: 1,\n model,\n apiEndpoint,\n });\n const iterableStream = streamToIterable(stream);\n return {\n readScript: readData(iterableStream, () => true),\n };", "score": 0.9581599235534668 }, { "filename": "src/helpers/completion.ts", "retrieved_chunk": "}) {\n const fullPrompt = getFullPrompt(prompt);\n const stream = await generateCompletion({\n prompt: fullPrompt,\n number: 1,\n key,\n model,\n apiEndpoint,\n });\n const iterableStream = streamToIterable(stream);", "score": 0.9528629779815674 }, { "filename": "src/helpers/completion.ts", "retrieved_chunk": " apiEndpoint,\n });\n const iterableStream = streamToIterable(stream);\n return { readExplanation: readData(iterableStream, () => true) };\n}\nexport async function getRevision({\n prompt,\n code,\n key,\n model,", "score": 0.920646071434021 }, { "filename": "src/helpers/completion.ts", "retrieved_chunk": " key: string;\n model?: string;\n apiEndpoint: string;\n}) {\n const prompt = getExplanationPrompt(script);\n const stream = await generateCompletion({\n prompt,\n key,\n number: 1,\n model,", "score": 0.90910404920578 }, { "filename": "src/helpers/completion.ts", "retrieved_chunk": " apiEndpoint,\n}: {\n prompt: string;\n code: string;\n key: string;\n model?: string;\n apiEndpoint: string;\n}) {\n const fullPrompt = getRevisionPrompt(prompt, code);\n const stream = await generateCompletion({", "score": 0.8892220258712769 } ]
typescript
readResponse: readData(iterableStream, () => true) };
import { OpenAIApi, Configuration, ChatCompletionRequestMessage } from 'openai'; import dedent from 'dedent'; import { IncomingMessage } from 'http'; import { KnownError } from './error'; import { streamToIterable } from './stream-to-iterable'; import { detectShell } from './os-detect'; import type { AxiosError } from 'axios'; import { streamToString } from './stream-to-string'; import './replace-all-polyfill'; import i18n from './i18n'; const explainInSecondRequest = true; function getOpenAi(key: string, apiEndpoint: string) { const openAi = new OpenAIApi( new Configuration({ apiKey: key, basePath: apiEndpoint }) ); return openAi; } // Openai outputs markdown format for code blocks. It oftne uses // a github style like: "```bash" const shellCodeStartRegex = /```[^\n]*/gi; export async function getScriptAndInfo({ prompt, key, model, apiEndpoint, }: { prompt: string; key: string; model?: string; apiEndpoint: string; }) { const fullPrompt = getFullPrompt(prompt); const stream = await generateCompletion({ prompt: fullPrompt, number: 1, key, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); const codeBlock = '```'; return { readScript: readData(iterableStream, () => true, shellCodeStartRegex), readInfo: readData( iterableStream, (content) => content.endsWith(codeBlock), shellCodeStartRegex ), }; } export async function generateCompletion({ prompt, number = 1, key, model, apiEndpoint, }: { prompt: string | ChatCompletionRequestMessage[]; number?: number; model?: string; key: string; apiEndpoint: string; }) { const openAi = getOpenAi(key, apiEndpoint); try { const completion = await openAi.createChatCompletion( { model: model || 'gpt-3.5-turbo', messages: Array.isArray(prompt) ? prompt : [{ role: 'user', content: prompt }], n: Math.min(number, 10), stream: true, }, { responseType: 'stream' } ); return completion.data as unknown as IncomingMessage; } catch (err) { const error = err as AxiosError; if (error.code === 'ENOTFOUND') { throw new KnownError( `Error connecting to ${error.request.hostname} (${error.request.syscall}). Are you connected to the internet?` ); } const response = error.response; let message = response?.data as string | object | IncomingMessage; if (response && message instanceof IncomingMessage) { message = await streamToString( response.data as unknown as IncomingMessage ); try { // Handle if the message is JSON. It should be but occasionally will // be HTML, so lets handle both message = JSON.parse(message); } catch (e) { // Ignore } } const messageString = message && JSON.stringify(message, null, 2); if (response?.status === 429) { throw new KnownError( dedent` Request to OpenAI failed with status 429. This is due to incorrect billing setup or excessive quota usage. Please follow this guide to fix it: https://help.openai.com/en/articles/6891831-error-code-429-you-exceeded-your-current-quota-please-check-your-plan-and-billing-details You can activate billing here: https://platform.openai.com/account/billing/overview . Make sure to add a payment method if not under an active grant from OpenAI. Full message from OpenAI: ` + '\n\n' + messageString + '\n' ); } else if (response && message) { throw new KnownError( dedent` Request to OpenAI failed with status ${response?.status}: ` + '\n\n' + messageString + '\n' ); } throw error; } } export async function getExplanation({ script, key, model, apiEndpoint, }: { script: string; key: string; model?: string; apiEndpoint: string; }) { const prompt = getExplanationPrompt(script); const stream = await generateCompletion({ prompt, key, number: 1, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); return { readExplanation: readData(iterableStream, () => true) }; } export async function getRevision({ prompt, code, key, model, apiEndpoint, }: { prompt: string; code: string; key: string; model?: string; apiEndpoint: string; }) { const fullPrompt = getRevisionPrompt(prompt, code); const stream = await generateCompletion({ prompt: fullPrompt, key, number: 1, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); return { readScript: readData(iterableStream, () => true), }; } export const readData = ( iterableStream: AsyncGenerator<string, void>, startSignal: (content: string) => boolean, excluded?: RegExp ) => (writer: (data: string) => void): Promise<string> => new Promise(async (resolve) => { let data = ''; let content = ''; let dataStart = false; let waitUntilNewline = false; for await (const chunk of iterableStream) { const payloads = chunk.toString().split('\n\n'); for (const payload of payloads) { if (payload.includes('[DONE]')) { dataStart = false; resolve(data); return; } if (payload.startsWith('data:')) { content = parseContent(payload); if (!dataStart && content.match(excluded ?? '')) { dataStart = startSignal(content); if (!content.includes('\n')) { waitUntilNewline = true; } if (excluded) break; } if (content && waitUntilNewline) { if (!content.includes('\n')) { continue; } waitUntilNewline = false; } if (dataStart && content) { const contentWithoutExcluded = excluded ? content.replaceAll(excluded, '') : content; data += contentWithoutExcluded; writer(contentWithoutExcluded); } } } } function parseContent(payload: string): string { const data = payload.replaceAll(/(\n)?^data:\s*/g, ''); try { const delta = JSON.parse(data.trim()); return delta.choices?.[0].delta?.content ?? ''; } catch (error) { return `Error with JSON.parse and ${payload}.\n${error}`; } } resolve(data); }); function getExplanationPrompt(script: string) { return dedent` ${explainScript} Please reply in ${
i18n.getCurrentLanguagenName()}
The script: ${script} `; } function getShellDetails() { const shellDetails = detectShell(); return dedent` The target shell is ${shellDetails} `; } const shellDetails = getShellDetails(); const explainScript = dedent` Please provide a clear, concise description of the script, using minimal words. Outline the steps in a list format. `; function getOperationSystemDetails() { const os = require('@nexssp/os/legacy'); return os.name(); } const generationDetails = dedent` Only reply with the single line command surrounded by three backticks. It must be able to be directly run in the target shell. Do not include any other text. Make sure the command runs on ${getOperationSystemDetails()} operating system. `; function getFullPrompt(prompt: string) { return dedent` Create a single line command that one can enter in a terminal and run, based on what is specified in the prompt. ${shellDetails} ${generationDetails} ${explainInSecondRequest ? '' : explainScript} The prompt is: ${prompt} `; } function getRevisionPrompt(prompt: string, code: string) { return dedent` Update the following script based on what is asked in the following prompt. The script: ${code} The prompt: ${prompt} ${generationDetails} `; }
src/helpers/completion.ts
BuilderIO-ai-shell-83e73ac
[ { "filename": "src/commands/config.ts", "retrieved_chunk": " );\n return;\n }\n throw new KnownError(`${i18n.t('Invalid mode')}: ${mode}`);\n })().catch((error) => {\n console.error(`\\n${red('✖')} ${error.message}`);\n handleCliError(error);\n process.exit(1);\n });\n }", "score": 0.8016265630722046 }, { "filename": "src/prompt.ts", "retrieved_chunk": " defaultValue: i18n.t('Say hello'),\n validate: (value) => {\n if (!value) return i18n.t('Please enter a prompt.');\n },\n }),\n },\n {\n onCancel: () => {\n p.cancel(i18n.t('Goodbye!'));\n process.exit(0);", "score": 0.7974512577056885 }, { "filename": "src/commands/chat.ts", "retrieved_chunk": " validate: (value) => {\n if (!value) return i18n.t('Please enter a prompt.');\n },\n })) as string;\n if (isCancel(userPrompt) || userPrompt === 'exit') {\n outro(i18n.t('Goodbye!'));\n process.exit(0);\n }\n const infoSpin = spinner();\n infoSpin.start(i18n.t(`THINKING...`));", "score": 0.7877295613288879 }, { "filename": "src/helpers/os-detect.ts", "retrieved_chunk": " return path.basename(os.userInfo().shell ?? 'bash');\n } catch (err: unknown) {\n if (err instanceof Error) {\n throw new Error(\n `${i18n.t('Shell detection failed unexpectedly')}: ${err.message}`\n );\n }\n }\n}", "score": 0.7841875553131104 }, { "filename": "src/prompt.ts", "retrieved_chunk": " prompt: revision,\n code: currentScript,\n key,\n model,\n apiEndpoint,\n });\n spin.stop(`${i18n.t(`Your new script`)}:`);\n console.log('');\n const script = await readScript(process.stdout.write.bind(process.stdout));\n console.log('');", "score": 0.7803316712379456 } ]
typescript
i18n.getCurrentLanguagenName()}
import { OpenAIApi, Configuration, ChatCompletionRequestMessage } from 'openai'; import dedent from 'dedent'; import { IncomingMessage } from 'http'; import { KnownError } from './error'; import { streamToIterable } from './stream-to-iterable'; import { detectShell } from './os-detect'; import type { AxiosError } from 'axios'; import { streamToString } from './stream-to-string'; import './replace-all-polyfill'; import i18n from './i18n'; const explainInSecondRequest = true; function getOpenAi(key: string, apiEndpoint: string) { const openAi = new OpenAIApi( new Configuration({ apiKey: key, basePath: apiEndpoint }) ); return openAi; } // Openai outputs markdown format for code blocks. It oftne uses // a github style like: "```bash" const shellCodeStartRegex = /```[^\n]*/gi; export async function getScriptAndInfo({ prompt, key, model, apiEndpoint, }: { prompt: string; key: string; model?: string; apiEndpoint: string; }) { const fullPrompt = getFullPrompt(prompt); const stream = await generateCompletion({ prompt: fullPrompt, number: 1, key, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); const codeBlock = '```'; return { readScript: readData(iterableStream, () => true, shellCodeStartRegex), readInfo: readData( iterableStream, (content) => content.endsWith(codeBlock), shellCodeStartRegex ), }; } export async function generateCompletion({ prompt, number = 1, key, model, apiEndpoint, }: { prompt: string | ChatCompletionRequestMessage[]; number?: number; model?: string; key: string; apiEndpoint: string; }) { const openAi = getOpenAi(key, apiEndpoint); try { const completion = await openAi.createChatCompletion( { model: model || 'gpt-3.5-turbo', messages: Array.isArray(prompt) ? prompt : [{ role: 'user', content: prompt }], n: Math.min(number, 10), stream: true, }, { responseType: 'stream' } ); return completion.data as unknown as IncomingMessage; } catch (err) { const error = err as AxiosError; if (error.code === 'ENOTFOUND') { throw new KnownError( `Error connecting to ${error.request.hostname} (${error.request.syscall}). Are you connected to the internet?` ); } const response = error.response; let message = response?.data as string | object | IncomingMessage; if (response && message instanceof IncomingMessage) {
message = await streamToString( response.data as unknown as IncomingMessage );
try { // Handle if the message is JSON. It should be but occasionally will // be HTML, so lets handle both message = JSON.parse(message); } catch (e) { // Ignore } } const messageString = message && JSON.stringify(message, null, 2); if (response?.status === 429) { throw new KnownError( dedent` Request to OpenAI failed with status 429. This is due to incorrect billing setup or excessive quota usage. Please follow this guide to fix it: https://help.openai.com/en/articles/6891831-error-code-429-you-exceeded-your-current-quota-please-check-your-plan-and-billing-details You can activate billing here: https://platform.openai.com/account/billing/overview . Make sure to add a payment method if not under an active grant from OpenAI. Full message from OpenAI: ` + '\n\n' + messageString + '\n' ); } else if (response && message) { throw new KnownError( dedent` Request to OpenAI failed with status ${response?.status}: ` + '\n\n' + messageString + '\n' ); } throw error; } } export async function getExplanation({ script, key, model, apiEndpoint, }: { script: string; key: string; model?: string; apiEndpoint: string; }) { const prompt = getExplanationPrompt(script); const stream = await generateCompletion({ prompt, key, number: 1, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); return { readExplanation: readData(iterableStream, () => true) }; } export async function getRevision({ prompt, code, key, model, apiEndpoint, }: { prompt: string; code: string; key: string; model?: string; apiEndpoint: string; }) { const fullPrompt = getRevisionPrompt(prompt, code); const stream = await generateCompletion({ prompt: fullPrompt, key, number: 1, model, apiEndpoint, }); const iterableStream = streamToIterable(stream); return { readScript: readData(iterableStream, () => true), }; } export const readData = ( iterableStream: AsyncGenerator<string, void>, startSignal: (content: string) => boolean, excluded?: RegExp ) => (writer: (data: string) => void): Promise<string> => new Promise(async (resolve) => { let data = ''; let content = ''; let dataStart = false; let waitUntilNewline = false; for await (const chunk of iterableStream) { const payloads = chunk.toString().split('\n\n'); for (const payload of payloads) { if (payload.includes('[DONE]')) { dataStart = false; resolve(data); return; } if (payload.startsWith('data:')) { content = parseContent(payload); if (!dataStart && content.match(excluded ?? '')) { dataStart = startSignal(content); if (!content.includes('\n')) { waitUntilNewline = true; } if (excluded) break; } if (content && waitUntilNewline) { if (!content.includes('\n')) { continue; } waitUntilNewline = false; } if (dataStart && content) { const contentWithoutExcluded = excluded ? content.replaceAll(excluded, '') : content; data += contentWithoutExcluded; writer(contentWithoutExcluded); } } } } function parseContent(payload: string): string { const data = payload.replaceAll(/(\n)?^data:\s*/g, ''); try { const delta = JSON.parse(data.trim()); return delta.choices?.[0].delta?.content ?? ''; } catch (error) { return `Error with JSON.parse and ${payload}.\n${error}`; } } resolve(data); }); function getExplanationPrompt(script: string) { return dedent` ${explainScript} Please reply in ${i18n.getCurrentLanguagenName()} The script: ${script} `; } function getShellDetails() { const shellDetails = detectShell(); return dedent` The target shell is ${shellDetails} `; } const shellDetails = getShellDetails(); const explainScript = dedent` Please provide a clear, concise description of the script, using minimal words. Outline the steps in a list format. `; function getOperationSystemDetails() { const os = require('@nexssp/os/legacy'); return os.name(); } const generationDetails = dedent` Only reply with the single line command surrounded by three backticks. It must be able to be directly run in the target shell. Do not include any other text. Make sure the command runs on ${getOperationSystemDetails()} operating system. `; function getFullPrompt(prompt: string) { return dedent` Create a single line command that one can enter in a terminal and run, based on what is specified in the prompt. ${shellDetails} ${generationDetails} ${explainInSecondRequest ? '' : explainScript} The prompt is: ${prompt} `; } function getRevisionPrompt(prompt: string, code: string) { return dedent` Update the following script based on what is asked in the following prompt. The script: ${code} The prompt: ${prompt} ${generationDetails} `; }
src/helpers/completion.ts
BuilderIO-ai-shell-83e73ac
[ { "filename": "src/helpers/os-detect.ts", "retrieved_chunk": " return path.basename(os.userInfo().shell ?? 'bash');\n } catch (err: unknown) {\n if (err instanceof Error) {\n throw new Error(\n `${i18n.t('Shell detection failed unexpectedly')}: ${err.message}`\n );\n }\n }\n}", "score": 0.7969934940338135 }, { "filename": "src/helpers/stream-to-string.ts", "retrieved_chunk": "import { IncomingMessage } from 'http';\nexport async function streamToString(stream: IncomingMessage): Promise<string> {\n let str = '';\n for await (const chunk of stream) {\n str += chunk;\n }\n return str;\n}", "score": 0.7814567685127258 }, { "filename": "src/prompt.ts", "retrieved_chunk": "export const parseAssert = (name: string, condition: any, message: string) => {\n if (!condition) {\n throw new KnownError(\n `${i18n.t('Invalid config property')} ${name}: ${message}`\n );\n }\n};", "score": 0.7769580483436584 }, { "filename": "src/helpers/stream-to-iterable.ts", "retrieved_chunk": "import { IncomingMessage } from 'http';\nexport async function* streamToIterable(stream: IncomingMessage) {\n let previous = '';\n for await (const chunk of stream) {\n const bufferChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n previous += bufferChunk;\n let eolIndex;\n while ((eolIndex = previous.indexOf('\\n')) >= 0) {\n // line includes the EOL\n const line = previous.slice(0, eolIndex + 1).trimEnd();", "score": 0.7664945721626282 }, { "filename": "src/commands/config.ts", "retrieved_chunk": " throw new KnownError(\n `${i18n.t('Invalid config property')}: ${key}`\n );\n }\n }\n return;\n }\n if (mode === 'set') {\n await setConfigs(\n keyValues.map((keyValue) => keyValue.split('=') as [string, string])", "score": 0.764504075050354 } ]
typescript
message = await streamToString( response.data as unknown as IncomingMessage );
import { command } from 'cleye'; import { spinner, intro, outro, text, isCancel } from '@clack/prompts'; import { cyan, green } from 'kolorist'; import { generateCompletion, readData } from '../helpers/completion'; import { getConfig } from '../helpers/config'; import { streamToIterable } from '../helpers/stream-to-iterable'; import { ChatCompletionRequestMessage } from 'openai'; import i18n from '../helpers/i18n'; export default command( { name: 'chat', help: { description: 'Start a new chat session to send and receive messages, continue replying until the user chooses to exit.', }, }, async () => { const { OPENAI_KEY: key, OPENAI_API_ENDPOINT: apiEndpoint, MODEL: model, } = await getConfig(); const chatHistory: ChatCompletionRequestMessage[] = []; console.log(''); intro(i18n.t('Starting new conversation')); const prompt = async () => { const msgYou = `${i18n.t('You')}:`; const userPrompt = (await text({ message: `${cyan(msgYou)}`, placeholder: i18n.t(`send a message ('exit' to quit)`), validate: (value) => { if (!value) return i18n.t('Please enter a prompt.'); }, })) as string; if (isCancel(userPrompt) || userPrompt === 'exit') { outro(i18n.t('Goodbye!')); process.exit(0); } const infoSpin = spinner(); infoSpin.start(i18n.t(`THINKING...`)); chatHistory.push({ role: 'user', content: userPrompt, }); const { readResponse } = await getResponse({ prompt: chatHistory, key, model, apiEndpoint, }); infoSpin.stop(`${green('AI Shell:')}`); console.log(''); const fullResponse = await readResponse( process.stdout.write.bind(process.stdout) ); chatHistory.push({ role: 'assistant', content: fullResponse, }); console.log(''); console.log(''); prompt(); }; prompt(); } ); async function getResponse({ prompt, number = 1, key, model, apiEndpoint, }: { prompt: string | ChatCompletionRequestMessage[]; number?: number; model?: string; key: string; apiEndpoint: string; }) { const stream = await generateCompletion({ prompt, key, model, number, apiEndpoint, }); const iterableStream = streamToIterable(stream);
return { readResponse: readData(iterableStream, () => true) };
}
src/commands/chat.ts
BuilderIO-ai-shell-83e73ac
[ { "filename": "src/helpers/completion.ts", "retrieved_chunk": "}) {\n const fullPrompt = getFullPrompt(prompt);\n const stream = await generateCompletion({\n prompt: fullPrompt,\n number: 1,\n key,\n model,\n apiEndpoint,\n });\n const iterableStream = streamToIterable(stream);", "score": 0.9594330787658691 }, { "filename": "src/helpers/completion.ts", "retrieved_chunk": " prompt: fullPrompt,\n key,\n number: 1,\n model,\n apiEndpoint,\n });\n const iterableStream = streamToIterable(stream);\n return {\n readScript: readData(iterableStream, () => true),\n };", "score": 0.9545589089393616 }, { "filename": "src/helpers/completion.ts", "retrieved_chunk": " apiEndpoint,\n });\n const iterableStream = streamToIterable(stream);\n return { readExplanation: readData(iterableStream, () => true) };\n}\nexport async function getRevision({\n prompt,\n code,\n key,\n model,", "score": 0.911247968673706 }, { "filename": "src/helpers/completion.ts", "retrieved_chunk": " key: string;\n model?: string;\n apiEndpoint: string;\n}) {\n const prompt = getExplanationPrompt(script);\n const stream = await generateCompletion({\n prompt,\n key,\n number: 1,\n model,", "score": 0.8990917205810547 }, { "filename": "src/helpers/completion.ts", "retrieved_chunk": " apiEndpoint,\n}: {\n prompt: string;\n code: string;\n key: string;\n model?: string;\n apiEndpoint: string;\n}) {\n const fullPrompt = getRevisionPrompt(prompt, code);\n const stream = await generateCompletion({", "score": 0.874832034111023 } ]
typescript
return { readResponse: readData(iterableStream, () => true) };
import { env } from "@/env.mjs"; import redis from "@/server/redis"; import { formatDateQueryString, getFormattedDate } from "./date"; const { RAPIDAPI_KEY, RAPIDAPI_HOST } = env; export type NetflixJSONData = { imdb_id: string; img: string; netflix_id: number; poster: string; rating: string; runtime: string; synopsis: string; title: string; title_date: string; title_type: "series" | "movie"; top250: number; top250tv: number; year: string; }; export type DailyNetflixJSON = { size: number; added: NetflixJSONData[]; deleted: NetflixDeleteJSONData[]; }; export type NetflixDeleteJSONData = { netflix_id: number; country_id: number; title: string; delete_date: string; country_code: string; }; export type BaseNetflixData<T> = { Object: { total: number; limit: number; offset: number; }; results: T[] | null; }; type RequestOptions = { route: string; method?: "GET" | "POST" | "PATCH" | "PUT" | "DELETE"; body?: BodyInit | null; headers?: HeadersInit | null; queries?: URLSearchParams | null; fetchAllCountries?: boolean | null; }; type FetchTitleOptions = { date: Date; force?: boolean; fetchAllCountries?: boolean; }; const BASE_URL = `https://${RAPIDAPI_HOST}`; const makeNetflixRequest = async <T>( options: RequestOptions ): Promise<BaseNetflixData<T>> => { const url = new URL(`${BASE_URL + options.route}`); if (!options.queries) { const params = new URLSearchParams(); if (!options.fetchAllCountries) params.set("country_list", "78"); options.queries = params; } if (!options.fetchAllCountries) options.queries.set("country_list", "78"); url.search = options.queries.toString(); return fetch(url, { headers: { ...options.headers, "X-RapidAPI-Key": RAPIDAPI_KEY, "X-RapidAPI-Host": RAPIDAPI_HOST, }, body: options.body, }).then((res: Response) => res.json() as Promise<BaseNetflixData<T>>); }; export const fetchDailyTitles = async ({ date }: FetchTitleOptions) => { const queryDate = formatDateQueryString(date); const data: DailyNetflixJSON = { size: 0, added: [], deleted: [], }; const promises = [fetchNewTitles({ date }), fetchDeletedTitles({ date })]; const results = await Promise.allSettled(promises); const addedContent = results[0]?.status === "fulfilled" ? results[0].value : []; const deletedContent = results[1]?.status === "fulfilled" ? results[1].value : []; if (addedContent) { data.added = [...data.added, ...addedContent] as NetflixJSONData[]; data.size += data.added.length; } if (deletedContent) { data.deleted = [ ...data.deleted, ...deletedContent, ] as NetflixDeleteJSONData[]; data.size += data.deleted.length; }
const dateFormatted = getFormattedDate(date);
const cachedDateExists = await redis.sismember("dates", queryDate); if (!cachedDateExists) { await redis.sadd("dates", dateFormatted); await redis.hset<DailyNetflixJSON>("daily-titles", { [dateFormatted]: data, }); } return data; }; export const fetchDeletedTitles = async ({ date, force, fetchAllCountries, }: FetchTitleOptions) => { const queryDate = formatDateQueryString(date); const queries = new URLSearchParams({ delete_date: queryDate, }); const cached = force ? null : await redis.hget<NetflixDeleteJSONData[]>("deleted-titles", queryDate); if (cached) return cached; const { results } = await makeNetflixRequest<NetflixDeleteJSONData>({ route: "/search/deleted", queries, fetchAllCountries, }); if (!results) return [] as NetflixJSONData[]; if (!force) await redis.hset<NetflixDeleteJSONData[]>("deleted-titles", { [getFormattedDate(date)]: results, }); return results; }; export const fetchNewTitles = async ({ date, force, fetchAllCountries, }: FetchTitleOptions) => { const queryDate = formatDateQueryString(date); const queries = new URLSearchParams({ order_by: "date", new_date: queryDate, }); const cached = force ? null : await redis.hget<NetflixJSONData[]>("added-titles", queryDate); if (cached) return cached; const { results } = await makeNetflixRequest<NetflixJSONData>({ route: "/search/titles", queries, fetchAllCountries, }); if (!results) return [] as NetflixJSONData[]; if (!force) await redis.hset<NetflixJSONData[]>("added-titles", { [getFormattedDate(date)]: results, }); return results; };
src/lib/netflix.ts
acollierr17-netflix-refresh-84bb5f2
[ { "filename": "src/server/twitter.ts", "retrieved_chunk": " stripIndents`\n Netflix Refresh (US) • ${getFriendlyFormattedDate(date)}\n Added: ${titles.added.length}\n Deleted: ${titles.deleted.length}\n `,\n ];\n if (titles.added.length > 0)\n tweetContent.push(stripIndents`\n Added Content:\n ${titles.added.map(displayTitle).join(\"\\n\")}", "score": 0.7307502627372742 }, { "filename": "src/pages/api/netflix/deleted-titles.ts", "retrieved_chunk": " metadata: {\n nonce: date.getTime(),\n },\n message: `The 'date' query parameter is not in the proper format! (ex. ${getFormattedDate(\n date\n )})`,\n });\n const formattedQueryDate = getFormattedDate(queryDate);\n const titles = await fetchDeletedTitles({ date: queryDate });\n if (titles.length < 1) {", "score": 0.7089717388153076 }, { "filename": "src/pages/api/add-new-titles.ts", "retrieved_chunk": " return res.json({\n metadata: {\n nonce: date.getTime(),\n size: titles.length,\n added: created.count,\n },\n data: titles,\n });\n } catch (e: any) {\n return res.status(500).json({", "score": 0.7078952789306641 }, { "filename": "src/server/twitter.ts", "retrieved_chunk": " `);\n if (titles.deleted.length > 0)\n tweetContent.push(stripIndents`\n Deleted Content:\n ${titles.deleted.map(displayTitle).join(\"\\n\")}\n `);\n return tweetContent;\n};", "score": 0.6965358257293701 }, { "filename": "src/server/twitter.ts", "retrieved_chunk": " date,\n titles,\n}: {\n date: Date;\n titles: DailyNetflixJSON;\n}): string[] => {\n const displayTitle = (title: NetflixJSONData | NetflixDeleteJSONData) => {\n const titleType = {\n series: \"Series\",\n movie: \"Movie\",", "score": 0.6953641176223755 } ]
typescript
const dateFormatted = getFormattedDate(date);
import { env } from "@/env.mjs"; import redis from "@/server/redis"; import { formatDateQueryString, getFormattedDate } from "./date"; const { RAPIDAPI_KEY, RAPIDAPI_HOST } = env; export type NetflixJSONData = { imdb_id: string; img: string; netflix_id: number; poster: string; rating: string; runtime: string; synopsis: string; title: string; title_date: string; title_type: "series" | "movie"; top250: number; top250tv: number; year: string; }; export type DailyNetflixJSON = { size: number; added: NetflixJSONData[]; deleted: NetflixDeleteJSONData[]; }; export type NetflixDeleteJSONData = { netflix_id: number; country_id: number; title: string; delete_date: string; country_code: string; }; export type BaseNetflixData<T> = { Object: { total: number; limit: number; offset: number; }; results: T[] | null; }; type RequestOptions = { route: string; method?: "GET" | "POST" | "PATCH" | "PUT" | "DELETE"; body?: BodyInit | null; headers?: HeadersInit | null; queries?: URLSearchParams | null; fetchAllCountries?: boolean | null; }; type FetchTitleOptions = { date: Date; force?: boolean; fetchAllCountries?: boolean; }; const BASE_URL = `https://${RAPIDAPI_HOST}`; const makeNetflixRequest = async <T>( options: RequestOptions ): Promise<BaseNetflixData<T>> => { const url = new URL(`${BASE_URL + options.route}`); if (!options.queries) { const params = new URLSearchParams(); if (!options.fetchAllCountries) params.set("country_list", "78"); options.queries = params; } if (!options.fetchAllCountries) options.queries.set("country_list", "78"); url.search = options.queries.toString(); return fetch(url, { headers: { ...options.headers, "X-RapidAPI-Key": RAPIDAPI_KEY, "X-RapidAPI-Host": RAPIDAPI_HOST, }, body: options.body, }).then((res: Response) => res.json() as Promise<BaseNetflixData<T>>); }; export const fetchDailyTitles = async ({ date }: FetchTitleOptions) => {
const queryDate = formatDateQueryString(date);
const data: DailyNetflixJSON = { size: 0, added: [], deleted: [], }; const promises = [fetchNewTitles({ date }), fetchDeletedTitles({ date })]; const results = await Promise.allSettled(promises); const addedContent = results[0]?.status === "fulfilled" ? results[0].value : []; const deletedContent = results[1]?.status === "fulfilled" ? results[1].value : []; if (addedContent) { data.added = [...data.added, ...addedContent] as NetflixJSONData[]; data.size += data.added.length; } if (deletedContent) { data.deleted = [ ...data.deleted, ...deletedContent, ] as NetflixDeleteJSONData[]; data.size += data.deleted.length; } const dateFormatted = getFormattedDate(date); const cachedDateExists = await redis.sismember("dates", queryDate); if (!cachedDateExists) { await redis.sadd("dates", dateFormatted); await redis.hset<DailyNetflixJSON>("daily-titles", { [dateFormatted]: data, }); } return data; }; export const fetchDeletedTitles = async ({ date, force, fetchAllCountries, }: FetchTitleOptions) => { const queryDate = formatDateQueryString(date); const queries = new URLSearchParams({ delete_date: queryDate, }); const cached = force ? null : await redis.hget<NetflixDeleteJSONData[]>("deleted-titles", queryDate); if (cached) return cached; const { results } = await makeNetflixRequest<NetflixDeleteJSONData>({ route: "/search/deleted", queries, fetchAllCountries, }); if (!results) return [] as NetflixJSONData[]; if (!force) await redis.hset<NetflixDeleteJSONData[]>("deleted-titles", { [getFormattedDate(date)]: results, }); return results; }; export const fetchNewTitles = async ({ date, force, fetchAllCountries, }: FetchTitleOptions) => { const queryDate = formatDateQueryString(date); const queries = new URLSearchParams({ order_by: "date", new_date: queryDate, }); const cached = force ? null : await redis.hget<NetflixJSONData[]>("added-titles", queryDate); if (cached) return cached; const { results } = await makeNetflixRequest<NetflixJSONData>({ route: "/search/titles", queries, fetchAllCountries, }); if (!results) return [] as NetflixJSONData[]; if (!force) await redis.hset<NetflixJSONData[]>("added-titles", { [getFormattedDate(date)]: results, }); return results; };
src/lib/netflix.ts
acollierr17-netflix-refresh-84bb5f2
[ { "filename": "src/pages/api/netflix/get-daily-titles.ts", "retrieved_chunk": "import { type NextApiRequest, type NextApiResponse } from \"next\";\nimport { fetchDailyTitles } from \"@/lib/netflix\";\nimport { convertDateQueryParam, getFormattedDate } from \"@/lib/date\";\nimport authenticateRequest from \"@/server/authenticateRequest\";\nasync function handler(req: NextApiRequest, res: NextApiResponse) {\n try {\n const date = new Date();\n const queryDate = convertDateQueryParam(req.query.date, date);\n if (!queryDate)\n return res.status(400).json({", "score": 0.7946649193763733 }, { "filename": "src/pages/api/netflix/added-titles.ts", "retrieved_chunk": "import { type NextApiRequest, type NextApiResponse } from \"next\";\nimport { fetchNewTitles } from \"@/lib/netflix\";\nimport { convertDateQueryParam, getFormattedDate } from \"@/lib/date\";\nimport authenticateRequest from \"@/server/authenticateRequest\";\nasync function handler(req: NextApiRequest, res: NextApiResponse) {\n try {\n const date = new Date();\n const queryDate = convertDateQueryParam(req.query.date, date);\n if (!queryDate)\n return res.status(400).json({", "score": 0.7879531383514404 }, { "filename": "src/pages/api/netflix/deleted-titles.ts", "retrieved_chunk": "import { type NextApiRequest, type NextApiResponse } from \"next\";\nimport { fetchDeletedTitles } from \"@/lib/netflix\";\nimport { convertDateQueryParam, getFormattedDate } from \"@/lib/date\";\nimport authenticateRequest from \"@/server/authenticateRequest\";\nasync function handler(req: NextApiRequest, res: NextApiResponse) {\n try {\n const date = new Date();\n const queryDate = convertDateQueryParam(req.query.date, date);\n if (!queryDate)\n return res.status(400).json({", "score": 0.7849241495132446 }, { "filename": "src/server/authenticateRequest.ts", "retrieved_chunk": "import type { NextApiHandler, NextApiRequest, NextApiResponse } from \"next\";\nimport { env } from \"@/env.mjs\";\nexport default function authenticateRequest(\n handler: NextApiHandler\n): NextApiHandler {\n const date = new Date();\n return (req: NextApiRequest, res: NextApiResponse) => {\n if (\n !req.headers[\"x-api-key\"] ||\n req.headers[\"x-api-key\"] !== env.API_TOKEN", "score": 0.777438223361969 }, { "filename": "src/pages/api/post-to-twitter.ts", "retrieved_chunk": "import { type NextApiRequest, type NextApiResponse } from \"next\";\nimport { verifySignature } from \"@upstash/qstash/nextjs\";\nimport authenticateRequest from \"@/server/authenticateRequest\";\nimport { fetchDailyTitles } from \"@/lib/netflix\";\nimport { buildThread, createTweetThread } from \"@/server/twitter\";\nasync function handler(req: NextApiRequest, res: NextApiResponse) {\n try {\n const date = new Date();\n const titles = await fetchDailyTitles({ date, force: true });\n if (!titles.size) {", "score": 0.773479700088501 } ]
typescript
const queryDate = formatDateQueryString(date);
import { Request, Response } from "express"; import expressAsyncHandler from "express-async-handler"; import { postRepositoryType } from "../../framework/database/Mongodb/repositories/postRepositeries"; import { postDbInterfaceType } from "../../application/repositories/postDbRepositories"; import { getAllPost, postCreate, getPostsByUser, getPostById, deletePostById, updateLike, insertComment, deleteComment, postEdit, postReport, getReportedUsers, replyComment } from '../../application/useCases/post/post' const postControllers = (postDbInterface: postDbInterfaceType, postRepositoryType: postRepositoryType) => { const dbRepositoriesPost = postDbInterface(postRepositoryType()) const getPosts = expressAsyncHandler(async (req: Request, res: Response) => { const posts = await getAllPost(dbRepositoriesPost) res.json({ status: "success", posts }) }) const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, description, userName, image, video } = req.body; const body = { userId, description, userName, image, video }; const newPost = await postCreate(body, dbRepositoriesPost); res.json({ status: 'upload-success', newPost }) }) const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => { const { userId } = req.params; const posts: any = await getPostsByUser(userId, dbRepositoriesPost); res.json({ status: 'posts find success', posts }) }) const getPost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const post: any = await getPostById(id, dbRepositoriesPost); res.json({ status: 'post find success', post }) }) const deletePost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const deletedData = await deletePostById(id, dbRepositoriesPost) res.json({ status: 'Deleted success', deletedData }) }) const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => { const { id, userId } = req.query; await updateLike(id, userId, dbRepositoriesPost) res.json({ status: 'like update success' }) }) const commentPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, userId } = req.params; const { comment } = req.body const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost) res.json({ status: 'comment success', comment: updateResult }) }) const commentReply = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { comment, reply } = req.body; const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({ status: updateResult }) }) const commentDelete = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, index } = req.params; const deleteResult = await deleteComment(postId, index, dbRepositoriesPost) res.json({ status: 'comment deleted', deletedComment: deleteResult }) }) const editPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const { description } = req.body; const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost) res.json({ status: 'post update success', response: postEditResult }) }) const reportPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { reason } = req.body;
const repostResponse = await postReport(userId, postId, reason, dbRepositoriesPost) res.json({
status: 'posted success', response: repostResponse }) }) const getReporters = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const users = await getReportedUsers(postId, dbRepositoriesPost); res.json({ status: 'reposted users fetched', users }) }) return { getPosts, uploadPost, getUserPosts, getPost, deletePost, postLikeUpdate, commentPost, commentReply, commentDelete, editPost, reportPost, getReporters } } export default postControllers;
src/adapters/controllers/postControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " users\n })\n })\n // update profile informations\n const updateProfile = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const { userName, bio, gender, city, file } = req.body;\n const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);\n res.json({\n status: 'Update success',", "score": 0.9272542595863342 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " data: updateResult\n })\n })\n // block user by user\n const blockUser = asyncHandler(async (req: Request, res: Response) => {\n const { userId, blockId } = req.params;\n const blockResult = await userBlock(userId, blockId, dbRepositoryUser);\n res.json({\n status: blockResult\n });", "score": 0.919386625289917 }, { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9192988872528076 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " res.json({\n status: response\n })\n })\n // accept or reject request\n const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => {\n const { id, friendId } = req.params;\n const { response } = req.body;\n const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser)\n res.json({", "score": 0.9150007367134094 }, { "filename": "src/adapters/controllers/messageController.ts", "retrieved_chunk": " res.json({\n status: 'success',\n response: createResponse\n })\n })\n const getUserMessages = expressAsyncHandler(async(req: Request, res: Response) => {\n const { chatId } = req.params;\n const messages = await getMessages(chatId, messageRepository);\n res.json({\n status: 'Message fetch success',", "score": 0.9115461111068726 } ]
typescript
const repostResponse = await postReport(userId, postId, reason, dbRepositoriesPost) res.json({
"use client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { httpBatchLink, getFetch, loggerLink } from "@trpc/client"; import { useState } from "react"; import superjson from "superjson"; import { api } from "./trpc"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; export const TrpcProvider: React.FC<{ children: React.ReactNode }> = ({ children, }) => { const [queryClient] = useState( () => new QueryClient({ defaultOptions: { queries: { staleTime: 5000 } }, }) ); const getBaseUrl = () => { if (typeof window !== "undefined") return ""; // browser should use relative url if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; // SSR should use vercel url return `http://localhost:${process.env.PORT ?? 3000}`; // dev SSR should use localhost }; const [trpcClient] = useState(() => api.createClient({ links: [ loggerLink({ enabled: (opts) => process.env.NODE_ENV === "development" || (opts.direction === "down" && opts.result instanceof Error), }), httpBatchLink({ url: `${getBaseUrl()}/api/trpc`, fetch: async (input, init?) => { const fetch = getFetch(); return fetch(input, { ...init, credentials: "include", }); }, }), ], transformer: superjson, }) ); return (
<api.Provider client={trpcClient} queryClient={queryClient}> <QueryClientProvider client={queryClient}> {children}
<ReactQueryDevtools /> </QueryClientProvider> </api.Provider> ); };
src/lib/trpc-provider.tsx
acollierr17-netflix-refresh-84bb5f2
[ { "filename": "src/components/fathom.tsx", "retrieved_chunk": " useEffect(() => {\n trackPageview();\n }, [pathname, searchParams]);\n return null;\n}\nexport default function Fathom() {\n return (\n <Suspense fallback={null}>\n <TrackPageView />\n </Suspense>", "score": 0.8108376860618591 }, { "filename": "src/app/api/trpc/[trpc]/route.ts", "retrieved_chunk": "const handler = (request: Request) => {\n console.log(`incoming request ${request.url}`);\n return fetchRequestHandler({\n endpoint: \"/api/trpc\",\n req: request,\n router: appRouter,\n createContext: function (\n opts: FetchCreateContextFnOptions\n ): CreateContextOptions {\n return {", "score": 0.7630501985549927 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " * errors on the backend.\n */\nconst t = initTRPC.context<typeof createTRPCContext>().create({\n transformer: superjson,\n errorFormatter({ shape, error }) {\n return {\n ...shape,\n data: {\n ...shape.data,\n zodError:", "score": 0.7531635761260986 }, { "filename": "src/app/api/trpc/[trpc]/route.ts", "retrieved_chunk": " prisma,\n };\n },\n onError:\n env.NODE_ENV === \"development\"\n ? ({ path, error }) => {\n console.error(\n `❌ tRPC failed on ${path ?? \"<no-path>\"}: ${error.message}`\n );\n }", "score": 0.729363203048706 }, { "filename": "src/pages/api/post-to-twitter.ts", "retrieved_chunk": " name: e.name,\n message: e.message,\n });\n }\n}\nexport default verifySignature(authenticateRequest(handler));\nexport const config = {\n api: {\n bodyParser: false,\n },", "score": 0.7250363230705261 } ]
typescript
<api.Provider client={trpcClient} queryClient={queryClient}> <QueryClientProvider client={queryClient}> {children}
import { Request, Response } from 'express'; import asyncHandler from 'express-async-handler'; import { AuthServices } from '../../framework/services/authServices'; import { AuthServiceInterface } from '../../application/services/authServiceInterface'; import { UserDbInterface } from '../../application/repositories/userDbRepositories'; import { userRepositoryMongoDB } from '../../framework/database/Mongodb/repositories/userRepositories'; import { userRegister, userLogin, googleAuthLogin, userBlock} from '../../application/useCases/auth/userAuth'; // authentication controllers const authControllers = ( authServiceInterface: AuthServiceInterface, authService: AuthServices, userDbInterface: UserDbInterface, userDbservice: userRepositoryMongoDB ) => { const dbUserRepository = userDbInterface(userDbservice()); const authServices = authServiceInterface(authService()); const registerUser = asyncHandler(async(req: Request, res: Response) => { const { name, userName, number,email, password } = req.body; const user = { name, userName, number, email, password, }; const token = await userRegister(user, dbUserRepository, authServices); res.json({ status:"success", message: "User registered", token }); }); const loginUser = asyncHandler(async(req: Request, res: Response) => { const { userName, password } : { userName: string; password: string} = req.body; const token = await userLogin(userName, password, dbUserRepository, authServices); // res.setHeader('authorization', token.token); res.json({ status: "success", message: "user verified", token }); }); const googleAuth = asyncHandler(async(req: Request, res: Response) => { console.log('-----------------------'); const { fullName, firstName, email } = req.body; const userData: any = { name:fullName, userName:firstName, number: 7594837203, email } console.log(userData); const {user, token} = await googleAuthLogin(userData, dbUserRepository, authServices) res.json({ status:'Google login success', user, token }) }) const blockUser = asyncHandler(async(req: Request, res: Response) => { const { id } = req.params; const blockResult = await
userBlock(id, dbUserRepository);
res.json({ status: `${blockResult} success` }) }) return { registerUser, loginUser, googleAuth, blockUser }; }; export default authControllers;
src/adapters/controllers/authControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " data: updateResult\n })\n })\n // block user by user\n const blockUser = asyncHandler(async (req: Request, res: Response) => {\n const { userId, blockId } = req.params;\n const blockResult = await userBlock(userId, blockId, dbRepositoryUser);\n res.json({\n status: blockResult\n });", "score": 0.9533887505531311 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const getUserById = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const user = await userById(id, dbRepositoryUser)\n res.json({\n status: \"success\",\n user\n });\n });\n // get followers list of the user\n const getFollowersList = asyncHandler(async (req: Request, res: Response) => {", "score": 0.9171394109725952 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " users\n })\n })\n // update profile informations\n const updateProfile = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const { userName, bio, gender, city, file } = req.body;\n const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);\n res.json({\n status: 'Update success',", "score": 0.9005558490753174 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " // get all users list\n const getAllUsers = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const users = await getUserDetails(id, dbRepositoryUser);\n res.json({\n status: 'Get users success',\n users\n })\n })\n // get a user details by id", "score": 0.8994598388671875 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " res.json({\n status: 'like update success'\n })\n })\n const commentPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { postId, userId } = req.params;\n const { comment } = req.body\n const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost)\n res.json({\n status: 'comment success',", "score": 0.8985055685043335 } ]
typescript
userBlock(id, dbUserRepository);
import { Request, Response } from 'express'; import asyncHandler from 'express-async-handler'; import { UserDbInterface } from '../../application/repositories/userDbRepositories'; import { userById, followers, followings, unfollow, getUserDetails, searchUserByPrefix, updateProfileInfo, userBlock, requestFriend, requestFriendResponse } from '../../application/useCases/user/user'; import { userRepositoryMongoDB } from '../../framework/database/Mongodb/repositories/userRepositories'; const userControllers = ( userDbRepository: UserDbInterface, userDbRepositoryService: userRepositoryMongoDB ) => { const dbRepositoryUser = userDbRepository(userDbRepositoryService()); // get all users list const getAllUsers = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const users = await getUserDetails(id, dbRepositoryUser); res.json({ status: 'Get users success', users }) }) // get a user details by id const getUserById = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const user = await userById(id, dbRepositoryUser) res.json({ status: "success", user }); }); // get followers list of the user const getFollowersList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followersList: any = await followers(id, dbRepositoryUser); res.json({ status: 'get followers success', followers: followersList }) }) // get following list of the user const getFollowingsList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followingList: any = await followings(id, dbRepositoryUser); res.json({ status: 'get following success', followings: followingList }) }) // send friend request to user const sendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const response = await requestFriend(id, friendId, dbRepositoryUser); res.json({ status: response }) }) // accept or reject request const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const { response } = req.body; const status
= await requestFriendResponse(id, friendId, response, dbRepositoryUser) res.json({
status }) }) // insert followers to user const unfollowUser = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.query; const { status, friend }: any = await unfollow(id, friendId, dbRepositoryUser); res.json({ status, friend }) }) // search user const searchUser = asyncHandler(async (req: Request, res: Response) => { const { prefix } = req.params; const { type } = req.query; console.log(type, 'par'); const users: any = await searchUserByPrefix(prefix, type, dbRepositoryUser); res.json({ status: 'searched success', users }) }) // update profile informations const updateProfile = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const { userName, bio, gender, city, file } = req.body; const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser); res.json({ status: 'Update success', data: updateResult }) }) // block user by user const blockUser = asyncHandler(async (req: Request, res: Response) => { const { userId, blockId } = req.params; const blockResult = await userBlock(userId, blockId, dbRepositoryUser); res.json({ status: blockResult }); }) return { getUserById, sendRequest, responseFriendRequest, getFollowersList, getFollowingsList, unfollowUser, getAllUsers, searchUser, updateProfile, blockUser }; }; export default userControllers;
src/adapters/controllers/userControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " comment: updateResult\n })\n })\n const commentReply = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, postId } = req.params;\n const { comment, reply } = req.body;\n const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost)\n res.json({\n status: updateResult\n })", "score": 0.9210464954376221 }, { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9156872034072876 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " res.json({\n status: 'like update success'\n })\n })\n const commentPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { postId, userId } = req.params;\n const { comment } = req.body\n const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost)\n res.json({\n status: 'comment success',", "score": 0.9092726111412048 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { postId } = req.params;\n const { description } = req.body;\n const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost)\n res.json({\n status: 'post update success',\n response: postEditResult\n })\n })\n const reportPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, postId } = req.params;", "score": 0.9080843925476074 }, { "filename": "src/adapters/controllers/messageController.ts", "retrieved_chunk": " res.json({\n status: 'success',\n response: createResponse\n })\n })\n const getUserMessages = expressAsyncHandler(async(req: Request, res: Response) => {\n const { chatId } = req.params;\n const messages = await getMessages(chatId, messageRepository);\n res.json({\n status: 'Message fetch success',", "score": 0.9078620672225952 } ]
typescript
= await requestFriendResponse(id, friendId, response, dbRepositoryUser) res.json({
import { Request, Response } from 'express'; import asyncHandler from 'express-async-handler'; import { UserDbInterface } from '../../application/repositories/userDbRepositories'; import { userById, followers, followings, unfollow, getUserDetails, searchUserByPrefix, updateProfileInfo, userBlock, requestFriend, requestFriendResponse } from '../../application/useCases/user/user'; import { userRepositoryMongoDB } from '../../framework/database/Mongodb/repositories/userRepositories'; const userControllers = ( userDbRepository: UserDbInterface, userDbRepositoryService: userRepositoryMongoDB ) => { const dbRepositoryUser = userDbRepository(userDbRepositoryService()); // get all users list const getAllUsers = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const users = await getUserDetails(id, dbRepositoryUser); res.json({ status: 'Get users success', users }) }) // get a user details by id const getUserById = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const user = await userById(id, dbRepositoryUser) res.json({ status: "success", user }); }); // get followers list of the user const getFollowersList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followersList: any = await followers(id, dbRepositoryUser); res.json({ status: 'get followers success', followers: followersList }) }) // get following list of the user const getFollowingsList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followingList: any = await followings(id, dbRepositoryUser); res.json({ status: 'get following success', followings: followingList }) }) // send friend request to user const sendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params;
const response = await requestFriend(id, friendId, dbRepositoryUser);
res.json({ status: response }) }) // accept or reject request const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const { response } = req.body; const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser) res.json({ status }) }) // insert followers to user const unfollowUser = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.query; const { status, friend }: any = await unfollow(id, friendId, dbRepositoryUser); res.json({ status, friend }) }) // search user const searchUser = asyncHandler(async (req: Request, res: Response) => { const { prefix } = req.params; const { type } = req.query; console.log(type, 'par'); const users: any = await searchUserByPrefix(prefix, type, dbRepositoryUser); res.json({ status: 'searched success', users }) }) // update profile informations const updateProfile = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const { userName, bio, gender, city, file } = req.body; const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser); res.json({ status: 'Update success', data: updateResult }) }) // block user by user const blockUser = asyncHandler(async (req: Request, res: Response) => { const { userId, blockId } = req.params; const blockResult = await userBlock(userId, blockId, dbRepositoryUser); res.json({ status: blockResult }); }) return { getUserById, sendRequest, responseFriendRequest, getFollowersList, getFollowingsList, unfollowUser, getAllUsers, searchUser, updateProfile, blockUser }; }; export default userControllers;
src/adapters/controllers/userControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/application/useCases/user/user.ts", "retrieved_chunk": " await repository.sendRequest(id, userName, friendName, dp, friendDp, friendId);\n return 'Request sended';\n }\n}\nexport const requestFriendResponse = async (id: string, friendId: string, { response }: any, repository: ReturnType<UserDbInterface>) => {\n if (response === 'accept') {\n await repository.followFriend(friendId, id);\n await repository.cancelRequest(friendId, id);\n return 'Request accepted'\n } else {", "score": 0.9094099402427673 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { id } = req.params;\n const deletedData = await deletePostById(id, dbRepositoriesPost)\n res.json({\n status: 'Deleted success',\n deletedData\n })\n })\n const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => {\n const { id, userId } = req.query;\n await updateLike(id, userId, dbRepositoriesPost)", "score": 0.9093784689903259 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " newPost\n })\n })\n const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId } = req.params;\n const posts: any = await getPostsByUser(userId, dbRepositoriesPost);\n res.json({\n status: 'posts find success',\n posts\n })", "score": 0.9093576669692993 }, { "filename": "src/adapters/controllers/messageController.ts", "retrieved_chunk": " res.json({\n status: 'success',\n response: createResponse\n })\n })\n const getUserMessages = expressAsyncHandler(async(req: Request, res: Response) => {\n const { chatId } = req.params;\n const messages = await getMessages(chatId, messageRepository);\n res.json({\n status: 'Message fetch success',", "score": 0.9067084789276123 }, { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9040908813476562 } ]
typescript
const response = await requestFriend(id, friendId, dbRepositoryUser);
import { Request, Response } from 'express'; import asyncHandler from 'express-async-handler'; import { UserDbInterface } from '../../application/repositories/userDbRepositories'; import { userById, followers, followings, unfollow, getUserDetails, searchUserByPrefix, updateProfileInfo, userBlock, requestFriend, requestFriendResponse } from '../../application/useCases/user/user'; import { userRepositoryMongoDB } from '../../framework/database/Mongodb/repositories/userRepositories'; const userControllers = ( userDbRepository: UserDbInterface, userDbRepositoryService: userRepositoryMongoDB ) => { const dbRepositoryUser = userDbRepository(userDbRepositoryService()); // get all users list const getAllUsers = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const users = await getUserDetails(id, dbRepositoryUser); res.json({ status: 'Get users success', users }) }) // get a user details by id const getUserById = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const user = await userById(id, dbRepositoryUser) res.json({ status: "success", user }); }); // get followers list of the user const getFollowersList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followersList: any = await followers(id, dbRepositoryUser); res.json({ status: 'get followers success', followers: followersList }) }) // get following list of the user const getFollowingsList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const
followingList: any = await followings(id, dbRepositoryUser);
res.json({ status: 'get following success', followings: followingList }) }) // send friend request to user const sendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const response = await requestFriend(id, friendId, dbRepositoryUser); res.json({ status: response }) }) // accept or reject request const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const { response } = req.body; const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser) res.json({ status }) }) // insert followers to user const unfollowUser = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.query; const { status, friend }: any = await unfollow(id, friendId, dbRepositoryUser); res.json({ status, friend }) }) // search user const searchUser = asyncHandler(async (req: Request, res: Response) => { const { prefix } = req.params; const { type } = req.query; console.log(type, 'par'); const users: any = await searchUserByPrefix(prefix, type, dbRepositoryUser); res.json({ status: 'searched success', users }) }) // update profile informations const updateProfile = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const { userName, bio, gender, city, file } = req.body; const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser); res.json({ status: 'Update success', data: updateResult }) }) // block user by user const blockUser = asyncHandler(async (req: Request, res: Response) => { const { userId, blockId } = req.params; const blockResult = await userBlock(userId, blockId, dbRepositoryUser); res.json({ status: blockResult }); }) return { getUserById, sendRequest, responseFriendRequest, getFollowersList, getFollowingsList, unfollowUser, getAllUsers, searchUser, updateProfile, blockUser }; }; export default userControllers;
src/adapters/controllers/userControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " newPost\n })\n })\n const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId } = req.params;\n const posts: any = await getPostsByUser(userId, dbRepositoriesPost);\n res.json({\n status: 'posts find success',\n posts\n })", "score": 0.9301407337188721 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { id } = req.params;\n const deletedData = await deletePostById(id, dbRepositoriesPost)\n res.json({\n status: 'Deleted success',\n deletedData\n })\n })\n const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => {\n const { id, userId } = req.query;\n await updateLike(id, userId, dbRepositoriesPost)", "score": 0.9103119373321533 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " res.json({\n status: 'like update success'\n })\n })\n const commentPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { postId, userId } = req.params;\n const { comment } = req.body\n const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost)\n res.json({\n status: 'comment success',", "score": 0.9093632698059082 }, { "filename": "src/adapters/controllers/chatController.ts", "retrieved_chunk": " res.json({\n status: 'success',\n chats: newChat\n })\n })\n const getChats = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId} = req.params;\n const chats = await getAllchats(userId, chatRepositeries);\n res.json({\n status: 'success',", "score": 0.9080805778503418 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { postId } = req.params;\n const { description } = req.body;\n const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost)\n res.json({\n status: 'post update success',\n response: postEditResult\n })\n })\n const reportPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, postId } = req.params;", "score": 0.9065345525741577 } ]
typescript
followingList: any = await followings(id, dbRepositoryUser);
import { Request, Response } from 'express'; import asyncHandler from 'express-async-handler'; import { UserDbInterface } from '../../application/repositories/userDbRepositories'; import { userById, followers, followings, unfollow, getUserDetails, searchUserByPrefix, updateProfileInfo, userBlock, requestFriend, requestFriendResponse } from '../../application/useCases/user/user'; import { userRepositoryMongoDB } from '../../framework/database/Mongodb/repositories/userRepositories'; const userControllers = ( userDbRepository: UserDbInterface, userDbRepositoryService: userRepositoryMongoDB ) => { const dbRepositoryUser = userDbRepository(userDbRepositoryService()); // get all users list const getAllUsers = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const users = await getUserDetails(id, dbRepositoryUser); res.json({ status: 'Get users success', users }) }) // get a user details by id const getUserById = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const user = await userById(id, dbRepositoryUser) res.json({ status: "success", user }); }); // get followers list of the user const getFollowersList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followersList: any = await followers(id, dbRepositoryUser); res.json({ status: 'get followers success', followers: followersList }) }) // get following list of the user const getFollowingsList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followingList: any = await followings(id, dbRepositoryUser); res.json({ status: 'get following success', followings: followingList }) }) // send friend request to user const sendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const response = await requestFriend(id, friendId, dbRepositoryUser); res.json({ status: response }) }) // accept or reject request const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const { response } = req.body; const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser) res.json({ status }) }) // insert followers to user const unfollowUser = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.query; const { status, friend
}: any = await unfollow(id, friendId, dbRepositoryUser);
res.json({ status, friend }) }) // search user const searchUser = asyncHandler(async (req: Request, res: Response) => { const { prefix } = req.params; const { type } = req.query; console.log(type, 'par'); const users: any = await searchUserByPrefix(prefix, type, dbRepositoryUser); res.json({ status: 'searched success', users }) }) // update profile informations const updateProfile = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const { userName, bio, gender, city, file } = req.body; const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser); res.json({ status: 'Update success', data: updateResult }) }) // block user by user const blockUser = asyncHandler(async (req: Request, res: Response) => { const { userId, blockId } = req.params; const blockResult = await userBlock(userId, blockId, dbRepositoryUser); res.json({ status: blockResult }); }) return { getUserById, sendRequest, responseFriendRequest, getFollowersList, getFollowingsList, unfollowUser, getAllUsers, searchUser, updateProfile, blockUser }; }; export default userControllers;
src/adapters/controllers/userControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/application/useCases/user/user.ts", "retrieved_chunk": " await repository.cancelRequest(friendId, id);\n return 'Request rejected'\n }\n}\nexport const unfollow = async (id: any, friendId: any, repository: ReturnType<UserDbInterface>) => {\n // this friend is already a follower\n const friend: any = await repository.unfollowFriend(id, friendId);\n return {\n status: 'unfollow',\n friend", "score": 0.9203801155090332 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { id } = req.params;\n const deletedData = await deletePostById(id, dbRepositoriesPost)\n res.json({\n status: 'Deleted success',\n deletedData\n })\n })\n const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => {\n const { id, userId } = req.query;\n await updateLike(id, userId, dbRepositoriesPost)", "score": 0.9022479057312012 }, { "filename": "src/application/useCases/user/user.ts", "retrieved_chunk": " await repository.sendRequest(id, userName, friendName, dp, friendDp, friendId);\n return 'Request sended';\n }\n}\nexport const requestFriendResponse = async (id: string, friendId: string, { response }: any, repository: ReturnType<UserDbInterface>) => {\n if (response === 'accept') {\n await repository.followFriend(friendId, id);\n await repository.cancelRequest(friendId, id);\n return 'Request accepted'\n } else {", "score": 0.9018510580062866 }, { "filename": "src/framework/database/Mongodb/repositories/userRepositories.ts", "retrieved_chunk": " };\n const findFriend = async (_id: string, friendId: any) => {\n const user: any = await User.findOne({ _id })\n const isUserExist: any = await user.followers.find((user: any) => user === friendId)\n return isUserExist;\n }\n const sendRequest = async (id: string, userName: string, friendName: string, dp: any, friendDp: string, friendId: string) => {\n await User.updateOne({ _id: friendId }, {\n $push: { requests: { id, userName, dp } }\n })", "score": 0.8981640338897705 }, { "filename": "src/application/repositories/userDbRepositories.ts", "retrieved_chunk": " return await repository.findFriend(id, friendId);\n }\n const sendRequest = async (id: string, userName: string, friendName: string, dp: any, friendDp: string, friendId: string) => {\n return await repository.sendRequest(id, userName, friendName,dp, friendDp, friendId);\n }\n const cancelRequest = async (id: string, friendId: string) => {\n return await repository.cancelRequest(id, friendId);\n }\n const unfollowFriend = async (id: string, friendId: string) => {\n return await repository.unfollowFriend(id, friendId)", "score": 0.8977397084236145 } ]
typescript
}: any = await unfollow(id, friendId, dbRepositoryUser);
import { Request, Response } from "express"; import expressAsyncHandler from "express-async-handler"; import { postRepositoryType } from "../../framework/database/Mongodb/repositories/postRepositeries"; import { postDbInterfaceType } from "../../application/repositories/postDbRepositories"; import { getAllPost, postCreate, getPostsByUser, getPostById, deletePostById, updateLike, insertComment, deleteComment, postEdit, postReport, getReportedUsers, replyComment } from '../../application/useCases/post/post' const postControllers = (postDbInterface: postDbInterfaceType, postRepositoryType: postRepositoryType) => { const dbRepositoriesPost = postDbInterface(postRepositoryType()) const getPosts = expressAsyncHandler(async (req: Request, res: Response) => { const posts = await getAllPost(dbRepositoriesPost) res.json({ status: "success", posts }) }) const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, description, userName, image, video } = req.body; const body = { userId, description, userName, image, video }; const newPost = await postCreate(body, dbRepositoriesPost); res.json({ status: 'upload-success', newPost }) }) const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => { const { userId } = req.params; const posts: any = await getPostsByUser(userId, dbRepositoriesPost); res.json({ status: 'posts find success', posts }) }) const getPost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const post: any = await getPostById(id, dbRepositoriesPost); res.json({ status: 'post find success', post }) }) const deletePost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const deletedData = await deletePostById(id, dbRepositoriesPost) res.json({ status: 'Deleted success', deletedData }) }) const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => { const { id, userId } = req.query; await updateLike(id, userId, dbRepositoriesPost) res.json({ status: 'like update success' }) }) const commentPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, userId } = req.params; const { comment } = req.body const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost) res.json({ status: 'comment success', comment: updateResult }) }) const commentReply = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { comment, reply } = req.body; const updateResult = await
replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({
status: updateResult }) }) const commentDelete = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, index } = req.params; const deleteResult = await deleteComment(postId, index, dbRepositoriesPost) res.json({ status: 'comment deleted', deletedComment: deleteResult }) }) const editPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const { description } = req.body; const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost) res.json({ status: 'post update success', response: postEditResult }) }) const reportPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { reason } = req.body; const repostResponse = await postReport(userId, postId, reason, dbRepositoriesPost) res.json({ status: 'posted success', response: repostResponse }) }) const getReporters = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const users = await getReportedUsers(postId, dbRepositoriesPost); res.json({ status: 'reposted users fetched', users }) }) return { getPosts, uploadPost, getUserPosts, getPost, deletePost, postLikeUpdate, commentPost, commentReply, commentDelete, editPost, reportPost, getReporters } } export default postControllers;
src/adapters/controllers/postControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " data: updateResult\n })\n })\n // block user by user\n const blockUser = asyncHandler(async (req: Request, res: Response) => {\n const { userId, blockId } = req.params;\n const blockResult = await userBlock(userId, blockId, dbRepositoryUser);\n res.json({\n status: blockResult\n });", "score": 0.9175612330436707 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " users\n })\n })\n // update profile informations\n const updateProfile = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const { userName, bio, gender, city, file } = req.body;\n const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);\n res.json({\n status: 'Update success',", "score": 0.916382908821106 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " res.json({\n status: response\n })\n })\n // accept or reject request\n const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => {\n const { id, friendId } = req.params;\n const { response } = req.body;\n const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser)\n res.json({", "score": 0.9141532778739929 }, { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9095902442932129 }, { "filename": "src/application/repositories/postDbRepositories.ts", "retrieved_chunk": " }\n const replyComment = async(postId: string,userId: string, comment: string, reply: string) => {\n const response = await repositories.replyComment(postId,userId, comment, reply);\n return response\n }\n const editPost = async(postId: string, body: any) => {\n const editPost = await repositories.editPost(postId, body)\n return editPost\n }\n const reportPost = async(userId: string, postId: string, reason: any) => {", "score": 0.9054045081138611 } ]
typescript
replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({
import { Request, Response } from "express"; import expressAsyncHandler from "express-async-handler"; import { postRepositoryType } from "../../framework/database/Mongodb/repositories/postRepositeries"; import { postDbInterfaceType } from "../../application/repositories/postDbRepositories"; import { getAllPost, postCreate, getPostsByUser, getPostById, deletePostById, updateLike, insertComment, deleteComment, postEdit, postReport, getReportedUsers, replyComment } from '../../application/useCases/post/post' const postControllers = (postDbInterface: postDbInterfaceType, postRepositoryType: postRepositoryType) => { const dbRepositoriesPost = postDbInterface(postRepositoryType()) const getPosts = expressAsyncHandler(async (req: Request, res: Response) => { const posts = await getAllPost(dbRepositoriesPost) res.json({ status: "success", posts }) }) const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, description, userName, image, video } = req.body; const body = { userId, description, userName, image, video }; const newPost = await postCreate(body, dbRepositoriesPost); res.json({ status: 'upload-success', newPost }) }) const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => { const { userId } = req.params; const posts: any = await getPostsByUser(userId, dbRepositoriesPost); res.json({ status: 'posts find success', posts }) }) const getPost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const post: any = await getPostById(id, dbRepositoriesPost); res.json({ status: 'post find success', post }) }) const deletePost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const deletedData = await deletePostById(id, dbRepositoriesPost) res.json({ status: 'Deleted success', deletedData }) }) const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => { const { id, userId } = req.query; await updateLike(id, userId, dbRepositoriesPost) res.json({ status: 'like update success' }) }) const commentPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, userId } = req.params; const { comment } = req.body const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost) res.json({ status: 'comment success', comment: updateResult }) }) const commentReply = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { comment, reply } = req.body; const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({ status: updateResult }) }) const commentDelete = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, index } = req.params; const deleteResult = await deleteComment(postId, index, dbRepositoriesPost) res.json({ status: 'comment deleted', deletedComment: deleteResult }) }) const editPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const { description } = req.body; const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost) res.json({ status: 'post update success', response: postEditResult }) }) const reportPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { reason } = req.body; const repostResponse = await postReport(userId, postId, reason, dbRepositoriesPost) res.json({ status: 'posted success', response: repostResponse }) }) const getReporters = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params;
const users = await getReportedUsers(postId, dbRepositoriesPost);
res.json({ status: 'reposted users fetched', users }) }) return { getPosts, uploadPost, getUserPosts, getPost, deletePost, postLikeUpdate, commentPost, commentReply, commentDelete, editPost, reportPost, getReporters } } export default postControllers;
src/adapters/controllers/postControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/application/repositories/postDbRepositories.ts", "retrieved_chunk": " const repostResponse = await repositories.reportPost(userId, postId, reason);\n return repostResponse;\n }\n const getReportedUsers = async (postId: string) => {\n const users = await repositories.getReportedUsers(postId);\n return users;\n }\n return {\n getAllPost,\n uploadPost,", "score": 0.9178112149238586 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " // get all users list\n const getAllUsers = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const users = await getUserDetails(id, dbRepositoryUser);\n res.json({\n status: 'Get users success',\n users\n })\n })\n // get a user details by id", "score": 0.9147902131080627 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const { id } = req.params;\n const followersList: any = await followers(id, dbRepositoryUser);\n res.json({\n status: 'get followers success',\n followers: followersList\n })\n })\n // get following list of the user\n const getFollowingsList = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;", "score": 0.9118275046348572 }, { "filename": "src/framework/database/Mongodb/repositories/postRepositeries.ts", "retrieved_chunk": " }\n const reportPost = async (userId: string, postId: string, reason: any) => {\n const repostResponse = await Post.findByIdAndUpdate({ _id: postId }, {\n $push: { reports: { userId, reason } }\n })\n return repostResponse;\n }\n const getReportedUsers = async (postId: string) => {\n const postDetails: any = await Post.findOne({ _id: postId });\n const users: any = await Promise.all(", "score": 0.905168890953064 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const getUserById = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const user = await userById(id, dbRepositoryUser)\n res.json({\n status: \"success\",\n user\n });\n });\n // get followers list of the user\n const getFollowersList = asyncHandler(async (req: Request, res: Response) => {", "score": 0.9045200943946838 } ]
typescript
const users = await getReportedUsers(postId, dbRepositoriesPost);
import { Request, Response } from "express"; import expressAsyncHandler from "express-async-handler"; import { postRepositoryType } from "../../framework/database/Mongodb/repositories/postRepositeries"; import { postDbInterfaceType } from "../../application/repositories/postDbRepositories"; import { getAllPost, postCreate, getPostsByUser, getPostById, deletePostById, updateLike, insertComment, deleteComment, postEdit, postReport, getReportedUsers, replyComment } from '../../application/useCases/post/post' const postControllers = (postDbInterface: postDbInterfaceType, postRepositoryType: postRepositoryType) => { const dbRepositoriesPost = postDbInterface(postRepositoryType()) const getPosts = expressAsyncHandler(async (req: Request, res: Response) => { const posts = await getAllPost(dbRepositoriesPost) res.json({ status: "success", posts }) }) const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, description, userName, image, video } = req.body; const body = { userId, description, userName, image, video }; const newPost = await postCreate(body, dbRepositoriesPost); res.json({ status: 'upload-success', newPost }) }) const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => { const { userId } = req.params; const posts: any = await getPostsByUser(userId, dbRepositoriesPost); res.json({ status: 'posts find success', posts }) }) const getPost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const post: any = await getPostById(id, dbRepositoriesPost); res.json({ status: 'post find success', post }) }) const deletePost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const deletedData
= await deletePostById(id, dbRepositoriesPost) res.json({
status: 'Deleted success', deletedData }) }) const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => { const { id, userId } = req.query; await updateLike(id, userId, dbRepositoriesPost) res.json({ status: 'like update success' }) }) const commentPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, userId } = req.params; const { comment } = req.body const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost) res.json({ status: 'comment success', comment: updateResult }) }) const commentReply = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { comment, reply } = req.body; const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({ status: updateResult }) }) const commentDelete = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, index } = req.params; const deleteResult = await deleteComment(postId, index, dbRepositoriesPost) res.json({ status: 'comment deleted', deletedComment: deleteResult }) }) const editPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const { description } = req.body; const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost) res.json({ status: 'post update success', response: postEditResult }) }) const reportPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { reason } = req.body; const repostResponse = await postReport(userId, postId, reason, dbRepositoriesPost) res.json({ status: 'posted success', response: repostResponse }) }) const getReporters = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const users = await getReportedUsers(postId, dbRepositoriesPost); res.json({ status: 'reposted users fetched', users }) }) return { getPosts, uploadPost, getUserPosts, getPost, deletePost, postLikeUpdate, commentPost, commentReply, commentDelete, editPost, reportPost, getReporters } } export default postControllers;
src/adapters/controllers/postControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " // get all users list\n const getAllUsers = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const users = await getUserDetails(id, dbRepositoryUser);\n res.json({\n status: 'Get users success',\n users\n })\n })\n // get a user details by id", "score": 0.9209674596786499 }, { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9199005365371704 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const getUserById = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const user = await userById(id, dbRepositoryUser)\n res.json({\n status: \"success\",\n user\n });\n });\n // get followers list of the user\n const getFollowersList = asyncHandler(async (req: Request, res: Response) => {", "score": 0.9140675067901611 }, { "filename": "src/adapters/controllers/messageController.ts", "retrieved_chunk": " res.json({\n status: 'success',\n response: createResponse\n })\n })\n const getUserMessages = expressAsyncHandler(async(req: Request, res: Response) => {\n const { chatId } = req.params;\n const messages = await getMessages(chatId, messageRepository);\n res.json({\n status: 'Message fetch success',", "score": 0.9120766520500183 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " users\n })\n })\n // update profile informations\n const updateProfile = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const { userName, bio, gender, city, file } = req.body;\n const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);\n res.json({\n status: 'Update success',", "score": 0.9084264636039734 } ]
typescript
= await deletePostById(id, dbRepositoriesPost) res.json({
import { Request, Response } from "express"; import expressAsyncHandler from "express-async-handler"; import { postRepositoryType } from "../../framework/database/Mongodb/repositories/postRepositeries"; import { postDbInterfaceType } from "../../application/repositories/postDbRepositories"; import { getAllPost, postCreate, getPostsByUser, getPostById, deletePostById, updateLike, insertComment, deleteComment, postEdit, postReport, getReportedUsers, replyComment } from '../../application/useCases/post/post' const postControllers = (postDbInterface: postDbInterfaceType, postRepositoryType: postRepositoryType) => { const dbRepositoriesPost = postDbInterface(postRepositoryType()) const getPosts = expressAsyncHandler(async (req: Request, res: Response) => { const posts = await getAllPost(dbRepositoriesPost) res.json({ status: "success", posts }) }) const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, description, userName, image, video } = req.body; const body = { userId, description, userName, image, video }; const newPost = await postCreate(body, dbRepositoriesPost); res.json({ status: 'upload-success', newPost }) }) const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => { const { userId } = req.params; const posts: any = await getPostsByUser(userId, dbRepositoriesPost); res.json({ status: 'posts find success', posts }) }) const getPost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const post: any = await getPostById(id, dbRepositoriesPost); res.json({ status: 'post find success', post }) }) const deletePost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const deletedData = await deletePostById(id, dbRepositoriesPost) res.json({ status: 'Deleted success', deletedData }) }) const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => { const { id, userId } = req.query; await updateLike(id, userId, dbRepositoriesPost) res.json({ status: 'like update success' }) }) const commentPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, userId } = req.params; const { comment } = req.body const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost) res.json({ status: 'comment success', comment: updateResult }) }) const commentReply = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { comment, reply } = req.body; const
updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({
status: updateResult }) }) const commentDelete = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, index } = req.params; const deleteResult = await deleteComment(postId, index, dbRepositoriesPost) res.json({ status: 'comment deleted', deletedComment: deleteResult }) }) const editPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const { description } = req.body; const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost) res.json({ status: 'post update success', response: postEditResult }) }) const reportPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { reason } = req.body; const repostResponse = await postReport(userId, postId, reason, dbRepositoriesPost) res.json({ status: 'posted success', response: repostResponse }) }) const getReporters = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const users = await getReportedUsers(postId, dbRepositoriesPost); res.json({ status: 'reposted users fetched', users }) }) return { getPosts, uploadPost, getUserPosts, getPost, deletePost, postLikeUpdate, commentPost, commentReply, commentDelete, editPost, reportPost, getReporters } } export default postControllers;
src/adapters/controllers/postControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " data: updateResult\n })\n })\n // block user by user\n const blockUser = asyncHandler(async (req: Request, res: Response) => {\n const { userId, blockId } = req.params;\n const blockResult = await userBlock(userId, blockId, dbRepositoryUser);\n res.json({\n status: blockResult\n });", "score": 0.9172853827476501 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " users\n })\n })\n // update profile informations\n const updateProfile = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const { userName, bio, gender, city, file } = req.body;\n const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);\n res.json({\n status: 'Update success',", "score": 0.917020320892334 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " res.json({\n status: response\n })\n })\n // accept or reject request\n const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => {\n const { id, friendId } = req.params;\n const { response } = req.body;\n const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser)\n res.json({", "score": 0.9139066338539124 }, { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9097260236740112 }, { "filename": "src/application/repositories/postDbRepositories.ts", "retrieved_chunk": " }\n const replyComment = async(postId: string,userId: string, comment: string, reply: string) => {\n const response = await repositories.replyComment(postId,userId, comment, reply);\n return response\n }\n const editPost = async(postId: string, body: any) => {\n const editPost = await repositories.editPost(postId, body)\n return editPost\n }\n const reportPost = async(userId: string, postId: string, reason: any) => {", "score": 0.904103696346283 } ]
typescript
updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({
import { Request, Response } from 'express'; import asyncHandler from 'express-async-handler'; import { UserDbInterface } from '../../application/repositories/userDbRepositories'; import { userById, followers, followings, unfollow, getUserDetails, searchUserByPrefix, updateProfileInfo, userBlock, requestFriend, requestFriendResponse } from '../../application/useCases/user/user'; import { userRepositoryMongoDB } from '../../framework/database/Mongodb/repositories/userRepositories'; const userControllers = ( userDbRepository: UserDbInterface, userDbRepositoryService: userRepositoryMongoDB ) => { const dbRepositoryUser = userDbRepository(userDbRepositoryService()); // get all users list const getAllUsers = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const users = await getUserDetails(id, dbRepositoryUser); res.json({ status: 'Get users success', users }) }) // get a user details by id const getUserById = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const user = await userById(id, dbRepositoryUser) res.json({ status: "success", user }); }); // get followers list of the user const getFollowersList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followersList: any = await followers(id, dbRepositoryUser); res.json({ status: 'get followers success', followers: followersList }) }) // get following list of the user const getFollowingsList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followingList: any = await followings(id, dbRepositoryUser); res.json({ status: 'get following success', followings: followingList }) }) // send friend request to user const sendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const response = await requestFriend(id, friendId, dbRepositoryUser); res.json({ status: response }) }) // accept or reject request const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const { response } = req.body; const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser) res.json({ status }) }) // insert followers to user const unfollowUser = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.query; const { status, friend }: any = await unfollow(id, friendId, dbRepositoryUser); res.json({ status, friend }) }) // search user const searchUser = asyncHandler(async (req: Request, res: Response) => { const { prefix } = req.params; const { type } = req.query; console.log(type, 'par'); const users: any = await searchUserByPrefix(prefix, type, dbRepositoryUser); res.json({ status: 'searched success', users }) }) // update profile informations const updateProfile = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const { userName, bio, gender, city, file } = req.body;
const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);
res.json({ status: 'Update success', data: updateResult }) }) // block user by user const blockUser = asyncHandler(async (req: Request, res: Response) => { const { userId, blockId } = req.params; const blockResult = await userBlock(userId, blockId, dbRepositoryUser); res.json({ status: blockResult }); }) return { getUserById, sendRequest, responseFriendRequest, getFollowersList, getFollowingsList, unfollowUser, getAllUsers, searchUser, updateProfile, blockUser }; }; export default userControllers;
src/adapters/controllers/userControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " status: \"success\",\n posts\n })\n })\n const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, description, userName, image, video } = req.body;\n const body = { userId, description, userName, image, video };\n const newPost = await postCreate(body, dbRepositoriesPost);\n res.json({\n status: 'upload-success',", "score": 0.9376461505889893 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " res.json({\n status: 'like update success'\n })\n })\n const commentPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { postId, userId } = req.params;\n const { comment } = req.body\n const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost)\n res.json({\n status: 'comment success',", "score": 0.9250861406326294 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { postId } = req.params;\n const { description } = req.body;\n const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost)\n res.json({\n status: 'post update success',\n response: postEditResult\n })\n })\n const reportPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, postId } = req.params;", "score": 0.923319399356842 }, { "filename": "src/framework/database/Mongodb/repositories/userRepositories.ts", "retrieved_chunk": " bio: string,\n gender: string,\n city: string\n }) => {\n const { userName, file, bio, gender, city } = data;\n const updateResult = await User.findByIdAndUpdate(_id, {\n $set: {\n userName,\n dp: file,\n bio,", "score": 0.9177855253219604 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { id } = req.params;\n const deletedData = await deletePostById(id, dbRepositoriesPost)\n res.json({\n status: 'Deleted success',\n deletedData\n })\n })\n const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => {\n const { id, userId } = req.query;\n await updateLike(id, userId, dbRepositoriesPost)", "score": 0.9162739515304565 } ]
typescript
const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);
import { Request, Response } from 'express'; import asyncHandler from 'express-async-handler'; import { UserDbInterface } from '../../application/repositories/userDbRepositories'; import { userById, followers, followings, unfollow, getUserDetails, searchUserByPrefix, updateProfileInfo, userBlock, requestFriend, requestFriendResponse } from '../../application/useCases/user/user'; import { userRepositoryMongoDB } from '../../framework/database/Mongodb/repositories/userRepositories'; const userControllers = ( userDbRepository: UserDbInterface, userDbRepositoryService: userRepositoryMongoDB ) => { const dbRepositoryUser = userDbRepository(userDbRepositoryService()); // get all users list const getAllUsers = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const users = await getUserDetails(id, dbRepositoryUser); res.json({ status: 'Get users success', users }) }) // get a user details by id const getUserById = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const user = await userById(id, dbRepositoryUser) res.json({ status: "success", user }); }); // get followers list of the user const getFollowersList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followersList: any = await followers(id, dbRepositoryUser); res.json({ status: 'get followers success', followers: followersList }) }) // get following list of the user const getFollowingsList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followingList: any = await followings(id, dbRepositoryUser); res.json({ status: 'get following success', followings: followingList }) }) // send friend request to user const sendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const response = await requestFriend(id, friendId, dbRepositoryUser); res.json({ status: response }) }) // accept or reject request const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const { response } = req.body; const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser) res.json({ status }) }) // insert followers to user const unfollowUser = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.query; const { status, friend }: any = await unfollow(id, friendId, dbRepositoryUser); res.json({ status, friend }) }) // search user const searchUser = asyncHandler(async (req: Request, res: Response) => { const { prefix } = req.params; const { type } = req.query; console.log(type, 'par'); const users: any = await searchUserByPrefix(prefix, type, dbRepositoryUser); res.json({ status: 'searched success', users }) }) // update profile informations const updateProfile = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const { userName, bio, gender, city, file } = req.body; const updateResult =
await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);
res.json({ status: 'Update success', data: updateResult }) }) // block user by user const blockUser = asyncHandler(async (req: Request, res: Response) => { const { userId, blockId } = req.params; const blockResult = await userBlock(userId, blockId, dbRepositoryUser); res.json({ status: blockResult }); }) return { getUserById, sendRequest, responseFriendRequest, getFollowersList, getFollowingsList, unfollowUser, getAllUsers, searchUser, updateProfile, blockUser }; }; export default userControllers;
src/adapters/controllers/userControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " status: \"success\",\n posts\n })\n })\n const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, description, userName, image, video } = req.body;\n const body = { userId, description, userName, image, video };\n const newPost = await postCreate(body, dbRepositoriesPost);\n res.json({\n status: 'upload-success',", "score": 0.9361124038696289 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { postId } = req.params;\n const { description } = req.body;\n const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost)\n res.json({\n status: 'post update success',\n response: postEditResult\n })\n })\n const reportPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, postId } = req.params;", "score": 0.9201778769493103 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " res.json({\n status: 'like update success'\n })\n })\n const commentPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { postId, userId } = req.params;\n const { comment } = req.body\n const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost)\n res.json({\n status: 'comment success',", "score": 0.9164557456970215 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " comment: updateResult\n })\n })\n const commentReply = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, postId } = req.params;\n const { comment, reply } = req.body;\n const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost)\n res.json({\n status: updateResult\n })", "score": 0.9139902591705322 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " newPost\n })\n })\n const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId } = req.params;\n const posts: any = await getPostsByUser(userId, dbRepositoriesPost);\n res.json({\n status: 'posts find success',\n posts\n })", "score": 0.9107413291931152 } ]
typescript
await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);
import { Request, Response } from 'express'; import asyncHandler from 'express-async-handler'; import { AuthServices } from '../../framework/services/authServices'; import { AuthServiceInterface } from '../../application/services/authServiceInterface'; import { UserDbInterface } from '../../application/repositories/userDbRepositories'; import { userRepositoryMongoDB } from '../../framework/database/Mongodb/repositories/userRepositories'; import { userRegister, userLogin, googleAuthLogin, userBlock} from '../../application/useCases/auth/userAuth'; // authentication controllers const authControllers = ( authServiceInterface: AuthServiceInterface, authService: AuthServices, userDbInterface: UserDbInterface, userDbservice: userRepositoryMongoDB ) => { const dbUserRepository = userDbInterface(userDbservice()); const authServices = authServiceInterface(authService()); const registerUser = asyncHandler(async(req: Request, res: Response) => { const { name, userName, number,email, password } = req.body; const user = { name, userName, number, email, password, }; const token = await userRegister(user, dbUserRepository, authServices); res.json({ status:"success", message: "User registered", token }); }); const loginUser = asyncHandler(async(req: Request, res: Response) => { const { userName, password } : { userName: string; password: string} = req.body; const token = await userLogin(userName, password, dbUserRepository, authServices); // res.setHeader('authorization', token.token); res.json({ status: "success", message: "user verified", token }); }); const googleAuth = asyncHandler(async(req: Request, res: Response) => { console.log('-----------------------'); const { fullName, firstName, email } = req.body; const userData: any = { name:fullName, userName:firstName, number: 7594837203, email } console.log(userData);
const {user, token} = await googleAuthLogin(userData, dbUserRepository, authServices) res.json({
status:'Google login success', user, token }) }) const blockUser = asyncHandler(async(req: Request, res: Response) => { const { id } = req.params; const blockResult = await userBlock(id, dbUserRepository); res.json({ status: `${blockResult} success` }) }) return { registerUser, loginUser, googleAuth, blockUser }; }; export default authControllers;
src/adapters/controllers/authControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " users\n })\n })\n // update profile informations\n const updateProfile = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const { userName, bio, gender, city, file } = req.body;\n const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);\n res.json({\n status: 'Update success',", "score": 0.8907389640808105 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " })\n })\n // search user \n const searchUser = asyncHandler(async (req: Request, res: Response) => {\n const { prefix } = req.params;\n const { type } = req.query;\n console.log(type, 'par');\n const users: any = await searchUserByPrefix(prefix, type, dbRepositoryUser);\n res.json({\n status: 'searched success',", "score": 0.882156252861023 }, { "filename": "src/adapters/controllers/adminAuthController.ts", "retrieved_chunk": " authService: AuthServices,\n adminDbInterface: AdminDbInterface,\n adminDbservice: adminRepositoryMongoDB\n) => {\n const dbAdminRepository = adminDbInterface(adminDbservice());\n const authServices = authServiceInterface(authService());\n const loginAdmin = asyncHandler(async(req: Request, res: Response) => {\n console.log('-------------------------------------------------------'); \n const { email, password } = req.body;\n const token = await adminLogin(email, password, dbAdminRepository, authServices)", "score": 0.878476619720459 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " status: \"success\",\n posts\n })\n })\n const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, description, userName, image, video } = req.body;\n const body = { userId, description, userName, image, video };\n const newPost = await postCreate(body, dbRepositoriesPost);\n res.json({\n status: 'upload-success',", "score": 0.8745211362838745 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const getUserById = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const user = await userById(id, dbRepositoryUser)\n res.json({\n status: \"success\",\n user\n });\n });\n // get followers list of the user\n const getFollowersList = asyncHandler(async (req: Request, res: Response) => {", "score": 0.8733115196228027 } ]
typescript
const {user, token} = await googleAuthLogin(userData, dbUserRepository, authServices) res.json({
import { Request, Response } from "express"; import expressAsyncHandler from "express-async-handler"; import { postRepositoryType } from "../../framework/database/Mongodb/repositories/postRepositeries"; import { postDbInterfaceType } from "../../application/repositories/postDbRepositories"; import { getAllPost, postCreate, getPostsByUser, getPostById, deletePostById, updateLike, insertComment, deleteComment, postEdit, postReport, getReportedUsers, replyComment } from '../../application/useCases/post/post' const postControllers = (postDbInterface: postDbInterfaceType, postRepositoryType: postRepositoryType) => { const dbRepositoriesPost = postDbInterface(postRepositoryType()) const getPosts = expressAsyncHandler(async (req: Request, res: Response) => { const posts = await getAllPost(dbRepositoriesPost) res.json({ status: "success", posts }) }) const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, description, userName, image, video } = req.body; const body = { userId, description, userName, image, video }; const newPost = await postCreate(body, dbRepositoriesPost); res.json({ status: 'upload-success', newPost }) }) const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => { const { userId } = req.params; const posts: any = await getPostsByUser(userId, dbRepositoriesPost); res.json({ status: 'posts find success', posts }) }) const getPost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const post: any = await getPostById(id, dbRepositoriesPost); res.json({ status: 'post find success', post }) }) const deletePost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const deletedData = await
deletePostById(id, dbRepositoriesPost) res.json({
status: 'Deleted success', deletedData }) }) const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => { const { id, userId } = req.query; await updateLike(id, userId, dbRepositoriesPost) res.json({ status: 'like update success' }) }) const commentPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, userId } = req.params; const { comment } = req.body const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost) res.json({ status: 'comment success', comment: updateResult }) }) const commentReply = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { comment, reply } = req.body; const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({ status: updateResult }) }) const commentDelete = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, index } = req.params; const deleteResult = await deleteComment(postId, index, dbRepositoriesPost) res.json({ status: 'comment deleted', deletedComment: deleteResult }) }) const editPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const { description } = req.body; const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost) res.json({ status: 'post update success', response: postEditResult }) }) const reportPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { reason } = req.body; const repostResponse = await postReport(userId, postId, reason, dbRepositoriesPost) res.json({ status: 'posted success', response: repostResponse }) }) const getReporters = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const users = await getReportedUsers(postId, dbRepositoriesPost); res.json({ status: 'reposted users fetched', users }) }) return { getPosts, uploadPost, getUserPosts, getPost, deletePost, postLikeUpdate, commentPost, commentReply, commentDelete, editPost, reportPost, getReporters } } export default postControllers;
src/adapters/controllers/postControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9208346605300903 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " // get all users list\n const getAllUsers = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const users = await getUserDetails(id, dbRepositoryUser);\n res.json({\n status: 'Get users success',\n users\n })\n })\n // get a user details by id", "score": 0.9205127954483032 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const getUserById = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const user = await userById(id, dbRepositoryUser)\n res.json({\n status: \"success\",\n user\n });\n });\n // get followers list of the user\n const getFollowersList = asyncHandler(async (req: Request, res: Response) => {", "score": 0.9143780469894409 }, { "filename": "src/adapters/controllers/messageController.ts", "retrieved_chunk": " res.json({\n status: 'success',\n response: createResponse\n })\n })\n const getUserMessages = expressAsyncHandler(async(req: Request, res: Response) => {\n const { chatId } = req.params;\n const messages = await getMessages(chatId, messageRepository);\n res.json({\n status: 'Message fetch success',", "score": 0.911685049533844 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " data: updateResult\n })\n })\n // block user by user\n const blockUser = asyncHandler(async (req: Request, res: Response) => {\n const { userId, blockId } = req.params;\n const blockResult = await userBlock(userId, blockId, dbRepositoryUser);\n res.json({\n status: blockResult\n });", "score": 0.90899658203125 } ]
typescript
deletePostById(id, dbRepositoriesPost) res.json({
import { Request, Response } from "express"; import expressAsyncHandler from "express-async-handler"; import { postRepositoryType } from "../../framework/database/Mongodb/repositories/postRepositeries"; import { postDbInterfaceType } from "../../application/repositories/postDbRepositories"; import { getAllPost, postCreate, getPostsByUser, getPostById, deletePostById, updateLike, insertComment, deleteComment, postEdit, postReport, getReportedUsers, replyComment } from '../../application/useCases/post/post' const postControllers = (postDbInterface: postDbInterfaceType, postRepositoryType: postRepositoryType) => { const dbRepositoriesPost = postDbInterface(postRepositoryType()) const getPosts = expressAsyncHandler(async (req: Request, res: Response) => { const posts = await getAllPost(dbRepositoriesPost) res.json({ status: "success", posts }) }) const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, description, userName, image, video } = req.body; const body = { userId, description, userName, image, video }; const newPost = await postCreate(body, dbRepositoriesPost); res.json({ status: 'upload-success', newPost }) }) const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => { const { userId } = req.params; const posts: any = await getPostsByUser(userId, dbRepositoriesPost); res.json({ status: 'posts find success', posts }) }) const getPost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const post: any = await getPostById(id, dbRepositoriesPost); res.json({ status: 'post find success', post }) }) const deletePost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const deletedData = await deletePostById(id, dbRepositoriesPost) res.json({ status: 'Deleted success', deletedData }) }) const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => { const { id, userId } = req.query; await updateLike(id, userId, dbRepositoriesPost) res.json({ status: 'like update success' }) }) const commentPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, userId } = req.params; const { comment } = req.body const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost) res.json({ status: 'comment success', comment: updateResult }) }) const commentReply = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { comment, reply } = req.body; const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({ status: updateResult }) }) const commentDelete = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, index } = req.params; const deleteResult = await deleteComment(postId, index, dbRepositoriesPost) res.json({ status: 'comment deleted', deletedComment: deleteResult }) }) const editPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const { description } = req.body;
const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost) res.json({
status: 'post update success', response: postEditResult }) }) const reportPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { reason } = req.body; const repostResponse = await postReport(userId, postId, reason, dbRepositoriesPost) res.json({ status: 'posted success', response: repostResponse }) }) const getReporters = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const users = await getReportedUsers(postId, dbRepositoriesPost); res.json({ status: 'reposted users fetched', users }) }) return { getPosts, uploadPost, getUserPosts, getPost, deletePost, postLikeUpdate, commentPost, commentReply, commentDelete, editPost, reportPost, getReporters } } export default postControllers;
src/adapters/controllers/postControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " users\n })\n })\n // update profile informations\n const updateProfile = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const { userName, bio, gender, city, file } = req.body;\n const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);\n res.json({\n status: 'Update success',", "score": 0.9207130670547485 }, { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9127361178398132 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " data: updateResult\n })\n })\n // block user by user\n const blockUser = asyncHandler(async (req: Request, res: Response) => {\n const { userId, blockId } = req.params;\n const blockResult = await userBlock(userId, blockId, dbRepositoryUser);\n res.json({\n status: blockResult\n });", "score": 0.9105088710784912 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " res.json({\n status: response\n })\n })\n // accept or reject request\n const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => {\n const { id, friendId } = req.params;\n const { response } = req.body;\n const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser)\n res.json({", "score": 0.909521222114563 }, { "filename": "src/adapters/controllers/messageController.ts", "retrieved_chunk": " res.json({\n status: 'success',\n response: createResponse\n })\n })\n const getUserMessages = expressAsyncHandler(async(req: Request, res: Response) => {\n const { chatId } = req.params;\n const messages = await getMessages(chatId, messageRepository);\n res.json({\n status: 'Message fetch success',", "score": 0.9042476415634155 } ]
typescript
const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost) res.json({
import Post from "../models/postModel"; import User from "../models/userModel"; import { ObjectId } from 'mongodb' import cloudinary from 'cloudinary' // post database operations export const postRepositoryMongoDb = () => { const getAllPost = async () => { return await Post.find().sort({ createdAt: -1 }); } const uploadPost = (async (post: { userId: string; description: string; image: string; video: string; userName: string; }) => { const newpost = new Post(post); return await newpost.save(); }) const getPostsByUser = async (userId: any) => { return await Post.find({ userId }) } const getPostById = async (_id: string) => { const posts = await Post.findById({ _id: new ObjectId(_id) }) return posts; } const deletePost = async (_id: string) => { const deletedData = await Post.findByIdAndDelete({ _id: new ObjectId(_id) }) return deletedData } const dislikePost = async (_id: string, userId: string) => { await Post.findByIdAndUpdate({ _id }, { $pull: { likes: userId } }) } const likePost = async (_id: string, userId: string) => { await Post.findByIdAndUpdate({ _id }, { $push: { likes: userId } }) } const insertComment = async (postId: string, userId: string, comment: string) => { const updateResult = await Post.findByIdAndUpdate({ _id: postId }, { $push: { comments: { userId, comment, reply: [] } } }); return updateResult; } const replyComment = async (_id: string, userId: string, comment: string, reply: string) => { const updateResult = await Post.updateOne( { _id, "comments.comment": comment }, { $push: { "comments.$.reply": { userId, reply } } } ); return updateResult; }; const editPost = async (_id: string, description: any) => { const updateResult = await Post.findByIdAndUpdate({ _id }, { $set: { description } }) return updateResult } const reportPost = async (userId: string, postId: string, reason: any) => { const repostResponse = await Post.findByIdAndUpdate({ _id: postId }, { $push: { reports: { userId, reason } } }) return repostResponse; } const getReportedUsers = async (postId: string) => { const postDetails: any = await Post.findOne({ _id: postId }); const users: any = await Promise.all( postDetails.reports.map(async ({ userId }: any) => {
return await User.findOne({ _id: userId }) }) ) return users;
} return { getAllPost, uploadPost, getPostsByUser, getPostById, deletePost, dislikePost, likePost, insertComment, replyComment, editPost, reportPost, getReportedUsers } } export type postRepositoryType = typeof postRepositoryMongoDb;
src/framework/database/Mongodb/repositories/postRepositeries.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/framework/database/Mongodb/repositories/userRepositories.ts", "retrieved_chunk": " return followers;\n };\n const getFollowings = async (_id: string) => {\n const user: any = await User.findOne({ _id });\n const followings: any[] = await Promise.all(\n user.following.map(async (following: any) => {\n return await User.findOne({ _id: following });\n })\n );\n return followings;", "score": 0.9125638008117676 }, { "filename": "src/application/repositories/postDbRepositories.ts", "retrieved_chunk": " const repostResponse = await repositories.reportPost(userId, postId, reason);\n return repostResponse;\n }\n const getReportedUsers = async (postId: string) => {\n const users = await repositories.getReportedUsers(postId);\n return users;\n }\n return {\n getAllPost,\n uploadPost,", "score": 0.9076582193374634 }, { "filename": "src/framework/database/Mongodb/repositories/userRepositories.ts", "retrieved_chunk": " throw error;\n }\n };\n const getFollowers = async (_id: string) => {\n const user: any = await User.findOne({ _id });\n const followers: any[] = await Promise.all(\n user.followers.map(async (follower: any) => {\n return await User.findOne({ _id: follower });\n })\n );", "score": 0.9051766991615295 }, { "filename": "src/framework/database/Mongodb/repositories/userRepositories.ts", "retrieved_chunk": " };\n const getUserByUserName = async (userName: string) => {\n const user: any = await User.findOne({ userName })\n return user;\n };\n const getUserById = async (id: string) => {\n try {\n const user: any = await User.findOne({ _id: id }).select('-password');\n return user;\n } catch (error) {", "score": 0.9039095640182495 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " newPost\n })\n })\n const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId } = req.params;\n const posts: any = await getPostsByUser(userId, dbRepositoriesPost);\n res.json({\n status: 'posts find success',\n posts\n })", "score": 0.9035072922706604 } ]
typescript
return await User.findOne({ _id: userId }) }) ) return users;
import { Request, Response } from "express"; import expressAsyncHandler from "express-async-handler"; import { postRepositoryType } from "../../framework/database/Mongodb/repositories/postRepositeries"; import { postDbInterfaceType } from "../../application/repositories/postDbRepositories"; import { getAllPost, postCreate, getPostsByUser, getPostById, deletePostById, updateLike, insertComment, deleteComment, postEdit, postReport, getReportedUsers, replyComment } from '../../application/useCases/post/post' const postControllers = (postDbInterface: postDbInterfaceType, postRepositoryType: postRepositoryType) => { const dbRepositoriesPost = postDbInterface(postRepositoryType()) const getPosts = expressAsyncHandler(async (req: Request, res: Response) => { const posts = await getAllPost(dbRepositoriesPost) res.json({ status: "success", posts }) }) const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, description, userName, image, video } = req.body; const body = { userId, description, userName, image, video }; const newPost = await postCreate(body, dbRepositoriesPost); res.json({ status: 'upload-success', newPost }) }) const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => { const { userId } = req.params; const posts: any = await getPostsByUser(userId, dbRepositoriesPost); res.json({ status: 'posts find success', posts }) }) const getPost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const post: any = await getPostById(id, dbRepositoriesPost); res.json({ status: 'post find success', post }) }) const deletePost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const deletedData = await deletePostById(id, dbRepositoriesPost) res.json({ status: 'Deleted success', deletedData }) }) const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => { const { id, userId } = req.query; await updateLike(id, userId, dbRepositoriesPost) res.json({ status: 'like update success' }) }) const commentPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, userId } = req.params; const { comment } = req.body
const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost) res.json({
status: 'comment success', comment: updateResult }) }) const commentReply = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { comment, reply } = req.body; const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({ status: updateResult }) }) const commentDelete = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, index } = req.params; const deleteResult = await deleteComment(postId, index, dbRepositoriesPost) res.json({ status: 'comment deleted', deletedComment: deleteResult }) }) const editPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const { description } = req.body; const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost) res.json({ status: 'post update success', response: postEditResult }) }) const reportPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { reason } = req.body; const repostResponse = await postReport(userId, postId, reason, dbRepositoriesPost) res.json({ status: 'posted success', response: repostResponse }) }) const getReporters = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const users = await getReportedUsers(postId, dbRepositoriesPost); res.json({ status: 'reposted users fetched', users }) }) return { getPosts, uploadPost, getUserPosts, getPost, deletePost, postLikeUpdate, commentPost, commentReply, commentDelete, editPost, reportPost, getReporters } } export default postControllers;
src/adapters/controllers/postControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9192871451377869 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " users\n })\n })\n // update profile informations\n const updateProfile = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const { userName, bio, gender, city, file } = req.body;\n const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);\n res.json({\n status: 'Update success',", "score": 0.9164782762527466 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " res.json({\n status: response\n })\n })\n // accept or reject request\n const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => {\n const { id, friendId } = req.params;\n const { response } = req.body;\n const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser)\n res.json({", "score": 0.9142857789993286 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " data: updateResult\n })\n })\n // block user by user\n const blockUser = asyncHandler(async (req: Request, res: Response) => {\n const { userId, blockId } = req.params;\n const blockResult = await userBlock(userId, blockId, dbRepositoryUser);\n res.json({\n status: blockResult\n });", "score": 0.9142852425575256 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const getUserById = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const user = await userById(id, dbRepositoryUser)\n res.json({\n status: \"success\",\n user\n });\n });\n // get followers list of the user\n const getFollowersList = asyncHandler(async (req: Request, res: Response) => {", "score": 0.9109742045402527 } ]
typescript
const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost) res.json({
import { Request, Response } from 'express'; import asyncHandler from 'express-async-handler'; import { UserDbInterface } from '../../application/repositories/userDbRepositories'; import { userById, followers, followings, unfollow, getUserDetails, searchUserByPrefix, updateProfileInfo, userBlock, requestFriend, requestFriendResponse } from '../../application/useCases/user/user'; import { userRepositoryMongoDB } from '../../framework/database/Mongodb/repositories/userRepositories'; const userControllers = ( userDbRepository: UserDbInterface, userDbRepositoryService: userRepositoryMongoDB ) => { const dbRepositoryUser = userDbRepository(userDbRepositoryService()); // get all users list const getAllUsers = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const users = await getUserDetails(id, dbRepositoryUser); res.json({ status: 'Get users success', users }) }) // get a user details by id const getUserById = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const user = await userById(id, dbRepositoryUser) res.json({ status: "success", user }); }); // get followers list of the user const getFollowersList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followersList: any = await followers(id, dbRepositoryUser); res.json({ status: 'get followers success', followers: followersList }) }) // get following list of the user const getFollowingsList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followingList: any = await followings(id, dbRepositoryUser); res.json({ status: 'get following success', followings: followingList }) }) // send friend request to user const sendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const response = await requestFriend(id, friendId, dbRepositoryUser); res.json({ status: response }) }) // accept or reject request const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const { response } = req.body; const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser) res.json({ status }) }) // insert followers to user const unfollowUser = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.query; const { status, friend }: any = await unfollow(id, friendId, dbRepositoryUser); res.json({ status, friend }) }) // search user const searchUser = asyncHandler(async (req: Request, res: Response) => { const { prefix } = req.params; const { type } = req.query; console.log(type, 'par');
const users: any = await searchUserByPrefix(prefix, type, dbRepositoryUser);
res.json({ status: 'searched success', users }) }) // update profile informations const updateProfile = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const { userName, bio, gender, city, file } = req.body; const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser); res.json({ status: 'Update success', data: updateResult }) }) // block user by user const blockUser = asyncHandler(async (req: Request, res: Response) => { const { userId, blockId } = req.params; const blockResult = await userBlock(userId, blockId, dbRepositoryUser); res.json({ status: blockResult }); }) return { getUserById, sendRequest, responseFriendRequest, getFollowersList, getFollowingsList, unfollowUser, getAllUsers, searchUser, updateProfile, blockUser }; }; export default userControllers;
src/adapters/controllers/userControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " newPost\n })\n })\n const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId } = req.params;\n const posts: any = await getPostsByUser(userId, dbRepositoriesPost);\n res.json({\n status: 'posts find success',\n posts\n })", "score": 0.9036513566970825 }, { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.8956941366195679 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { id } = req.params;\n const deletedData = await deletePostById(id, dbRepositoriesPost)\n res.json({\n status: 'Deleted success',\n deletedData\n })\n })\n const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => {\n const { id, userId } = req.query;\n await updateLike(id, userId, dbRepositoriesPost)", "score": 0.8903168439865112 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " })\n const getPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const post: any = await getPostById(id, dbRepositoriesPost);\n res.json({\n status: 'post find success',\n post\n })\n })\n const deletePost = expressAsyncHandler(async (req: Request, res: Response) => {", "score": 0.8879581689834595 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { postId } = req.params;\n const { description } = req.body;\n const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost)\n res.json({\n status: 'post update success',\n response: postEditResult\n })\n })\n const reportPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, postId } = req.params;", "score": 0.8835626840591431 } ]
typescript
const users: any = await searchUserByPrefix(prefix, type, dbRepositoryUser);
import { Request, Response } from 'express'; import asyncHandler from 'express-async-handler'; import { UserDbInterface } from '../../application/repositories/userDbRepositories'; import { userById, followers, followings, unfollow, getUserDetails, searchUserByPrefix, updateProfileInfo, userBlock, requestFriend, requestFriendResponse } from '../../application/useCases/user/user'; import { userRepositoryMongoDB } from '../../framework/database/Mongodb/repositories/userRepositories'; const userControllers = ( userDbRepository: UserDbInterface, userDbRepositoryService: userRepositoryMongoDB ) => { const dbRepositoryUser = userDbRepository(userDbRepositoryService()); // get all users list const getAllUsers = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const users = await getUserDetails(id, dbRepositoryUser); res.json({ status: 'Get users success', users }) }) // get a user details by id const getUserById = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const user = await userById(id, dbRepositoryUser) res.json({ status: "success", user }); }); // get followers list of the user const getFollowersList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followersList: any = await followers(id, dbRepositoryUser); res.json({ status: 'get followers success', followers: followersList }) }) // get following list of the user const getFollowingsList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followingList: any = await followings(id, dbRepositoryUser); res.json({ status: 'get following success', followings: followingList }) }) // send friend request to user const sendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const response = await requestFriend(id, friendId, dbRepositoryUser); res.json({ status: response }) }) // accept or reject request const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const { response } = req.body; const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser) res.json({ status }) }) // insert followers to user const unfollowUser = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.query; const { status, friend }: any = await unfollow(id, friendId, dbRepositoryUser); res.json({ status, friend }) }) // search user const searchUser = asyncHandler(async (req: Request, res: Response) => { const { prefix } = req.params; const { type } = req.query; console.log(type, 'par'); const users: any = await searchUserByPrefix(prefix, type, dbRepositoryUser); res.json({ status: 'searched success', users }) }) // update profile informations const updateProfile = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const { userName, bio, gender, city, file } = req.body; const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser); res.json({ status: 'Update success', data: updateResult }) }) // block user by user const blockUser = asyncHandler(async (req: Request, res: Response) => { const { userId, blockId } = req.params;
const blockResult = await userBlock(userId, blockId, dbRepositoryUser);
res.json({ status: blockResult }); }) return { getUserById, sendRequest, responseFriendRequest, getFollowersList, getFollowingsList, unfollowUser, getAllUsers, searchUser, updateProfile, blockUser }; }; export default userControllers;
src/adapters/controllers/userControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9529788494110107 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " res.json({\n status: 'like update success'\n })\n })\n const commentPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { postId, userId } = req.params;\n const { comment } = req.body\n const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost)\n res.json({\n status: 'comment success',", "score": 0.924662709236145 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { postId } = req.params;\n const { description } = req.body;\n const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost)\n res.json({\n status: 'post update success',\n response: postEditResult\n })\n })\n const reportPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, postId } = req.params;", "score": 0.9235613942146301 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " status: \"success\",\n posts\n })\n })\n const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, description, userName, image, video } = req.body;\n const body = { userId, description, userName, image, video };\n const newPost = await postCreate(body, dbRepositoriesPost);\n res.json({\n status: 'upload-success',", "score": 0.9220438599586487 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " comment: updateResult\n })\n })\n const commentReply = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, postId } = req.params;\n const { comment, reply } = req.body;\n const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost)\n res.json({\n status: updateResult\n })", "score": 0.9195665121078491 } ]
typescript
const blockResult = await userBlock(userId, blockId, dbRepositoryUser);
import { Request, Response } from "express"; import expressAsyncHandler from "express-async-handler"; import { postRepositoryType } from "../../framework/database/Mongodb/repositories/postRepositeries"; import { postDbInterfaceType } from "../../application/repositories/postDbRepositories"; import { getAllPost, postCreate, getPostsByUser, getPostById, deletePostById, updateLike, insertComment, deleteComment, postEdit, postReport, getReportedUsers, replyComment } from '../../application/useCases/post/post' const postControllers = (postDbInterface: postDbInterfaceType, postRepositoryType: postRepositoryType) => { const dbRepositoriesPost = postDbInterface(postRepositoryType()) const getPosts = expressAsyncHandler(async (req: Request, res: Response) => { const posts = await getAllPost(dbRepositoriesPost) res.json({ status: "success", posts }) }) const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, description, userName, image, video } = req.body; const body = { userId, description, userName, image, video }; const newPost = await postCreate(body, dbRepositoriesPost); res.json({ status: 'upload-success', newPost }) }) const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => { const { userId } = req.params; const posts: any = await getPostsByUser(userId, dbRepositoriesPost); res.json({ status: 'posts find success', posts }) }) const getPost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const post: any = await getPostById(id, dbRepositoriesPost); res.json({ status: 'post find success', post }) }) const deletePost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const deletedData = await deletePostById(id, dbRepositoriesPost) res.json({ status: 'Deleted success', deletedData }) }) const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => { const { id, userId } = req.query; await updateLike(id, userId, dbRepositoriesPost) res.json({ status: 'like update success' }) }) const commentPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, userId } = req.params; const { comment } = req.body const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost) res.json({ status: 'comment success', comment: updateResult }) }) const commentReply = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { comment, reply } = req.body; const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({ status: updateResult }) }) const commentDelete = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, index } = req.params;
const deleteResult = await deleteComment(postId, index, dbRepositoriesPost) res.json({
status: 'comment deleted', deletedComment: deleteResult }) }) const editPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const { description } = req.body; const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost) res.json({ status: 'post update success', response: postEditResult }) }) const reportPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { reason } = req.body; const repostResponse = await postReport(userId, postId, reason, dbRepositoriesPost) res.json({ status: 'posted success', response: repostResponse }) }) const getReporters = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const users = await getReportedUsers(postId, dbRepositoriesPost); res.json({ status: 'reposted users fetched', users }) }) return { getPosts, uploadPost, getUserPosts, getPost, deletePost, postLikeUpdate, commentPost, commentReply, commentDelete, editPost, reportPost, getReporters } } export default postControllers;
src/adapters/controllers/postControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/application/repositories/postDbRepositories.ts", "retrieved_chunk": " }\n const replyComment = async(postId: string,userId: string, comment: string, reply: string) => {\n const response = await repositories.replyComment(postId,userId, comment, reply);\n return response\n }\n const editPost = async(postId: string, body: any) => {\n const editPost = await repositories.editPost(postId, body)\n return editPost\n }\n const reportPost = async(userId: string, postId: string, reason: any) => {", "score": 0.9081482887268066 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " data: updateResult\n })\n })\n // block user by user\n const blockUser = asyncHandler(async (req: Request, res: Response) => {\n const { userId, blockId } = req.params;\n const blockResult = await userBlock(userId, blockId, dbRepositoryUser);\n res.json({\n status: blockResult\n });", "score": 0.9045397043228149 }, { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9044553637504578 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " res.json({\n status: response\n })\n })\n // accept or reject request\n const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => {\n const { id, friendId } = req.params;\n const { response } = req.body;\n const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser)\n res.json({", "score": 0.901517391204834 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const getUserById = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const user = await userById(id, dbRepositoryUser)\n res.json({\n status: \"success\",\n user\n });\n });\n // get followers list of the user\n const getFollowersList = asyncHandler(async (req: Request, res: Response) => {", "score": 0.8986485004425049 } ]
typescript
const deleteResult = await deleteComment(postId, index, dbRepositoriesPost) res.json({
import { Request, Response } from 'express'; import asyncHandler from 'express-async-handler'; import { AuthServices } from '../../framework/services/authServices'; import { AuthServiceInterface } from '../../application/services/authServiceInterface'; import { UserDbInterface } from '../../application/repositories/userDbRepositories'; import { userRepositoryMongoDB } from '../../framework/database/Mongodb/repositories/userRepositories'; import { userRegister, userLogin, googleAuthLogin, userBlock} from '../../application/useCases/auth/userAuth'; // authentication controllers const authControllers = ( authServiceInterface: AuthServiceInterface, authService: AuthServices, userDbInterface: UserDbInterface, userDbservice: userRepositoryMongoDB ) => { const dbUserRepository = userDbInterface(userDbservice()); const authServices = authServiceInterface(authService()); const registerUser = asyncHandler(async(req: Request, res: Response) => { const { name, userName, number,email, password } = req.body; const user = { name, userName, number, email, password, }; const token = await userRegister(user, dbUserRepository, authServices); res.json({ status:"success", message: "User registered", token }); }); const loginUser = asyncHandler(async(req: Request, res: Response) => { const { userName, password } : { userName: string; password: string} = req.body; const token = await userLogin(userName, password, dbUserRepository, authServices); // res.setHeader('authorization', token.token); res.json({ status: "success", message: "user verified", token }); }); const googleAuth = asyncHandler(async(req: Request, res: Response) => { console.log('-----------------------'); const { fullName, firstName, email } = req.body; const userData: any = { name:fullName, userName:firstName, number: 7594837203, email } console.log(userData); const {user, token} = await googleAuthLogin(userData, dbUserRepository, authServices) res.json({ status:'Google login success', user, token }) }) const blockUser = asyncHandler(async(req: Request, res: Response) => { const { id } = req.params;
const blockResult = await userBlock(id, dbUserRepository);
res.json({ status: `${blockResult} success` }) }) return { registerUser, loginUser, googleAuth, blockUser }; }; export default authControllers;
src/adapters/controllers/authControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " data: updateResult\n })\n })\n // block user by user\n const blockUser = asyncHandler(async (req: Request, res: Response) => {\n const { userId, blockId } = req.params;\n const blockResult = await userBlock(userId, blockId, dbRepositoryUser);\n res.json({\n status: blockResult\n });", "score": 0.9409858584403992 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const getUserById = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const user = await userById(id, dbRepositoryUser)\n res.json({\n status: \"success\",\n user\n });\n });\n // get followers list of the user\n const getFollowersList = asyncHandler(async (req: Request, res: Response) => {", "score": 0.9174336194992065 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " // get all users list\n const getAllUsers = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const users = await getUserDetails(id, dbRepositoryUser);\n res.json({\n status: 'Get users success',\n users\n })\n })\n // get a user details by id", "score": 0.9002424478530884 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { postId } = req.params;\n const { description } = req.body;\n const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost)\n res.json({\n status: 'post update success',\n response: postEditResult\n })\n })\n const reportPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, postId } = req.params;", "score": 0.8986577987670898 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const { id } = req.params;\n const followersList: any = await followers(id, dbRepositoryUser);\n res.json({\n status: 'get followers success',\n followers: followersList\n })\n })\n // get following list of the user\n const getFollowingsList = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;", "score": 0.8975350856781006 } ]
typescript
const blockResult = await userBlock(id, dbUserRepository);
import Post from "../models/postModel"; import User from "../models/userModel"; import { ObjectId } from 'mongodb' import cloudinary from 'cloudinary' // post database operations export const postRepositoryMongoDb = () => { const getAllPost = async () => { return await Post.find().sort({ createdAt: -1 }); } const uploadPost = (async (post: { userId: string; description: string; image: string; video: string; userName: string; }) => { const newpost = new Post(post); return await newpost.save(); }) const getPostsByUser = async (userId: any) => { return await Post.find({ userId }) } const getPostById = async (_id: string) => { const posts = await Post.findById({ _id: new ObjectId(_id) }) return posts; } const deletePost = async (_id: string) => { const deletedData = await Post.findByIdAndDelete({ _id: new ObjectId(_id) }) return deletedData } const dislikePost = async (_id: string, userId: string) => { await Post.findByIdAndUpdate({ _id }, { $pull: { likes: userId } }) } const likePost = async (_id: string, userId: string) => { await Post.findByIdAndUpdate({ _id }, { $push: { likes: userId } }) } const insertComment = async (postId: string, userId: string, comment: string) => { const updateResult = await Post.findByIdAndUpdate({ _id: postId }, { $push: { comments: { userId, comment, reply: [] } } }); return updateResult; } const replyComment = async (_id: string, userId: string, comment: string, reply: string) => { const updateResult = await Post.updateOne( { _id, "comments.comment": comment }, { $push: { "comments.$.reply": { userId, reply } } } ); return updateResult; }; const editPost = async (_id: string, description: any) => { const updateResult = await Post.findByIdAndUpdate({ _id }, { $set: { description } }) return updateResult } const reportPost = async (userId: string, postId: string, reason: any) => { const repostResponse = await Post.findByIdAndUpdate({ _id: postId }, { $push: { reports: { userId, reason } } }) return repostResponse; } const getReportedUsers = async (postId: string) => { const postDetails: any =
await Post.findOne({ _id: postId });
const users: any = await Promise.all( postDetails.reports.map(async ({ userId }: any) => { return await User.findOne({ _id: userId }) }) ) return users; } return { getAllPost, uploadPost, getPostsByUser, getPostById, deletePost, dislikePost, likePost, insertComment, replyComment, editPost, reportPost, getReportedUsers } } export type postRepositoryType = typeof postRepositoryMongoDb;
src/framework/database/Mongodb/repositories/postRepositeries.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/application/repositories/postDbRepositories.ts", "retrieved_chunk": " }\n const replyComment = async(postId: string,userId: string, comment: string, reply: string) => {\n const response = await repositories.replyComment(postId,userId, comment, reply);\n return response\n }\n const editPost = async(postId: string, body: any) => {\n const editPost = await repositories.editPost(postId, body)\n return editPost\n }\n const reportPost = async(userId: string, postId: string, reason: any) => {", "score": 0.916179358959198 }, { "filename": "src/application/repositories/postDbRepositories.ts", "retrieved_chunk": " const repostResponse = await repositories.reportPost(userId, postId, reason);\n return repostResponse;\n }\n const getReportedUsers = async (postId: string) => {\n const users = await repositories.getReportedUsers(postId);\n return users;\n }\n return {\n getAllPost,\n uploadPost,", "score": 0.9057844877243042 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { reason } = req.body;\n const repostResponse = await postReport(userId, postId, reason, dbRepositoriesPost)\n res.json({\n status: 'posted success',\n response: repostResponse\n })\n })\n const getReporters = expressAsyncHandler(async (req: Request, res: Response) => {\n const { postId } = req.params;\n const users = await getReportedUsers(postId, dbRepositoriesPost);", "score": 0.9001150727272034 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { postId } = req.params;\n const { description } = req.body;\n const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost)\n res.json({\n status: 'post update success',\n response: postEditResult\n })\n })\n const reportPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, postId } = req.params;", "score": 0.8995392918586731 }, { "filename": "src/application/repositories/postDbRepositories.ts", "retrieved_chunk": " }\n const dislikePost = async (id: string, userId: string) => {\n await repositories.dislikePost(id, userId)\n }\n const likePost = async (id: string, userId: string) => {\n await repositories.likePost(id, userId)\n }\n const insertComment = async(postId: string, userId: string, comment: string) => {\n const insertResult = await repositories.insertComment(postId, userId, comment);\n return insertResult", "score": 0.8926888704299927 } ]
typescript
await Post.findOne({ _id: postId });
import { Request, Response } from "express"; import expressAsyncHandler from "express-async-handler"; import { postRepositoryType } from "../../framework/database/Mongodb/repositories/postRepositeries"; import { postDbInterfaceType } from "../../application/repositories/postDbRepositories"; import { getAllPost, postCreate, getPostsByUser, getPostById, deletePostById, updateLike, insertComment, deleteComment, postEdit, postReport, getReportedUsers, replyComment } from '../../application/useCases/post/post' const postControllers = (postDbInterface: postDbInterfaceType, postRepositoryType: postRepositoryType) => { const dbRepositoriesPost = postDbInterface(postRepositoryType()) const getPosts = expressAsyncHandler(async (req: Request, res: Response) => { const posts = await getAllPost(dbRepositoriesPost) res.json({ status: "success", posts }) }) const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, description, userName, image, video } = req.body; const body = { userId, description, userName, image, video }; const newPost = await postCreate(body, dbRepositoriesPost); res.json({ status: 'upload-success', newPost }) }) const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => { const { userId } = req.params; const posts: any = await getPostsByUser(userId, dbRepositoriesPost); res.json({ status: 'posts find success', posts }) }) const getPost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const post: any = await getPostById(id, dbRepositoriesPost); res.json({ status: 'post find success', post }) }) const deletePost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const deletedData = await deletePostById(id, dbRepositoriesPost) res.json({ status: 'Deleted success', deletedData }) }) const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => { const { id, userId } = req.query; await updateLike(id, userId, dbRepositoriesPost) res.json({ status: 'like update success' }) }) const commentPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, userId } = req.params; const { comment } = req.body const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost) res.json({ status: 'comment success', comment: updateResult }) }) const commentReply = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { comment, reply } = req.body; const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({ status: updateResult }) }) const commentDelete = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, index } = req.params; const deleteResult = await deleteComment(postId, index, dbRepositoriesPost) res.json({ status: 'comment deleted', deletedComment: deleteResult }) }) const editPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const { description } = req.body; const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost) res.json({ status: 'post update success', response: postEditResult }) }) const reportPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { reason } = req.body; const repostResponse
= await postReport(userId, postId, reason, dbRepositoriesPost) res.json({
status: 'posted success', response: repostResponse }) }) const getReporters = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const users = await getReportedUsers(postId, dbRepositoriesPost); res.json({ status: 'reposted users fetched', users }) }) return { getPosts, uploadPost, getUserPosts, getPost, deletePost, postLikeUpdate, commentPost, commentReply, commentDelete, editPost, reportPost, getReporters } } export default postControllers;
src/adapters/controllers/postControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " users\n })\n })\n // update profile informations\n const updateProfile = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const { userName, bio, gender, city, file } = req.body;\n const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);\n res.json({\n status: 'Update success',", "score": 0.9219133853912354 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " data: updateResult\n })\n })\n // block user by user\n const blockUser = asyncHandler(async (req: Request, res: Response) => {\n const { userId, blockId } = req.params;\n const blockResult = await userBlock(userId, blockId, dbRepositoryUser);\n res.json({\n status: blockResult\n });", "score": 0.9138807058334351 }, { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9129011631011963 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " res.json({\n status: response\n })\n })\n // accept or reject request\n const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => {\n const { id, friendId } = req.params;\n const { response } = req.body;\n const status = await requestFriendResponse(id, friendId, response, dbRepositoryUser)\n res.json({", "score": 0.903637170791626 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " // get all users list\n const getAllUsers = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const users = await getUserDetails(id, dbRepositoryUser);\n res.json({\n status: 'Get users success',\n users\n })\n })\n // get a user details by id", "score": 0.9036090970039368 } ]
typescript
= await postReport(userId, postId, reason, dbRepositoriesPost) res.json({
import { HttpStatus } from '../../../types/httpstatuscodes'; import AppError from '../../../utilities/appError'; import { UserDbInterface } from '../../repositories/userDbRepositories'; export const getUserDetails = async (id: string, repository: ReturnType<UserDbInterface>) => { // Get all users const users: any[] = await repository.getAllUsers(); if (id !== 'undefined') { // Get blocked users const { blockedUsers } = await repository.getUserById(id); // Filter out blocked users const filtered = users.filter((user: any) => !blockedUsers.includes(user._id)); return filtered; } else { return users } }; export const userById = async (id: string, repository: ReturnType<UserDbInterface>) => { const user: any = await repository.getUserById(id) if (!user) { throw new AppError("user not exist", HttpStatus.UNAUTHORIZED); } return user; } export const followers = async (id: string, repository: ReturnType<UserDbInterface>) => { const followers: any = await repository.getFollowers(id); return followers; } export const followings = async (id: string, repository: ReturnType<UserDbInterface>) => { const followings: any = await repository.getFollowings(id); return followings } export const requestFriend = async (id: string, friendId: string, repository: ReturnType<UserDbInterface>) => { const { userName, dp } = await repository.getUserById(id); const { requests, userName: friendName, dp: friendDp } = await repository.getUserById(friendId); // check user is already in request list const isRequested = requests.find((request: any) => request.id === id); if (isRequested) { await repository.cancelRequest(id, friendId); return 'Request canceled'; } else { await repository.sendRequest(id, userName, friendName, dp, friendDp, friendId); return 'Request sended'; } } export const requestFriendResponse = async (id: string, friendId: string, { response }: any, repository: ReturnType<UserDbInterface>) => { if (response === 'accept') { await repository.followFriend(friendId, id); await repository.cancelRequest(friendId, id); return 'Request accepted' } else { await repository.cancelRequest(friendId, id); return 'Request rejected' } } export const unfollow = async (id: any, friendId: any, repository: ReturnType<UserDbInterface>) => { // this friend is already a follower const friend: any = await repository.unfollowFriend(id, friendId); return { status: 'unfollow', friend } } export const searchUserByPrefix = async (prefix: any, type: any, repository: ReturnType<UserDbInterface>) => {
if (!prefix) return HttpStatus.NOT_FOUND const searchedUsers: any = await repository.searchUser(prefix, type) return searchedUsers }
export const updateProfileInfo = async (id: string, body: any, repository: ReturnType<UserDbInterface>) => { if (!body || !id) return HttpStatus.NOT_FOUND const updateProfile: any = await repository.updateProfile(id, body); return updateProfile } export const userBlock = async (userId: string, blockId: string, repository: ReturnType<UserDbInterface>) => { const { blockingUsers } = await repository.getUserById(userId); // check user is already blocked const isBlocked = blockingUsers.some((user: any) => user === blockId); if (isBlocked) { // user already blocked const updateResult: any = await repository.unBlockUserByUser(userId, blockId); return updateResult; } else { // user not blocked const updateResult: any = await repository.blockUserByUser(userId, blockId); return updateResult; } }
src/application/useCases/user/user.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/application/repositories/userDbRepositories.ts", "retrieved_chunk": " }\n const followFriend = async (id: string, friendId: string) => {\n return await repository.followFriend(id, friendId)\n }\n const searchUser = async (prefix: string, type: string) => {\n return await repository.searchUser(prefix, type);\n }\n const updateProfile = async (id: string, body: any) => {\n return await repository.updateProfile(id, body)\n }", "score": 0.8799945712089539 }, { "filename": "src/application/useCases/post/post.ts", "retrieved_chunk": " const deletedData = await repositories.deletePost(id)\n if (!deletedData) {\n throw new AppError('No data found for delete', HttpStatus.BAD_REQUEST)\n }\n return deletedData\n}\n// like or dislike post \nexport const updateLike = async (id: any, userId: any, repositories: ReturnType<postDbInterfaceType>) => {\n // find the post by id\n const post = await repositories.getPostById(id);", "score": 0.8775103092193604 }, { "filename": "src/application/useCases/post/post.ts", "retrieved_chunk": " respositories: ReturnType<postDbInterfaceType>\n) => {\n const newpost = await respositories.uploadPost(postDetails)\n if (!newpost) {\n throw new AppError('Uploading failed', HttpStatus.BAD_REQUEST)\n }\n return newpost\n};\n// get all post by a user\nexport const getPostsByUser = async (userId: any, repositories: ReturnType<postDbInterfaceType>) => {", "score": 0.8604426383972168 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const { id } = req.params;\n const followersList: any = await followers(id, dbRepositoryUser);\n res.json({\n status: 'get followers success',\n followers: followersList\n })\n })\n // get following list of the user\n const getFollowingsList = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;", "score": 0.8567841053009033 }, { "filename": "src/framework/database/Mongodb/repositories/userRepositories.ts", "retrieved_chunk": " };\n const findFriend = async (_id: string, friendId: any) => {\n const user: any = await User.findOne({ _id })\n const isUserExist: any = await user.followers.find((user: any) => user === friendId)\n return isUserExist;\n }\n const sendRequest = async (id: string, userName: string, friendName: string, dp: any, friendDp: string, friendId: string) => {\n await User.updateOne({ _id: friendId }, {\n $push: { requests: { id, userName, dp } }\n })", "score": 0.8565642833709717 } ]
typescript
if (!prefix) return HttpStatus.NOT_FOUND const searchedUsers: any = await repository.searchUser(prefix, type) return searchedUsers }
import { Request, Response } from 'express'; import asyncHandler from 'express-async-handler'; import { UserDbInterface } from '../../application/repositories/userDbRepositories'; import { userById, followers, followings, unfollow, getUserDetails, searchUserByPrefix, updateProfileInfo, userBlock, requestFriend, requestFriendResponse } from '../../application/useCases/user/user'; import { userRepositoryMongoDB } from '../../framework/database/Mongodb/repositories/userRepositories'; const userControllers = ( userDbRepository: UserDbInterface, userDbRepositoryService: userRepositoryMongoDB ) => { const dbRepositoryUser = userDbRepository(userDbRepositoryService()); // get all users list const getAllUsers = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const users = await getUserDetails(id, dbRepositoryUser); res.json({ status: 'Get users success', users }) }) // get a user details by id const getUserById = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const user = await userById(id, dbRepositoryUser) res.json({ status: "success", user }); }); // get followers list of the user const getFollowersList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followersList: any = await followers(id, dbRepositoryUser); res.json({ status: 'get followers success', followers: followersList }) }) // get following list of the user const getFollowingsList = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const followingList: any = await followings(id, dbRepositoryUser); res.json({ status: 'get following success', followings: followingList }) }) // send friend request to user const sendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const response = await requestFriend(id, friendId, dbRepositoryUser); res.json({ status: response }) }) // accept or reject request const responseFriendRequest = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.params; const { response } = req.body; const
status = await requestFriendResponse(id, friendId, response, dbRepositoryUser) res.json({
status }) }) // insert followers to user const unfollowUser = asyncHandler(async (req: Request, res: Response) => { const { id, friendId } = req.query; const { status, friend }: any = await unfollow(id, friendId, dbRepositoryUser); res.json({ status, friend }) }) // search user const searchUser = asyncHandler(async (req: Request, res: Response) => { const { prefix } = req.params; const { type } = req.query; console.log(type, 'par'); const users: any = await searchUserByPrefix(prefix, type, dbRepositoryUser); res.json({ status: 'searched success', users }) }) // update profile informations const updateProfile = asyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const { userName, bio, gender, city, file } = req.body; const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser); res.json({ status: 'Update success', data: updateResult }) }) // block user by user const blockUser = asyncHandler(async (req: Request, res: Response) => { const { userId, blockId } = req.params; const blockResult = await userBlock(userId, blockId, dbRepositoryUser); res.json({ status: blockResult }); }) return { getUserById, sendRequest, responseFriendRequest, getFollowersList, getFollowingsList, unfollowUser, getAllUsers, searchUser, updateProfile, blockUser }; }; export default userControllers;
src/adapters/controllers/userControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " comment: updateResult\n })\n })\n const commentReply = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, postId } = req.params;\n const { comment, reply } = req.body;\n const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost)\n res.json({\n status: updateResult\n })", "score": 0.9184536933898926 }, { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9140812754631042 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " res.json({\n status: 'like update success'\n })\n })\n const commentPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { postId, userId } = req.params;\n const { comment } = req.body\n const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost)\n res.json({\n status: 'comment success',", "score": 0.9062588810920715 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " const { postId } = req.params;\n const { description } = req.body;\n const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost)\n res.json({\n status: 'post update success',\n response: postEditResult\n })\n })\n const reportPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, postId } = req.params;", "score": 0.9049467444419861 }, { "filename": "src/adapters/controllers/messageController.ts", "retrieved_chunk": " res.json({\n status: 'success',\n response: createResponse\n })\n })\n const getUserMessages = expressAsyncHandler(async(req: Request, res: Response) => {\n const { chatId } = req.params;\n const messages = await getMessages(chatId, messageRepository);\n res.json({\n status: 'Message fetch success',", "score": 0.9047244191169739 } ]
typescript
status = await requestFriendResponse(id, friendId, response, dbRepositoryUser) res.json({
import { Request, Response } from "express"; import expressAsyncHandler from "express-async-handler"; import { postRepositoryType } from "../../framework/database/Mongodb/repositories/postRepositeries"; import { postDbInterfaceType } from "../../application/repositories/postDbRepositories"; import { getAllPost, postCreate, getPostsByUser, getPostById, deletePostById, updateLike, insertComment, deleteComment, postEdit, postReport, getReportedUsers, replyComment } from '../../application/useCases/post/post' const postControllers = (postDbInterface: postDbInterfaceType, postRepositoryType: postRepositoryType) => { const dbRepositoriesPost = postDbInterface(postRepositoryType()) const getPosts = expressAsyncHandler(async (req: Request, res: Response) => { const posts = await getAllPost(dbRepositoriesPost) res.json({ status: "success", posts }) }) const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, description, userName, image, video } = req.body; const body = { userId, description, userName, image, video }; const newPost = await postCreate(body, dbRepositoriesPost); res.json({ status: 'upload-success', newPost }) }) const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => { const { userId } = req.params; const posts: any = await getPostsByUser(userId, dbRepositoriesPost); res.json({ status: 'posts find success', posts }) }) const getPost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const post: any = await getPostById(id, dbRepositoriesPost); res.json({ status: 'post find success', post }) }) const deletePost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const deletedData = await deletePostById(id, dbRepositoriesPost) res.json({ status: 'Deleted success', deletedData }) }) const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => { const { id, userId } = req.query;
await updateLike(id, userId, dbRepositoriesPost) res.json({
status: 'like update success' }) }) const commentPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, userId } = req.params; const { comment } = req.body const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost) res.json({ status: 'comment success', comment: updateResult }) }) const commentReply = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { comment, reply } = req.body; const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({ status: updateResult }) }) const commentDelete = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, index } = req.params; const deleteResult = await deleteComment(postId, index, dbRepositoriesPost) res.json({ status: 'comment deleted', deletedComment: deleteResult }) }) const editPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const { description } = req.body; const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost) res.json({ status: 'post update success', response: postEditResult }) }) const reportPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { reason } = req.body; const repostResponse = await postReport(userId, postId, reason, dbRepositoriesPost) res.json({ status: 'posted success', response: repostResponse }) }) const getReporters = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const users = await getReportedUsers(postId, dbRepositoriesPost); res.json({ status: 'reposted users fetched', users }) }) return { getPosts, uploadPost, getUserPosts, getPost, deletePost, postLikeUpdate, commentPost, commentReply, commentDelete, editPost, reportPost, getReporters } } export default postControllers;
src/adapters/controllers/postControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/authControllers.ts", "retrieved_chunk": " user,\n token\n })\n })\n const blockUser = asyncHandler(async(req: Request, res: Response) => {\n const { id } = req.params;\n const blockResult = await userBlock(id, dbUserRepository);\n res.json({\n status: `${blockResult} success`\n })", "score": 0.9115724563598633 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const getUserById = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const user = await userById(id, dbRepositoryUser)\n res.json({\n status: \"success\",\n user\n });\n });\n // get followers list of the user\n const getFollowersList = asyncHandler(async (req: Request, res: Response) => {", "score": 0.9102077484130859 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " // get all users list\n const getAllUsers = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const users = await getUserDetails(id, dbRepositoryUser);\n res.json({\n status: 'Get users success',\n users\n })\n })\n // get a user details by id", "score": 0.9083282947540283 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const followingList: any = await followings(id, dbRepositoryUser);\n res.json({\n status: 'get following success',\n followings: followingList\n })\n })\n // send friend request to user\n const sendRequest = asyncHandler(async (req: Request, res: Response) => {\n const { id, friendId } = req.params;\n const response = await requestFriend(id, friendId, dbRepositoryUser);", "score": 0.9071369767189026 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const { id } = req.params;\n const followersList: any = await followers(id, dbRepositoryUser);\n res.json({\n status: 'get followers success',\n followers: followersList\n })\n })\n // get following list of the user\n const getFollowingsList = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;", "score": 0.9057218432426453 } ]
typescript
await updateLike(id, userId, dbRepositoriesPost) res.json({
import Post from "../models/postModel"; import User from "../models/userModel"; import { ObjectId } from 'mongodb' import cloudinary from 'cloudinary' // post database operations export const postRepositoryMongoDb = () => { const getAllPost = async () => { return await Post.find().sort({ createdAt: -1 }); } const uploadPost = (async (post: { userId: string; description: string; image: string; video: string; userName: string; }) => { const newpost = new Post(post); return await newpost.save(); }) const getPostsByUser = async (userId: any) => { return await Post.find({ userId }) } const getPostById = async (_id: string) => { const posts = await Post.findById({ _id: new ObjectId(_id) }) return posts; } const deletePost = async (_id: string) => { const deletedData = await Post.findByIdAndDelete({ _id: new ObjectId(_id) }) return deletedData } const dislikePost = async (_id: string, userId: string) => { await Post.findByIdAndUpdate({ _id }, { $pull: { likes: userId } }) } const likePost = async (_id: string, userId: string) => { await Post.findByIdAndUpdate({ _id }, { $push: { likes: userId } }) } const insertComment = async (postId: string, userId: string, comment: string) => { const updateResult = await Post.findByIdAndUpdate({ _id: postId }, { $push: { comments: { userId, comment, reply: [] } } }); return updateResult; } const replyComment = async (_id: string, userId: string, comment: string, reply: string) => {
const updateResult = await Post.updateOne( { _id, "comments.comment": comment }, {
$push: { "comments.$.reply": { userId, reply } } } ); return updateResult; }; const editPost = async (_id: string, description: any) => { const updateResult = await Post.findByIdAndUpdate({ _id }, { $set: { description } }) return updateResult } const reportPost = async (userId: string, postId: string, reason: any) => { const repostResponse = await Post.findByIdAndUpdate({ _id: postId }, { $push: { reports: { userId, reason } } }) return repostResponse; } const getReportedUsers = async (postId: string) => { const postDetails: any = await Post.findOne({ _id: postId }); const users: any = await Promise.all( postDetails.reports.map(async ({ userId }: any) => { return await User.findOne({ _id: userId }) }) ) return users; } return { getAllPost, uploadPost, getPostsByUser, getPostById, deletePost, dislikePost, likePost, insertComment, replyComment, editPost, reportPost, getReportedUsers } } export type postRepositoryType = typeof postRepositoryMongoDb;
src/framework/database/Mongodb/repositories/postRepositeries.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/application/repositories/postDbRepositories.ts", "retrieved_chunk": " }\n const replyComment = async(postId: string,userId: string, comment: string, reply: string) => {\n const response = await repositories.replyComment(postId,userId, comment, reply);\n return response\n }\n const editPost = async(postId: string, body: any) => {\n const editPost = await repositories.editPost(postId, body)\n return editPost\n }\n const reportPost = async(userId: string, postId: string, reason: any) => {", "score": 0.9003947973251343 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " res.json({\n status: 'like update success'\n })\n })\n const commentPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { postId, userId } = req.params;\n const { comment } = req.body\n const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost)\n res.json({\n status: 'comment success',", "score": 0.8940907120704651 }, { "filename": "src/application/repositories/postDbRepositories.ts", "retrieved_chunk": " }\n const dislikePost = async (id: string, userId: string) => {\n await repositories.dislikePost(id, userId)\n }\n const likePost = async (id: string, userId: string) => {\n await repositories.likePost(id, userId)\n }\n const insertComment = async(postId: string, userId: string, comment: string) => {\n const insertResult = await repositories.insertComment(postId, userId, comment);\n return insertResult", "score": 0.8897296190261841 }, { "filename": "src/framework/database/Mongodb/repositories/userRepositories.ts", "retrieved_chunk": " gender,\n city,\n }\n }, { new: true });\n return updateResult;\n };\n const blockUser = async (_id: string) => {\n await User.findByIdAndUpdate({ _id }, {\n $set: { isBlock: true }\n })", "score": 0.8871095180511475 }, { "filename": "src/framework/database/Mongodb/repositories/userRepositories.ts", "retrieved_chunk": " };\n const findFriend = async (_id: string, friendId: any) => {\n const user: any = await User.findOne({ _id })\n const isUserExist: any = await user.followers.find((user: any) => user === friendId)\n return isUserExist;\n }\n const sendRequest = async (id: string, userName: string, friendName: string, dp: any, friendDp: string, friendId: string) => {\n await User.updateOne({ _id: friendId }, {\n $push: { requests: { id, userName, dp } }\n })", "score": 0.8831440210342407 } ]
typescript
const updateResult = await Post.updateOne( { _id, "comments.comment": comment }, {
import { Request, Response } from "express"; import expressAsyncHandler from "express-async-handler"; import { postRepositoryType } from "../../framework/database/Mongodb/repositories/postRepositeries"; import { postDbInterfaceType } from "../../application/repositories/postDbRepositories"; import { getAllPost, postCreate, getPostsByUser, getPostById, deletePostById, updateLike, insertComment, deleteComment, postEdit, postReport, getReportedUsers, replyComment } from '../../application/useCases/post/post' const postControllers = (postDbInterface: postDbInterfaceType, postRepositoryType: postRepositoryType) => { const dbRepositoriesPost = postDbInterface(postRepositoryType()) const getPosts = expressAsyncHandler(async (req: Request, res: Response) => { const posts = await getAllPost(dbRepositoriesPost) res.json({ status: "success", posts }) }) const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, description, userName, image, video } = req.body; const body = { userId, description, userName, image, video }; const newPost = await postCreate(body, dbRepositoriesPost); res.json({ status: 'upload-success', newPost }) }) const getUserPosts = expressAsyncHandler(async (req: Request, res: Response) => { const { userId } = req.params; const posts: any = await getPostsByUser(userId, dbRepositoriesPost); res.json({ status: 'posts find success', posts }) }) const getPost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const post: any = await getPostById(id, dbRepositoriesPost); res.json({ status: 'post find success', post }) }) const deletePost = expressAsyncHandler(async (req: Request, res: Response) => { const { id } = req.params; const deletedData = await deletePostById(id, dbRepositoriesPost) res.json({ status: 'Deleted success', deletedData }) }) const postLikeUpdate = expressAsyncHandler(async (req: Request, res: Response) => { const { id, userId } = req.query; await updateLike(id, userId, dbRepositoriesPost) res.json({ status: 'like update success' }) }) const commentPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, userId } = req.params; const { comment } = req.body const updateResult = await insertComment(postId, userId, comment, dbRepositoriesPost) res.json({ status: 'comment success', comment: updateResult }) }) const commentReply = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { comment, reply } = req.body; const updateResult = await replyComment(postId, userId, comment, reply, dbRepositoriesPost) res.json({ status: updateResult }) }) const commentDelete = expressAsyncHandler(async (req: Request, res: Response) => { const { postId, index } = req.params; const deleteResult = await deleteComment(postId, index, dbRepositoriesPost) res.json({ status: 'comment deleted', deletedComment: deleteResult }) }) const editPost = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const { description } = req.body; const postEditResult: any = await postEdit(postId, description, dbRepositoriesPost) res.json({ status: 'post update success', response: postEditResult }) }) const reportPost = expressAsyncHandler(async (req: Request, res: Response) => { const { userId, postId } = req.params; const { reason } = req.body; const repostResponse = await postReport(userId, postId, reason, dbRepositoriesPost) res.json({ status: 'posted success', response: repostResponse }) }) const getReporters = expressAsyncHandler(async (req: Request, res: Response) => { const { postId } = req.params; const users
= await getReportedUsers(postId, dbRepositoriesPost);
res.json({ status: 'reposted users fetched', users }) }) return { getPosts, uploadPost, getUserPosts, getPost, deletePost, postLikeUpdate, commentPost, commentReply, commentDelete, editPost, reportPost, getReporters } } export default postControllers;
src/adapters/controllers/postControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/application/repositories/postDbRepositories.ts", "retrieved_chunk": " const repostResponse = await repositories.reportPost(userId, postId, reason);\n return repostResponse;\n }\n const getReportedUsers = async (postId: string) => {\n const users = await repositories.getReportedUsers(postId);\n return users;\n }\n return {\n getAllPost,\n uploadPost,", "score": 0.9189969897270203 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " // get all users list\n const getAllUsers = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const users = await getUserDetails(id, dbRepositoryUser);\n res.json({\n status: 'Get users success',\n users\n })\n })\n // get a user details by id", "score": 0.9173851013183594 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const { id } = req.params;\n const followersList: any = await followers(id, dbRepositoryUser);\n res.json({\n status: 'get followers success',\n followers: followersList\n })\n })\n // get following list of the user\n const getFollowingsList = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;", "score": 0.9101948738098145 }, { "filename": "src/framework/database/Mongodb/repositories/postRepositeries.ts", "retrieved_chunk": " }\n const reportPost = async (userId: string, postId: string, reason: any) => {\n const repostResponse = await Post.findByIdAndUpdate({ _id: postId }, {\n $push: { reports: { userId, reason } }\n })\n return repostResponse;\n }\n const getReportedUsers = async (postId: string) => {\n const postDetails: any = await Post.findOne({ _id: postId });\n const users: any = await Promise.all(", "score": 0.9067165851593018 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const getUserById = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const user = await userById(id, dbRepositoryUser)\n res.json({\n status: \"success\",\n user\n });\n });\n // get followers list of the user\n const getFollowersList = asyncHandler(async (req: Request, res: Response) => {", "score": 0.9037980437278748 } ]
typescript
= await getReportedUsers(postId, dbRepositoriesPost);
import Post from "../models/postModel"; import User from "../models/userModel"; import { ObjectId } from 'mongodb' import cloudinary from 'cloudinary' // post database operations export const postRepositoryMongoDb = () => { const getAllPost = async () => { return await Post.find().sort({ createdAt: -1 }); } const uploadPost = (async (post: { userId: string; description: string; image: string; video: string; userName: string; }) => { const newpost = new Post(post); return await newpost.save(); }) const getPostsByUser = async (userId: any) => { return await Post.find({ userId }) } const getPostById = async (_id: string) => { const posts = await Post.findById({ _id: new ObjectId(_id) }) return posts; } const deletePost = async (_id: string) => { const deletedData = await Post.findByIdAndDelete({ _id: new ObjectId(_id) }) return deletedData } const dislikePost = async (_id: string, userId: string) => { await Post.findByIdAndUpdate({ _id }, { $pull: { likes: userId } }) } const likePost = async (_id: string, userId: string) => { await Post.findByIdAndUpdate({ _id }, { $push: { likes: userId } }) } const insertComment = async (postId: string, userId: string, comment: string) => { const updateResult = await Post.findByIdAndUpdate({ _id: postId }, { $push: { comments: { userId, comment, reply: [] } } }); return updateResult; } const replyComment = async (_id: string, userId: string, comment: string, reply: string) => { const updateResult = await Post.updateOne( { _id, "comments.comment": comment }, { $push: { "comments.$.reply": { userId, reply } } } ); return updateResult; }; const editPost = async (_id: string, description: any) => { const updateResult = await Post.findByIdAndUpdate({ _id }, { $set: { description } }) return updateResult } const reportPost = async (userId: string, postId: string, reason: any) => { const repostResponse = await Post.findByIdAndUpdate({ _id: postId }, { $push: { reports: { userId, reason } } }) return repostResponse; } const getReportedUsers = async (postId: string) => { const postDetails: any = await Post.findOne({ _id: postId }); const users: any = await Promise.all( postDetails.reports.map(async ({ userId }: any) => { return await User.
findOne({ _id: userId }) }) ) return users;
} return { getAllPost, uploadPost, getPostsByUser, getPostById, deletePost, dislikePost, likePost, insertComment, replyComment, editPost, reportPost, getReportedUsers } } export type postRepositoryType = typeof postRepositoryMongoDb;
src/framework/database/Mongodb/repositories/postRepositeries.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/framework/database/Mongodb/repositories/userRepositories.ts", "retrieved_chunk": " return followers;\n };\n const getFollowings = async (_id: string) => {\n const user: any = await User.findOne({ _id });\n const followings: any[] = await Promise.all(\n user.following.map(async (following: any) => {\n return await User.findOne({ _id: following });\n })\n );\n return followings;", "score": 0.9129903316497803 }, { "filename": "src/framework/database/Mongodb/repositories/userRepositories.ts", "retrieved_chunk": " throw error;\n }\n };\n const getFollowers = async (_id: string) => {\n const user: any = await User.findOne({ _id });\n const followers: any[] = await Promise.all(\n user.followers.map(async (follower: any) => {\n return await User.findOne({ _id: follower });\n })\n );", "score": 0.9072834253311157 }, { "filename": "src/framework/database/Mongodb/repositories/userRepositories.ts", "retrieved_chunk": " };\n const getUserByUserName = async (userName: string) => {\n const user: any = await User.findOne({ userName })\n return user;\n };\n const getUserById = async (id: string) => {\n try {\n const user: any = await User.findOne({ _id: id }).select('-password');\n return user;\n } catch (error) {", "score": 0.896884024143219 }, { "filename": "src/application/repositories/postDbRepositories.ts", "retrieved_chunk": " const repostResponse = await repositories.reportPost(userId, postId, reason);\n return repostResponse;\n }\n const getReportedUsers = async (postId: string) => {\n const users = await repositories.getReportedUsers(postId);\n return users;\n }\n return {\n getAllPost,\n uploadPost,", "score": 0.8958873152732849 }, { "filename": "src/application/repositories/postDbRepositories.ts", "retrieved_chunk": " }) => { return repositories.uploadPost(post)}\n const getPostsByUser = async (userId: string) => {\n return await repositories.getPostsByUser(userId)\n };\n const getPostById =async (id:string) => {\n return await repositories.getPostById(id)\n }\n const deletePost = async (id: string) => {\n const deletedData = await repositories.deletePost(id)\n return deletedData;", "score": 0.8951233625411987 } ]
typescript
findOne({ _id: userId }) }) ) return users;
import { Request, Response } from 'express'; import asyncHandler from 'express-async-handler'; import { AuthServices } from '../../framework/services/authServices'; import { AuthServiceInterface } from '../../application/services/authServiceInterface'; import { UserDbInterface } from '../../application/repositories/userDbRepositories'; import { userRepositoryMongoDB } from '../../framework/database/Mongodb/repositories/userRepositories'; import { userRegister, userLogin, googleAuthLogin, userBlock} from '../../application/useCases/auth/userAuth'; // authentication controllers const authControllers = ( authServiceInterface: AuthServiceInterface, authService: AuthServices, userDbInterface: UserDbInterface, userDbservice: userRepositoryMongoDB ) => { const dbUserRepository = userDbInterface(userDbservice()); const authServices = authServiceInterface(authService()); const registerUser = asyncHandler(async(req: Request, res: Response) => { const { name, userName, number,email, password } = req.body; const user = { name, userName, number, email, password, }; const token = await userRegister(user, dbUserRepository, authServices); res.json({ status:"success", message: "User registered", token }); }); const loginUser = asyncHandler(async(req: Request, res: Response) => { const { userName, password } : { userName: string; password: string} = req.body; const token = await userLogin(userName, password, dbUserRepository, authServices); // res.setHeader('authorization', token.token); res.json({ status: "success", message: "user verified", token }); }); const googleAuth = asyncHandler(async(req: Request, res: Response) => { console.log('-----------------------'); const { fullName, firstName, email } = req.body; const userData: any = { name:fullName, userName:firstName, number: 7594837203, email } console.log(userData); const {user,
token} = await googleAuthLogin(userData, dbUserRepository, authServices) res.json({
status:'Google login success', user, token }) }) const blockUser = asyncHandler(async(req: Request, res: Response) => { const { id } = req.params; const blockResult = await userBlock(id, dbUserRepository); res.json({ status: `${blockResult} success` }) }) return { registerUser, loginUser, googleAuth, blockUser }; }; export default authControllers;
src/adapters/controllers/authControllers.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " users\n })\n })\n // update profile informations\n const updateProfile = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const { userName, bio, gender, city, file } = req.body;\n const updateResult = await updateProfileInfo(id, { userName, file, bio, gender, city }, dbRepositoryUser);\n res.json({\n status: 'Update success',", "score": 0.8932450413703918 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " })\n })\n // search user \n const searchUser = asyncHandler(async (req: Request, res: Response) => {\n const { prefix } = req.params;\n const { type } = req.query;\n console.log(type, 'par');\n const users: any = await searchUserByPrefix(prefix, type, dbRepositoryUser);\n res.json({\n status: 'searched success',", "score": 0.8853877186775208 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " const getUserById = asyncHandler(async (req: Request, res: Response) => {\n const { id } = req.params;\n const user = await userById(id, dbRepositoryUser)\n res.json({\n status: \"success\",\n user\n });\n });\n // get followers list of the user\n const getFollowersList = asyncHandler(async (req: Request, res: Response) => {", "score": 0.8790460824966431 }, { "filename": "src/adapters/controllers/adminAuthController.ts", "retrieved_chunk": " authService: AuthServices,\n adminDbInterface: AdminDbInterface,\n adminDbservice: adminRepositoryMongoDB\n) => {\n const dbAdminRepository = adminDbInterface(adminDbservice());\n const authServices = authServiceInterface(authService());\n const loginAdmin = asyncHandler(async(req: Request, res: Response) => {\n console.log('-------------------------------------------------------'); \n const { email, password } = req.body;\n const token = await adminLogin(email, password, dbAdminRepository, authServices)", "score": 0.8786494731903076 }, { "filename": "src/adapters/controllers/postControllers.ts", "retrieved_chunk": " status: \"success\",\n posts\n })\n })\n const uploadPost = expressAsyncHandler(async (req: Request, res: Response) => {\n const { userId, description, userName, image, video } = req.body;\n const body = { userId, description, userName, image, video };\n const newPost = await postCreate(body, dbRepositoriesPost);\n res.json({\n status: 'upload-success',", "score": 0.878462553024292 } ]
typescript
token} = await googleAuthLogin(userData, dbUserRepository, authServices) res.json({
import User from "../models/userModel"; export const userRepositoryMongoDB = () => { const addUser = async (user: { name: string; userName: string; email: string; number?: number; password?: string; }) => { const newUser = new User(user); return await newUser.save(); }; const getAllUsers = async () => { const users: any = await User.find(); // const users: any = await User.find({ _id: { $ne: '646fa8515333e77cdec159c2' }, followers: { $nin: ['6471800e2ed680381cbae276', '6477705ef858f715f868093a'] } }); return users; } const getUserByEmail = async (email: string) => { const user: any = await User.findOne({ email }).select('-password'); return user }; const getUserByUserName = async (userName: string) => { const user: any = await User.findOne({ userName }) return user; }; const getUserById = async (id: string) => { try { const user: any = await User.findOne({ _id: id }).select('-password'); return user; } catch (error) { throw error; } }; const getFollowers = async (_id: string) => { const user: any = await User.findOne({ _id }); const followers: any[] = await Promise.all( user.followers.map(async (follower: any) => { return await User.findOne({ _id: follower }); }) ); return followers; }; const getFollowings = async (_id: string) => { const user: any = await User.findOne({ _id }); const followings: any[] = await Promise.all( user.following.map(async (following: any) => { return await User.findOne({ _id: following }); }) ); return followings; }; const findFriend = async (_id: string, friendId: any) => { const user: any = await User.findOne({ _id }) const isUserExist: any = await user.followers.find((user: any) => user === friendId) return isUserExist; } const sendRequest = async (id: string, userName: string, friendName: string, dp: any, friendDp: string, friendId: string) => {
await User.updateOne({ _id: friendId }, {
$push: { requests: { id, userName, dp } } }) await User.updateOne({ _id: id }, { $push: { requested: { id: friendId, userName: friendName, dp: friendDp } } }) return; } const cancelRequest = async (id: string, friendId: string) => { await User.updateOne({ _id: friendId }, { $pull: { requests: { id } } }) await User.updateOne({ _id: id }, { $pull: { requested: { id: friendId } } }) return; } const unfollowFriend = async (_id: string, friendId: string) => { // remove friend from user follower list await User.findByIdAndUpdate({ _id }, { $pull: { followers: friendId } }); await User.findByIdAndUpdate({ _id: friendId }, { $pull: { following: _id } }) const friendDetails: any = await User.findOne({ _id: friendId }); return friendDetails } const followFriend = async (_id: string, friendId: string) => { // add friend to user follower list await User.findByIdAndUpdate({ _id }, { $push: { followers: friendId } }); await User.findByIdAndUpdate({ _id: friendId }, { $push: { following: _id } }) const friendDetails: any = await User.findOne({ _id: friendId }); return friendDetails } const searchUser = async (prefix: any, type: any) => { if (type === 'userName') { const regex = new RegExp(`^${prefix}`, 'i'); const users = await User.find({ userName: regex }); return users } else if (type === 'gender') { const regex = new RegExp(`^${prefix}`, 'i'); const users = await User.find({ gender: regex }); return users } else { const regex = new RegExp(`^${prefix}`, 'i'); const users = await User.find({ city: regex }); return users } } const updateProfile = async (_id: string, data: { userName: string, file: string, bio: string, gender: string, city: string }) => { const { userName, file, bio, gender, city } = data; const updateResult = await User.findByIdAndUpdate(_id, { $set: { userName, dp: file, bio, gender, city, } }, { new: true }); return updateResult; }; const blockUser = async (_id: string) => { await User.findByIdAndUpdate({ _id }, { $set: { isBlock: true } }) return 'Blocked' } const unBlockUser = async (_id: string) => { await User.findByIdAndUpdate({ _id }, { $set: { isBlock: false } }) return 'UnBlocked' } const blockUserByUser = async (blockingUser: string, blockedUser: string) => { await User.findByIdAndUpdate({ _id: blockedUser }, { $push: { blockedUsers: blockingUser } }); await User.findByIdAndUpdate({ _id: blockingUser }, { $push: { blockingUsers: blockedUser } }); return 'Blocked'; } const unBlockUserByUser = async (blockingUser: string, blockedUser: string) => { await User.findByIdAndUpdate({ _id: blockedUser }, { $pull: { blockedUsers: blockingUser } }); await User.findByIdAndUpdate({ _id: blockingUser }, { $pull: { blockingUsers: blockedUser } }); return 'Unblocked'; } return { addUser, getUserByEmail, getUserByUserName, getUserById, getFollowers, getFollowings, findFriend, sendRequest, cancelRequest, unfollowFriend, followFriend, getAllUsers, searchUser, updateProfile, blockUser, unBlockUser, blockUserByUser, unBlockUserByUser }; } export type userRepositoryMongoDB = typeof userRepositoryMongoDB;
src/framework/database/Mongodb/repositories/userRepositories.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/application/repositories/userDbRepositories.ts", "retrieved_chunk": " return await repository.findFriend(id, friendId);\n }\n const sendRequest = async (id: string, userName: string, friendName: string, dp: any, friendDp: string, friendId: string) => {\n return await repository.sendRequest(id, userName, friendName,dp, friendDp, friendId);\n }\n const cancelRequest = async (id: string, friendId: string) => {\n return await repository.cancelRequest(id, friendId);\n }\n const unfollowFriend = async (id: string, friendId: string) => {\n return await repository.unfollowFriend(id, friendId)", "score": 0.9105034470558167 }, { "filename": "src/application/repositories/userDbRepositories.ts", "retrieved_chunk": " const getUserById = async (id: string) => {\n return await repository.getUserById(id);\n };\n const getFollowers = async (id: string) => {\n return await repository.getFollowers(id);\n };\n const getFollowings = async (id: string) => {\n return await repository.getFollowings(id);\n };\n const findFriend = async (id: string, friendId: string) => {", "score": 0.9064512252807617 }, { "filename": "src/application/repositories/userDbRepositories.ts", "retrieved_chunk": " }\n const followFriend = async (id: string, friendId: string) => {\n return await repository.followFriend(id, friendId)\n }\n const searchUser = async (prefix: string, type: string) => {\n return await repository.searchUser(prefix, type);\n }\n const updateProfile = async (id: string, body: any) => {\n return await repository.updateProfile(id, body)\n }", "score": 0.9037235975265503 }, { "filename": "src/application/useCases/user/user.ts", "retrieved_chunk": " await repository.cancelRequest(friendId, id);\n return 'Request rejected'\n }\n}\nexport const unfollow = async (id: any, friendId: any, repository: ReturnType<UserDbInterface>) => {\n // this friend is already a follower\n const friend: any = await repository.unfollowFriend(id, friendId);\n return {\n status: 'unfollow',\n friend", "score": 0.9022518992424011 }, { "filename": "src/application/useCases/user/user.ts", "retrieved_chunk": "}\nexport const requestFriend = async (id: string, friendId: string, repository: ReturnType<UserDbInterface>) => {\n const { userName, dp } = await repository.getUserById(id);\n const { requests, userName: friendName, dp: friendDp } = await repository.getUserById(friendId);\n // check user is already in request list\n const isRequested = requests.find((request: any) => request.id === id);\n if (isRequested) {\n await repository.cancelRequest(id, friendId);\n return 'Request canceled';\n } else {", "score": 0.9002214074134827 } ]
typescript
await User.updateOne({ _id: friendId }, {
import User from "../models/userModel"; export const userRepositoryMongoDB = () => { const addUser = async (user: { name: string; userName: string; email: string; number?: number; password?: string; }) => { const newUser = new User(user); return await newUser.save(); }; const getAllUsers = async () => { const users: any = await User.find(); // const users: any = await User.find({ _id: { $ne: '646fa8515333e77cdec159c2' }, followers: { $nin: ['6471800e2ed680381cbae276', '6477705ef858f715f868093a'] } }); return users; } const getUserByEmail = async (email: string) => { const user: any = await User.findOne({ email }).select('-password'); return user }; const getUserByUserName = async (userName: string) => { const user: any = await User.findOne({ userName }) return user; }; const getUserById = async (id: string) => { try { const user: any = await User.findOne({ _id: id }).select('-password'); return user; } catch (error) { throw error; } }; const getFollowers = async (_id: string) => { const user: any = await User.findOne({ _id }); const followers: any[] = await Promise.all( user.followers.map(async (follower: any) => { return await User.findOne({ _id: follower }); }) ); return followers; }; const getFollowings = async (_id: string) => { const user: any = await User.findOne({ _id }); const followings: any[] = await Promise.all( user.following.map(async (following: any) => { return await User.findOne({ _id: following }); }) ); return followings; }; const findFriend = async (_id: string, friendId: any) => { const user: any = await User.findOne({ _id }) const isUserExist: any = await user.followers.find((user: any) => user === friendId) return isUserExist; } const sendRequest = async (id: string, userName: string, friendName: string, dp: any, friendDp: string, friendId: string) => { await User.updateOne({ _id: friendId }, { $push: { requests: { id, userName, dp } } }) await User.updateOne({ _id: id }, { $push: { requested: { id: friendId, userName: friendName, dp: friendDp } } }) return; } const cancelRequest = async (id: string, friendId: string) => { await User.updateOne({ _id: friendId }, { $pull: { requests: { id } } }) await User.updateOne({ _id: id }, { $pull: { requested: { id: friendId } } }) return; } const unfollowFriend = async (_id: string, friendId: string) => { // remove friend from user follower list
await User.findByIdAndUpdate({ _id }, { $pull: { followers: friendId } });
await User.findByIdAndUpdate({ _id: friendId }, { $pull: { following: _id } }) const friendDetails: any = await User.findOne({ _id: friendId }); return friendDetails } const followFriend = async (_id: string, friendId: string) => { // add friend to user follower list await User.findByIdAndUpdate({ _id }, { $push: { followers: friendId } }); await User.findByIdAndUpdate({ _id: friendId }, { $push: { following: _id } }) const friendDetails: any = await User.findOne({ _id: friendId }); return friendDetails } const searchUser = async (prefix: any, type: any) => { if (type === 'userName') { const regex = new RegExp(`^${prefix}`, 'i'); const users = await User.find({ userName: regex }); return users } else if (type === 'gender') { const regex = new RegExp(`^${prefix}`, 'i'); const users = await User.find({ gender: regex }); return users } else { const regex = new RegExp(`^${prefix}`, 'i'); const users = await User.find({ city: regex }); return users } } const updateProfile = async (_id: string, data: { userName: string, file: string, bio: string, gender: string, city: string }) => { const { userName, file, bio, gender, city } = data; const updateResult = await User.findByIdAndUpdate(_id, { $set: { userName, dp: file, bio, gender, city, } }, { new: true }); return updateResult; }; const blockUser = async (_id: string) => { await User.findByIdAndUpdate({ _id }, { $set: { isBlock: true } }) return 'Blocked' } const unBlockUser = async (_id: string) => { await User.findByIdAndUpdate({ _id }, { $set: { isBlock: false } }) return 'UnBlocked' } const blockUserByUser = async (blockingUser: string, blockedUser: string) => { await User.findByIdAndUpdate({ _id: blockedUser }, { $push: { blockedUsers: blockingUser } }); await User.findByIdAndUpdate({ _id: blockingUser }, { $push: { blockingUsers: blockedUser } }); return 'Blocked'; } const unBlockUserByUser = async (blockingUser: string, blockedUser: string) => { await User.findByIdAndUpdate({ _id: blockedUser }, { $pull: { blockedUsers: blockingUser } }); await User.findByIdAndUpdate({ _id: blockingUser }, { $pull: { blockingUsers: blockedUser } }); return 'Unblocked'; } return { addUser, getUserByEmail, getUserByUserName, getUserById, getFollowers, getFollowings, findFriend, sendRequest, cancelRequest, unfollowFriend, followFriend, getAllUsers, searchUser, updateProfile, blockUser, unBlockUser, blockUserByUser, unBlockUserByUser }; } export type userRepositoryMongoDB = typeof userRepositoryMongoDB;
src/framework/database/Mongodb/repositories/userRepositories.ts
RoshanDasan-clean-architecture-Node.js-0f6a879
[ { "filename": "src/framework/database/Mongodb/repositories/postRepositeries.ts", "retrieved_chunk": " const dislikePost = async (_id: string, userId: string) => {\n await Post.findByIdAndUpdate({ _id },\n { $pull: { likes: userId } })\n }\n const likePost = async (_id: string, userId: string) => {\n await Post.findByIdAndUpdate({ _id },\n { $push: { likes: userId } })\n }\n const insertComment = async (postId: string, userId: string, comment: string) => {\n const updateResult = await Post.findByIdAndUpdate({ _id: postId }, {", "score": 0.8833789229393005 }, { "filename": "src/application/useCases/user/user.ts", "retrieved_chunk": " await repository.cancelRequest(friendId, id);\n return 'Request rejected'\n }\n}\nexport const unfollow = async (id: any, friendId: any, repository: ReturnType<UserDbInterface>) => {\n // this friend is already a follower\n const friend: any = await repository.unfollowFriend(id, friendId);\n return {\n status: 'unfollow',\n friend", "score": 0.8777575492858887 }, { "filename": "src/adapters/controllers/userControllers.ts", "retrieved_chunk": " status\n })\n })\n // insert followers to user\n const unfollowUser = asyncHandler(async (req: Request, res: Response) => {\n const { id, friendId } = req.query;\n const { status, friend }: any = await unfollow(id, friendId, dbRepositoryUser);\n res.json({\n status,\n friend", "score": 0.8599311113357544 }, { "filename": "src/application/repositories/userDbRepositories.ts", "retrieved_chunk": " const getUserById = async (id: string) => {\n return await repository.getUserById(id);\n };\n const getFollowers = async (id: string) => {\n return await repository.getFollowers(id);\n };\n const getFollowings = async (id: string) => {\n return await repository.getFollowings(id);\n };\n const findFriend = async (id: string, friendId: string) => {", "score": 0.8531462550163269 }, { "filename": "src/framework/database/Mongodb/repositories/postRepositeries.ts", "retrieved_chunk": " }\n const reportPost = async (userId: string, postId: string, reason: any) => {\n const repostResponse = await Post.findByIdAndUpdate({ _id: postId }, {\n $push: { reports: { userId, reason } }\n })\n return repostResponse;\n }\n const getReportedUsers = async (postId: string) => {\n const postDetails: any = await Post.findOne({ _id: postId });\n const users: any = await Promise.all(", "score": 0.8507903814315796 } ]
typescript
await User.findByIdAndUpdate({ _id }, { $pull: { followers: friendId } });
import * as core from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { DiffInfo, EventInfo, Junit } from './types'; export const commentCoverage = async ( eventInfo: EventInfo, body: string, ): Promise<void> => { const { eventName, payload } = context; const octokit = getOctokit(eventInfo.token); if (eventName === 'push') { await octokit.rest.repos.createCommitComment({ repo: eventInfo.repo, owner: eventInfo.owner, commit_sha: eventInfo.commitSha, body, }); } else if (eventName === 'pull_request') { if (eventInfo.overrideComment) { const { data: comments } = await octokit.rest.issues.listComments({ repo: eventInfo.repo, owner: eventInfo.owner, issue_number: payload.pull_request ? payload.pull_request.number : 0, }); const comment = comments.find( (comment) => comment.user?.login === 'github-actions[bot]' && comment.body?.startsWith(eventInfo.commentId), ); if (comment) { await octokit.rest.issues.updateComment({ repo: eventInfo.repo, owner: eventInfo.owner, comment_id: comment.id, body, }); } else { await octokit.rest.issues.createComment({ repo: eventInfo.repo, owner: eventInfo.owner, issue_number: payload.pull_request?.number || 0, body, }); } } else { await octokit.rest.issues.createComment({ repo: eventInfo.repo, owner: eventInfo.owner, issue_number: payload.pull_request?.number || 0, body, }); } } }; export const buildBody = ( eventInfo: EventInfo,
junitInfo: Junit | undefined, diffsInfo: DiffInfo[], ): string => {
let body = `${eventInfo.commentId}\n`; body += `## ${eventInfo.commentTitle} :page_facing_up:\n`; body += buildTestsStatusMarkdown(junitInfo); body += buildJunitMarkdown(eventInfo, junitInfo); body += buildDiffCoverHtml(eventInfo, diffsInfo); return body; }; const buildTestsStatusMarkdown = (junitInfo: Junit | undefined) => { if (junitInfo) { const markdown = junitInfo.failures?.count || junitInfo.errors ? '### Tests Failure :x:' : '### Tests Succees :white_check_mark:'; return `${markdown}\n`; } return ''; }; const buildJunitMarkdown = (eventInfo: EventInfo, junitInfo: Junit | undefined) => { if (eventInfo.showJunit && junitInfo) { let markdown = `| Total Tests | Failures ${ junitInfo.failures.count ? ':x:' : '' } | Errors ${junitInfo.errors ? ':x:' : ''} | Skipped ${ junitInfo.skipped ? ':no_entry_sign:' : '' } | Time :hourglass_flowing_sand: |\n`; markdown += '| ------------------ | --------------------- | ------------------- | -------------------- | ----------------- |\n'; markdown += `| ${junitInfo.tests} | ${junitInfo.failures.count} | ${junitInfo.errors} | ${junitInfo.skipped} | ${junitInfo.time} |\n`; if ( eventInfo.showFailuresInfo && junitInfo.failures.count > 0 && junitInfo.failures.info ) { markdown += `<details><table><summary><b>Failures Details</b>\n\n</summary><tr><th>File</th><th>Test Name</th><th>Error Message</th></tr>`; for (const failure of junitInfo.failures.info) { markdown += `<tr><td>TODO</td><td>${failure.name}</td><td>${failure.error}</td></tr>`; } markdown += '</table></details>\n'; } // markdown += `\nThis is a [hover text](## "your hover text") example.`; return '### JUnit Details\n' + markdown + '\n'; } if (eventInfo.showJunit && !junitInfo) { return 'No JUnit details to present\n'; } return ''; }; const buildDiffCoverHtml = (eventInfo: EventInfo, diffsInfo: DiffInfo[]) => { if (!eventInfo.showDiffcover) { return ''; } else { if (diffsInfo.length === 0) { return `### Coverage Details :ballot_box_with_check:\nNo coverage details to present`; } else { let html = `<details><table><summary><b>Diff Cover Details</b>\n\n</summary><tr><th>File</th><th colspan="2">Covered Lines</th><th>Missing Lines</th></tr>`; let totalLines = 0; let totalMissing = 0; for (const diffInfo of diffsInfo) { if (diffInfo.changedLines.length > 0) { const href = `https://github.com/${eventInfo.owner}/${eventInfo.repo}/blob/${eventInfo.commitSha}/${diffInfo.file}`; const fileWithHref = `<a href="${href}">${diffInfo.file}</a>`; const lines = diffInfo.changedLines.length; totalLines += lines; const missed = diffInfo.missedLines.length; totalMissing += missed; const covered = lines - missed; const percentage = Math.round((covered / lines) * 100); const missedRanges: string[] = getMissedWithRanges(diffInfo); const missedRangesWithHref = missedRanges.map((missed) => { const range = missed .split('-') .map((val) => `L${val}`) .join('-'); return `<a href="${href}#${range}">${missed}</a>`; }); html += `<tr><td>${fileWithHref}</td><td>${covered}/${lines}</td><td>${percentage}%</td><td>${missedRangesWithHref}</td></tr>`; } } const totalCovered = totalLines - totalMissing; const totalPercentage = Math.round((totalCovered / totalLines) * 100); if (isNaN(totalPercentage)) { return ''; } html += `<tr><td>Total</td><td>${totalCovered}/${totalLines}</td><td>${totalPercentage}%</td><td></td></tr>`; html += '</table></details>'; if ( eventInfo.failUnderCoveragePercentage && totalPercentage < +eventInfo.minCoveragePercentage ) { core.setFailed('low coverage'); } return ( `### Coverage Details ${ totalPercentage >= +eventInfo.minCoveragePercentage ? `(${totalPercentage}% >= ${eventInfo.minCoveragePercentage}%) :white_check_mark:` : `(${totalPercentage}% < ${eventInfo.minCoveragePercentage}%) :x:` }\n\n` + html ); } } }; const getMissedWithRanges = (diffInfo: DiffInfo): string[] => { const missedRanges: string[] = []; let currIndex = 0; for (let i = 0; i < diffInfo.missedLines.length; i++) { if (+diffInfo.missedLines[i] + 1 === +diffInfo.missedLines[i + 1]) { if (missedRanges.length === currIndex) { missedRanges.push(`${diffInfo.missedLines[i]}-`); } } else { if (missedRanges.length !== currIndex) { missedRanges[currIndex] = missedRanges[currIndex] + diffInfo.missedLines[i]; } else { missedRanges.push(diffInfo.missedLines[i]); } currIndex++; } } return missedRanges; };
src/commentCoverage.ts
aGallea-tests-coverage-report-7728fb4
[ { "filename": "src/diffCover.ts", "retrieved_chunk": " }\n return [];\n};\nconst getDiff = async (\n coverageInfo: CoverageTypeInfo,\n changedFiles: string[],\n commitsSha: string[],\n referral: DiffCoverRef,\n): Promise<DiffInfo[]> => {\n const diffInfo: DiffInfo[] = [];", "score": 0.8650072813034058 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " taken: 1,\n });\n branchNumber++;\n }\n }\n });\n }\n return branches;\n};\nconst unpackage = (coverage: any, pwd: string): CoverInfo[] => {", "score": 0.8534390330314636 }, { "filename": "src/parsers/junit.ts", "retrieved_chunk": " core.error(`failed to parseContent. err: ${error.message}`);\n reject(error);\n }\n }\n });\n });\n};\nconst parseFolder = async (folder: string): Promise<Junit | undefined> => {\n const mergedTestSuites: any = {\n $: {},", "score": 0.852541446685791 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " return reject(new Error('invalid or missing xml content'));\n }\n const result = unpackage(parseResult.coverage, pwd);\n resolve(result);\n });\n });\n};\nexport const parseFile = async (file: string, pwd: string): Promise<CoverInfo[]> => {\n return new Promise((resolve, reject) => {\n if (!file || file === '') {", "score": 0.8174155950546265 }, { "filename": "src/parsers/junit.ts", "retrieved_chunk": " }\n const result = unpackage(parseResult.testsuites);\n resolve(result);\n });\n });\n};\nexport const parse = async (path: string): Promise<Junit | undefined> => {\n if (!path || path === '') {\n core.info('no junit file/folder specified');\n return undefined;", "score": 0.8038434386253357 } ]
typescript
junitInfo: Junit | undefined, diffsInfo: DiffInfo[], ): string => {
/* eslint-disable @typescript-eslint/no-explicit-any */ import fs from 'fs'; import { CoverInfo, CoverInfoFunctionsDetails, CoverInfoLinesDetails } from '../types'; import parseString from 'xml2js'; import * as core from '@actions/core'; const classDetailsFromProjects = (projects: any) => { let classDetails: any[] = []; let packageName = null; const parseFileObject = (fileObj: any, packageName: string) => { if (fileObj.class) { fileObj['class'].forEach((classObj: any) => { classDetails = classDetails.concat({ name: classObj.$.name, metrics: classObj.metrics[0], fileName: fileObj.$.name, fileMetrics: fileObj.metrics[0], lines: fileObj.line, packageName: packageName, }); }); } else { classDetails = classDetails.concat({ name: null, metrics: null, fileName: fileObj.$.name, fileMetrics: fileObj.metrics[0], lines: fileObj.line, packageName: packageName, }); } }; projects.forEach((projectObj: any) => { if (projectObj.package) { projectObj.package.forEach((data: any) => { if (data.$?.name) { packageName = data.$.name; } else { packageName = null; } data.file.forEach(parseFileObject); }); } if (projectObj.file) { packageName = null; projectObj.file.forEach(parseFileObject); } }); return classDetails; };
const unpackage = (projects: any): CoverInfo[] => {
const classDetails = classDetailsFromProjects(projects); return classDetails.map((c: any) => { const methodStats: CoverInfoFunctionsDetails[] = []; const lineStats: CoverInfoLinesDetails[] = []; if (c.lines) { c.lines.forEach((l: any) => { if (l.$.type === 'method') { methodStats.push({ name: l.$.name, line: Number(l.$.num), hit: Number(l.$.count), }); } else { lineStats.push({ line: Number(l.$.num), hit: Number(l.$.count), }); } }); } const classCov: CoverInfo = { title: c.name, file: c.fileName, functions: { found: methodStats.length, hit: 0, details: methodStats, }, lines: { found: lineStats.length, hit: 0, details: lineStats, }, branches: { found: 0, hit: 0, details: [], }, }; classCov.functions.hit = classCov.functions.details.reduce((acc, val) => { return acc + (val.hit > 0 ? 1 : 0); }, 0); classCov.lines.hit = classCov.lines.details.reduce((acc, val) => { return acc + (val.hit > 0 ? 1 : 0); }, 0); return classCov; }); }; const parseContent = (xml: any): Promise<CoverInfo[]> => { return new Promise((resolve, reject) => { parseString.parseString(xml, (err, parseResult) => { if (err) { reject(err); } if (!parseResult?.coverage?.project) { return reject(new Error('invalid or missing xml content')); } const result = unpackage(parseResult.coverage.project); resolve(result); }); }); }; export const parseFile = async (file: string): Promise<CoverInfo[]> => { return new Promise((resolve, reject) => { if (!file || file === '') { core.info('no clover file specified'); resolve([]); } else { fs.readFile( file, 'utf8', async (err: NodeJS.ErrnoException | null, data: string) => { if (err) { core.error(`failed to read file: ${file}. error: ${err.message}`); reject(err); } else { try { const info = await parseContent(data); // console.log('====== clover ======'); // console.log(JSON.stringify(info, null, 2)); resolve(info); } catch (error) { core.error(`failed to parseContent. err: ${error.message}`); reject(error); } } }, ); } }); };
src/parsers/clover.ts
aGallea-tests-coverage-report-7728fb4
[ { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " taken: 1,\n });\n branchNumber++;\n }\n }\n });\n }\n return branches;\n};\nconst unpackage = (coverage: any, pwd: string): CoverInfo[] => {", "score": 0.8474198579788208 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " pack.classes.forEach((c: any) => {\n classes.push(...c.class);\n });\n });\n });\n return classes;\n};\nconst extractLcovStyleBranches = (c: any) => {\n const branches: CoverInfoBranchesDetails[] = [];\n if (c.lines && c.lines[0].line) {", "score": 0.8408148288726807 }, { "filename": "src/parsers/jacoco.ts", "retrieved_chunk": " }\n const result = unpackage(parseResult.report);\n resolve(result);\n });\n });\n};\nexport const parseFile = async (file: string): Promise<CoverInfo[]> => {\n return new Promise((resolve, reject) => {\n if (!file || file === '') {\n core.info('no jacoco file specified');", "score": 0.8156996965408325 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " return reject(new Error('invalid or missing xml content'));\n }\n const result = unpackage(parseResult.coverage, pwd);\n resolve(result);\n });\n });\n};\nexport const parseFile = async (file: string, pwd: string): Promise<CoverInfo[]> => {\n return new Promise((resolve, reject) => {\n if (!file || file === '') {", "score": 0.8140778541564941 }, { "filename": "src/parsers/junit.ts", "retrieved_chunk": " core.error(`failed to parseContent. err: ${error.message}`);\n reject(error);\n }\n }\n });\n });\n};\nconst parseFolder = async (folder: string): Promise<Junit | undefined> => {\n const mergedTestSuites: any = {\n $: {},", "score": 0.8107488751411438 } ]
typescript
const unpackage = (projects: any): CoverInfo[] => {
import * as core from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { DiffInfo, EventInfo, Junit } from './types'; export const commentCoverage = async ( eventInfo: EventInfo, body: string, ): Promise<void> => { const { eventName, payload } = context; const octokit = getOctokit(eventInfo.token); if (eventName === 'push') { await octokit.rest.repos.createCommitComment({ repo: eventInfo.repo, owner: eventInfo.owner, commit_sha: eventInfo.commitSha, body, }); } else if (eventName === 'pull_request') { if (eventInfo.overrideComment) { const { data: comments } = await octokit.rest.issues.listComments({ repo: eventInfo.repo, owner: eventInfo.owner, issue_number: payload.pull_request ? payload.pull_request.number : 0, }); const comment = comments.find( (comment) => comment.user?.login === 'github-actions[bot]' && comment.body?.startsWith(eventInfo.commentId), ); if (comment) { await octokit.rest.issues.updateComment({ repo: eventInfo.repo, owner: eventInfo.owner, comment_id: comment.id, body, }); } else { await octokit.rest.issues.createComment({ repo: eventInfo.repo, owner: eventInfo.owner, issue_number: payload.pull_request?.number || 0, body, }); } } else { await octokit.rest.issues.createComment({ repo: eventInfo.repo, owner: eventInfo.owner, issue_number: payload.pull_request?.number || 0, body, }); } } }; export const buildBody = ( eventInfo: EventInfo, junitInfo: Junit | undefined,
diffsInfo: DiffInfo[], ): string => {
let body = `${eventInfo.commentId}\n`; body += `## ${eventInfo.commentTitle} :page_facing_up:\n`; body += buildTestsStatusMarkdown(junitInfo); body += buildJunitMarkdown(eventInfo, junitInfo); body += buildDiffCoverHtml(eventInfo, diffsInfo); return body; }; const buildTestsStatusMarkdown = (junitInfo: Junit | undefined) => { if (junitInfo) { const markdown = junitInfo.failures?.count || junitInfo.errors ? '### Tests Failure :x:' : '### Tests Succees :white_check_mark:'; return `${markdown}\n`; } return ''; }; const buildJunitMarkdown = (eventInfo: EventInfo, junitInfo: Junit | undefined) => { if (eventInfo.showJunit && junitInfo) { let markdown = `| Total Tests | Failures ${ junitInfo.failures.count ? ':x:' : '' } | Errors ${junitInfo.errors ? ':x:' : ''} | Skipped ${ junitInfo.skipped ? ':no_entry_sign:' : '' } | Time :hourglass_flowing_sand: |\n`; markdown += '| ------------------ | --------------------- | ------------------- | -------------------- | ----------------- |\n'; markdown += `| ${junitInfo.tests} | ${junitInfo.failures.count} | ${junitInfo.errors} | ${junitInfo.skipped} | ${junitInfo.time} |\n`; if ( eventInfo.showFailuresInfo && junitInfo.failures.count > 0 && junitInfo.failures.info ) { markdown += `<details><table><summary><b>Failures Details</b>\n\n</summary><tr><th>File</th><th>Test Name</th><th>Error Message</th></tr>`; for (const failure of junitInfo.failures.info) { markdown += `<tr><td>TODO</td><td>${failure.name}</td><td>${failure.error}</td></tr>`; } markdown += '</table></details>\n'; } // markdown += `\nThis is a [hover text](## "your hover text") example.`; return '### JUnit Details\n' + markdown + '\n'; } if (eventInfo.showJunit && !junitInfo) { return 'No JUnit details to present\n'; } return ''; }; const buildDiffCoverHtml = (eventInfo: EventInfo, diffsInfo: DiffInfo[]) => { if (!eventInfo.showDiffcover) { return ''; } else { if (diffsInfo.length === 0) { return `### Coverage Details :ballot_box_with_check:\nNo coverage details to present`; } else { let html = `<details><table><summary><b>Diff Cover Details</b>\n\n</summary><tr><th>File</th><th colspan="2">Covered Lines</th><th>Missing Lines</th></tr>`; let totalLines = 0; let totalMissing = 0; for (const diffInfo of diffsInfo) { if (diffInfo.changedLines.length > 0) { const href = `https://github.com/${eventInfo.owner}/${eventInfo.repo}/blob/${eventInfo.commitSha}/${diffInfo.file}`; const fileWithHref = `<a href="${href}">${diffInfo.file}</a>`; const lines = diffInfo.changedLines.length; totalLines += lines; const missed = diffInfo.missedLines.length; totalMissing += missed; const covered = lines - missed; const percentage = Math.round((covered / lines) * 100); const missedRanges: string[] = getMissedWithRanges(diffInfo); const missedRangesWithHref = missedRanges.map((missed) => { const range = missed .split('-') .map((val) => `L${val}`) .join('-'); return `<a href="${href}#${range}">${missed}</a>`; }); html += `<tr><td>${fileWithHref}</td><td>${covered}/${lines}</td><td>${percentage}%</td><td>${missedRangesWithHref}</td></tr>`; } } const totalCovered = totalLines - totalMissing; const totalPercentage = Math.round((totalCovered / totalLines) * 100); if (isNaN(totalPercentage)) { return ''; } html += `<tr><td>Total</td><td>${totalCovered}/${totalLines}</td><td>${totalPercentage}%</td><td></td></tr>`; html += '</table></details>'; if ( eventInfo.failUnderCoveragePercentage && totalPercentage < +eventInfo.minCoveragePercentage ) { core.setFailed('low coverage'); } return ( `### Coverage Details ${ totalPercentage >= +eventInfo.minCoveragePercentage ? `(${totalPercentage}% >= ${eventInfo.minCoveragePercentage}%) :white_check_mark:` : `(${totalPercentage}% < ${eventInfo.minCoveragePercentage}%) :x:` }\n\n` + html ); } } }; const getMissedWithRanges = (diffInfo: DiffInfo): string[] => { const missedRanges: string[] = []; let currIndex = 0; for (let i = 0; i < diffInfo.missedLines.length; i++) { if (+diffInfo.missedLines[i] + 1 === +diffInfo.missedLines[i + 1]) { if (missedRanges.length === currIndex) { missedRanges.push(`${diffInfo.missedLines[i]}-`); } } else { if (missedRanges.length !== currIndex) { missedRanges[currIndex] = missedRanges[currIndex] + diffInfo.missedLines[i]; } else { missedRanges.push(diffInfo.missedLines[i]); } currIndex++; } } return missedRanges; };
src/commentCoverage.ts
aGallea-tests-coverage-report-7728fb4
[ { "filename": "src/diffCover.ts", "retrieved_chunk": " }\n return [];\n};\nconst getDiff = async (\n coverageInfo: CoverageTypeInfo,\n changedFiles: string[],\n commitsSha: string[],\n referral: DiffCoverRef,\n): Promise<DiffInfo[]> => {\n const diffInfo: DiffInfo[] = [];", "score": 0.8650072813034058 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " taken: 1,\n });\n branchNumber++;\n }\n }\n });\n }\n return branches;\n};\nconst unpackage = (coverage: any, pwd: string): CoverInfo[] => {", "score": 0.8534390330314636 }, { "filename": "src/parsers/junit.ts", "retrieved_chunk": " core.error(`failed to parseContent. err: ${error.message}`);\n reject(error);\n }\n }\n });\n });\n};\nconst parseFolder = async (folder: string): Promise<Junit | undefined> => {\n const mergedTestSuites: any = {\n $: {},", "score": 0.852541446685791 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " return reject(new Error('invalid or missing xml content'));\n }\n const result = unpackage(parseResult.coverage, pwd);\n resolve(result);\n });\n });\n};\nexport const parseFile = async (file: string, pwd: string): Promise<CoverInfo[]> => {\n return new Promise((resolve, reject) => {\n if (!file || file === '') {", "score": 0.8174155950546265 }, { "filename": "src/parsers/junit.ts", "retrieved_chunk": " }\n const result = unpackage(parseResult.testsuites);\n resolve(result);\n });\n });\n};\nexport const parse = async (path: string): Promise<Junit | undefined> => {\n if (!path || path === '') {\n core.info('no junit file/folder specified');\n return undefined;", "score": 0.8038434386253357 } ]
typescript
diffsInfo: DiffInfo[], ): string => {
/* eslint-disable @typescript-eslint/no-explicit-any */ import fs from 'fs'; import { CoverInfo, CoverInfoFunctionsDetails, CoverInfoLinesDetails } from '../types'; import parseString from 'xml2js'; import * as core from '@actions/core'; const classDetailsFromProjects = (projects: any) => { let classDetails: any[] = []; let packageName = null; const parseFileObject = (fileObj: any, packageName: string) => { if (fileObj.class) { fileObj['class'].forEach((classObj: any) => { classDetails = classDetails.concat({ name: classObj.$.name, metrics: classObj.metrics[0], fileName: fileObj.$.name, fileMetrics: fileObj.metrics[0], lines: fileObj.line, packageName: packageName, }); }); } else { classDetails = classDetails.concat({ name: null, metrics: null, fileName: fileObj.$.name, fileMetrics: fileObj.metrics[0], lines: fileObj.line, packageName: packageName, }); } }; projects.forEach((projectObj: any) => { if (projectObj.package) { projectObj.package.forEach((data: any) => { if (data.$?.name) { packageName = data.$.name; } else { packageName = null; } data.file.forEach(parseFileObject); }); } if (projectObj.file) { packageName = null; projectObj.file.forEach(parseFileObject); } }); return classDetails; }; const unpackage = (projects: any): CoverInfo[] => { const classDetails = classDetailsFromProjects(projects); return classDetails.map((c: any) => { const methodStats
: CoverInfoFunctionsDetails[] = [];
const lineStats: CoverInfoLinesDetails[] = []; if (c.lines) { c.lines.forEach((l: any) => { if (l.$.type === 'method') { methodStats.push({ name: l.$.name, line: Number(l.$.num), hit: Number(l.$.count), }); } else { lineStats.push({ line: Number(l.$.num), hit: Number(l.$.count), }); } }); } const classCov: CoverInfo = { title: c.name, file: c.fileName, functions: { found: methodStats.length, hit: 0, details: methodStats, }, lines: { found: lineStats.length, hit: 0, details: lineStats, }, branches: { found: 0, hit: 0, details: [], }, }; classCov.functions.hit = classCov.functions.details.reduce((acc, val) => { return acc + (val.hit > 0 ? 1 : 0); }, 0); classCov.lines.hit = classCov.lines.details.reduce((acc, val) => { return acc + (val.hit > 0 ? 1 : 0); }, 0); return classCov; }); }; const parseContent = (xml: any): Promise<CoverInfo[]> => { return new Promise((resolve, reject) => { parseString.parseString(xml, (err, parseResult) => { if (err) { reject(err); } if (!parseResult?.coverage?.project) { return reject(new Error('invalid or missing xml content')); } const result = unpackage(parseResult.coverage.project); resolve(result); }); }); }; export const parseFile = async (file: string): Promise<CoverInfo[]> => { return new Promise((resolve, reject) => { if (!file || file === '') { core.info('no clover file specified'); resolve([]); } else { fs.readFile( file, 'utf8', async (err: NodeJS.ErrnoException | null, data: string) => { if (err) { core.error(`failed to read file: ${file}. error: ${err.message}`); reject(err); } else { try { const info = await parseContent(data); // console.log('====== clover ======'); // console.log(JSON.stringify(info, null, 2)); resolve(info); } catch (error) { core.error(`failed to parseContent. err: ${error.message}`); reject(error); } } }, ); } }); };
src/parsers/clover.ts
aGallea-tests-coverage-report-7728fb4
[ { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " pack.classes.forEach((c: any) => {\n classes.push(...c.class);\n });\n });\n });\n return classes;\n};\nconst extractLcovStyleBranches = (c: any) => {\n const branches: CoverInfoBranchesDetails[] = [];\n if (c.lines && c.lines[0].line) {", "score": 0.8742774724960327 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " taken: 1,\n });\n branchNumber++;\n }\n }\n });\n }\n return branches;\n};\nconst unpackage = (coverage: any, pwd: string): CoverInfo[] => {", "score": 0.8141013383865356 }, { "filename": "src/parsers/jacoco.ts", "retrieved_chunk": " })[0] || {\n $: {\n covered: 0,\n missed: 0,\n },\n }\n );\n};\nconst unpackage = (report: any): CoverInfo[] => {\n const packages = report.package;", "score": 0.8138062953948975 }, { "filename": "src/diffCover.ts", "retrieved_chunk": " }\n return [];\n};\nconst getDiff = async (\n coverageInfo: CoverageTypeInfo,\n changedFiles: string[],\n commitsSha: string[],\n referral: DiffCoverRef,\n): Promise<DiffInfo[]> => {\n const diffInfo: DiffInfo[] = [];", "score": 0.8083020448684692 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " return reject(new Error('invalid or missing xml content'));\n }\n const result = unpackage(parseResult.coverage, pwd);\n resolve(result);\n });\n });\n};\nexport const parseFile = async (file: string, pwd: string): Promise<CoverInfo[]> => {\n return new Promise((resolve, reject) => {\n if (!file || file === '') {", "score": 0.7952142953872681 } ]
typescript
: CoverInfoFunctionsDetails[] = [];
/* eslint-disable @typescript-eslint/no-explicit-any */ import fs from 'fs'; import path from 'path'; import { CoverInfo, CoverInfoBranchesDetails } from '../types'; import parseString from 'xml2js'; import * as core from '@actions/core'; const classesFromPackages = (packages: any) => { const classes: any[] = []; packages.forEach((packages: any) => { packages.package.forEach((pack: any) => { pack.classes.forEach((c: any) => { classes.push(...c.class); }); }); }); return classes; }; const extractLcovStyleBranches = (c: any) => { const branches: CoverInfoBranchesDetails[] = []; if (c.lines && c.lines[0].line) { c.lines[0].line.forEach((l: any) => { if (l.$.branch == 'true') { const branchFraction = l.$['condition-coverage'].split(' '); const branchStats = branchFraction[1].match(/\d+/g); const coveredBranches = Number(branchStats[0]); const totalBranches = Number(branchStats[1]); const leftBranches = totalBranches - coveredBranches; let branchNumber = 0; for (let i = 0; i < leftBranches; i++) { branches.push({ line: Number(l.$.number), branch: branchNumber, taken: 0, }); branchNumber++; } for (let i = 0; i < coveredBranches; i++) { branches.push({ line: Number(l.$.number), branch: branchNumber, taken: 1, }); branchNumber++; } } }); } return branches; };
const unpackage = (coverage: any, pwd: string): CoverInfo[] => {
const packages = coverage.packages; const source = coverage.sources[0].source[0]; const classes = classesFromPackages(packages); return classes.map((c) => { const branches = extractLcovStyleBranches(c); const classCov: CoverInfo = { title: c.$.name, // file: c.$.filename, file: path.join(source, c.$.filename).replace(pwd, ''), functions: { found: c.methods && c.methods[0].method ? c.methods[0].method.length : 0, hit: 0, details: !c.methods || !c.methods[0].method ? [] : c.methods[0].method.map((m: any) => { return { name: m.$.name, line: Number(m.lines[0].line[0].$.number), hit: Number(m.lines[0].line[0].$.hits), }; }), }, lines: { found: c.lines && c.lines[0].line ? c.lines[0].line.length : 0, hit: 0, details: !c.lines || !c.lines[0].line ? [] : c.lines[0].line.map((l: any) => { return { line: Number(l.$.number), hit: Number(l.$.hits), }; }), }, branches: { found: branches.length, hit: branches.filter((br) => { return br.taken > 0; }).length, details: branches, }, }; classCov.functions.hit = classCov.functions.details.reduce((acc: any, val: any) => { return acc + (val.hit > 0 ? 1 : 0); }, 0); classCov.lines.hit = classCov.lines.details.reduce((acc: any, val: any) => { return acc + (val.hit > 0 ? 1 : 0); }, 0); return classCov; }); }; const parseContent = (xml: string, pwd: string): Promise<CoverInfo[]> => { return new Promise((resolve, reject) => { parseString.parseString(xml, (err, parseResult) => { if (err) { return reject(err); } if (!parseResult?.coverage) { return reject(new Error('invalid or missing xml content')); } const result = unpackage(parseResult.coverage, pwd); resolve(result); }); }); }; export const parseFile = async (file: string, pwd: string): Promise<CoverInfo[]> => { return new Promise((resolve, reject) => { if (!file || file === '') { core.info('no cobertura file specified'); resolve([]); } else { fs.readFile( file, 'utf8', async (err: NodeJS.ErrnoException | null, data: string) => { if (err) { core.error(`failed to read file: ${file}. error: ${err.message}`); reject(err); } else { try { const info = await parseContent(data, pwd); // console.log('====== cobertura ======'); // console.log(JSON.stringify(info, null, 2)); resolve(info); } catch (error) { core.error(`failed to parseContent. err: ${error.message}`); reject(error); } } }, ); } }); };
src/parsers/cobertura.ts
aGallea-tests-coverage-report-7728fb4
[ { "filename": "src/parsers/junit.ts", "retrieved_chunk": " core.error(`failed to parseContent. err: ${error.message}`);\n reject(error);\n }\n }\n });\n });\n};\nconst parseFolder = async (folder: string): Promise<Junit | undefined> => {\n const mergedTestSuites: any = {\n $: {},", "score": 0.8688853979110718 }, { "filename": "src/parsers/jacoco.ts", "retrieved_chunk": " }\n return branches;\n })\n .flat() || [],\n },\n };\n return classCov;\n });\n output = output.concat(cov);\n });", "score": 0.8595315217971802 }, { "filename": "src/parsers/clover.ts", "retrieved_chunk": " });\n }\n if (projectObj.file) {\n packageName = null;\n projectObj.file.forEach(parseFileObject);\n }\n });\n return classDetails;\n};\nconst unpackage = (projects: any): CoverInfo[] => {", "score": 0.8474650382995605 }, { "filename": "src/utils.ts", "retrieved_chunk": " status: 'success',\n stdout,\n });\n });\n });\n};", "score": 0.830299437046051 }, { "filename": "src/parsers/jacoco.ts", "retrieved_chunk": " })[0] || {\n $: {\n covered: 0,\n missed: 0,\n },\n }\n );\n};\nconst unpackage = (report: any): CoverInfo[] => {\n const packages = report.package;", "score": 0.8263945579528809 } ]
typescript
const unpackage = (coverage: any, pwd: string): CoverInfo[] => {
import * as core from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { DiffInfo, EventInfo, Junit } from './types'; export const commentCoverage = async ( eventInfo: EventInfo, body: string, ): Promise<void> => { const { eventName, payload } = context; const octokit = getOctokit(eventInfo.token); if (eventName === 'push') { await octokit.rest.repos.createCommitComment({ repo: eventInfo.repo, owner: eventInfo.owner, commit_sha: eventInfo.commitSha, body, }); } else if (eventName === 'pull_request') { if (eventInfo.overrideComment) { const { data: comments } = await octokit.rest.issues.listComments({ repo: eventInfo.repo, owner: eventInfo.owner, issue_number: payload.pull_request ? payload.pull_request.number : 0, }); const comment = comments.find( (comment) => comment.user?.login === 'github-actions[bot]' && comment.body?.startsWith(eventInfo.commentId), ); if (comment) { await octokit.rest.issues.updateComment({ repo: eventInfo.repo, owner: eventInfo.owner, comment_id: comment.id, body, }); } else { await octokit.rest.issues.createComment({ repo: eventInfo.repo, owner: eventInfo.owner, issue_number: payload.pull_request?.number || 0, body, }); } } else { await octokit.rest.issues.createComment({ repo: eventInfo.repo, owner: eventInfo.owner, issue_number: payload.pull_request?.number || 0, body, }); } } }; export const buildBody = ( eventInfo: EventInfo, junitInfo: Junit | undefined, diffsInfo: DiffInfo[], ): string => { let body = `${eventInfo.commentId}\n`; body += `## ${eventInfo.commentTitle} :page_facing_up:\n`; body += buildTestsStatusMarkdown(junitInfo); body += buildJunitMarkdown(eventInfo, junitInfo); body += buildDiffCoverHtml(eventInfo, diffsInfo); return body; }; const buildTestsStatusMarkdown = (junitInfo: Junit | undefined) => { if (junitInfo) { const markdown = junitInfo.failures?.count || junitInfo.errors ? '### Tests Failure :x:' : '### Tests Succees :white_check_mark:'; return `${markdown}\n`; } return ''; }; const buildJunitMarkdown = (eventInfo: EventInfo, junitInfo: Junit | undefined) => { if (eventInfo.showJunit && junitInfo) { let markdown = `| Total Tests | Failures ${ junitInfo.failures.count ? ':x:' : '' } | Errors ${junitInfo.errors ? ':x:' : ''} | Skipped ${ junitInfo.skipped ? ':no_entry_sign:' : '' } | Time :hourglass_flowing_sand: |\n`; markdown += '| ------------------ | --------------------- | ------------------- | -------------------- | ----------------- |\n'; markdown += `| ${junitInfo.tests} | ${junitInfo.failures.count} | ${junitInfo.errors} | ${junitInfo.skipped} | ${junitInfo.time} |\n`; if ( eventInfo.showFailuresInfo && junitInfo.failures.count > 0 && junitInfo.failures.info ) { markdown += `<details><table><summary><b>Failures Details</b>\n\n</summary><tr><th>File</th><th>Test Name</th><th>Error Message</th></tr>`; for (const failure of junitInfo.failures.info) { markdown += `<tr><td>TODO</td><td>${failure.name}</td><td>${failure.error}</td></tr>`; } markdown += '</table></details>\n'; } // markdown += `\nThis is a [hover text](## "your hover text") example.`; return '### JUnit Details\n' + markdown + '\n'; } if (eventInfo.showJunit && !junitInfo) { return 'No JUnit details to present\n'; } return ''; }; const buildDiffCoverHtml = (eventInfo: EventInfo, diffsInfo: DiffInfo[]) => { if (!eventInfo.showDiffcover) { return ''; } else { if (diffsInfo.length === 0) { return `### Coverage Details :ballot_box_with_check:\nNo coverage details to present`; } else { let html = `<details><table><summary><b>Diff Cover Details</b>\n\n</summary><tr><th>File</th><th colspan="2">Covered Lines</th><th>Missing Lines</th></tr>`; let totalLines = 0; let totalMissing = 0; for (const diffInfo of diffsInfo) {
if (diffInfo.changedLines.length > 0) {
const href = `https://github.com/${eventInfo.owner}/${eventInfo.repo}/blob/${eventInfo.commitSha}/${diffInfo.file}`; const fileWithHref = `<a href="${href}">${diffInfo.file}</a>`; const lines = diffInfo.changedLines.length; totalLines += lines; const missed = diffInfo.missedLines.length; totalMissing += missed; const covered = lines - missed; const percentage = Math.round((covered / lines) * 100); const missedRanges: string[] = getMissedWithRanges(diffInfo); const missedRangesWithHref = missedRanges.map((missed) => { const range = missed .split('-') .map((val) => `L${val}`) .join('-'); return `<a href="${href}#${range}">${missed}</a>`; }); html += `<tr><td>${fileWithHref}</td><td>${covered}/${lines}</td><td>${percentage}%</td><td>${missedRangesWithHref}</td></tr>`; } } const totalCovered = totalLines - totalMissing; const totalPercentage = Math.round((totalCovered / totalLines) * 100); if (isNaN(totalPercentage)) { return ''; } html += `<tr><td>Total</td><td>${totalCovered}/${totalLines}</td><td>${totalPercentage}%</td><td></td></tr>`; html += '</table></details>'; if ( eventInfo.failUnderCoveragePercentage && totalPercentage < +eventInfo.minCoveragePercentage ) { core.setFailed('low coverage'); } return ( `### Coverage Details ${ totalPercentage >= +eventInfo.minCoveragePercentage ? `(${totalPercentage}% >= ${eventInfo.minCoveragePercentage}%) :white_check_mark:` : `(${totalPercentage}% < ${eventInfo.minCoveragePercentage}%) :x:` }\n\n` + html ); } } }; const getMissedWithRanges = (diffInfo: DiffInfo): string[] => { const missedRanges: string[] = []; let currIndex = 0; for (let i = 0; i < diffInfo.missedLines.length; i++) { if (+diffInfo.missedLines[i] + 1 === +diffInfo.missedLines[i + 1]) { if (missedRanges.length === currIndex) { missedRanges.push(`${diffInfo.missedLines[i]}-`); } } else { if (missedRanges.length !== currIndex) { missedRanges[currIndex] = missedRanges[currIndex] + diffInfo.missedLines[i]; } else { missedRanges.push(diffInfo.missedLines[i]); } currIndex++; } } return missedRanges; };
src/commentCoverage.ts
aGallea-tests-coverage-report-7728fb4
[ { "filename": "src/diffCover.ts", "retrieved_chunk": " for (const fileCoverInfo of coverageInfo[referral]) {\n for (const currFile of changedFiles) {\n const changedLinesExec = await execCommand(\n `git blame ${currFile} | grep -n '${commitsSha.join('\\\\|')}' | cut -f1 -d:`,\n );\n if (changedLinesExec.status === 'success') {\n const changedLines =\n changedLinesExec.stdout?.split('\\n').filter((line) => line) || [];\n if (changedLines.length) {\n if (fileCoverInfo.lines.details.length) {", "score": 0.7609965801239014 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " c.lines[0].line.forEach((l: any) => {\n if (l.$.branch == 'true') {\n const branchFraction = l.$['condition-coverage'].split(' ');\n const branchStats = branchFraction[1].match(/\\d+/g);\n const coveredBranches = Number(branchStats[0]);\n const totalBranches = Number(branchStats[1]);\n const leftBranches = totalBranches - coveredBranches;\n let branchNumber = 0;\n for (let i = 0; i < leftBranches; i++) {\n branches.push({", "score": 0.7604238986968994 }, { "filename": "src/parsers/clover.ts", "retrieved_chunk": " const classDetails = classDetailsFromProjects(projects);\n return classDetails.map((c: any) => {\n const methodStats: CoverInfoFunctionsDetails[] = [];\n const lineStats: CoverInfoLinesDetails[] = [];\n if (c.lines) {\n c.lines.forEach((l: any) => {\n if (l.$.type === 'method') {\n methodStats.push({\n name: l.$.name,\n line: Number(l.$.num),", "score": 0.752112865447998 }, { "filename": "src/diffCover.ts", "retrieved_chunk": " );\n core.info(`diffCover on file=${currFile}`);\n core.info(`misses: [${misses}]`);\n core.info(\n `coverage: ${Math.round(\n (1 - misses.length / changedLines.length) * 100,\n )}%`,\n );\n diffInfo.push({\n file: currFile,", "score": 0.7396723031997681 }, { "filename": "src/parsers/junit.ts", "retrieved_chunk": "};\nconst buildMainContent = (testSuiteList: any[]) => {\n const main = {\n tests: 0,\n failures: 0,\n errors: 0,\n skipped: 0,\n name: '',\n time: 0,\n };", "score": 0.7331922054290771 } ]
typescript
if (diffInfo.changedLines.length > 0) {
/* eslint-disable @typescript-eslint/no-explicit-any */ import fs from 'fs'; import { CoverInfo, CoverInfoFunctionsDetails, CoverInfoLinesDetails } from '../types'; import parseString from 'xml2js'; import * as core from '@actions/core'; const classDetailsFromProjects = (projects: any) => { let classDetails: any[] = []; let packageName = null; const parseFileObject = (fileObj: any, packageName: string) => { if (fileObj.class) { fileObj['class'].forEach((classObj: any) => { classDetails = classDetails.concat({ name: classObj.$.name, metrics: classObj.metrics[0], fileName: fileObj.$.name, fileMetrics: fileObj.metrics[0], lines: fileObj.line, packageName: packageName, }); }); } else { classDetails = classDetails.concat({ name: null, metrics: null, fileName: fileObj.$.name, fileMetrics: fileObj.metrics[0], lines: fileObj.line, packageName: packageName, }); } }; projects.forEach((projectObj: any) => { if (projectObj.package) { projectObj.package.forEach((data: any) => { if (data.$?.name) { packageName = data.$.name; } else { packageName = null; } data.file.forEach(parseFileObject); }); } if (projectObj.file) { packageName = null; projectObj.file.forEach(parseFileObject); } }); return classDetails; }; const unpackage = (projects: any): CoverInfo[] => { const classDetails = classDetailsFromProjects(projects); return classDetails.map((c: any) => { const methodStats: CoverInfoFunctionsDetails[] = []; const lineStats: CoverInfoLinesDetails[] = []; if (c.lines) { c.lines.forEach((l: any) => { if (l.$.type === 'method') { methodStats.push({ name: l.$.name, line: Number(l.$.num), hit: Number(l.$.count), }); } else { lineStats.push({ line: Number(l.$.num), hit: Number(l.$.count), }); } }); } const classCov: CoverInfo = { title: c.name, file: c.fileName, functions: { found: methodStats.length, hit: 0, details: methodStats, }, lines: { found: lineStats.length, hit: 0, details: lineStats, }, branches: { found: 0, hit: 0, details: [], }, };
classCov.functions.hit = classCov.functions.details.reduce((acc, val) => {
return acc + (val.hit > 0 ? 1 : 0); }, 0); classCov.lines.hit = classCov.lines.details.reduce((acc, val) => { return acc + (val.hit > 0 ? 1 : 0); }, 0); return classCov; }); }; const parseContent = (xml: any): Promise<CoverInfo[]> => { return new Promise((resolve, reject) => { parseString.parseString(xml, (err, parseResult) => { if (err) { reject(err); } if (!parseResult?.coverage?.project) { return reject(new Error('invalid or missing xml content')); } const result = unpackage(parseResult.coverage.project); resolve(result); }); }); }; export const parseFile = async (file: string): Promise<CoverInfo[]> => { return new Promise((resolve, reject) => { if (!file || file === '') { core.info('no clover file specified'); resolve([]); } else { fs.readFile( file, 'utf8', async (err: NodeJS.ErrnoException | null, data: string) => { if (err) { core.error(`failed to read file: ${file}. error: ${err.message}`); reject(err); } else { try { const info = await parseContent(data); // console.log('====== clover ======'); // console.log(JSON.stringify(info, null, 2)); resolve(info); } catch (error) { core.error(`failed to parseContent. err: ${error.message}`); reject(error); } } }, ); } }); };
src/parsers/clover.ts
aGallea-tests-coverage-report-7728fb4
[ { "filename": "src/parsers/lcov.ts", "retrieved_chunk": " found: 0,\n hit: 0,\n details: [],\n },\n functions: {\n hit: 0,\n found: 0,\n details: [],\n },\n branches: {", "score": 0.9054104685783386 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " }).length,\n details: branches,\n },\n };\n classCov.functions.hit = classCov.functions.details.reduce((acc: any, val: any) => {\n return acc + (val.hit > 0 ? 1 : 0);\n }, 0);\n classCov.lines.hit = classCov.lines.details.reduce((acc: any, val: any) => {\n return acc + (val.hit > 0 ? 1 : 0);\n }, 0);", "score": 0.8698519468307495 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " return {\n line: Number(l.$.number),\n hit: Number(l.$.hits),\n };\n }),\n },\n branches: {\n found: branches.length,\n hit: branches.filter((br) => {\n return br.taken > 0;", "score": 0.8641664981842041 }, { "filename": "src/parsers/jacoco.ts", "retrieved_chunk": " })[0] || {\n $: {\n covered: 0,\n missed: 0,\n },\n }\n );\n};\nconst unpackage = (report: any): CoverInfo[] => {\n const packages = report.package;", "score": 0.8613920211791992 }, { "filename": "src/parsers/lcov.ts", "retrieved_chunk": " fn = parts[1].split(',');\n item.functions.details.push({\n name: fn[1],\n line: Number(fn[0]),\n hit: 0,\n });\n break;\n case 'FNDA':\n fn = parts[1].split(',');\n item.functions.details.some((i: any, k: any) => {", "score": 0.8422549366950989 } ]
typescript
classCov.functions.hit = classCov.functions.details.reduce((acc, val) => {
/* eslint-disable @typescript-eslint/no-explicit-any */ import fs from 'fs'; import { CoverInfo, CoverInfoFunctionsDetails, CoverInfoLinesDetails } from '../types'; import parseString from 'xml2js'; import * as core from '@actions/core'; const classDetailsFromProjects = (projects: any) => { let classDetails: any[] = []; let packageName = null; const parseFileObject = (fileObj: any, packageName: string) => { if (fileObj.class) { fileObj['class'].forEach((classObj: any) => { classDetails = classDetails.concat({ name: classObj.$.name, metrics: classObj.metrics[0], fileName: fileObj.$.name, fileMetrics: fileObj.metrics[0], lines: fileObj.line, packageName: packageName, }); }); } else { classDetails = classDetails.concat({ name: null, metrics: null, fileName: fileObj.$.name, fileMetrics: fileObj.metrics[0], lines: fileObj.line, packageName: packageName, }); } }; projects.forEach((projectObj: any) => { if (projectObj.package) { projectObj.package.forEach((data: any) => { if (data.$?.name) { packageName = data.$.name; } else { packageName = null; } data.file.forEach(parseFileObject); }); } if (projectObj.file) { packageName = null; projectObj.file.forEach(parseFileObject); } }); return classDetails; }; const unpackage = (projects: any): CoverInfo[] => { const classDetails = classDetailsFromProjects(projects); return classDetails.map((c: any) => { const methodStats: CoverInfoFunctionsDetails[] = []; const lineStats: CoverInfoLinesDetails[] = []; if (c.lines) { c.lines.forEach((l: any) => { if (l.$.type === 'method') { methodStats.push({ name: l.$.name, line: Number(l.$.num), hit: Number(l.$.count), }); } else { lineStats.push({ line: Number(l.$.num), hit: Number(l.$.count), }); } }); } const classCov: CoverInfo = { title: c.name, file: c.fileName, functions: { found: methodStats.length, hit: 0, details: methodStats, }, lines: { found: lineStats.length, hit: 0, details: lineStats, }, branches: { found: 0, hit: 0, details: [], }, }; classCov.functions.hit
= classCov.functions.details.reduce((acc, val) => {
return acc + (val.hit > 0 ? 1 : 0); }, 0); classCov.lines.hit = classCov.lines.details.reduce((acc, val) => { return acc + (val.hit > 0 ? 1 : 0); }, 0); return classCov; }); }; const parseContent = (xml: any): Promise<CoverInfo[]> => { return new Promise((resolve, reject) => { parseString.parseString(xml, (err, parseResult) => { if (err) { reject(err); } if (!parseResult?.coverage?.project) { return reject(new Error('invalid or missing xml content')); } const result = unpackage(parseResult.coverage.project); resolve(result); }); }); }; export const parseFile = async (file: string): Promise<CoverInfo[]> => { return new Promise((resolve, reject) => { if (!file || file === '') { core.info('no clover file specified'); resolve([]); } else { fs.readFile( file, 'utf8', async (err: NodeJS.ErrnoException | null, data: string) => { if (err) { core.error(`failed to read file: ${file}. error: ${err.message}`); reject(err); } else { try { const info = await parseContent(data); // console.log('====== clover ======'); // console.log(JSON.stringify(info, null, 2)); resolve(info); } catch (error) { core.error(`failed to parseContent. err: ${error.message}`); reject(error); } } }, ); } }); };
src/parsers/clover.ts
aGallea-tests-coverage-report-7728fb4
[ { "filename": "src/parsers/lcov.ts", "retrieved_chunk": " found: 0,\n hit: 0,\n details: [],\n },\n functions: {\n hit: 0,\n found: 0,\n details: [],\n },\n branches: {", "score": 0.8839070200920105 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " }).length,\n details: branches,\n },\n };\n classCov.functions.hit = classCov.functions.details.reduce((acc: any, val: any) => {\n return acc + (val.hit > 0 ? 1 : 0);\n }, 0);\n classCov.lines.hit = classCov.lines.details.reduce((acc: any, val: any) => {\n return acc + (val.hit > 0 ? 1 : 0);\n }, 0);", "score": 0.8671390414237976 }, { "filename": "src/parsers/jacoco.ts", "retrieved_chunk": " })[0] || {\n $: {\n covered: 0,\n missed: 0,\n },\n }\n );\n};\nconst unpackage = (report: any): CoverInfo[] => {\n const packages = report.package;", "score": 0.8506003022193909 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " return {\n line: Number(l.$.number),\n hit: Number(l.$.hits),\n };\n }),\n },\n branches: {\n found: branches.length,\n hit: branches.filter((br) => {\n return br.taken > 0;", "score": 0.8498413562774658 }, { "filename": "src/parsers/lcov.ts", "retrieved_chunk": " fn = parts[1].split(',');\n item.functions.details.push({\n name: fn[1],\n line: Number(fn[0]),\n hit: 0,\n });\n break;\n case 'FNDA':\n fn = parts[1].split(',');\n item.functions.details.some((i: any, k: any) => {", "score": 0.8266150951385498 } ]
typescript
= classCov.functions.details.reduce((acc, val) => {
import * as core from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { DiffInfo, EventInfo, Junit } from './types'; export const commentCoverage = async ( eventInfo: EventInfo, body: string, ): Promise<void> => { const { eventName, payload } = context; const octokit = getOctokit(eventInfo.token); if (eventName === 'push') { await octokit.rest.repos.createCommitComment({ repo: eventInfo.repo, owner: eventInfo.owner, commit_sha: eventInfo.commitSha, body, }); } else if (eventName === 'pull_request') { if (eventInfo.overrideComment) { const { data: comments } = await octokit.rest.issues.listComments({ repo: eventInfo.repo, owner: eventInfo.owner, issue_number: payload.pull_request ? payload.pull_request.number : 0, }); const comment = comments.find( (comment) => comment.user?.login === 'github-actions[bot]' && comment.body?.startsWith(eventInfo.commentId), ); if (comment) { await octokit.rest.issues.updateComment({ repo: eventInfo.repo, owner: eventInfo.owner, comment_id: comment.id, body, }); } else { await octokit.rest.issues.createComment({ repo: eventInfo.repo, owner: eventInfo.owner, issue_number: payload.pull_request?.number || 0, body, }); } } else { await octokit.rest.issues.createComment({ repo: eventInfo.repo, owner: eventInfo.owner, issue_number: payload.pull_request?.number || 0, body, }); } } }; export const buildBody = ( eventInfo: EventInfo, junitInfo: Junit | undefined, diffsInfo: DiffInfo[], ): string => { let body = `${eventInfo.commentId}\n`; body += `## ${eventInfo.commentTitle} :page_facing_up:\n`; body += buildTestsStatusMarkdown(junitInfo); body += buildJunitMarkdown(eventInfo, junitInfo); body += buildDiffCoverHtml(eventInfo, diffsInfo); return body; }; const buildTestsStatusMarkdown = (junitInfo: Junit | undefined) => { if (junitInfo) { const markdown = junitInfo.failures?.count || junitInfo.errors ? '### Tests Failure :x:' : '### Tests Succees :white_check_mark:'; return `${markdown}\n`; } return ''; }; const buildJunitMarkdown = (eventInfo: EventInfo, junitInfo: Junit | undefined) => { if (eventInfo.showJunit && junitInfo) { let markdown = `| Total Tests | Failures ${ junitInfo.failures.count ? ':x:' : '' } | Errors ${junitInfo.errors ? ':x:' : ''} | Skipped ${ junitInfo.skipped ? ':no_entry_sign:' : '' } | Time :hourglass_flowing_sand: |\n`; markdown += '| ------------------ | --------------------- | ------------------- | -------------------- | ----------------- |\n'; markdown += `| ${junitInfo.tests} | ${junitInfo.failures.count} | ${junitInfo.errors} | ${junitInfo.skipped} | ${junitInfo.time} |\n`; if ( eventInfo.showFailuresInfo && junitInfo.failures.count > 0 && junitInfo.failures.info ) { markdown += `<details><table><summary><b>Failures Details</b>\n\n</summary><tr><th>File</th><th>Test Name</th><th>Error Message</th></tr>`; for (const failure of junitInfo.failures.info) { markdown += `<tr><td>TODO</td><td>${failure.name}</td><td>${failure.error}</td></tr>`; } markdown += '</table></details>\n'; } // markdown += `\nThis is a [hover text](## "your hover text") example.`; return '### JUnit Details\n' + markdown + '\n'; } if (eventInfo.showJunit && !junitInfo) { return 'No JUnit details to present\n'; } return ''; }; const buildDiffCoverHtml = (eventInfo: EventInfo, diffsInfo: DiffInfo[]) => { if (!eventInfo.showDiffcover) { return ''; } else { if (diffsInfo.length === 0) { return `### Coverage Details :ballot_box_with_check:\nNo coverage details to present`; } else { let html = `<details><table><summary><b>Diff Cover Details</b>\n\n</summary><tr><th>File</th><th colspan="2">Covered Lines</th><th>Missing Lines</th></tr>`; let totalLines = 0; let totalMissing = 0; for (const diffInfo of diffsInfo) { if (diffInfo.changedLines.length > 0) { const href = `https://github.com/${eventInfo.owner}/${eventInfo.repo}/blob/${eventInfo.commitSha}/${diffInfo.file}`; const fileWithHref = `<a href="${href}">${diffInfo.file}</a>`; const lines = diffInfo.changedLines.length; totalLines += lines;
const missed = diffInfo.missedLines.length;
totalMissing += missed; const covered = lines - missed; const percentage = Math.round((covered / lines) * 100); const missedRanges: string[] = getMissedWithRanges(diffInfo); const missedRangesWithHref = missedRanges.map((missed) => { const range = missed .split('-') .map((val) => `L${val}`) .join('-'); return `<a href="${href}#${range}">${missed}</a>`; }); html += `<tr><td>${fileWithHref}</td><td>${covered}/${lines}</td><td>${percentage}%</td><td>${missedRangesWithHref}</td></tr>`; } } const totalCovered = totalLines - totalMissing; const totalPercentage = Math.round((totalCovered / totalLines) * 100); if (isNaN(totalPercentage)) { return ''; } html += `<tr><td>Total</td><td>${totalCovered}/${totalLines}</td><td>${totalPercentage}%</td><td></td></tr>`; html += '</table></details>'; if ( eventInfo.failUnderCoveragePercentage && totalPercentage < +eventInfo.minCoveragePercentage ) { core.setFailed('low coverage'); } return ( `### Coverage Details ${ totalPercentage >= +eventInfo.minCoveragePercentage ? `(${totalPercentage}% >= ${eventInfo.minCoveragePercentage}%) :white_check_mark:` : `(${totalPercentage}% < ${eventInfo.minCoveragePercentage}%) :x:` }\n\n` + html ); } } }; const getMissedWithRanges = (diffInfo: DiffInfo): string[] => { const missedRanges: string[] = []; let currIndex = 0; for (let i = 0; i < diffInfo.missedLines.length; i++) { if (+diffInfo.missedLines[i] + 1 === +diffInfo.missedLines[i + 1]) { if (missedRanges.length === currIndex) { missedRanges.push(`${diffInfo.missedLines[i]}-`); } } else { if (missedRanges.length !== currIndex) { missedRanges[currIndex] = missedRanges[currIndex] + diffInfo.missedLines[i]; } else { missedRanges.push(diffInfo.missedLines[i]); } currIndex++; } } return missedRanges; };
src/commentCoverage.ts
aGallea-tests-coverage-report-7728fb4
[ { "filename": "src/diffCover.ts", "retrieved_chunk": " );\n }\n const commitsSha = gitLogExec.stdout?.split('\\n').filter((sha) => sha) || [];\n core.info(`commitsSha list:[${commitsSha}]`);\n const changedFiles = [\n ...filesStatus.added,\n ...filesStatus.modified,\n ...filesStatus.changed,\n ];\n return getDiff(coverageInfo, changedFiles, commitsSha, eventInfo.diffcoverRef);", "score": 0.7330963611602783 }, { "filename": "src/diffCover.ts", "retrieved_chunk": " );\n core.info(`diffCover on file=${currFile}`);\n core.info(`misses: [${misses}]`);\n core.info(\n `coverage: ${Math.round(\n (1 - misses.length / changedLines.length) * 100,\n )}%`,\n );\n diffInfo.push({\n file: currFile,", "score": 0.7236003875732422 }, { "filename": "src/diffCover.ts", "retrieved_chunk": " for (const fileCoverInfo of coverageInfo[referral]) {\n for (const currFile of changedFiles) {\n const changedLinesExec = await execCommand(\n `git blame ${currFile} | grep -n '${commitsSha.join('\\\\|')}' | cut -f1 -d:`,\n );\n if (changedLinesExec.status === 'success') {\n const changedLines =\n changedLinesExec.stdout?.split('\\n').filter((line) => line) || [];\n if (changedLines.length) {\n if (fileCoverInfo.lines.details.length) {", "score": 0.7111825942993164 }, { "filename": "src/diffCover.ts", "retrieved_chunk": " eventInfo: EventInfo,\n filesStatus: FilesStatus,\n coverageInfo: CoverageTypeInfo,\n): Promise<DiffInfo[]> => {\n if (eventInfo.showDiffcover) {\n const gitLogCommand = `git log --oneline origin/${eventInfo.baseRef}..origin/${eventInfo.headRef} -- | cut -f1 -d' '`;\n const gitLogExec = await execCommand(gitLogCommand);\n if (gitLogExec.status !== 'success') {\n throw new Error(\n `failed to retrieve git log: ${eventInfo.baseRef}..${eventInfo.headRef}. error: ${gitLogExec.message}`,", "score": 0.7074213027954102 }, { "filename": "src/changedFiles.ts", "retrieved_chunk": " owner: eventInfo.owner,\n repo: eventInfo.repo,\n basehead: `${eventInfo.baseRef}...${eventInfo.headRef}`,\n per_page: 50,\n page: currPage,\n });\n if (files) {\n pages = Math.ceil(total_commits / 50);\n for (const file of files) {\n allFiles.all.push(file.filename);", "score": 0.6981145143508911 } ]
typescript
const missed = diffInfo.missedLines.length;
/* eslint-disable @typescript-eslint/no-explicit-any */ import fs from 'fs'; import { CoverInfo, CoverInfoFunctionsDetails, CoverInfoLinesDetails } from '../types'; import parseString from 'xml2js'; import * as core from '@actions/core'; const classDetailsFromProjects = (projects: any) => { let classDetails: any[] = []; let packageName = null; const parseFileObject = (fileObj: any, packageName: string) => { if (fileObj.class) { fileObj['class'].forEach((classObj: any) => { classDetails = classDetails.concat({ name: classObj.$.name, metrics: classObj.metrics[0], fileName: fileObj.$.name, fileMetrics: fileObj.metrics[0], lines: fileObj.line, packageName: packageName, }); }); } else { classDetails = classDetails.concat({ name: null, metrics: null, fileName: fileObj.$.name, fileMetrics: fileObj.metrics[0], lines: fileObj.line, packageName: packageName, }); } }; projects.forEach((projectObj: any) => { if (projectObj.package) { projectObj.package.forEach((data: any) => { if (data.$?.name) { packageName = data.$.name; } else { packageName = null; } data.file.forEach(parseFileObject); }); } if (projectObj.file) { packageName = null; projectObj.file.forEach(parseFileObject); } }); return classDetails; }; const unpackage = (projects: any): CoverInfo[] => { const classDetails = classDetailsFromProjects(projects); return classDetails.map((c: any) => {
const methodStats: CoverInfoFunctionsDetails[] = [];
const lineStats: CoverInfoLinesDetails[] = []; if (c.lines) { c.lines.forEach((l: any) => { if (l.$.type === 'method') { methodStats.push({ name: l.$.name, line: Number(l.$.num), hit: Number(l.$.count), }); } else { lineStats.push({ line: Number(l.$.num), hit: Number(l.$.count), }); } }); } const classCov: CoverInfo = { title: c.name, file: c.fileName, functions: { found: methodStats.length, hit: 0, details: methodStats, }, lines: { found: lineStats.length, hit: 0, details: lineStats, }, branches: { found: 0, hit: 0, details: [], }, }; classCov.functions.hit = classCov.functions.details.reduce((acc, val) => { return acc + (val.hit > 0 ? 1 : 0); }, 0); classCov.lines.hit = classCov.lines.details.reduce((acc, val) => { return acc + (val.hit > 0 ? 1 : 0); }, 0); return classCov; }); }; const parseContent = (xml: any): Promise<CoverInfo[]> => { return new Promise((resolve, reject) => { parseString.parseString(xml, (err, parseResult) => { if (err) { reject(err); } if (!parseResult?.coverage?.project) { return reject(new Error('invalid or missing xml content')); } const result = unpackage(parseResult.coverage.project); resolve(result); }); }); }; export const parseFile = async (file: string): Promise<CoverInfo[]> => { return new Promise((resolve, reject) => { if (!file || file === '') { core.info('no clover file specified'); resolve([]); } else { fs.readFile( file, 'utf8', async (err: NodeJS.ErrnoException | null, data: string) => { if (err) { core.error(`failed to read file: ${file}. error: ${err.message}`); reject(err); } else { try { const info = await parseContent(data); // console.log('====== clover ======'); // console.log(JSON.stringify(info, null, 2)); resolve(info); } catch (error) { core.error(`failed to parseContent. err: ${error.message}`); reject(error); } } }, ); } }); };
src/parsers/clover.ts
aGallea-tests-coverage-report-7728fb4
[ { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " pack.classes.forEach((c: any) => {\n classes.push(...c.class);\n });\n });\n });\n return classes;\n};\nconst extractLcovStyleBranches = (c: any) => {\n const branches: CoverInfoBranchesDetails[] = [];\n if (c.lines && c.lines[0].line) {", "score": 0.8782181739807129 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " taken: 1,\n });\n branchNumber++;\n }\n }\n });\n }\n return branches;\n};\nconst unpackage = (coverage: any, pwd: string): CoverInfo[] => {", "score": 0.8200591802597046 }, { "filename": "src/parsers/jacoco.ts", "retrieved_chunk": " })[0] || {\n $: {\n covered: 0,\n missed: 0,\n },\n }\n );\n};\nconst unpackage = (report: any): CoverInfo[] => {\n const packages = report.package;", "score": 0.8028968572616577 }, { "filename": "src/parsers/cobertura.ts", "retrieved_chunk": " return reject(new Error('invalid or missing xml content'));\n }\n const result = unpackage(parseResult.coverage, pwd);\n resolve(result);\n });\n });\n};\nexport const parseFile = async (file: string, pwd: string): Promise<CoverInfo[]> => {\n return new Promise((resolve, reject) => {\n if (!file || file === '') {", "score": 0.7908570766448975 }, { "filename": "src/parsers/junit.ts", "retrieved_chunk": " core.error(`failed to parseContent. err: ${error.message}`);\n reject(error);\n }\n }\n });\n });\n};\nconst parseFolder = async (folder: string): Promise<Junit | undefined> => {\n const mergedTestSuites: any = {\n $: {},", "score": 0.7892622351646423 } ]
typescript
const methodStats: CoverInfoFunctionsDetails[] = [];