repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
Obsidian-PaperBell
github_2023
PaperBell-Org
typescript
setFolderState
function setFolderState(folderElement: HTMLElement, collapsed: boolean) { return collapsed ? folderElement.classList.remove("open") : folderElement.classList.add("open") }
/** * Toggles the state of a given folder * @param folderElement <div class="folder-outer"> Element of folder (parent) * @param collapsed if folder should be set to collapsed or not */
https://github.com/PaperBell-Org/Obsidian-PaperBell/blob/2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92/quartz/components/scripts/explorer.inline.ts#L118-L120
2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92
Obsidian-PaperBell
github_2023
PaperBell-Org
typescript
toggleCollapsedByPath
function toggleCollapsedByPath(array: FolderState[], path: string) { const entry = array.find((item) => item.path === path) if (entry) { entry.collapsed = !entry.collapsed } }
/** * Toggles visibility of a folder * @param array array of FolderState (`fileTree`, either get from local storage or data attribute) * @param path path to folder (e.g. 'advanced/more/more2') */
https://github.com/PaperBell-Org/Obsidian-PaperBell/blob/2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92/quartz/components/scripts/explorer.inline.ts#L127-L132
2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92
Obsidian-PaperBell
github_2023
PaperBell-Org
typescript
color
const color = (d: NodeData) => { const isCurrent = d.id === slug if (isCurrent) { return "var(--secondary)" } else if (visited.has(d.id) || d.id.startsWith("tags/")) { return "var(--tertiary)" } else { return "var(--gray)" } }
// calculate color
https://github.com/PaperBell-Org/Obsidian-PaperBell/blob/2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92/quartz/components/scripts/graph.inline.ts#L151-L160
2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92
Obsidian-PaperBell
github_2023
PaperBell-Org
typescript
fillDocument
async function fillDocument(data: { [key: FullSlug]: ContentDetails }) { let id = 0 const promises: Array<Promise<unknown>> = [] for (const [slug, fileData] of Object.entries<ContentDetails>(data)) { promises.push( index.addAsync(id++, { id, slug: slug as FullSlug, title: fileDat...
/** * Fills flexsearch document with data * @param index index to fill * @param data data to fill index with */
https://github.com/PaperBell-Org/Obsidian-PaperBell/blob/2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92/quartz/components/scripts/search.inline.ts#L475-L491
2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92
Obsidian-PaperBell
github_2023
PaperBell-Org
typescript
parseDependencies
const parseDependencies = (argv: Argv, hast: Root, file: VFile): string[] => { const dependencies: string[] = [] visit(hast, "element", (elem): void => { let ref: string | null = null if ( ["script", "img", "audio", "video", "source", "iframe"].includes(elem.tagName) && elem?.properties?.src ...
// get all the dependencies for the markdown file
https://github.com/PaperBell-Org/Obsidian-PaperBell/blob/2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92/quartz/plugins/emitters/contentPage.tsx#L21-L52
2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92
Obsidian-PaperBell
github_2023
PaperBell-Org
typescript
_rebaseHtmlElement
const _rebaseHtmlElement = (el: Element, attr: string, newBase: string | URL) => { const rebased = new URL(el.getAttribute(attr)!, newBase) el.setAttribute(attr, rebased.pathname + rebased.hash) }
// from micromorph/src/utils.ts
https://github.com/PaperBell-Org/Obsidian-PaperBell/blob/2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92/quartz/util/path.ts#L106-L109
2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92
Obsidian-PaperBell
github_2023
PaperBell-Org
typescript
isFolderPath
function isFolderPath(fplike: string): boolean { return ( fplike.endsWith("/") || endsWith(fplike, "index") || endsWith(fplike, "index.md") || endsWith(fplike, "index.html") ) }
// path helpers
https://github.com/PaperBell-Org/Obsidian-PaperBell/blob/2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92/quartz/util/path.ts#L237-L244
2c49cbd8e71e0232f3cdbcc7548d9bd0b40d3a92
remembrall
github_2023
reductoai
typescript
handler
const handler = (req: Request) => fetchRequestHandler({ endpoint: "/api/trpc", req, router: appRouter, createContext: createTRPCContext, onError: env.NODE_ENV === "development" ? ({ path, error }) => { console.error( `❌ tRPC failed on ${path ?? "<no-path>"}:...
// This function can run for a maximum of 300 seconds
https://github.com/reductoai/remembrall/blob/b9537f7f057fc92ec0a2844286ad53ce96ec46bc/src/app/api/trpc/[trpc]/route.ts#L9-L23
b9537f7f057fc92ec0a2844286ad53ce96ec46bc
feishu-pages
github_2023
longbridge
typescript
MarkdownRenderer.parsePageMeta
parsePageMeta(block: Block) { if (block?.block_type !== BlockType.Code) { if (block.children?.length > 0) { return this.parsePageMeta(this.blockMap[block.children[0]]); } else { return false; } } // Only support YAML if (block?.code?.style?.language !== CodeLanguage.YA...
/** * Parse this first block as PageMeta * * Return false if not found first code block. * Otherwise return true if parsed as YAML, false if not YAML. * * https://longbridge.github.io/feishu-pages/zh-CN/page-meta * * @param block * @returns */
https://github.com/longbridge/feishu-pages/blob/5de303b2e644afcfe8ab0369320fce088f05cd65/feishu-docx/src/markdown_renderer.ts#L171-L202
5de303b2e644afcfe8ab0369320fce088f05cd65
feishu-pages
github_2023
longbridge
typescript
Renderer.parse
parse(): string { const entryBlock = this.blockMap[this.documentId]; return this.parseBlock(entryBlock, 0); }
/** * Parse Feishu doc to new format * @returns Text of new format content. */
https://github.com/longbridge/feishu-pages/blob/5de303b2e644afcfe8ab0369320fce088f05cd65/feishu-docx/src/renderer.ts#L37-L40
5de303b2e644afcfe8ab0369320fce088f05cd65
feishu-pages
github_2023
longbridge
typescript
Renderer.withSubIndent
withSubIndent(fn: () => void) { const oldIndent = this.indent; fn(); this.indent = oldIndent; }
/** * Wrap with sub indent, after the function, will restore the old indent * @param indent * @param fn */
https://github.com/longbridge/feishu-pages/blob/5de303b2e644afcfe8ab0369320fce088f05cd65/feishu-docx/src/renderer.ts#L51-L55
5de303b2e644afcfe8ab0369320fce088f05cd65
feishu-pages
github_2023
longbridge
typescript
Renderer.addFileToken
addFileToken(type: 'file' | 'image' | 'board', token: string) { this.fileTokens[token] = { token, type, }; }
/** * Add a file token to context * @param type * @param token */
https://github.com/longbridge/feishu-pages/blob/5de303b2e644afcfe8ab0369320fce088f05cd65/feishu-docx/src/renderer.ts#L62-L67
5de303b2e644afcfe8ab0369320fce088f05cd65
feishu-pages
github_2023
longbridge
typescript
Buffer.trimLastIfEndsWith
trimLastIfEndsWith(part: string): boolean { if (part.length == 0) { return false; } const lastIdx = this.buffer.length - 1; const lastStr = this.buffer[lastIdx]; if (!lastStr) { return false; } if (lastStr.endsWith(part)) { this.buffer[lastIdx] = lastStr.slice(0, -part.len...
/** * Remove last string if ends with part * @param part * @returns */
https://github.com/longbridge/feishu-pages/blob/5de303b2e644afcfe8ab0369320fce088f05cd65/feishu-docx/src/string_buffer.ts#L36-L53
5de303b2e644afcfe8ab0369320fce088f05cd65
feishu-pages
github_2023
longbridge
typescript
isValidCacheExist
const isValidCacheExist = (cacheFilePath: string) => { if (fs.existsSync(cacheFilePath)) { const stats = fs.statSync(cacheFilePath); if (stats.size > 0) { return true; } else { console.warn("file", cacheFilePath, "size is 0"); } } return false; };
/** * Check if Cache File exist, and content-length > 0 */
https://github.com/longbridge/feishu-pages/blob/5de303b2e644afcfe8ab0369320fce088f05cd65/feishu-pages/src/feishu.ts#L224-L234
5de303b2e644afcfe8ab0369320fce088f05cd65
feishu-pages
github_2023
longbridge
typescript
downloadFiles
const downloadFiles = async ( content: string, fileTokens: Record<string, FileToken>, hasDocCache: boolean, ) => { if (SKIP_ASSETS) { console.info('skip assets download.'); return content; } for (const fileToken in fileTokens) { let base_filename = fileToken; if (fileTokens[fileToken].type =...
/** * This alwasy download assets into ./assets into the docFolder (same folder as the doc). * * @param content * @param fileTokens * @param boardTokens * @param docFolder * @returns */
https://github.com/longbridge/feishu-pages/blob/5de303b2e644afcfe8ab0369320fce088f05cd65/feishu-pages/src/index.ts#L147-L182
5de303b2e644afcfe8ab0369320fce088f05cd65
tinijs
github_2023
tinijs
typescript
hasLinebreak
const hasLinebreak = (str: string) => str.indexOf('\r') !== -1 || str.indexOf('\n') !== -1;
// utils
https://github.com/tinijs/tinijs/blob/a6c0110a9b21f1831c3eb7f8fbe06854d6f4e606/apps/tinijs.dev/app/utils/code.ts#L20-L21
a6c0110a9b21f1831c3eb7f8fbe06854d6f4e606
tinijs
github_2023
tinijs
typescript
pending
const pending = async () => { let result = dependencyRegistry.instances.get(depId); if (!result) { const register = dependencyRegistry.registers.get(depId); if (!register) throw NO_REGISTER_ERROR(depId); result = dependencyRegistry.instances .set(depId, await register()) ...
// the pending
https://github.com/tinijs/tinijs/blob/a6c0110a9b21f1831c3eb7f8fbe06854d6f4e606/packages/core/lib/decorators/inject.ts#L10-L20
a6c0110a9b21f1831c3eb7f8fbe06854d6f4e606
tinijs
github_2023
tinijs
typescript
BaseLayoutElement.composeStyles
protected composeStyles(props: LayoutProps) { const result: string[] = []; /* eslint-disable prettier/prettier */ if (props.container) result.push(`container: ${props.container};`); if (props.containerType) result.push(`container-type: ${props.containerType};`); if (props.containerName) result.push(...
/* eslint-enable prettier/prettier */
https://github.com/tinijs/tinijs/blob/a6c0110a9b21f1831c3eb7f8fbe06854d6f4e606/packages/ui/lib/classes/layout.ts#L260-L362
a6c0110a9b21f1831c3eb7f8fbe06854d6f4e606
sophosia
github_2023
sophosia
typescript
_updateAppState
async function _updateAppState(state: AppState) { try { await db.put(state); } catch (error) { console.log(error); } }
/** * Asynchronously updates the application state in the database. * * @param {AppState} state - The AppState object containing the current state of the application. * This object should include various state parameters such as ribbon toggle button UID, menu sizes, * visibility flags for different menus, the sele...
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/appState/index.ts#L61-L67
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
JsonDB.nanoid
get nanoid() { return nanoid(); }
/** * Generate a length-8 id with alphabets 0-9A-Z */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/jsondb.ts#L32-L34
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
JsonDB.get
async get(id: string): Promise<Doc> { if (!this.config.storagePath) throw Error("storagePath not set"); const code2Folder = { SA: "pdfAnnotation", SS: "pdfState", }; let path = ""; if (id.slice(0, 2) in code2Folder) path = await join( this.config.storagePath, ".soph...
/** * Retrieves a document by its ID from storage. * * @param {string} id - The identifier of the document. * @returns {Promise<Doc>} The document associated with the given ID. * @throws Error if storage path is not set or if the document is not found. * * Determines the file path based on the ID a...
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/jsondb.ts#L45-L70
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
JsonDB.put
async put(doc: Doc) { if (!this.config.storagePath) throw Error("storagePath not set"); let path = await join( this.config.storagePath, ".sophosia", doc.dataType, `${doc._id}.json` ); await writeTextFile(path, JSON.stringify(doc)); }
/** * Stores a document in the storage. * * @param {Doc} doc - The document to store or update. * @throws Error if the storage path is not set. * * Serializes the document as JSON and writes it to the specified path. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/jsondb.ts#L80-L89
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
JsonDB.post
async post(doc: { dataType: string }) { if (!this.config.storagePath) throw Error("storagePath not set"); (doc as Doc)._id = nanoid(10); await this.put(doc as Doc); }
/** * Asynchronously adds a new document with a unique ID to the storage. * * @param {Object} doc - An object with the 'dataType' property. * @throws Error if the storage path is not configured. * * Generates a unique '_id' for the document, then uses the 'put' method to store it. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/jsondb.ts#L99-L103
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
JsonDB.getDocs
async getDocs(dataType: string): Promise<Doc[]> { if (!this.config.storagePath) throw Error("storagePath not set"); let dir = await join(this.config.storagePath, ".sophosia", dataType); let files = await readDir(dir); let promises = files.map(async (file) => { try { return JSON.parse(await...
/** * Retrieves all documents of a specific data type from storage. * * @param {string} dataType - The type of the documents to retrieve. * @returns {Promise<Doc[]>} An array of documents of the specified type. * @throws Error if the storage path is not set. * * Reads all files from the directory a...
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/jsondb.ts#L125-L138
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
JsonDB.bulkDocs
async bulkDocs(docs: Doc[]) { if (!this.config.storagePath) throw Error("storagePath not set"); let promises = docs.map(async (doc) => { try { await this.put(doc); } catch (error) { console.log(error); } }); return await Promise.all(promises); }
/** * Stores multiple documents in storage in bulk. * * @param {Doc[]} docs - An array of documents to be stored. * @throws Error if the storage path is not set. * * Utilizes the 'put' method to store each document. Handles errors individually for each document. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/jsondb.ts#L148-L159
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
JsonDB.getConfig
async getConfig() { try { let config = JSON.parse( await readTextFile("workspace.json", { dir: BaseDirectory.AppConfig }) ); this.config.storagePath = config.storagePath; this.config.language = config.language || "en_US"; this.config.lastScanTime = config.lastScanTime || 0; ...
/** * Loads and sets configuration settings from a JSON file. * * Reads the 'workspace.json' file and updates the configuration settings. * Defaults are provided for unspecified settings. * * Handles and logs any errors that occur during file reading or parsing. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/jsondb.ts#L169-L183
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
JsonDB.setConfig
async setConfig(config: Config) { try { if (!(await exists(await appConfigDir()))) await createDir(await appConfigDir()); // we need to assign variable even if it is "", unless it's undefined if (config.language !== undefined) this.config.language = config.language; if (config.storag...
/** * Updates and saves configuration settings to a JSON file. * * @param {Config} config - The configuration settings to be updated. * * Validates and updates the application's configuration based on the provided 'config' object. * Ensures the configuration directory exists before saving the file. ...
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/jsondb.ts#L194-L215
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
JsonDB.createHiddenFolders
async createHiddenFolders() { if (!this.config.storagePath) throw Error("storagePath not set"); try { for (let folder of [ "appState", "layout", "pdfAnnotation", "pdfState", "image", "plugin", ]) { const folderPath = await join( this....
/** * Creates a series of hidden folders for application data storage. * * Ensures the existence of a base '.sophosia' folder and specific subfolders within the configured storage path. * Handles and logs any errors encountered during folder creation. * * @throws Error if the storage path is not set. ...
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/jsondb.ts#L226-L249
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
SQLDatabase.createTables
async createTables() { const _sqldb = await this.load(); if (!_sqldb) return; // store a meta, _id is understood as projectId await _sqldb.execute( "CREATE VIRTUAL TABLE IF NOT EXISTS metas USING fts5 (_id, type, citationKey, originalTitle, title, abstract, issued, publisher, containerTitle, conta...
/** * Creates virtual tables if they do not exist, do nothing if they exist. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/sqlite.ts#L37-L72
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
getFolders
async function getFolders(): Promise<Folder[] | undefined> { try { const path = await join(db.config.storagePath, ".sophosia", "folder"); if (!(await exists(path))) return; const entries = await readDir(path); const folders = [] as Folder[]; for (const entry of entries) { folders.push(JSON.p...
/** * Get all folder data from the hidden folder * * @returns {Promise<Folder[] | undefined>} folders - folder data */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/migration/v0.17.0tov0.18.0.ts#L76-L87
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
removeFolders
async function removeFolders() { const path = await join(db.config.storagePath, ".sophosia", "folder"); await removeDir(path, { recursive: true }); }
/** * Remove the folder directory from the hidden folder */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/migration/v0.17.0tov0.18.0.ts#L92-L95
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
buildIdToPathMap
function buildIdToPathMap(folders: Folder[]): Record<string, string> { const idToFolderMap: Record<string, Folder> = {}; const idToPathMap: Record<string, string> = {}; // step 1: create a map from folderId to Folder for easy lookup folders.forEach((folder) => { idToFolderMap[folder._id] = folder; }); ...
/** * Build a map to convert folderId to category path * * @example * folderIdToPathMap[SF123456] -> library/Plasma Physics * * @param {Folder[]} folders - folder data * @returns {Record<string, string>} folderIdToPathMap - a hasmap like this {folderId: categoryPath} */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/migration/v0.17.0tov0.18.0.ts#L106-L143
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
getPath
function getPath(folderId: string): string { if (idToPathMap[folderId]) { return idToPathMap[folderId]; } const folder = idToFolderMap[folderId]; if (!folder) return ""; // for library folder, keep it to library instead of Library or 项目库 const path = folder._id === "SFlibrary" ? "library...
// step 2: function to build path recursively
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/database/migration/v0.17.0tov0.18.0.ts#L116-L135
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
getNodeCluster
async function getNodeCluster(itemId: string | undefined): Promise<NodeUI[]> { const nodes = [] as NodeUI[]; if (!itemId) return nodes; let parent: string | undefined; let label: string; let type: "project" | "note" | "annotation"; const dataType = getDataType(itemId); if (dataType === "note") { const...
/** * Given an itemId, return the cluster of nodes consists of the item itself, project and notes associated with item. * * @param {string} itemId * @returns {Promise<NodeUI[]>} nodes * * @example * project * |-- notes * | |-- note1 * | |-- note2 * | * |-- annots * |-- annot...
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/graph/index.ts#L128-L174
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
extractMetaFromMarkdown
async function extractMetaFromMarkdown(filePath: string) { const projectId = pathToId(filePath).split("/")[0]; const project = (await projectFileAGUD.getProject(projectId)) as Project; await projectSQLAGUD.addProject(project); }
/** * Extract meta data from a folder note * * @param {string} filePath - path to the folder note */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/indexer/index.ts#L124-L128
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
extractMarkdownContent
async function extractMarkdownContent(filePath: string) { const noteId = pathToId(filePath); const projectId = noteId.split("/")[0]; const content = await readTextFile(filePath); const meta = await metadata(filePath); const note = { _id: noteId, projectId: projectId, type: NoteType.MARKDOWN, t...
/** * Extract content from a normal markdown note * * @param {string} filePath - path to the markdown note */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/indexer/index.ts#L135-L149
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
extractMarkdownLinks
async function extractMarkdownLinks(filePath: string) { const source = pathToId(filePath); const content = await readTextFile(filePath); const regex = /\[[\w\/\:\-]*\]\((?!www\.)(?!http:)(?!https:)[\w\/\:\-]*\)/g; const matches = content.match(regex) || []; for (const match of matches) { const submatch = ...
/** * Extract all out links given the content of the markdown file * * @param filePath[string] - absolute path to the markdown file */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/indexer/index.ts#L156-L167
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
extractExcalidrawContent
async function extractExcalidrawContent(filePath: string) { const meta = await metadata(filePath); const data = JSON.parse(await readTextFile(filePath)); let texts = [] as string[]; for (const element of data.elements) { if (element.type === "text" && !element.isDeleted) { texts.push(`${element.text}`...
/** * Extract texts from an excalidraw file * * @param {string} filePath - absolute path to the excalidraw file */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/indexer/index.ts#L174-L195
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
extractAnnotContent
async function extractAnnotContent(filePath: string) { const annot = JSON.parse(await readTextFile(filePath)) as AnnotationData; insertAnnot(annot); }
/** * Extract content of a PDF annotation * * @param {string} filePath - absolute path to the annotation json file */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/indexer/index.ts#L202-L205
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
insertAnnot
async function insertAnnot(annot: AnnotationData) { await sqldb.execute("DELETE FROM annotations WHERE _id = $1", [annot._id]); await sqldb.execute( `INSERT INTO annotations (projectId, _id, type, rects, color, pageNumber, content, timestampAdded, timestampModified) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,...
/** * Insert annotation into pdf_annotations table * * @param {AnnotationData} annot - a PDF annotaiton */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/indexer/index.ts#L212-L229
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
insertNote
async function insertNote(note: { _id: string; projectId: string; type: NoteType; content: string; timestampAdded: number; timestampModified: number; }) { await sqldb.execute("DELETE FROM notes WHERE _id = $1", [note._id]); await sqldb.execute( `INSERT INTO notes (projectId, _id, type, content, time...
/** * Insert a note into notes table * * @param {{ id: string; projectId: string; type: NoteType; content: string; timestampAdded: number; timestampModified: number; }} note - note to be inserted */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/indexer/index.ts#L243-L264
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
_updateLayout
async function _updateLayout(layout: Layout) { try { await db.put({ _id: "layout", dataType: "layout", layout: layout, } as LayoutData); } catch (error) { console.log(error); } }
/** * Asynchronously updates the layout configuration in the database. * * @param {Layout} layout - The configuration object for the layout. * * The function retrieves the current layout configuration from the database, updates its configuration with * the provided config object, and then saves the updated layout...
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/layout/index.ts#L53-L63
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
insertOrUpdateNote
async function insertOrUpdateNote( noteId: string, props: Note & { content: string; timestampAdded: number; timestampModified: number; } ) { await sqldb.execute("DELETE FROM notes WHERE _id = $1", [noteId]); await sqldb.execute( `INSERT INTO notes (projectId, _id, type, content, timestampAdded...
/** * Insert or update a note in notes table * * @async * @param {string} noteId - the original noteId * @param {Note & { content: string; timestampAdded: number; timestampModified: number; }} props - new properties of the note */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/note/index.ts#L101-L122
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
AnnotationFactory.getSelectionRects
getSelectionRects(): Rect[] { let selection = window.getSelection(); if (!selection || selection.isCollapsed) return []; let range = selection.getRangeAt(0); // convert DOMRectList to Array since we need filter function let rects = Array.from(range.getClientRects()); // remove invalid selection...
/** * Get user selected rects * @returns selection rectangles */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfannotation/annotationFactory.ts#L27-L92
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
AnnotationFactory.build
build(annotData: AnnotationData) { let annot: Annotation | null; switch (annotData.type) { case AnnotationType.HIGHLIGHT: annot = new Highlight(annotData); break; case AnnotationType.UNDERLINE: annot = new Underline(annotData); break; case AnnotationType.STRIKEO...
/** * Build Annotation by annotation data * @param annotData * @returns */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfannotation/annotationFactory.ts#L122-L148
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
AnnotationFactory.buildSelectionBasedAnnot
buildSelectionBasedAnnot( tool: AnnotationType, color: string, e: { pageNumber: number; source: PDFPageView } ) { let rects = this.getSelectionRects(); if (rects.length === 0) return; let canvasWrapper = e.source.canvas?.parentElement as HTMLElement; for (let [i, rect] of rects.entries()) ...
/** * Used to build Highlight, Underline, and Strikeout annotation * @param tool * @param color * @param e * @returns */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfannotation/annotationFactory.ts#L157-L182
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
AnnotationStore.add
async add(annot: Annotation, saveToDB?: boolean) { if (saveToDB) await annot.update({} as AnnotationData); if (!this.getById(annot.data._id)) this.annots.push(annot); }
/** * Save annotData to db and push it to annots list * @param annot * @param saveToDB */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfannotation/annotationStore.ts#L32-L35
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
AnnotationStore.update
async update(annotId: string, props: AnnotationData) { let annot = this.getById(annotId); if (annot) await annot.update(props); }
/** * Update annotData in db, the annot object in the list will be updated automatically * @param annotId * @param props */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfannotation/annotationStore.ts#L42-L45
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
AnnotationStore.delete
async delete(annotId: string) { let ind = this.annots.findIndex((annot) => annot.data._id === annotId); if (ind > -1) { let annot = this.annots[ind]; await annot.delete(); this.annots.splice(ind, 1); } }
/** * Delete annotData in db and remove it from annots list * @param annotId */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfannotation/annotationStore.ts#L51-L58
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
AnnotationStore.loadFromDB
async loadFromDB() { try { // try to get it from sqldb first let annotDatas = (await sqldb.select<AnnotationData[]>( "SELECT * FROM annotations WHERE projectId = $1", [this.projectId] )) || []; if (annotDatas.length > 0) { for (const annotData of annotDa...
/** * Load and return annotDatas with current projectId from db * @returns annotDatas */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfannotation/annotationStore.ts#L64-L92
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
Ink.setDrawable
setDrawable(isDrawable: boolean) { if (!this.annotationEditorLayer) return; this.annotationEditorLayer.style.pointerEvents = isDrawable ? "auto" : "none"; }
// for dev use
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfannotation/annotations.ts#L414-L419
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.init
init(container: HTMLDivElement) { const eventBus = new pdfjsViewer.EventBus(); const pdfLinkService = new pdfjsViewer.PDFLinkService({ eventBus, }); const pdfFindController = new pdfjsViewer.PDFFindController({ eventBus, linkService: pdfLinkService, }); // l10n resource co...
/** * Initializes the PDF viewer and associated components. * @param {HTMLDivElement} container - The container element for the PDF viewer. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L91-L282
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.loadPDF
async loadPDF(filePath: string) { const cMapUrl = (process.env.DEV ? "http://localhost:9000/" : "") + "pdfjs/cmaps/"; // TODO: wait until tauri-v2 to have a better performance on this // let buffer = await readBinaryFile(filePath); const url = await convertFileSrc(filePath); this.pdfDocument =...
/** * Loads a PDF document into the viewer. * @param {string} filePath - The file path of the PDF document. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L288-L308
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.loadState
async loadState(projectId: string): Promise<PDFState | undefined> { try { let state = await db.get("SS" + projectId.slice(2)); // doing this we can make sure if anything missing from db, the default values are there Object.assign(this.state, state); return this.state; } catch (error) { ...
/** * Loads the saved state for a specific project. * @param {string} projectId - The project ID. * @returns {Promise<PDFState | undefined>} The loaded PDF state or undefined if an error occurs. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L315-L324
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication._saveState
private async _saveState(state: PDFState) { if (!this.container) return; // also save the scroll position state.scrollLeft = this.container.scrollLeft; state.scrollTop = this.container.scrollTop; try { if (!state._id) state._id = `SS${state.projectId.slice(2)}`; await db.put(state); ...
/** * Saves the current state of the PDF viewer. * @param {PDFState} state - The state to save. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L330-L347
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.loadAnnotations
async loadAnnotations() { let annotDatas = await this.annotStore.loadFromDB(); for (let annotData of annotDatas) { let annot = this.annotFactory.build(annotData); if (annot) this.annotStore.add(annot); } }
/** * Create annotations from db */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L352-L358
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.changePageNumber
changePageNumber(pageNumber: number) { if (!this.pdfViewer) return; this.pdfViewer.currentPageNumber = pageNumber; }
/** * Changes the current page number in the PDF viewer. * @param {number} pageNumber - The page number to navigate to. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L364-L367
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.jumpToPageHistory
jumpToPageHistory(indexDelta: number) { this.isPageHistoryJump = true; if ( this.pageHistoryIndex.value + indexDelta < 0 || this.pageHistoryIndex.value + indexDelta > this.state.pageHistory.length - 1 ) return; this.pageHistoryIndex.value += indexDelta; const pageNumber = t...
/** * Jump to next/previous history page * @param {number} indexDelta - Next history: +1, previous history: -1 */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L373-L384
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.changeSpreadMode
changeSpreadMode(spreadMode: SpreadMode) { if (!this.pdfViewer) return; this.pdfViewer.spreadMode = spreadMode; }
/** * Sets the spread mode for viewing pages in the PDF. * @param {SpreadMode} spreadMode - The spread mode to apply. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L390-L393
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.changeScale
changeScale(params: { delta?: number; scaleValue?: "page-width" | "page-height"; scale?: number; }) { if (!this.pdfViewer) return; if (!!params.delta) this.pdfViewer.currentScale += params.delta; if (!!params.scaleValue) this.pdfViewer.currentScaleValue = params.scaleValue; if (!!p...
/** * Adjusts the scale of the PDF view. * @param {Object} params - Parameters for scaling, including delta, scale value, and scale factor. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L399-L411
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.changeTool
changeTool(tool: AnnotationType) { this.state.tool = tool; }
/** * Changes the current annotation tool. * @param {AnnotationType} tool - The annotation tool to be set. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L417-L419
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.changeColor
changeColor(color: string) { this.state.color = color; }
/** * Updates the color setting for annotations. * @param {string} color - The color value to set. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L425-L427
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.changeViewMode
changeViewMode(darkMode: boolean) { this.state.darkMode = darkMode; let viewer = this.container?.querySelector( ".pdfViewer" ) as HTMLElement | null; if (!viewer) return; if (darkMode) viewer.style.filter = "invert(64%) contrast(228%) brightness(80%) hue-rotate(180deg)"; else...
/** * Toggles the dark mode view for the PDF. * @param {boolean} darkMode - Indicates whether to enable or disable dark mode. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L433-L443
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.changeInkThickness
changeInkThickness(thickness: number) { this.state.inkThickness = thickness; }
/** * Sets the thickness for ink-based annotations. * @param {number} thickness - The thickness of the ink. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L449-L451
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.changeInkOpacity
changeInkOpacity(opacity: number) { this.state.inkOpacity = opacity; }
/** * Sets the opacity for ink-based annotations. * @param {number} opacity - The opacity level of the ink. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L457-L459
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication._centerAtPos
_centerAtPos(oldScale: number, x: number, y: number) { if (!this.pdfViewer) return; const scaleDiff = this.pdfViewer.currentScale / oldScale - 1; if (scaleDiff !== 0) { const [top, left] = this.pdfViewer.containerTopLeft; this.pdfViewer.container.scrollLeft += (x - left) * scaleDiff; this....
/** * Restore to cursor position after zoom * @param oldScale - previous zoom scale * @param x - current cursor x-coord, event.clientX * @param x - current cursor y-coord, event.clientY */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L467-L475
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.handleCtrlScroll
handleCtrlScroll(e: WheelEvent) { if (!this.pdfViewer || !this.container) return; if (e.ctrlKey === true) { // this is not scrolling, so we need to // disable the default action avoid the offsetParent not set error e.preventDefault(); const MIN_SCALE = 0.5; const MAX_SCALE = 2.5; ...
/** * Handles scroll events with control key for zooming in and out. * @param {WheelEvent} e - The wheel event triggered by user action. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L481-L505
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.getPageLabels
async getPageLabels() { if (this.pdfDocument === undefined) return []; let labels = await this.pdfDocument.getPageLabels(); if (labels === null) labels = []; Object.assign(this.pageLabels, labels); }
/** * Retrieves page labels for the PDF document. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L510-L515
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.getTOC
async getTOC() { if (this.pdfDocument === undefined) return []; function _dfs(oldNodes: TOCNode[]): TOCNode[] { const tree = [] as TOCNode[]; for (let k in oldNodes) { let node = { label: oldNodes[k].title, children: _dfs(oldNodes[k].items), } as TOCNode; ...
/** * Loads the table of contents for the PDF document. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L520-L546
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.getTOCPage
async getTOCPage(node: TOCNode): Promise<number> { if (this.pdfDocument === undefined) return 1; let pageNumber = 1; if (node.ref === undefined) { let dest = await this.pdfDocument.getDestination(node.dest as string); if (!!dest && dest?.length > 0) { let ref = dest[0]; let pag...
/** * Retrieves the page number associated with a TOCNode. * @param {TOCNode} node - The table of contents node. * @returns {Promise<number>} The page number associated with the TOCNode. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L553-L570
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.clickTOC
async clickTOC(node: TOCNode) { let pageNumber = await this.getTOCPage(node); this.changePageNumber(pageNumber); }
/** * Navigates to a specified page from the table of contents. * @param {TOCNode} node - The TOCNode representing the target page. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L576-L579
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.searchText
searchText(search: PDFSearch) { if (!this.eventBus) return; this.eventBus.dispatch("find", search); }
/** * Initiates a text search in the PDF document. * @param {PDFSearch} search - The search parameters. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L585-L588
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.changeMatch
changeMatch(delta: number) { if (!this.pdfFindController || !this.eventBus) return; // delta can only be +1 (next) or -1 (prev) // highlight the next/previous match if (this.pdfFindController.selected === undefined) return; if (this.pdfFindController.pageMatches === undefined) return; let curre...
/** * Navigates to the next or previous search match. * @param {number} delta - The direction and magnitude to move among search matches. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L594-L629
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PDFApplication.scrollAnnotIntoView
scrollAnnotIntoView(annotId: string) { if (!!!annotId) return; let annot = this.annotStore.getById(annotId) as Annotation; // change number first in case the dom is not rendered this.changePageNumber(annot.data.pageNumber); annot.doms[0].scrollIntoView({ block: "center", inline: "center"...
/** * Scrolls the view to center on a specified annotation. * @param {string} annotId - The ID of the annotation to view. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/index.ts#L635-L647
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PeekManager.create
create(link: HTMLAnchorElement) { if ( this.links.findIndex( (l) => l.getAttribute("id") === link.getAttribute("id") ) === -1 ) this.links.push(link); }
/** * Create a peeker for the given link */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/peekManager.ts#L16-L23
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PeekManager.destroy
destroy(elementId: string) { if (!this.supposeToDestroy) return; // don't know why filter doesn't work here let ind = this.links.findIndex((link) => link.id === elementId); if (ind > -1) this.links.splice(ind, 1); }
/** * Destroy the peeker of the given peekerId */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/pdfreader/peekManager.ts#L28-L33
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PluginManager.init
async init() { await this.loadAll(); }
/** * Initialize pluginManager */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/plugin/index.ts#L59-L61
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PluginManager.filter
filter(text: string | null, local: boolean): PluginManifest[] { const manifests = local ? this.pluginManifests : this.communityManifests; if (!text) return manifests.value; const re = RegExp(text, "i"); // case insensitive return manifests.value.filter((meta) => { for (const [key, value] of Object...
/** * Filter plugin metas * @param text * @param local - are we filtering local plugins or community plugins */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/plugin/index.ts#L71-L80
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PluginManager.download
async download(meta: PluginManifest) { const client = await getClient(); for (const file of ["main.js", "style.css", "manifest.json"]) { const directory = await join(await this.pluginFolder(), meta.id); const filePath = await join(directory, file); if (!(await exists(directory))) await createD...
/** * Download 3 files: main.js, styles.css, and manifest.json * To update plugin, simply download it again */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/plugin/index.ts#L100-L114
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PluginManager.delete
async delete(meta: PluginManifest) { this.statusMap.value.delete(meta.id); this.plugins.value.delete(meta.id); this.pluginManifests.value = this.pluginManifests.value.filter( (m) => m.id != meta.id ); await this.saveStatus(); const directory = await join(await this.pluginFolder(), meta.id)...
/** * Delete a plugin on disk */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/plugin/index.ts#L119-L128
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PluginManager.loadAll
async loadAll() { await this.loadStatus(); for (const [id, status] of this.statusMap.value.entries()) { if (!this.plugins.value.has(id)) await this.load(id, status.enabled); } }
/** * Load all plugins */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/plugin/index.ts#L136-L141
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PluginManager.reloadAll
async reloadAll() { this.statusMap.value.clear(); this.pluginManifests.value = []; this.communityManifests.value = []; this.plugins.value.clear(); await this.loadAll(); }
/** * Clear all data and then load all plugins */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/plugin/index.ts#L146-L153
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PluginManager.load
async load(pluginId: string, enabled: boolean) { const pluginPath = await join(await this.pluginFolder(), pluginId); const manifestPath = await join(pluginPath, "manifest.json"); const manifest = JSON.parse(await readTextFile(manifestPath)); let jsPath = await join(pluginPath, "main.js"); let styleP...
/** * Load all plugins from disk */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/plugin/index.ts#L158-L178
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PluginManager._load
private _load(pluginId: string, plugin: Plugin) { // register elements plugin.addButton = (button) => { button.id = `${pluginId}-${button.id}`; this.buttons.value.push(button); }; plugin.addView = (view) => { view.id = `${pluginId}-${view.id}`; this.views.value.push(view); };...
/** * Bind functions to the plugin class instance * @param plugin */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/plugin/index.ts#L184-L233
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PluginManager.toggle
async toggle(pluginId: string, enabled: boolean) { const plugin = this.plugins.value.get(pluginId); if (!plugin) return; let status = this.statusMap.value.get(pluginId); // if no status, meaning we just downloaded, it shouldn't be updatable if (!status) status = { enabled: enabled, updatable: false...
/** * Enable / Disable a plugin * @param enabled */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/plugin/index.ts#L239-L261
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PluginManager.loadStatus
async loadStatus() { const filePath = await join(await this.pluginFolder(), "status.json"); if (!(await exists(filePath))) return; const status = JSON.parse(await readTextFile(filePath)); this.statusMap.value = new Map(Object.entries(status)); }
/** * Get plugin status * {pluginId: {enabled: boolean, updatable: boolean}} */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/plugin/index.ts#L267-L272
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PluginManager.getButtons
getButtons(component: Component) { return this.buttons.value.filter((btn) => btn.component == component); }
/*********************************************************** * Getters for buttons and views **********************************************************/
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/plugin/index.ts#L284-L286
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
PluginManager.pluginFolder
private async pluginFolder(): Promise<string> { return await join(db.config.storagePath, ".sophosia", "plugin"); }
/** * Get the path to `plugins` folder * @returns path to `plugins` folder */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/plugin/index.ts#L337-L339
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
ProjectFileAGUD.getPDF
async getPDF(projectId: string) { try { const projectFolder = idToPath(projectId); const entries = await readDir(projectFolder); for (const entry of entries) { try { if ((await extname(entry.path)) === "pdf") return entry.path; } catch (error) {} } } catch (erro...
/** * Retrieve the path of the first PDF file found within a project folder. * * @param projectId - The unique identifier of the project. * @returns The path of the first PDF file found, or undefined if no PDF is found or an error occurs. */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/project/fileOps.ts#L86-L98
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
ProjectFileAGUD.renamePDF
async renamePDF(projectId: string, renameRule: string) { const project = await this.getProject(projectId); if (!project) return; project.path = await this.getPDF(projectId); if (project.path === undefined) return; const oldPath = project.path; const fileName = generateCiteKey(project, renameRule...
/** * Renames the PDF file associated with a project based on a generated citation key. * * @param projectId - The project whose associated PDF needs renaming. * @returns The new path of the renamed PDF file or undefined if the project has no associated path. * * Generates a new filename using the cit...
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/project/fileOps.ts#L108-L118
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
ProjectFileAGUD.attachPDF
async attachPDF(projectId: string): Promise<string | undefined> { const filePath = await open({ multiple: false, filters: [{ name: "*.pdf", extensions: ["pdf"] }], }); if (typeof filePath !== "string") return; const oldPDFPath = await this.getPDF(projectId); if (oldPDFPath) await remove...
/** * Attaches a PDF file to a project by copying it to the project's folder. * * @param {string} projectId - The ID of the project to attach the PDF to. * @returns {Promise<string | undefined>} The path of the copied PDF file in the project's folder, or undefined if no file is selected. * * Opens a f...
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/project/fileOps.ts#L139-L149
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
ProjectFileAGUD.loadProjectNote
async loadProjectNote(projectId: string): Promise<Project | undefined> { try { const folderNote = await readTextFile( idToPath(`${projectId}/${projectId}.md`) ); const lines = folderNote.split("\n"); const startIndex = lines.indexOf("```json"); const endIndex = lines.indexOf("`...
/** * Load project from markdown note in project folder * * @param {string} projectId * @returns {Promise<Project | undefined>} - Project data without pdf and notes */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/project/fileOps.ts#L178-L194
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
ProjectFileAGUD.createProjectFolder
async createProjectFolder(project: Project) { try { // create project folder const projectPath = idToPath(project._id); if (!(await exists(projectPath))) await createDir(projectPath); await this.saveProjectNote(project); } catch (error) { console.log(error); } }
/** * Creates a project folder and initializes a Markdown note file for the given project. * * @param {Project} project - The project for which the folder and note file are to be created. * * Creates a new directory for the project in the designated storage path, and a Markdown file * with basic proje...
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/project/fileOps.ts#L207-L216
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
ProjectFileAGUD.deleteProjectFolder
async deleteProjectFolder(projectId: string) { try { await removeDir(idToPath(projectId), { recursive: true }); } catch (error) { console.log(error); } }
/** * Delete the project folder in storage path * @param projectId */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/project/fileOps.ts#L222-L228
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
ProjectFileAGUD.copyFileToProjectFolder
async copyFileToProjectFolder( srcPath: string, projectId: string ): Promise<string | undefined> { try { const fileName = await basename(srcPath); const dstPath = idToPath(`${projectId}/${fileName}`); await copyFile(srcPath, dstPath); return fileName; } catch (error) { c...
/** * Copy file to the corresponding project folder and returns the filename * @param srcPath * @param projectId * @returns dstPath */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/project/fileOps.ts#L236-L249
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
ProjectSQLAGUD.addProject
async addProject(project: Project): Promise<void> { await this.insertMeta(project); await this.insertTags(project._id, project.tags); await this.insertCategories(project._id, project.categories); await this.insertAuthors(project._id, project.author); }
/** * Insert/replace a project into sqlite database * * @param {Project} project * @returns {Promise<void>} */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/project/sqliteOps.ts#L36-L41
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
ProjectSQLAGUD.insertMeta
async insertMeta(meta: Project) { await sqldb.execute("DELETE FROM metas WHERE _id = $1", [meta._id]); await sqldb.execute( `INSERT INTO metas (_id, type, citationKey, originalTitle, title, abstract, issued, publisher, containerTitle, containerTitleShort, volume, DOI, ISBN, ISSN, URL, favorite, timestampA...
/** * Insert/replace meta of a project into metas table * * @param {Project} meta - meta to be inserted */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/project/sqliteOps.ts#L48-L74
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
ProjectSQLAGUD.insertAuthors
async insertAuthors(projectId: string, authors: Author[]) { for (const author of authors) { const given = author.given || ""; const family = author.family || ""; const literal = author.literal || ""; const affiliation = author.literal || ""; // insert the meta-author relation into auth...
/** * Insert/replace authors into authors table and insert relations of authors to a project * * @param {string} projectId - id to the meta * @param {Author[]} authors - list of authors to be inserted */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/project/sqliteOps.ts#L82-L95
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
ProjectSQLAGUD.insertTags
async insertTags(projectId: string, tags: string[]) { await sqldb.execute("DELETE FROM tags WHERE projectId = $1", [projectId]); for (const tag of tags) { sqldb.execute( `INSERT INTO tags (projectId, tag) SELECT $1, $2 WHERE NOT EXISTS (SELECT 1 FROM tags WHERE projectId = $1 AND tag = $2)`, ...
/** * Insert/replace tags of a project into the tags table * * @param {string} projectId - id of the meta * @param {string[]} tags - keywords of the proejcts */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/project/sqliteOps.ts#L103-L113
81080c1f9c6f96aa4f57b7e6b6f76bf209624879
sophosia
github_2023
sophosia
typescript
ProjectSQLAGUD.insertCategories
async insertCategories(projectId: string, categories: any) { await sqldb.execute("DELETE FROM categories WHERE projectId = $1", [ projectId, ]); for (const category of categories) { await sqldb.execute( `INSERT INTO categories (projectId, category) SELECT $1, $2 WHERE NOT EXISTS (SELECT ...
/** * Insert/replace categories of a project into the categories table * * @param {string} projectId - id of the project * @param {any} categories - the categories the project belongs to */
https://github.com/sophosia/sophosia/blob/81080c1f9c6f96aa4f57b7e6b6f76bf209624879/src/backend/project/sqliteOps.ts#L121-L133
81080c1f9c6f96aa4f57b7e6b6f76bf209624879