repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
hatchet
github_2023
hatchet-dev
typescript
Api.userUpdateGithubAppOauthCallback
metadataGet = (params: RequestParams = {}) => this.request<APICloudMetadata, APIErrors>({ path: `/api/v1/cloud/metadata`, method: "GET", format: "json", ...params, })
/** * @description List Github App branches * * @tags Github * @name GithubAppListBranches * @summary List Github App branches * @request GET:/api/v1/cloud/github-app/installations/{gh-installation}/repos/{gh-repo-owner}/{gh-repo-name}/branches * @secure */
https://github.com/hatchet-dev/hatchet/blob/b6bff6ba2dbbdac4ef5d7cafe8aa6d41bb52eb0a/frontend/app/src/lib/api/generated/cloud/Api.ts
b6bff6ba2dbbdac4ef5d7cafe8aa6d41bb52eb0a
hatchet
github_2023
hatchet-dev
typescript
MyApp
function MyApp({ Component, pageProps }: AppProps) { return ( <LanguageProvider> <PostHogProvider client={posthog}> <main> <Component {...pageProps} /> </main> </PostHogProvider> </LanguageProvider> ); }
// const inter = Inter({ subsets: ["latin"] });
https://github.com/hatchet-dev/hatchet/blob/b6bff6ba2dbbdac4ef5d7cafe8aa6d41bb52eb0a/frontend/docs/pages/_app.tsx#L24-L34
b6bff6ba2dbbdac4ef5d7cafe8aa6d41bb52eb0a
PandoraHelper
github_2023
nianhua99
typescript
onOpenChange
const onOpenChange: MenuProps['onOpenChange'] = (keys) => { const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1); if (latestOpenKey) { setOpenKeys(keys); } else { setOpenKeys([]); } };
/** * events */
https://github.com/nianhua99/PandoraHelper/blob/1186fa9869d06e79a491da06e7bf320aa5cad24d/frontend/src/layouts/dashboard/nav-horizontal.tsx#L42-L49
1186fa9869d06e79a491da06e7bf320aa5cad24d
PandoraHelper
github_2023
nianhua99
typescript
setLocale
const setLocale = (locale: Locale) => { i18n.changeLanguage(locale); };
/** * localstorage -> i18nextLng change */
https://github.com/nianhua99/PandoraHelper/blob/1186fa9869d06e79a491da06e7bf320aa5cad24d/frontend/src/locales/useLocale.ts#L37-L39
1186fa9869d06e79a491da06e7bf320aa5cad24d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
listener
const listener = (event: MouseEvent) => { if (isMouseEventExternal(event, backlinkItemEl)) { backlinkItemEl.removeClass('hovered-backlink'); el.removeEventListener('mouseout', listener); } };
// clear highlights in backlink pane
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/backlink-visualizer.ts#L160-L165
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
RectangleCache.getRectsForSelection
getRectsForSelection(pageNumber: number, id: string) { const idToRects = this.getIdToRectsMap(pageNumber); let rects = idToRects.get(id) ?? null; if (rects) return rects; rects = this.computeRectsForSelection(pageNumber, id); if (rects) { idToRects.set(id, rects); return rects; } return null; }
/** * Get the rectangles for the given selection id. * If the rectangles have already been computed, return the cached value. * Otherwise, newly compute and cache them. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/backlink-visualizer.ts#L276-L286
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
RectangleCache.computeRectsForSelection
computeRectsForSelection(pageNumber: number, id: string) { const pageView = this.child.getPage(pageNumber); const { beginIndex, beginOffset, endIndex, endOffset } = PDFPageBacklinkIndex.selectionIdToParams(id); const textLayer = pageView.textLayer; if (!textLayer) return null; const textLayerInfo = getTextLayerInfo(textLayer); if (!textLayerInfo || !textLayerInfo.textDivs.length) return null; const rects = this.lib.highlight.geometry.computeMergedHighlightRects(textLayerInfo, beginIndex, beginOffset, endIndex, endOffset); return rects; }
/** * Newly compute the rectangles for the given selection id. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/backlink-visualizer.ts#L291-L302
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
BibliographyManager.parseBibliographyText
async parseBibliographyText(text: string): Promise<AnystyleJson[] | null> { const { app, plugin, settings } = this; const anystylePath = settings.anystylePath; if (!anystylePath) return null; const anystyleDirPath = plugin.getAnyStyleInputDir(); // Node.js is available only in the desktop app if (Platform.isDesktopApp && app.vault.adapter instanceof FileSystemAdapter && anystyleDirPath) { // Anystyle only accepts a file as input, so we need to write the text to a file. // We store the file under the `anystyle` folder in the plugin's directory to avoid cluttering the vault. const anystyleDirFullPath = app.vault.adapter.getFullPath(anystyleDirPath); await FileSystemAdapter.mkdir(anystyleDirFullPath); const anystyleInputPath = anystyleDirPath + `/${genId()}.txt`; const anystyleInputFullPath = app.vault.adapter.getFullPath(anystyleInputPath); await app.vault.adapter.write(anystyleInputPath, text); // Clean up the file when this PDF viewer is unloaded this.register(() => app.vault.adapter.remove(anystyleInputPath)); // eslint-disable-next-line @typescript-eslint/no-var-requires const { spawn } = require('child_process') as typeof import('child_process'); return new Promise<any>((resolve) => { const anystyleProcess = spawn(anystylePath, ['parse', anystyleInputFullPath]); let resultJson = ''; anystyleProcess.stdout.on('data', (resultBuffer: Buffer | null) => { if (resultBuffer) { resultJson += resultBuffer.toString(); return; } resolve(null); }); anystyleProcess.on('error', (err: Error & { code: string }) => { if ('code' in err && err.code === 'ENOENT') { const msg = `${plugin.manifest.name}: AnyStyle not found at the path "${anystylePath}".`; if (plugin.settings.anystylePath) { const notice = new Notice(msg, 8000); notice.noticeEl.appendText(' Click '); notice.noticeEl.createEl('a', { text: 'here' }, (anchorEl) => { anchorEl.addEventListener('click', () => { plugin.openSettingTab().scrollTo('anystylePath'); }); }); notice.noticeEl.appendText(' to update the path.'); console.error(msg); } else console.warn(msg); return resolve(null); } }); anystyleProcess.on('close', (code) => { if (code) return resolve(null); const results = JSON.parse(resultJson); if (Array.isArray(results)) { // Add 'year' entry to each result for (const result of results) { for (const date of result.date ?? []) { const yearMatch = date.match(/\d{4}/); if (yearMatch) { result.year = yearMatch[0]; break; } } } resolve(results); } resolve(null); }); }); } return null; }
/** Parse a bibliography text using Anystyle. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/bib.ts#L125-L201
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
BibliographyTextExtractor.getTextContentItemsFromPageRef
async getTextContentItemsFromPageRef(pageRef: PDFJsDestArray[0]) { const refStr = JSON.stringify(pageRef); return this.pageRefToTextContentItemsPromise[refStr] ?? ( this.pageRefToTextContentItemsPromise[refStr] = (async () => { const pageNumber = await this.doc.getPageIndex(pageRef) + 1; const page = await this.doc.getPage(pageNumber); const items = (await page.getTextContent()).items as TextContentItem[]; return items; })() ); }
/** Get `TextContentItem`s contained in the specified page. This method avoids fetching the same info multiple times. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/bib.ts#L250-L261
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusContextMenu.addItems
async addItems(evt?: MouseEvent) { const { child, plugin, lib, app } = this; const pdfViewer = child.pdfViewer.pdfViewer; // const canvas = lib.workspace.getActiveCanvasView()?.canvas; const selectionObj = this.win.getSelection(); const pageAndSelection = lib.copyLink.getPageAndTextRangeFromSelection(selectionObj) ?? (pdfViewer ? { page: pdfViewer.currentPageNumber } : null); if (!pageAndSelection) return; // selection is undefined when the selection spans multiple pages const { page: pageNumber, selection } = pageAndSelection; const selectedText = lib.toSingleLine(selectionObj?.toString() ?? ''); const isVisible = (id: string) => { return this.settings.contextMenuConfig.find((section) => section.id === id)?.visible; }; // If macOS, add "look up selection" action if (Platform.isMacOS && Platform.isDesktopApp && this.win.electron && selectedText && isVisible('action')) { this.addItem((item) => { return item .setSection('action') .setTitle(`Look up "${selectedText.length <= 25 ? selectedText : selectedText.slice(0, 24).trim() + '…'}"`) .setIcon('lucide-library') .onClick(() => { // @ts-ignore this.win.electron!.remote.getCurrentWebContents().showDefinitionForSelection(); }); }); } //// Add items //// if (selectedText) { // copy with custom formats // if (selectedText && selection && child.palette) { if (isVisible('selection')) { PDFPlusProductMenuComponent .create(this, child.palette) .setSection('selection', 'Copy link to selection', 'lucide-copy') .addItems(plugin.settings.selectionProductMenuConfig) .onItemClick(({ copyFormat, displayTextFormat, colorName }) => { lib.copyLink.copyLinkToSelection(false, { copyFormat, displayTextFormat }, colorName ?? undefined); }); } // // Create a Canvas card // if (canvas && plugin.settings.canvasContextMenu) { // for (const { name, template } of formats) { // this.addItem((item) => { // return item // .setSection('selection-canvas') // .setTitle(`Create Canvas card from selection with format "${name}"`) // .setIcon('lucide-sticky-note') // .onClick(() => { // lib.copyLink.makeCanvasTextNodeFromSelection(false, canvas, template, colorName); // }); // }); // } // } if (lib.isEditable(child) && isVisible('write-file')) { PDFPlusProductMenuComponent .create(this, child.palette) .setSection('write-file', `Add ${plugin.settings.selectionBacklinkVisualizeStyle} to file`, 'lucide-edit') .setShowNoColorButton(false) .addItems(plugin.settings.writeFileProductMenuConfig) .onItemClick(({ copyFormat, displayTextFormat, colorName }) => { lib.copyLink.writeHighlightAnnotationToSelectionIntoFileAndCopyLink(false, { copyFormat, displayTextFormat }, colorName ?? undefined); }); } } } // Get annotation & annotated text const pageView = child.getPage(pageNumber); const annot = evt && child.getAnnotationFromEvt(pageView, evt); let annotatedText: string | null = null; await (async () => { if (annot) { const { id } = lib.getAnnotationInfoFromAnnotationElement(annot); annotatedText = await child.getAnnotatedText(pageView, id); // copy link to annotation with custom formats // if (child.palette && isVisible('annotation')) { PDFPlusProductMenuComponent .create(this, child.palette) .setSection('annotation', 'Copy link to annotation', 'lucide-copy') .addItems(plugin.settings.annotationProductMenuConfig) .onItemClick(({ copyFormat, displayTextFormat }) => { lib.copyLink.copyLinkToAnnotation(child, false, { copyFormat, displayTextFormat }, pageNumber, id, false, true); }); } // // Createa a Canvas card // if (canvas && plugin.settings.canvasContextMenu) { // for (const { name, template } of formats) { // this.addItem((item) => { // return item // .setSection('annotation-canvas') // .setTitle(`Create Canvas card from annotation with format "${name}"`) // .setIcon('lucide-sticky-note') // .onClick(() => { // lib.copyLink.makeCanvasTextNodeFromAnnotation(false, canvas, child, template, pageNumber, id); // }); // }); // } // } // edit & delete annotation // if (lib.isEditable(child) && isVisible('modify-annotation')) { if (plugin.settings.enableAnnotationContentEdit && PDFAnnotationEditModal.isSubtypeSupported(annot.data.subtype)) { const subtype = annot.data.subtype; this.addItem((item) => { return item .setSection('modify-annotation') .setTitle('Edit annotation') .setIcon('lucide-pencil') .onClick(() => { if (child.file) { PDFAnnotationEditModal .forSubtype(subtype, plugin, child.file, pageNumber, id) .open(); } }); }); } if (plugin.settings.enableAnnotationDeletion) { this.addItem((item) => { return item .setSection('modify-annotation') .setTitle('Delete annotation') .setIcon('lucide-trash') .onClick(() => { if (child.file) { new PDFAnnotationDeleteModal(plugin, child.file, pageNumber, id) .openIfNeccessary(); } }); }); } } if (annot.data.subtype === 'Link' && isVisible('link')) { const doc = child.pdfViewer.pdfViewer?.pdfDocument; if ('dest' in annot.data && typeof annot.data.dest === 'string' && doc && child.file) { const destId = annot.data.dest; const file = child.file; // copy PDF internal link as Obsidian wikilink (or markdown link) // this.addItem((item) => { item.setSection('link') .setTitle('Copy PDF link') .setIcon('lucide-copy') .onClick(async () => { const subpath = await lib.destIdToSubpath(destId, doc); if (typeof subpath === 'string') { let display = annotatedText; if (!display && annot.data.rect) { display = child.getTextByRect(pageView, annot.data.rect); } const link = lib.generateMarkdownLink(file, '', subpath, display ?? undefined).slice(1); // How does the electron version differ? navigator.clipboard.writeText(link); plugin.lastCopiedDestInfo = { file, destName: destId }; } }); }); if (plugin.lib.isCitationId(destId)) { this.addItem((item) => { item.setSection('link') .setTitle('Search on Google Scholar') .setIcon('lucide-search') .onClick(() => { const url = this.child.bib?.getGoogleScholarSearchUrlFromDest(destId); if (typeof url !== 'string') { new Notice(`${plugin.manifest.name}: Failed to find bibliographic information.`); return; } window.open(url, '_blank'); }); }); } } if ('url' in annot.data && typeof annot.data.url === 'string') { const url = annot.data.url; this.currentSection = 'link'; app.workspace.handleExternalLinkContextMenu(this, url); this.currentSection = null; } } } })(); // Add a PDF internal link to selection if (selectedText && selection && lib.isEditable(child) && plugin.lastCopiedDestInfo && plugin.lastCopiedDestInfo.file === child.file && isVisible('link')) { if ('destArray' in plugin.lastCopiedDestInfo) { const destArray = plugin.lastCopiedDestInfo.destArray; this.addItem((item) => { return item .setSection('link') .setTitle('Paste copied PDF link to selection') .setIcon('lucide-clipboard-paste') .onClick(() => { lib.highlight.writeFile.addLinkAnnotationToSelection(destArray); }); }); } else if ('destName' in plugin.lastCopiedDestInfo) { const destName = plugin.lastCopiedDestInfo.destName; this.addItem((item) => { return item .setSection('link') .setTitle('Paste copied link to selection') .setIcon('lucide-clipboard-paste') .onClick(() => { lib.highlight.writeFile.addLinkAnnotationToSelection(destName); }); }); } } // copy selected text only // if (selectedText && isVisible('text')) { this.addItem((item) => { return item .setSection('text') .setTitle('Copy selected text') .setIcon('lucide-copy') .onClick(() => { // How does the electron version differ? navigator.clipboard.writeText(this.plugin.settings.copyAsSingleLine ? selectedText : (selectionObj?.toString() ?? '')); }); }); } // copy annotated text only // if (annotatedText && isVisible('text')) { this.addItem((item) => { return item .setSection('text') .setTitle('Copy annotated text') .setIcon('lucide-copy') .onClick(() => { // How does the electron version differ? navigator.clipboard.writeText(annotatedText!); }); }); } if (selectedText && selection && isVisible('search')) { this.addItem((item) => { item.setSection('search') .setTitle('Copy link to search') .setIcon('lucide-search') .onClick(() => { lib.copyLink.copyLinkToSearch(false, child, pageNumber, selectedText.trim()); }); }); } if (lib.speech.isEnabled() && selectedText && isVisible('speech')) { this.addItem((item) => { item.setSection('speech') .setTitle('Read aloud selected text') .setIcon('lucide-speech') .onClick(() => { lib.speech.speak(selectedText); }); }); } if (!this.items.length && isVisible('page')) { this.addItem((item) => { item.setSection('page') .setTitle('Copy link to page') .setIcon('lucide-copy') .onClick((evt) => { const link = child.getMarkdownLink(`#page=${pageNumber}`, child.getPageLinkAlias(pageNumber)); evt.win.navigator.clipboard.writeText(link); const file = child.file; if (file) plugin.lastCopiedDestInfo = { file, destArray: [pageNumber - 1, 'XYZ', null, null, null] }; }); }); } if (this.items.length && isVisible('settings')) { this.addItem((item) => { item.setSection('settings') .setIcon('lucide-settings') .setTitle('Customize menu...') .onClick(() => { this.plugin.openSettingTab() .scrollToHeading('context-menu'); }); }); } app.workspace.trigger('pdf-menu', this, { pageNumber, selection: selectedText, annot }); }
// TODO: divide into smaller methods
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/context-menu.ts#L474-L788
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlus.cleanUpResources
async cleanUpResources() { await this.cleanUpAnystyleFiles(); }
/** Perform clean-ups not registered explicitly. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/main.ts#L126-L128
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlus.cleanUpAnystyleFiles
async cleanUpAnystyleFiles() { const adapter = this.app.vault.adapter; if (Platform.isDesktopApp && adapter instanceof FileSystemAdapter) { const anyStyleInputDir = this.getAnyStyleInputDir(); if (anyStyleInputDir) { try { await adapter.rmdir(anyStyleInputDir, true); } catch (err) { if (err.code !== 'ENOENT') throw err; } } } }
/** Clean up the AnyStyle input files and their directory (.obsidian/plugins/pdf-plus/anystyle) */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/main.ts#L131-L143
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlus.registerStyleSettings
private registerStyleSettings() { // See https://github.com/mgmeyers/obsidian-style-settings?tab=readme-ov-file#plugin-support this.app.workspace.trigger('parse-style-settings'); this.register(() => this.app.workspace.trigger('parse-style-settings')); }
/** * Tell the Style Settings plugin to parse styles.css on load and unload * so that the Style Settings pane can be updated. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/main.ts#L314-L318
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlus.registerEl
registerEl<HTMLElementType extends HTMLElement>(el: HTMLElementType) { this.register(() => el.remove()); return el; }
/** * Registers an HTML element that will be refreshed when a style setting is updated * and will be removed when the plugin gets unloaded. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/main.ts#L453-L456
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusSettingTab.redisplay
redisplay() { const scrollTop = this.contentEl.scrollTop; this.display(); this.contentEl.scroll({ top: scrollTop }); this.events.trigger('update'); }
/** Refresh the setting tab and then scroll back to the original position. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/settings.ts#L1560-L1566
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusCommands.writeHighlightAnnotationToSelectionIntoFileAndCopyLink
writeHighlightAnnotationToSelectionIntoFileAndCopyLink(checking: boolean, autoPaste: boolean = false) { const palette = this.lib.getColorPaletteAssociatedWithSelection(); if (!palette) return false; if (!palette.writeFile) return false; const template = this.settings.copyCommands[palette.actionIndex].template; // get the currently selected color const colorName = palette.selectedColorName ?? undefined; return this.lib.copyLink.writeHighlightAnnotationToSelectionIntoFileAndCopyLink(checking, { copyFormat: template }, colorName, autoPaste); }
// TODO: A better, more concise function name 😅
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/commands.ts#L270-L282
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusCommands._insertPage
_insertPage(file: TFile, page: number, basePage: number) { new PDFComposerModal( this.plugin, this.settings.askPageLabelUpdateWhenInsertPage, this.settings.pageLabelUpdateWhenInsertPage, false, false ) .ask() .then((answer) => { this.lib.composer.insertPage(file, page, basePage, answer); }); }
/** * @param file The PDF file to insert a page into * @param page The index of the new page to be inserted * @param basePage The page number to reference for the new page size */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/commands.ts#L552-L564
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFComposer.mergeFiles
async mergeFiles(file1: TFile, file2: TFile, keepLabels: boolean) { const pageCount = (await this.fileOperator.read(file1)).getPageCount(); return await this.linkUpdater.updateLinks( () => this.fileOperator.mergeFiles(file1, file2, keepLabels), [file1, file2], (f, n) => { if (f === file1) return {}; return { file: file1, pageNumber: typeof n === 'number' ? n + pageCount : n }; } ); }
/** Merge file2 into file1 by appending all pages from file2 to file1. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/composer.ts#L55-L65
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFFileOperator.write
async write(path: string, pdfDoc: PDFDocument, existOk: boolean): Promise<TFile | null> { const buffer = await pdfDoc.save(); const file = this.app.vault.getAbstractFileByPath(path); if (file instanceof TFile) { if (!existOk) { new Notice(`${this.plugin.manifest.name}: File already exists: ${path}`); } await this.app.vault.modifyBinary(file, buffer); return file; } else if (file === null) { const folderPath = normalizePath(path.split('/').slice(0, -1).join('/')); if (folderPath) { const folderExists = !!(this.app.vault.getAbstractFileByPath(folderPath)); if (!folderExists) await this.app.vault.createFolder(folderPath); } return await this.app.vault.createBinary(path, buffer); } return null; }
/** Write the content of `pdfDoc` into the specified file. If the file does not exist, it will be created. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/composer.ts#L114-L134
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFFileOperator.insertPage
async insertPage(file: TFile, pageNumber: number, basePageNumber: number, keepLabels: boolean) { const doc = await this.read(file); this.pageLabelUpdater.insertPage(doc, pageNumber, keepLabels); const basePage = doc.getPage(basePageNumber - 1); const { width, height } = basePage.getSize(); doc.insertPage(pageNumber - 1, [width, height]); return await this.write(file.path, doc, true); }
/** * @param file The PDF file to insert a page into. * @param pageNumber The index of the new page to be inserted. * @param basePageNumber The page number to reference for the new page size. * @param keepLabels Whether to keep the page labels unchanged. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/composer.ts#L150-L161
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFFileOperator.mergeFiles
async mergeFiles(file1: TFile, file2: TFile, keepLabels: boolean): Promise<TFile | null> { const [doc1, doc2] = await Promise.all([ this.read(file1), this.read(file2) ]); // TODO: implement this this.pageLabelUpdater.mergeFiles(doc1, doc2, keepLabels); const pagesToAdd = await doc1.copyPages(doc2, doc2.getPageIndices()); for (const page of pagesToAdd) doc1.addPage(page); // TODO: update outlines const resultFile = await this.write(file1.path, doc1, true); if (resultFile === null) return null; await this.app.fileManager.trashFile(file2); return resultFile; }
/** Merge file2 into file1 by appending all pages from file2 to file1. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/composer.ts#L176-L197
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFFileOperator.extractPagesAsNewFile
async extractPagesAsNewFile(srcFile: TFile, pages: number[], dstPath: string, existOk: boolean, keepLabels: boolean) { // Create a copy of the source file const doc = await this.read(srcFile); // Get the pages not to include in the resulting document (pages not in the `pages` array) const pagesToRemove = []; for (let page = 1; page <= doc.getPageCount(); page++) { if (!pages.includes(page)) pagesToRemove.push(page); } // Update page labels before actually removing pages this.pageLabelUpdater.removePages(doc, pagesToRemove, keepLabels); // From the last page to the first page, so that the page numbers don't change for (const page of pagesToRemove.sort((a, b) => b - a)) { doc.removePage(page - 1); // pdf-lib uses 0-based page numbers } // Update outlines by iteratively pruning leaves whose destinations are not in the resulting document const outlines = await PDFOutlines.fromDocument(doc, this.plugin); await outlines.prune(); return await this.write(dstPath, doc, existOk); }
/** * Extract pages from the source file and save it as a new file. The original file is not modified. * We do this by making a copy of the source file and then removing the pages not to include in the resulting document. * * @param pages 1-based page numbers to extract */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/composer.ts#L255-L278
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFLinkUpdater.updateLinks
async updateLinks(operator: () => Promise<TFile | null>, files: TFile[], updater: LinkInfoUpdater): Promise<TFile | null> { await this.lib.metadataCacheUpdatePromise; const updateQueue = new Map<string, { position: Pos, newLink: string }[]>(); for (const file of files) { const backlinks = this.app.metadataCache.getBacklinksForFile(file); for (const sourcePath of backlinks.keys()) { const refCaches = backlinks.get(sourcePath); for (const refCache of refCaches ?? []) { const newLinktext = this.getNewLinkText(refCache.link, sourcePath, file, updater); if (typeof newLinktext !== 'string') continue; const newLink = this.getNewLink(refCache, newLinktext); const position = refCache.position; if (!updateQueue.has(sourcePath)) updateQueue.set(sourcePath, []); updateQueue.get(sourcePath)!.push({ position, newLink }); } } } const newFile = await operator(); if (!newFile) return null; // operation failed const promises: Promise<any>[] = []; const counts = { files: 0, links: 0 }; for (const [sourcePath, updates] of updateQueue) { const sourceFile = this.app.vault.getAbstractFileByPath(sourcePath); if (!(sourceFile instanceof TFile)) continue; updates.sort((a, b) => b.position.start.offset - a.position.start.offset); promises.push( this.app.vault.process(sourceFile, (data) => { for (const { position, newLink } of updates) { data = data.slice(0, position.start.offset) + newLink + data.slice(position.end.offset); counts.links++; } return data; }) ); if (updates.length > 0) counts.files++; } await Promise.all(promises); if (counts.links) { new Notice(`${this.plugin.manifest.name}: Updated ${counts.links} links in ${counts.files} files.`); } return newFile; }
// TODO: rewrite using PDFBacklinkIndex
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/composer.ts#L290-L343
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFLinkUpdater.updateLinkColor
async updateLinkColor( refCache: LinkCache | EmbedCache | FrontmatterLinkCache, sourcePath: string, newColor: { type: 'name', name: string } | { type: 'rgb', rgb: RGB } | null, options?: { linktext?: boolean, callout?: boolean } ) { options = Object.assign({ linktext: true, callout: true }, options); const file = this.app.vault.getAbstractFileByPath(sourcePath); if (!(file instanceof TFile)) return; const linktext = refCache.link; const { path, subpath } = parseLinktext(linktext); const params = new URLSearchParams(subpath.startsWith('#') ? subpath.slice(1) : subpath); if (newColor && options.linktext) { params.set('color', newColor.type === 'name' ? newColor.name.toLowerCase() : `${newColor.rgb.r},${newColor.rgb.g},${newColor.rgb.b}`); } else { params.delete('color'); } let newSubpath = ''; for (const [key, value] of params.entries()) { newSubpath += newSubpath ? `&${key}=${value}` : `#${key}=${value}`; } const newLinktext = path + newSubpath; const newLink = this.getNewLink(refCache, newLinktext); if ('position' in refCache) { // contents const position = refCache.position; await this.app.vault.process(file, (data) => { data = data.slice(0, position.start.offset) + newLink + data.slice(position.end.offset); if (options!.callout) { // Check if this link is inside a PDF++ callout const sections = this.app.metadataCache.getFileCache(file)?.sections ?? []; const section = sections.find((sec) => sec.position.start.offset <= position.start.offset && position.end.offset <= sec.position.end.offset); if (section && section.type === 'callout') { const lines = data.split(/\r?\n/); const lineNumber = section.position.start.line; const line = lines[lineNumber]; const pdfPlusCalloutPattern = new RegExp( `> *\\[\\! *${this.settings.calloutType} *(\\|(.*?))?\\]`, 'i' ); lines[lineNumber] = line.replace(pdfPlusCalloutPattern, `> [!${this.settings.calloutType}${newColor ? `|${newColor.type === 'name' ? newColor.name.toLowerCase() : `${newColor.rgb.r},${newColor.rgb.g},${newColor.rgb.b}`}` : ''}]`); data = lines.join('\n'); } } return data; }); } else { // properties const key = refCache.key; await this.app.fileManager.processFrontMatter(file, (frontmatter) => { frontmatter[key] = newLink; }); } }
/** * @param options Options for updating the link color: * - `linktext`: Whether the color should appear in the link text. * - `callout`: Whether the color should be updated in the PDF++ callout that contains the link if any. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/composer.ts#L411-L470
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
copyLinkLib.getTextSelectionRange
getTextSelectionRange(pageEl: HTMLElement, range: Range) { if (range && !range.collapsed) { const startTextLayerNode = getTextLayerNode(pageEl, range.startContainer); const endTextLayerNode = getTextLayerNode(pageEl, range.endContainer); if (startTextLayerNode && endTextLayerNode) { const beginIndex = startTextLayerNode.dataset.idx; const endIndex = endTextLayerNode.dataset.idx; const beginOffset = getOffsetInTextLayerNode(startTextLayerNode, range.startContainer, range.startOffset); const endOffset = getOffsetInTextLayerNode(endTextLayerNode, range.endContainer, range.endOffset); if (beginIndex !== undefined && endIndex !== undefined && beginOffset !== null && endOffset !== null) return { beginIndex: +beginIndex - this.plugin.textDivFirstIdx, beginOffset, endIndex: +endIndex - this.plugin.textDivFirstIdx, endOffset }; } } return null; }
// The same as getTextSelectionRangeStr in Obsidian's app.js, but returns an object instead of a string.
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/copy-link.ts#L42-L61
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
copyLinkLib.getTextToCopy
getTextToCopy(child: PDFViewerChild, template: string, displayTextFormat: string | undefined, file: TFile, page: number, subpath: string, text: string, colorName: string, sourcePath?: string, comment?: string) { const pageView = child.getPage(page); // need refactor if (typeof comment !== 'string') { const annotationId = subpathToParams(subpath).get('annotation'); // @ts-ignore comment = (typeof annotationId === 'string' && pageView?.annotationLayer?.annotationLayer?.getAnnotation(annotationId)?.data?.contentsObj?.str); comment = this.lib.toSingleLine(comment || ''); } const processor = new PDFPlusTemplateProcessor(this.plugin, { file, page, pageLabel: pageView.pageLabel ?? ('' + page), pageCount: child.pdfViewer.pagesCount, text, comment, colorName, calloutType: this.settings.calloutType, ...this.lib.copyLink.getLinkTemplateVariables(child, displayTextFormat, file, subpath, page, text, comment, sourcePath) }); const evaluated = processor.evalTemplate(template); return evaluated; }
/** * @param child * @param template * @param displayTextFormat * @param file * @param page * @param subpath * @param text * @param colorName * @param sourcePath * @param comment This will be used as the `comment` template variable. * Assuming the subpath points to an annotation (e.g. `#page=1&annotation=123R`), * if this parameter is not provided, the comment will be extracted from the annotation layer. * This means that if the page is not loaded yet (lazy loading), the comment will not be extracted. * (This is necessary for making this function synchronous.) * Therefore, you must extract the comment by yourself beforehand and provide it as the `comment` parameter * if the page may not be loaded yet. * (See also: https://github.com/RyotaUshio/obsidian-pdf-plus/issues/260) * @returns */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/copy-link.ts#L173-L198
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
copyLinkLib.writeHighlightAnnotationToSelectionIntoFileAndCopyLink
writeHighlightAnnotationToSelectionIntoFileAndCopyLink(checking: boolean, templates: { copyFormat: string, displayTextFormat?: string }, colorName?: string, autoPaste?: boolean): boolean { // Get and store the selected text before writing file because // the file modification will cause the PDF viewer to be reloaded, // which will clear the selection. const selection = activeWindow.getSelection(); if (!selection) return false; const text = this.lib.toSingleLine(selection.toString()); if (!text) return false; if (!checking) { const palette = this.lib.getColorPaletteAssociatedWithSelection(); palette?.setStatus('Writing highlight annotation into file...', 10000); this.lib.highlight.writeFile.addTextMarkupAnnotationToSelection( this.settings.selectionBacklinkVisualizeStyle === 'highlight' ? 'Highlight' : 'Underline', colorName ) .then((result) => { if (!result) return; const { child, file, page, annotationID, rects } = result; if (!annotationID || !file) return; setTimeout(() => { // After the file modification, the PDF viewer DOM is reloaded, so we need to // get the new DOM to access the newly loaded color palette instance. const newPalette = this.lib.getColorPaletteFromChild(child); newPalette?.setStatus('Link copied', this.statusDurationMs); const { r, g, b } = this.plugin.domManager.getRgb(colorName); this.copyLinkToAnnotationWithGivenTextAndFile(text, file, child, false, templates, page, annotationID, `${r}, ${g}, ${b}`, autoPaste); // TODO: Needs refactor if (rects) { const left = Math.min(...rects.map((rect) => rect[0])); const top = Math.max(...rects.map((rect) => rect[3])); if (typeof left === 'number' && typeof top === 'number') { this.plugin.lastCopiedDestInfo = { file, destArray: [page - 1, 'XYZ', left, top, null] }; } } }, 300); }); } return true; }
// TODO: A better, more concise function name 😅
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/copy-link.ts#L368-L411
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
copyLinkLib.prepareMarkdownLeafForPaste
async prepareMarkdownLeafForPaste(file: TFile) { let leaf = this.lib.workspace.getExistingLeafForMarkdownFile(file); const isExistingLeaf = !!leaf; if (!leaf && this.settings.openAutoFocusTargetIfNotOpened) { const paneType = this.settings.howToOpenAutoFocusTargetIfNotOpened; if (paneType === 'hover-editor') { const hoverLeaf = await this.lib.workspace.hoverEditor.createNewHoverEditorLeaf({ hoverPopover: null }, null, file.path, ''); if (hoverLeaf) leaf = hoverLeaf; } else { leaf = this.lib.workspace.getLeaf(paneType); await leaf.openFile(file, { active: false }); } if (leaf && this.settings.openAutoFocusTargetInEditingView) { // The follwoing line should be unnecesary because this block is // only executed when the leaf is newly created. // But I'll put it here just in case. await this.lib.workspace.ensureViewLoaded(leaf); const view = leaf.view; if (view instanceof MarkdownView) { await view.setState({ mode: 'source' }, { history: false }); view.setEphemeralState({ focus: false }); } } } if (leaf) { // GUARANTEE THAT THE VIEW IS LOADED await this.lib.workspace.ensureViewLoaded(leaf); this.lib.workspace.hoverEditor.postProcessHoverEditorLeaf(leaf); if (this.settings.closeSidebarWhenLostFocus) { this.lib.workspace.registerHideSidebar(leaf); } } return { leaf, isExistingLeaf }; }
/** * Note that if this method returns a workspace leaf, its view IS guaranteed to be loaded * (i.e. the view is not a detached view). */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/copy-link.ts#L695-L735
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
copyLinkLib.autoFocusOrAutoPaste
async autoFocusOrAutoPaste(evaluated: string, autoPaste?: boolean, palette?: ColorPalette) { if (autoPaste || this.settings.autoPaste) { const success = await this.autoPaste(evaluated); if (success) { palette?.setStatus('Link copied & pasted', this.statusDurationMs); if (!this.settings.focusEditorAfterAutoPaste && this.settings.clearSelectionAfterAutoPaste) { const selection = activeWindow.getSelection(); if (selection && this.lib.copyLink.getPageAndTextRangeFromSelection(selection)) { selection.empty(); } } } else palette?.setStatus('Link copied but paste target not identified', this.statusDurationMs); } else { if (this.settings.autoFocus) { const success = await this.autoFocus(); if (!success) palette?.setStatus('Link copied but paste target not identified', this.statusDurationMs); } } }
/** * Performs auto-focus or auto-paste as a post-processing according to the user's preferences and the executed commands. * If `this.settings.autoPaste` is `true` or this method is called via the auto-paste commands, perform auto-paste. * Otherwise, perform auto-focus if `this.settings.autoFocus` is `true`. * * @param evaluated The text that has just been copied. * @param autoPaste True if called via the auto-paste commands and false otherwise even if the auto-paste toggle is on. * @param palette The relevant color palette instance whose status text will be updated. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/copy-link.ts#L876-L894
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.registerPDFEvent
registerPDFEvent<K extends keyof PDFJsEventMap>(name: K, eventBus: EventBus, component: Component | null, callback: (data: PDFJsEventMap[K]) => any) { const listener = async (data: any) => { await callback(data); if (!component) eventBus.off(name, listener); }; component?.register(() => eventBus.off(name, listener)); eventBus.on(name, listener); }
/** * @param component A component such that the callback is unregistered when the component is unloaded, or `null` if the callback should be called only once. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L66-L73
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.onPageReady
onPageReady(viewer: ObsidianViewer, component: Component | null, cb: (pageNumber: number, pageView: PDFPageView, newlyRendered: boolean) => any) { viewer.pdfViewer?._pages .forEach((pageView, pageIndex) => { cb(pageIndex + 1, pageView, false); // page number is 1-based }); this.registerPDFEvent('pagerendered', viewer.eventBus, component, (data: { source: PDFPageView, pageNumber: number }) => { cb(data.pageNumber, data.source, true); }); }
/** * Register a callback executed when the PDFPageView for a page is ready. * This happens before the text layer and the annotation layer are ready. * Note that PDF rendering is "lazy"; a page view is not prepared until the page is scrolled into view. * * @param component A component such that the callback is unregistered when the component is unloaded, or `null` if the callback should be called only once. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L82-L90
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.onTextLayerReady
onTextLayerReady(viewer: ObsidianViewer, component: Component | null, cb: (pageNumber: number, pageView: PDFPageView, newlyRendered: boolean) => any) { viewer.pdfViewer?._pages .forEach((pageView, pageIndex) => { if (pageView.textLayer) { cb(pageIndex + 1, pageView, false); // page number is 1-based } }); this.registerPDFEvent('textlayerrendered', viewer.eventBus, component, (data: { source: PDFPageView, pageNumber: number }) => { cb(data.pageNumber, data.source, true); }); }
/** * Register a callback executed when the text layer for a page gets rendered. * * @param component A component such that the callback is unregistered when the component is unloaded, or `null` if the callback should be called only once. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L97-L107
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.onAnnotationLayerReady
onAnnotationLayerReady(viewer: ObsidianViewer, component: Component | null, cb: (pageNumber: number, pageView: PDFPageView, newlyRendered: boolean) => any) { viewer.pdfViewer?._pages .forEach((pageView, pageIndex) => { if (pageView.annotationLayer) { cb(pageIndex + 1, pageView, false); // page number is 1-based } }); this.registerPDFEvent('annotationlayerrendered', viewer.eventBus, component, (data: { source: PDFPageView, pageNumber: number }) => { cb(data.pageNumber, data.source, true); }); }
/** * Register a callback executed when the annotation layer for a page gets rendered. * * @param component A component such that the callback is unregistered when the component is unloaded, or `null` if the callback should be called only once. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L114-L124
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.destIdToSubpath
async destIdToSubpath(destId: string, doc: PDFDocumentProxy) { const dest = await doc.getDestination(destId) as PDFJsDestArray; if (!dest) return null; return this.pdfJsDestArrayToSubpath(dest, doc); }
/** * Convert a destination name (see the PDF spec (PDF 32000-1:2008), 12.3.2.3 "Named Destinations") * into a subpath of the form `#page=<pageNumber>&offset=<left>,<top>,<zoom>`. * * For how Obsidian handles the "offset" parameter, see the PDFViewerChild.prototype.applySubpath method * in Obsidian's app.js. * * The rule is: * - `offset` is a comma-separated list of three (or two) numbers, representing the "left", "top", and "zoom" parameters. * - If "left" is omitted, then only the "top" parameter is used and the destination is treated as "[page /FitBH top]". * - What is "FitBH"? Well, Table 151 in the PDF spec says: * > "Display the page designated by page, with the vertical coordinate top positioned at the top edge of * the window and the contents of the page magnified just enough to fit the entire width of its bounding box * within the window. * > A null value for top specifies that the current value of that parameter shall be retained unchanged." * - Otherwise, the destination is treated as "[page /XYZ left top zoom]". * - According to the PDF spec, "XYZ" means: * > "Display the page designated by page, with the coordinates (left, top) positioned at the upper-left corner of * the window and the contents of the page magnified by the factor zoom. * > A null value for any of the parameters left, top, or zoom specifies that the current value of that parameter * shall be retained unchanged. A zoom value of 0 has the same meaning as a null value." */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L290-L294
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.normalizePDFJsDestArray
normalizePDFJsDestArray(dest: PDFJsDestArray, pageNumber: number): DestArray { return [ pageNumber - 1, dest[1].name, ...dest .slice(2) as (number | null)[] // .filter((param: number | null): param is number => typeof param === 'number') ]; }
/** * * @param dest * @param pageNumber 1-based page number */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L306-L314
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.destArrayToSubpath
destArrayToSubpath(destArray: DestArray) { const pageNumber = destArray[0]; let top = ''; let left = ''; let zoom = ''; if (destArray[1] === 'XYZ') { if (typeof destArray[2] === 'number') left += Math.round(destArray[2]); if (typeof destArray[3] === 'number') top += Math.round(destArray[3]); // Obsidian recognizes the `offset` parameter as "FitBH" if the third parameter is omitted. // from the PDF spec: "A zoom value of 0 has the same meaning as a null value." zoom = '' + Math.round((destArray[4] ?? 0) * 100) / 100; } else if (destArray[1] === 'FitBH') { if (typeof destArray[2] === 'number') top += destArray[2]; } const subpath = `#page=${pageNumber + 1}&offset=${left},${top},${zoom}`; return subpath; }
/** * page: a 0-based page number * destType.name: Obsidian only supports "XYZ" and "FitBH" */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L361-L381
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.generateMarkdownLink
generateMarkdownLink(file: TFile, sourcePath: string, subpath?: string, alias?: string) { const app = this.app; const useMarkdownLinks = app.vault.getConfig('useMarkdownLinks'); const useWikilinks = !useMarkdownLinks; const linkpath = app.metadataCache.fileToLinktext(file, sourcePath, useWikilinks); let linktext = linkpath + (subpath || ''); if (file.path === sourcePath && subpath) linktext = subpath; let nonEmbedLink; if (useMarkdownLinks) { nonEmbedLink = '['.concat(alias || file.basename, '](').concat(encodeLinktext(linktext), ')'); } else { if (alias && alias.toLowerCase() === linktext.toLowerCase()) { linktext = alias; alias = undefined; } nonEmbedLink = alias ? '[['.concat(linktext, '|').concat(alias, ']]') : '[['.concat(linktext, ']]'); } return 'md' !== file.extension ? '!' + nonEmbedLink : nonEmbedLink; }
/** * The same as `app.fileManager.generateMarkdownLink()`, but before Obsidian 1.7, it did not respect * the `alias` parameter for non-markdown files. * This function fixes that issue. Other than that, it is the same as the original function. * * Note that this problem has been fixed in Obsidian 1.7. However, it will make sense to keep using this * function for make this plugin work for older versions of Obsidian without an extra `requireApiVersion` check. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L466-L488
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.isBacklinked
isBacklinked(file: TFile, subpathParams?: { page: number, selection?: [number, number, number, number], annotation?: string }): boolean { // validate parameters if (subpathParams) { const { page, selection, annotation } = subpathParams; if (isNaN(page) || page < 1) throw new Error('Invalid page number'); if (selection && (selection.length !== 4 || selection.some((pos) => isNaN(pos)))) throw new Error('Invalid selection'); if (selection && typeof annotation === 'string') throw new Error('Selection and annotation cannot be used together'); } // query type const isFileQuery = !subpathParams; const isPageQuery = subpathParams && !subpathParams.selection && !subpathParams.annotation; const isSelectionQuery = subpathParams && !!(subpathParams.selection); const isAnnotationQuery = typeof subpathParams?.annotation === 'string'; const backlinkDict = this.app.metadataCache.getBacklinksForFile(file); if (isFileQuery) return backlinkDict.count() > 0; for (const sourcePath of backlinkDict.keys()) { const backlinks = backlinkDict.get(sourcePath); if (!backlinks) continue; for (const backlink of backlinks) { const { subpath } = parseLinktext(backlink.link); const result = parsePDFSubpath(subpath); if (!result) continue; if (isPageQuery && result.page === subpathParams.page) return true; if (isSelectionQuery && 'beginIndex' in result && result.page === subpathParams.page && result.beginIndex === subpathParams.selection![0] && result.beginOffset === subpathParams.selection![1] && result.endIndex === subpathParams.selection![2] && result.endOffset === subpathParams.selection![3] ) return true; if (isAnnotationQuery && 'annotation' in result && result.page === subpathParams.page && result.annotation === subpathParams.annotation ) return true; } } return false; }
// TODO: rewrite using PDFBacklinkIndex
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L507-L553
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.getPDFEmbed
getPDFEmbed(activeOnly: boolean = false): PDFEmbed | null { const activeEmbed = this.getPDFEmbedInActiveView(); if (activeEmbed) return activeEmbed; if (!activeOnly) { let pdfEmbed: PDFEmbed | null = null; this.app.workspace.iterateAllLeaves((leaf) => { if (pdfEmbed) return; const view = leaf.view; // We should not use view.getViewType() here because it cannot detect deferred views. if (view instanceof MarkdownView) { pdfEmbed = this.getPDFEmbedInMarkdownView(view); } else if (this.isCanvasView(view)) { pdfEmbed = this.getPDFEmbedInCanvasView(view); } }); if (pdfEmbed) return pdfEmbed; } return null; }
/** Get an instance of Obsidian's built-in PDFEmbed. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L629-L649
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.getExternalPDFUrl
async getExternalPDFUrl(file: TFile): Promise<string | null> { if (file.stat.size > 300) return null; const content = (await this.app.vault.read(file)).trim(); // A PDF file must start with a header of the form "%PDF-x.y" // so it's safe to assume that a file starting with "https://", "http://" or "file:///" // is not a usual PDF file. if (content.startsWith('https://') || content.startsWith('http://')) { const res = await requestUrl(content); if (res.status === 200) { const url = URL.createObjectURL(new Blob([res.arrayBuffer], { type: 'application/pdf' })); return url; } } else if (content.startsWith('file:///')) { return Platform.resourcePathPrefix + content.substring(8); } return null; }
/** * If the given PDF file is a "dummy" file containing only a URL (https://, http://, file:///), * return the URL. Otherwise, return null. * For the exact usage, refer to the comment in the patcher for `PDFViewerChild.prototype.loadFile`. * * @param file * @returns */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L738-L756
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.pdfPageToImageDataUrl
async pdfPageToImageDataUrl(page: PDFPageProxy, options?: { type?: string, encoderOptions?: number, resolution?: number, cropRect?: Rect }): Promise<string> { const [left, bottom, right, top] = page.view; const pageWidth = right - left; const pageHeight = top - bottom; const type = options?.type; const encoderOptions = options?.encoderOptions; let resolution = options?.resolution; if (typeof resolution !== 'number') { resolution = // Requiring too much resolution on mobile devices seems to cause the rendering to fail (Platform.isDesktop ? 7 : Platform.isTablet ? 4 : (window.devicePixelRatio || 1)) * (this.plugin.settings.rectEmbedResolution / 100); } const cropRect = options?.cropRect; const canvas = await this.renderPDFPageToCanvas(page, resolution); if (!cropRect) return canvas.toDataURL(type, encoderOptions); const rotatedCanvas = rotateCanvas(canvas, 360 - page.rotate); const scaleX = rotatedCanvas.width / pageWidth; const scaleY = rotatedCanvas.height / pageHeight; const crop = { left: (cropRect[0] - left) * scaleX, top: (bottom + pageHeight - cropRect[3]) * scaleY, width: (cropRect[2] - cropRect[0]) * scaleX, height: (cropRect[3] - cropRect[1]) * scaleY, }; const croppedCanvas = rotateCanvas(cropCanvas(rotatedCanvas, crop), page.rotate); return croppedCanvas.toDataURL(type, encoderOptions); }
/** * @param options The following options are supported: * - type: The image format passed to HTMLCanvasElement.toDataURL(). The default is 'image/png'. * - encoderOptions: The quality of the image format passed to HTMLCanvasElement.toDataURL(). * - resolution: The resolution of the PDF page rendering. * - cropRect: The rectangle to crop the PDF page to. The coordinates are in PDF space. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L912-L943
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.pdfPageToImageArrayBuffer
async pdfPageToImageArrayBuffer(page: PDFPageProxy, options?: { type?: string, encoderOptions?: number, resolution?: number, cropRect?: Rect }): Promise<ArrayBuffer> { const dataUrl = await this.pdfPageToImageDataUrl(page, options); const base64 = dataUrl.match(/^data:image\/\w+;base64,(.*)/)?.[1]; if (!base64) throw new Error('Failed to convert data URL to base64'); return base64ToArrayBuffer(base64); }
/** * @param options Supports the same options as pdfPageToImageDataUrl. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L948-L953
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.toSingleLine
toSingleLine(str: string): string { return toSingleLine(str, this.plugin.settings.removeWhitespaceBetweenCJChars); }
/** Process (possibly) multiline strings cleverly to convert it into a single line string. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L1001-L1003
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPlusLib.write
async write(path: string, data: string | ArrayBuffer, existOk: boolean): Promise<TFile | null> { const file = this.app.vault.getAbstractFileByPath(path); if (file instanceof TFile) { if (!existOk) { new Notice(`${this.plugin.manifest.name}: File already exists: ${path}`); } if (typeof data === 'string') { await this.app.vault.modify(file, data); } else { await this.app.vault.modifyBinary(file, data); } return file; } else if (file === null) { const folderPath = normalizePath(path.split('/').slice(0, -1).join('/')); if (folderPath) { const folderExists = !!(this.app.vault.getAbstractFileByPath(folderPath)); if (!folderExists) await this.app.vault.createFolder(folderPath); } if (typeof data === 'string') { return await this.app.vault.create(path, data); } else { return await this.app.vault.createBinary(path, data); } } return null; }
/** Write data to the file at path. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/index.ts#L1006-L1033
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFOutlines.lib
get lib() { return this.plugin.lib; }
// }
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/outlines.ts#L37-L39
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFOutlines.findPDFjsOutlineTreeNode
async findPDFjsOutlineTreeNode(node: PDFOutlineTreeNode): Promise<PDFOutlineItem | null> { let found: PDFOutlineItem | null = null; await this.iterAsync({ enter: async (outlineItem) => { if (found || outlineItem.isRoot()) return; if (node.item.title === outlineItem.title) { const dest = node.item.dest; const outlineDest = outlineItem.getNormalizedDestination(); if (typeof dest === 'string') { if (typeof outlineDest === 'string' && dest === outlineDest) { found = outlineItem; } } else { const pageNumber = await node.getPageNumber(); if (JSON.stringify(this.lib.normalizePDFJsDestArray(dest, pageNumber)) === JSON.stringify(outlineDest)) { found = outlineItem; } } } } }); return found; }
/** Iterate over the outline items and find the matching one from the tree. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/outlines.ts#L135-L160
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFOutlineItem.name
get name(): string { if (this.isRoot()) return '(Root)'; let name = this.title; this.iterAncestors((ancestor) => { if (!ancestor.isRoot()) name = `${ancestor.title}/${name}`; }); return name; }
/** A human-readable name for this item. This is not a part of the PDF spec. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/outlines.ts#L325-L333
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFOutlineItem.countVisibleDescendants
countVisibleDescendants(): number { let count = 0; this.iterChildren(() => count++); this.iterChildren((child) => { if (typeof child.count === 'number' && child.count > 0) { count += child.countVisibleDescendants(); } }); return count; }
/** Compute the value of the "Count" entry following the algirithm described in Table 153 of the PDF spec. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/outlines.ts#L582-L591
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPageLabelDict.fromPDFDict
static fromPDFDict(dict: PDFDict) { const instance = new PDFPageLabelDict(); const start = dict.get(PDFName.of('St')); if (start instanceof PDFNumber) { instance.start = start.asNumber(); } const style = dict.get(PDFName.of('S')); if (style instanceof PDFName) { const decoded = style.decodeText(); if (isPageLabelNumberingStyle(decoded)) { instance.style = decoded; } } const prefix = dict.get(PDFName.of('P')); if (prefix instanceof PDFString || prefix instanceof PDFHexString) { instance.prefix = prefix.decodeText(); } return instance; }
// "P" entry
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/page-labels.ts#L35-L57
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPageLabels.constructor
constructor(public doc: PDFDocument, public ranges: { pageFrom: number, dict: PDFPageLabelDict }[]) { this.normalize(); }
// pageFrom: converted into a 1-based page index for easier use; it's 0-based in the original PDF document
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/page-labels.ts#L63-L65
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPageLabels.divideRangeAtPage
divideRangeAtPage(page: number, keepLabels: boolean, processDict?: (newDict: PDFPageLabelDict) => void) { const index = this.getRangeIndexAtPage(page); if (index === -1) return this; if (page === this.getStartOfRange(index)) return this; const range = this.ranges[index]; const newDict = new PDFPageLabelDict(); newDict.prefix = range.dict.prefix; newDict.style = range.dict.style; if (keepLabels) newDict.start = page - range.pageFrom + (range.dict.start ?? 1); processDict?.(newDict); this.ranges.splice(index + 1, 0, { pageFrom: page, dict: newDict }); return this; }
/** * * @param page The 1-based index of the page the new range should start from * @param keepLabels If the original page labels should be kept after the split * @returns */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/page-labels.ts#L175-L192
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
WorkspaceLib.getExistingLeafForPDFFile
getExistingLeafForPDFFile(file: TFile): WorkspaceLeaf | null { return this.getExistingLeafForFile(file); }
/** * Get an existing leaf that holds the given PDF file, if any. * If the leaf has been already loaded, `leaf.view` will be an instance of `PDFView`. * If not, `leaf.view` will be an instance of `DeferredView`. If you want to ensure that * the view is `PDFView`, do `await leaf.loadIfDeferred()` followed by `if (lib.isPDFView(leaf.view))`. * * @param file Must be a PDF file. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/workspace-lib.ts#L119-L121
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
WorkspaceLib.getMarkdownLeafInSidebar
getMarkdownLeafInSidebar(sidebarType: SidebarType) { if (this.settings.singleMDLeafInSidebar) { return this.lib.workspace.getExistingMarkdownLeafInSidebar(sidebarType) ?? this.lib.workspace.getNewLeafInSidebar(sidebarType); } else { return this.lib.workspace.getNewLeafInSidebar(sidebarType); } }
/** * Get a leaf to open a markdown file in. The leaf can be an existing one or a new one, * depending on the user preference and the current state of the workspace. * * Note that the returned leaf might contain a deferred view, so it is not guaranteed * that `leaf.view` is an instance of `MarkdownView`. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/workspace-lib.ts#L186-L193
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
WorkspaceLib.getMarkdownLeafForLinkFromPDF
getMarkdownLeafForLinkFromPDF(linktext: string, sourcePath: string): WorkspaceLeaf { const { path: linkpath } = parseLinktext(linktext); const file = this.app.metadataCache.getFirstLinkpathDest(linkpath, sourcePath); // 1. If the target markdown file is already opened, open the link in the same leaf // 2. If not, create a new leaf under the same parent split as the first existing markdown leaf let markdownLeaf: WorkspaceLeaf | undefined; let markdownLeafParent: WorkspaceSplit | undefined; this.app.workspace.iterateAllLeaves((leaf) => { if (markdownLeaf) return; let createInSameParent = true; // The following line uses `getViewType() === 'markdown'` instead of // `instanceof MarkdownView` in order to ensure a leaf with a deferred markdown views // are also caught. if (leaf.view.getViewType() === 'markdown') { const root = leaf.getRoot(); for (const split of this.settings.ignoreExistingMarkdownTabIn) { if (root === this.app.workspace[split]) return; } if (leaf.parentSplit instanceof WorkspaceTabs) { const sharesSameTabParentWithThePDF = leaf.parentSplit.children.some((item) => { if (item instanceof WorkspaceLeaf && item.view.getViewType() === 'pdf') { return this.getFilePathFromView(item.view) === sourcePath; // The following will not work if the view is a DeferredView // const view = item.view as PDFView; // return view.file?.path === sourcePath; } }); if (sharesSameTabParentWithThePDF) { createInSameParent = false; } } if (createInSameParent) markdownLeafParent = leaf.parentSplit; if (file && this.getFilePathFromView(leaf.view) === file.path) { markdownLeaf = leaf; } } }); if (!markdownLeaf) { if (isSidebarType(this.settings.paneTypeForFirstMDLeaf) && this.settings.singleMDLeafInSidebar && markdownLeafParent && this.isInSidebar(markdownLeafParent)) { markdownLeaf = this.getExistingMarkdownLeafInSidebar(this.settings.paneTypeForFirstMDLeaf) ?? this.lib.workspace.getNewLeafInSidebar(this.settings.paneTypeForFirstMDLeaf); } else { markdownLeaf = markdownLeafParent ? this.app.workspace.createLeafInParent(markdownLeafParent, -1) : this.getLeaf(this.plugin.settings.paneTypeForFirstMDLeaf); } } return markdownLeaf; }
/** * Given a link from a PDF file to a markdown file, return a leaf to open the link in. * The returned leaf can be an existing one or a new one. * Note that the leaf might contain a deferred view, so you need to call `await leaf.loadIfDeferred()` * before accessing any properties specific to the view type. * * @param linktext A link text to a markdown file. * @param sourcePath If non-empty, it should end with ".pdf". */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/workspace-lib.ts#L204-L265
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
WorkspaceLib.getExistingMarkdownLeafInSidebar
getExistingMarkdownLeafInSidebar(sidebarType: SidebarType): WorkspaceLeaf | null { let sidebarLeaf: WorkspaceLeaf | undefined; const root = sidebarType === 'right-sidebar' ? this.app.workspace.rightSplit : this.app.workspace.leftSplit; this.app.workspace.iterateAllLeaves((leaf) => { if (sidebarLeaf || leaf.getRoot() !== root) return; // Don't use `instanceof MarkdownView` here because the view might be a deferred view. if (leaf.view.getViewType() === 'markdown') sidebarLeaf = leaf; }); return sidebarLeaf ?? null; }
/** * Get an existing leaf that is opened a markdown file in the sidebar * specified by `sidebarType`, if any. * Note that the returned leaf can contain a deferred view, so it is not guaranteed * that `leaf.view` is an instance of `MarkdownView`. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/workspace-lib.ts#L305-L319
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
WorkspaceLib.revealLeaf
async revealLeaf(leaf: WorkspaceLeaf) { if (requireApiVersion('1.5.11')) { await this.app.workspace.revealLeaf(leaf); return; } if (!Platform.isDesktopApp) { // on mobile, we don't need to care about new windows so just use the original method this.app.workspace.revealLeaf(leaf); return; } // Fix the bug that had existed before Obsidian v1.5.11 const root = leaf.getRoot(); if (root instanceof WorkspaceSidedock && root.collapsed) { root.toggle(); } const parent = leaf.parent; if (parent instanceof WorkspaceTabs) { parent.selectTab(leaf); } // This is the only difference from the original `revealLeaf` method. // Obsidian's `revealLeaf` uses `root.getContainer().focus()` instead, which causes a bug that the main window is focused when the leaf is in a secondary window. leaf.getContainer().focus(); }
/** * Almost the same as Workspace.prototype.revealLeaf, but this version * properly reveals a leaf even when it is contained in a secondary window. * * Update: The upstream bug of Obsidian has been fixed in v1.5.11: https://obsidian.md/changelog/2024-03-13-desktop-v1.5.11/ * * Update 2: From Obsidian v1.7.2, the original `revealLeaf` is async (it now awaits `loadIfDeferred` inside), hence this method is now async as well. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/workspace-lib.ts#L337-L363
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
WorkspaceLib.openPDFLinkTextInExistingLeafForTargetPDF
openPDFLinkTextInExistingLeafForTargetPDF(linktext: string, sourcePath: string, openViewState?: OpenViewState, targetFile?: TFile): { exists: boolean, promise: Promise<void> } { if (!targetFile) { const { path } = parseLinktext(linktext); targetFile = this.app.metadataCache.getFirstLinkpathDest(path, sourcePath) ?? undefined; } if (!targetFile) return { exists: false, promise: Promise.resolve() }; const sameFileLeaf = this.getExistingLeafForPDFFile(targetFile); if (!sameFileLeaf) return { exists: false, promise: Promise.resolve() }; // Ignore the "dontActivateAfterOpenPDF" option when opening a link in a tab in the same split as the current tab // I believe using activeLeaf (which is deprecated) is inevitable here if (!(sameFileLeaf.parentSplit instanceof WorkspaceTabs && sameFileLeaf.parentSplit === this.app.workspace.activeLeaf?.parentSplit)) { openViewState = openViewState ?? {}; openViewState.active = !this.settings.dontActivateAfterOpenPDF; } if (sameFileLeaf.isVisible() && this.settings.highlightExistingTab) { sameFileLeaf.containerEl.addClass('pdf-plus-link-opened', 'is-highlighted'); setTimeout(() => sameFileLeaf.containerEl.removeClass('pdf-plus-link-opened', 'is-highlighted'), this.settings.existingTabHighlightDuration * 1000); } const promise = this.openPDFLinkTextInLeaf(sameFileLeaf, linktext, sourcePath, openViewState); return { exists: true, promise }; }
/** * If the target PDF file is already opened in a tab, open the link in that tab. * * @param linktext A link text to a PDF file. * @param sourcePath * @param openViewState `active` will be overwritten acccording to `this.plugin.settings.dontActivateAfterOpenPDF`. * @param targetFile If provided, it must be the target PDF file that the link points to. * @returns An object containing a boolean value indicating whether a tab with the target PDF file already exists and a promise that resolves when the link is opened. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/workspace-lib.ts#L394-L419
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
WorkspaceLib.getExistingLeafForFile
getExistingLeafForFile(file: TFile): WorkspaceLeaf | null { // Get the view type that corresponds to the file extension. // e.g. 'markdown' for '.md', 'pdf' for '.pdf' const viewType = this.app.viewRegistry.getTypeByExtension(file.extension); if (!viewType) return null; let leaf: WorkspaceLeaf | null = null; this.app.workspace.iterateAllLeaves((l) => { if (leaf) return; // About the if check below: // Before Obsidian v1.7.2 introduced DeferredView, the condition was something like // `l.view instanceof (...)View && l.view.file === file`. // Now, it is invalid because the first condition will filter out `DeferredView`, // which is not the desired behavior in most cases. // (Also, a `DeferredView` does not have a `file` property.) // One more thing to note is that the view type checking is crucial // to filtering out "linked file views" like backlink views, outgoing link views, and outline views. if (l.view.getViewType() === viewType && this.getFilePathFromView(l.view) === file.path) { leaf = l; } }); return leaf; }
/** * Get an existing leaf that holds the given file, if any. * If the leaf has been already loaded, `leaf.view` will be an instance of a subclass of `FileView`, * e.g., `PDFView` for a PDF file, `MarkdownView` for a markdown file. * If not, `leaf.view` will be an instance of `DeferredView`. If you want to ensure that * the view is not deferred and is indeed an instance of a view class corresponding to the file type, * do `await leaf.loadIfDeferred()` followed by `if (lib.isPDFView(leaf.view))`. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/workspace-lib.ts#L429-L456
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
WorkspaceLib.getExistingLeafForMarkdownFile
getExistingLeafForMarkdownFile(file: TFile): WorkspaceLeaf | null { return this.getExistingLeafForFile(file); }
/** * Returns a leaf that holds the given markdown file, if any. * `leaf.view` can be an instance of `MarkdownView` or `DeferredView`. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/workspace-lib.ts#L462-L464
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
WorkspaceLib.getFilePathFromView
getFilePathFromView(view: View): string | null { // `view.file?.path` will fail if the view is a `DeferredView`. const path = view.getState().file; return typeof path === 'string' ? path : null; }
/** * Returns the path of the file opened in the given view. * This method ensures that it works even if the view is a `DeferredView`. * @param view An actual `FileView` or a `DefferedView` for a `FileView`. * @returns */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/workspace-lib.ts#L492-L496
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
WorkspaceLib.ensureViewLoaded
async ensureViewLoaded(leaf: WorkspaceLeaf): Promise<void> { if (requireApiVersion('1.7.2')) { await leaf.loadIfDeferred(); } }
/** * Ensuress that the view in the given leaf is fully loaded (not deferred) * after the returned promise is resolved. Never forget to await it when you call this method. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/workspace-lib.ts#L502-L506
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
HighlightExtractor.getTextByRect
getTextByRect(items: TextContentItem[], rect: Rect): PDFTextRange { const [left, bottom, right, top] = rect; let text = ''; let from: { index: number, offset: number } = { index: -1, offset: -1 }; let to: { index: number, offset: number } = { index: -1, offset: -1 }; for (let index = 0; index < items.length; index++) { const item = items[index]; if (item.chars && item.chars.length) { for (let offset = 0; offset < item.chars.length; offset++) { const char = item.chars[offset]; const xMiddle = (char.r[0] + char.r[2]) / 2; const yMiddle = (char.r[1] + char.r[3]) / 2; if (left <= xMiddle && xMiddle <= right && bottom <= yMiddle && yMiddle <= top) { text += char.u; if (from.index === -1 && from.offset === -1) from = { index, offset }; to = { index, offset: offset + 1 }; } } } } return { text, from, to }; }
/** Inspired by PDFViewerChild.prototype.getTextByRect in Obsidian's app.js */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/highlights/extract.ts#L72-L99
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
HighlightGeometryLib.computeMergedHighlightRects
computeMergedHighlightRects(textLayer: { textDivs: HTMLElement[], textContentItems: TextContentItem[] }, beginIndex: number, beginOffset: number, endIndex: number, endOffset: number): MergedRect[] { const { textContentItems, textDivs } = textLayer; const results: MergedRect[] = []; let mergedRect: Rect | null = null; let mergedIndices: number[] = []; // If the selection ends at the beginning of a text content item, // replace the end point with the end of the previous text content item. if (endOffset === 0) { endIndex--; endOffset = textContentItems[endIndex].str.length; } for (let index = beginIndex; index <= endIndex; index++) { const item = textContentItems[index]; const textDiv = textDivs[index]; if (!item.str) continue; // the minimum rectangle that contains all the chars of this text content item const rect = this.computeHighlightRectForItem(item, textDiv, index, beginIndex, beginOffset, endIndex, endOffset); if (!rect) continue; if (!mergedRect) { mergedRect = rect; mergedIndices = [index]; } else { const mergeable = this.areRectanglesMergeable(mergedRect, rect); if (mergeable) { mergedRect = this.mergeRectangles(mergedRect, rect); mergedIndices.push(index); } else { results.push({ rect: mergedRect, indices: mergedIndices }); mergedRect = rect; mergedIndices = [index]; } } } if (mergedRect) results.push({ rect: mergedRect, indices: mergedIndices }); return results; }
/** * Returns an array of rectangles that cover the background of the text selection speficied by the given parameters. * Each rectangle is obtained by merging the rectangles of the text content items contained in the selection, when possible (typically when the text selection is within a single line). * Each rectangle is associated with an array of indices of the text content items contained in the rectangle. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/highlights/geometry.ts#L15-L60
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
ViewerHighlightLib.highlightSubpath
highlightSubpath(child: PDFViewerChild, duration: number) { if (child.subpathHighlight?.type === 'text') { const component = new Component(); component.load(); this.lib.onTextLayerReady(child.pdfViewer, component, (pageNumber) => { if (child.subpathHighlight?.type !== 'text') return; const { page, range } = child.subpathHighlight; if (page !== pageNumber) return; child.highlightText(page, range); if (duration > 0) { setTimeout(() => { child.clearTextHighlight(); }, duration * 1000); } component.unload(); }); } else if (child.subpathHighlight?.type === 'annotation') { const component = new Component(); component.load(); this.lib.onAnnotationLayerReady(child.pdfViewer, component, (pageNumber) => { if (child.subpathHighlight?.type !== 'annotation') return; const { page, id } = child.subpathHighlight; if (page !== pageNumber) return; child.highlightAnnotation(page, id); if (duration > 0) setTimeout(() => child.clearAnnotationHighlight(), duration * 1000); component.unload(); }); } else if (child.subpathHighlight?.type === 'rect') { const component = new Component(); component.load(); this.lib.onPageReady(child.pdfViewer, component, (pageNumber) => { if (child.subpathHighlight?.type !== 'rect') return; const { page, rect } = child.subpathHighlight; if (page !== pageNumber) return; this.highlightRect(child, page, rect); if (duration > 0) { setTimeout(() => { this.clearRectHighlight(child); }, duration * 1000); } component.unload(); }); } }
/** * Render highlighting DOM elements for `subpathHighlight` of the given `child`. * `subpathHighlight` must be set by `child.applySubpath` before calling this method. * * @param child * @param duration The duration in seconds to highlight the subpath. If it's 0, the highlight will not be removed until the user clicks on the page. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/highlights/viewer.ts#L44-L97
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
ViewerHighlightLib.highlightRect
highlightRect(child: PDFViewerChild, page: number, rect: Rect) { this.clearRectHighlight(child); if (1 <= page && page <= child.pdfViewer.pagesCount) { const pageView = child.getPage(page); if (pageView?.div.dataset.loaded) { child.rectHighlight = this.placeRectInPage(rect, pageView); child.rectHighlight.addClass('rect-highlight'); // If `zoomToFitRect === true`, it will be handled by `PDFViewerChild.prototype.applySubpath` as a FitR destination. if (!this.settings.zoomToFitRect) { activeWindow.setTimeout(() => { window.pdfjsViewer.scrollIntoView(child.rectHighlight, { top: - this.settings.embedMargin }); }); } } } }
/** * The counterpart of `PDFViewerChild.prototype.highlightText` and `PDFViewerChild.prototype.highlightAnnotation` * for rectangular selections. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/highlights/viewer.ts#L103-L122
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
ViewerHighlightLib.clearRectHighlight
clearRectHighlight(child: PDFViewerChild) { if (child.rectHighlight) { child.rectHighlight.detach(); child.rectHighlight = null; } }
/** * The counterpart of `PDFViewerChild.prototype.clearTextHighlight` and `PDFViewerChild.prototype.clearAnnotationHighlight` * for rectangular selections. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/highlights/viewer.ts#L128-L133
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
AnnotationWriteFileLib.addLinkAnnotationToSelection
async addLinkAnnotationToSelection(dest: DestArray | string) { return this.addAnnotationToSelection(async (file, page, rects) => { const io = this.getPdfIo(); return await io.addLinkAnnotation(file, page, rects, dest); }); }
/** * @param dest A destination, represented either by its name (named destination) or as a DestArray (explicit destination). */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/highlights/write-file/index.ts#L34-L39
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
AnnotationWriteFileLib.addAnnotationToTextRange
async addAnnotationToTextRange(annotator: Annotator, child: PDFViewerChild, pageNumber: number, beginIndex: number, beginOffset: number, endIndex: number, endOffset: number) { if (!child.file) return; if (1 <= pageNumber && pageNumber <= child.pdfViewer.pagesCount) { const pageView = child.getPage(pageNumber); if (pageView?.textLayer && pageView.div.dataset.loaded) { const textLayerInfo = getTextLayerInfo(pageView.textLayer); if (textLayerInfo) { const results = this.lib.highlight.geometry.computeMergedHighlightRects(textLayerInfo, beginIndex, beginOffset, endIndex, endOffset); const rects = results.map(({ rect }) => rect); let annotationID; try { annotationID = await annotator(child.file, pageNumber, rects); } catch (e) { new Notice(`${this.plugin.manifest.name}: An error occurred while attemping to add an annotation.`); console.error(e); } return { annotationID, rects }; } } } }
/** Add a highlight annotation to a text selection specified by a subpath of the form `#page=<pageNumber>&selection=<beginIndex>,<beginOffset>,<endIndex>,<endOffset>`. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/lib/highlights/write-file/index.ts#L60-L81
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFOutlineTitleModal.constructor
constructor(plugin: PDFPlus, modalTitle: string) { super(plugin); this.modalTitle = modalTitle; // Don't use `Scope` or `keydown` because they will cause the modal to be closed // when hitting Enter with IME on this.component.registerDomEvent(this.modalEl.doc, 'keypress', (evt) => { if (evt.key === 'Enter') { this.submitAndClose(); } }); }
// the title of an outline item
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/modals/outline-modals.ts#L19-L30
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
patchObsidianViewer
const patchObsidianViewer = (plugin: PDFPlus, pdfViewer: ObsidianViewer) => { // What this prototype actually is will change depending on the Obsidian version. // // In Obsidian v1.7.7 or earlier, `pdfViewer` is an instance of the `ObsidianViewer` (which is a class). // Therefore, `prototype` is the prototype of the `ObsidianViewer` class, that is // `Object.getPrototypeOf(pdfViewer) === pdfViewer.constructor.prototype === window.pdfjsViewer.ObsidianViewer.prototype`. // // In Obsidian v1.8.0 or later, `pdfViewer` is a raw object whose prototype is `PDFViewerApplication`. // `PDFViewerApplication` was a class (the base class of `ObsidianViewer`) in the previous versions, // but it is now a raw object. Therefore, `prototype` is the `PDFViewerApplication` object itself, that is // `Object.getPrototypeOf(pdfViewer) === window.pdfjsViewer.PDFViewerApplication`. // // See the docstring of the `ObsidianViewer` interface for more details. const prototype = Object.getPrototypeOf(pdfViewer); plugin.register(around(prototype, { open(old) { return async function (this: ObsidianViewer, args: any) { if (this.pdfPlusRedirect) { const { from, to } = this.pdfPlusRedirect; const url = args.url; if (typeof url === 'string' && url.startsWith(from) // on desktop, Vault.getResourcePath() returns a path with a query string like "?1629350400000" ) { args.url = to; } } delete this.pdfPlusRedirect; return await old.call(this, args); }; }, load(old) { return function (this: ObsidianViewer, doc: PDFDocumentProxy, ...args: any[]) { const callbacks = this.pdfPlusCallbacksOnDocumentLoaded; if (callbacks) { for (const callback of callbacks) { callback(doc); } } delete this.pdfPlusCallbacksOnDocumentLoaded; return old.call(this, doc, ...args); }; } })); };
/** Monkey-patch ObsidianViewer so that it can open external PDF files. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/patchers/pdf-internals.ts#L1003-L1050
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
onKeyDown
const onKeyDown = (e: KeyboardEvent) => { if (removed) return; if (doc.body.contains(targetEl)) { if (Keymap.isModifier(e, 'Mod')) { removeHandlers(); callback(); } } else removeHandlers(); };
// Watch for the mod key press
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/utils/events.ts#L109-L117
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
onMouseOver
const onMouseOver = (e: MouseEvent) => { if (removed) return; if (isTargetNode(e, e.target) && !targetEl.contains(e.target)) removeHandlers(); };
// Stop watching for the mod key press when the mouse escapes away from the target element
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/utils/events.ts#L119-L122
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
onMouseLeave
const onMouseLeave = (e: MouseEvent) => { if (removed) return; if (e.target === doc) removeHandlers(); };
// Stop watching for the mod key press when the mouse leaves the document
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/utils/events.ts#L124-L127
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
knuth_mod
function knuth_mod(dividend: number, divisor: number) { return dividend - divisor * Math.floor(dividend / divisor); }
/** * Takes sign of divisor -- incl. returning -0 * * Taken from https://github.com/tridactyl/tridactyl/blob/4a4c9c7306b436611088b6ff2dceff77e7ccbfd6/src/lib/number.mod.ts#L9-L12 */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/vim/hintnames.ts#L300-L302
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
ScrollController.scrollVerticallyByVisualPage
scrollVerticallyByVisualPage(times: number) { if (!this.viewerContainerEl) return; let offset = this.viewerContainerEl.clientHeight; offset *= times; this.viewerContainerEl.scrollBy({ top: offset, behavior: (this.settings.vimSmoothScroll ? 'smooth' : 'instant') as ScrollBehavior }); }
/** Here "page" does not mean the PDF page but the "visual page", i.e. the region of the screen that is currently visible. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/vim/scroll.ts#L91-L98
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
ScrollController.scrollHorizontallyByVisualPage
scrollHorizontallyByVisualPage(times: number) { if (!this.viewerContainerEl) return; let offset = this.viewerContainerEl.clientWidth; offset *= times; this.viewerContainerEl.scrollBy({ left: offset, behavior: (this.settings.vimSmoothScroll ? 'smooth' : 'instant') as ScrollBehavior }); }
/** Here "page" does not mean the PDF page but the "visual page", i.e. the region of the screen that is currently visible. */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/vim/scroll.ts#L101-L108
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPageTextStructureParser.getBoundIndicesOfLine
getBoundIndicesOfLine(itemIndex: number, lineOffset: number) { const lineStart = this._getIndexWithinLineStartIndicesForLineContainingItem(itemIndex); const lineStartIndex = this.lineStartIndices![lineStart + lineOffset] ?? null; if (lineStartIndex === null) return null; const nextLineStartIndex = this.lineStartIndices![lineStart + 1 + lineOffset]; let lineEndIndex = nextLineStartIndex === undefined ? this.items.length - 1 : nextLineStartIndex - 1; // Exclude detached EOL element that's replaced with <br> while (lineEndIndex > lineStartIndex && !this.items[lineEndIndex].str.length) lineEndIndex--; return { start: lineStartIndex, end: lineEndIndex }; }
/** * Get the indices of the text content items that start and end a line. * The line is specified by the index of the text content item that belongs to the line and the offset of the line from the item. * @param itemIndex * @param lineOffset */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/vim/text-structure-parser.ts#L74-L83
6744d590cb22a5171d2f5168d7a1c9e87775941d
obsidian-pdf-plus
github_2023
RyotaUshio
typescript
PDFPageTextStructureParser._getIndexWithinLineStartIndicesForLineContainingItem
_getIndexWithinLineStartIndicesForLineContainingItem(itemIndex: number) { if (!this.lineStartIndices) { this.parse(); } const { found, index: lineStartIndex } = binarySearch(this.lineStartIndices!, (i) => itemIndex - i); return found ? lineStartIndex : lineStartIndex - 1; }
/** * The name says it all, but to give some example: * * If `index`-th text content item belongs to the 5th line, and the 5th line starts from the 10th item, * then this function returns 10. * * @param itemIndex * @returns */
https://github.com/RyotaUshio/obsidian-pdf-plus/blob/6744d590cb22a5171d2f5168d7a1c9e87775941d/src/vim/text-structure-parser.ts#L130-L137
6744d590cb22a5171d2f5168d7a1c9e87775941d
inkdrop-visualizer
github_2023
inkdrop-org
typescript
isEmptyValue
const isEmptyValue = (value: any): boolean => { return ( value === null || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof value === 'object' && value !== null && Object.keys(value).length === 0) ); };
// Checks if the value is considered empty (null, undefined, empty array, or empty object)
https://github.com/inkdrop-org/inkdrop-visualizer/blob/17a387d1afada68b7a1e96b3dea9262dee4f7aa1/tldraw-renderer/src/jsonPlanManager/jsonPlanManager.ts#L27-L34
17a387d1afada68b7a1e96b3dea9262dee4f7aa1
inkdrop-visualizer
github_2023
inkdrop-org
typescript
getValueString
const getValueString = (value: any) => stringify(value);
// Updated getValueString function to use stringify utility
https://github.com/inkdrop-org/inkdrop-visualizer/blob/17a387d1afada68b7a1e96b3dea9262dee4f7aa1/tldraw-renderer/src/jsonPlanManager/jsonPlanManager.ts#L38-L38
17a387d1afada68b7a1e96b3dea9262dee4f7aa1
inkdrop-visualizer
github_2023
inkdrop-org
typescript
isValid
const isValid = (value: any) => { return value !== undefined && value !== null && value !== '' && !isEmptyArray(value) && !isEmptyObject(value); };
// Updated isValid function to check for objects
https://github.com/inkdrop-org/inkdrop-visualizer/blob/17a387d1afada68b7a1e96b3dea9262dee4f7aa1/tldraw-renderer/src/jsonPlanManager/jsonPlanManager.ts#L46-L48
17a387d1afada68b7a1e96b3dea9262dee4f7aa1
inkdrop-visualizer
github_2023
inkdrop-org
typescript
isEmptyObject
const isEmptyObject = (value: any) => { return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.keys(value).length === 0; };
// Check if value is an empty object
https://github.com/inkdrop-org/inkdrop-visualizer/blob/17a387d1afada68b7a1e96b3dea9262dee4f7aa1/tldraw-renderer/src/jsonPlanManager/jsonPlanManager.ts#L51-L53
17a387d1afada68b7a1e96b3dea9262dee4f7aa1
mitex
github_2023
mitex-rs
typescript
Preview
const Preview = (output: State<string>) => { const svgData = van.state(""); van.derive(async () => { if (fontLoaded.val) { svgData.val = await $typst.svg({ mainContent: `#import "@preview/mitex:0.2.5": * #set page(width: auto, height: auto, margin: 1em); #set text(size: 24pt); ${darkModeStyle.val} #math.equation(eval("$" + \`${output.val}\`.text + "$", mode: "markup", scope: mitex-scope), block: true) `, }); } else { svgData.val = ""; } }); return div( { class: "mitex-preview" }, div({ innerHTML: van.derive(() => { if (!compilerLoaded.val) { return "Loading compiler from CDN..."; } else if (!fontLoaded.val) { return "Loading fonts from CDN..."; } else { return svgData.val; } }), }) ); };
/// The preview component
https://github.com/mitex-rs/mitex/blob/5fc83b64ab5e0b91918528ef2987037866e24086/packages/mitex-web/src/main.ts#L56-L87
5fc83b64ab5e0b91918528ef2987037866e24086
mitex
github_2023
mitex-rs
typescript
CopyButton
const CopyButton = (title: string, content: State<string>) => button({ onclick: () => navigator.clipboard.writeText(content.val), textContent: title, });
/// Copy a a derived string to clipboard
https://github.com/mitex-rs/mitex/blob/5fc83b64ab5e0b91918528ef2987037866e24086/packages/mitex-web/src/main.ts#L90-L94
5fc83b64ab5e0b91918528ef2987037866e24086
mitex
github_2023
mitex-rs
typescript
bufferToBase64Url
const bufferToBase64Url = async (data: Uint8Array) => { // Use a FileReader to generate a base64 data URI const base64url = await new Promise<string | null>((r, reject) => { const reader = new FileReader(); reader.onload = () => { const result = reader.result; if (typeof result === "string" || result === null) { r(result); } reject(new Error("Unexpected result type")); }; reader.readAsDataURL( new Blob([data], { type: "application/octet-binary" }) ); }); // remove the `data:...;base64,` part from the start return base64url; };
/// https://stackoverflow.com/questions/21797299/convert-base64-string-to-arraybuffer
https://github.com/mitex-rs/mitex/blob/5fc83b64ab5e0b91918528ef2987037866e24086/packages/mitex-web/src/tools/underleaf-fs.ts#L10-L28
5fc83b64ab5e0b91918528ef2987037866e24086
mitex
github_2023
mitex-rs
typescript
reloadAll
const reloadAll = async (state: FsState) => { const $typst = window.$typst; await Promise.all( (fsState.val?.fsList || []).map(async (f) => { return await $typst.mapShadow(f.path, f.data.val); }) ); focusFile.val = state.fsList.find( (t) => t.path === "/repo/fixtures/underleaf/ieee/main.tex" ); changeFocusFile.val = focusFile.val?.clone(); };
/// Reload all files to compiler and application
https://github.com/mitex-rs/mitex/blob/5fc83b64ab5e0b91918528ef2987037866e24086/packages/mitex-web/src/tools/underleaf-fs.ts#L153-L165
5fc83b64ab5e0b91918528ef2987037866e24086
mitex
github_2023
mitex-rs
typescript
isDarkMode
const isDarkMode = () => window.matchMedia?.("(prefers-color-scheme: dark)").matches;
/// Checks if the browser is in dark mode
https://github.com/mitex-rs/mitex/blob/5fc83b64ab5e0b91918528ef2987037866e24086/packages/mitex-web/src/tools/underleaf.ts#L17-L18
5fc83b64ab5e0b91918528ef2987037866e24086
mitex
github_2023
mitex-rs
typescript
ExportButton
const ExportButton = (title: string, onclick: () => void) => button({ onclick, textContent: title, });
/// Exports the document
https://github.com/mitex-rs/mitex/blob/5fc83b64ab5e0b91918528ef2987037866e24086/packages/mitex-web/src/tools/underleaf.ts#L21-L25
5fc83b64ab5e0b91918528ef2987037866e24086
ngrx-toolkit
github_2023
angular-architects
typescript
SignalReduxStore.connectFeatureStore
connectFeatureStore(mappers: MapperTypes<ActionCreator<any, any>[]>[]): void { mappers.forEach( mapper => mapper.types.forEach( action => this.mapperDict[action] = { storeMethod: mapper.storeMethod, resultMethod: mapper.resultMethod } ) ); }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
https://github.com/angular-architects/ngrx-toolkit/blob/eda4138f4208f75f9ef890d4588007e1541c6f26/libs/ngrx-toolkit/redux-connector/src/lib/signal-redux-store.ts#L40-L49
eda4138f4208f75f9ef890d4588007e1541c6f26
ngrx-toolkit
github_2023
angular-architects
typescript
DevtoolsSyncer.addStore
addStore( id: string, name: string, store: StateSource<object>, options: DevtoolsInnerOptions ) { let storeName = name; const names = Object.values(this.#stores).map((store) => store.name); if (names.includes(storeName)) { // const { options } = throwIfNull( // Object.values(this.#stores).find((store) => store.name === storeName) // ); if (!options.indexNames) { throw new Error(`An instance of the store ${storeName} already exists. \ Enable automatic indexing via withDevTools('${storeName}', { indexNames: true }), or rename it upon instantiation.`); } } for (let i = 1; names.includes(storeName); i++) { storeName = `${name}-${i}`; } this.#stores[id] = { name: storeName, options }; const tracker = options.tracker; if (!this.#trackers.includes(tracker)) { this.#trackers.push(tracker); } tracker.onChange((changedState) => this.syncToDevTools(changedState)); tracker.track(id, store); }
/** * Consumer provides the id. That is because we can only start * tracking the store in the init hook. * Unfortunately, methods for renaming having the final id * need to be defined already before. * That's why `withDevtools` requests first the id and * then registers itself later. */
https://github.com/angular-architects/ngrx-toolkit/blob/eda4138f4208f75f9ef890d4588007e1541c6f26/libs/ngrx-toolkit/src/lib/devtools/internal/devtools-syncer.service.ts#L109-L140
eda4138f4208f75f9ef890d4588007e1541c6f26
rpc-anywhere
github_2023
DaniGuardiola
typescript
el
function el<Element extends HTMLElement>(id: string) { const element = document.getElementById(id); if (!element) throw new Error(`Element with id ${id} not found`); return element as Element; }
// non-demo stuff - you can ignore this :)
https://github.com/DaniGuardiola/rpc-anywhere/blob/7ec394656c63e92eff1cbb3976f46da6df526ff7/demo/parent.ts#L111-L115
7ec394656c63e92eff1cbb3976f46da6df526ff7
rpc-anywhere
github_2023
DaniGuardiola
typescript
_setDebugHooks
function _setDebugHooks(newDebugHooks: DebugHooks) { debugHooks = newDebugHooks; }
/** * Sets the debug hooks that will be used to debug the RPC instance. */
https://github.com/DaniGuardiola/rpc-anywhere/blob/7ec394656c63e92eff1cbb3976f46da6df526ff7/src/rpc.ts#L89-L91
7ec394656c63e92eff1cbb3976f46da6df526ff7
rpc-anywhere
github_2023
DaniGuardiola
typescript
setTransport
function setTransport(newTransport: RPCTransport) { if (transport.unregisterHandler) transport.unregisterHandler(); transport = newTransport; transport.registerHandler?.(handler); }
/** * Sets the transport that will be used to send and receive requests, * responses and messages. */
https://github.com/DaniGuardiola/rpc-anywhere/blob/7ec394656c63e92eff1cbb3976f46da6df526ff7/src/rpc.ts#L99-L103
7ec394656c63e92eff1cbb3976f46da6df526ff7
rpc-anywhere
github_2023
DaniGuardiola
typescript
setRequestHandler
function setRequestHandler( /** * The function that will be set as the "request handler" function. */ handler: RPCRequestHandler<Schema["requests"]>, ) { if (typeof handler === "function") { requestHandler = handler; return; } requestHandler = (method: keyof Schema["requests"], params: any) => { const handlerFn = handler[method]; if (handlerFn) return handlerFn(params); const fallbackHandler = handler._; if (!fallbackHandler) throw new Error( `The requested method has no handler: ${method as string}`, ); return fallbackHandler(method, params); }; }
/** * Sets the function that will be used to handle requests from the * remote RPC instance. */
https://github.com/DaniGuardiola/rpc-anywhere/blob/7ec394656c63e92eff1cbb3976f46da6df526ff7/src/rpc.ts#L112-L132
7ec394656c63e92eff1cbb3976f46da6df526ff7
rpc-anywhere
github_2023
DaniGuardiola
typescript
requestFn
function requestFn<Method extends keyof RemoteSchema["requests"]>( method: Method, ...args: "params" extends keyof RemoteSchema["requests"][Method] ? undefined extends RemoteSchema["requests"][Method]["params"] ? [params?: RemoteSchema["requests"][Method]["params"]] : [params: RemoteSchema["requests"][Method]["params"]] : [] ): Promise<RPCRequestResponse<RemoteSchema["requests"], Method>> { const params = args[0]; return new Promise((resolve, reject) => { if (!transport.send) throw missingTransportMethodError(["send"], "make requests"); const requestId = getRequestId(); const request: _RPCRequestPacket = { type: "request", id: requestId, method, params, }; requestListeners.set(requestId, { resolve, reject }); if (maxRequestTime !== Infinity) requestTimeouts.set( requestId, setTimeout(() => { requestTimeouts.delete(requestId); reject(new Error("RPC request timed out.")); }, maxRequestTime), ); debugHooks.onSend?.(request); transport.send(request); }) as Promise<any>; }
/** * Sends a request to the remote RPC endpoint and returns a promise * with the response. */
https://github.com/DaniGuardiola/rpc-anywhere/blob/7ec394656c63e92eff1cbb3976f46da6df526ff7/src/rpc.ts#L160-L191
7ec394656c63e92eff1cbb3976f46da6df526ff7
rpc-anywhere
github_2023
DaniGuardiola
typescript
sendFn
function sendFn<Message extends keyof Schema["messages"]>( /** * The name of the message to send. */ message: Message, ...args: void extends RPCMessagePayload<Schema["messages"], Message> ? [] : undefined extends RPCMessagePayload<Schema["messages"], Message> ? [payload?: RPCMessagePayload<Schema["messages"], Message>] : [payload: RPCMessagePayload<Schema["messages"], Message>] ) { const payload = args[0]; if (!transport.send) throw missingTransportMethodError(["send"], "send messages"); const rpcMessage: _RPCMessagePacket = { type: "message", id: message as string, payload, }; debugHooks.onSend?.(rpcMessage); transport.send(rpcMessage); }
// messages
https://github.com/DaniGuardiola/rpc-anywhere/blob/7ec394656c63e92eff1cbb3976f46da6df526ff7/src/rpc.ts#L221-L242
7ec394656c63e92eff1cbb3976f46da6df526ff7
rpc-anywhere
github_2023
DaniGuardiola
typescript
addMessageListener
function addMessageListener<Message extends keyof RemoteSchema["messages"]>( /** * The name of the message to listen to. Use "*" to listen to all * messages. */ message: "*" | Message, /** * The function that will be called when a message is received. */ listener: | WildcardRPCMessageHandlerFn<RemoteSchema["messages"]> | RPCMessageHandlerFn<RemoteSchema["messages"], Message>, ): void { if (!transport.registerHandler) throw missingTransportMethodError( ["registerHandler"], "register message listeners", ); if (message === "*") { wildcardMessageListeners.add(listener as any); return; } if (!messageListeners.has(message)) messageListeners.set(message, new Set()); messageListeners.get(message)?.add(listener as any); }
/** * Adds a listener for a message (or all if "*" is used) from the * remote RPC endpoint. */
https://github.com/DaniGuardiola/rpc-anywhere/blob/7ec394656c63e92eff1cbb3976f46da6df526ff7/src/rpc.ts#L307-L332
7ec394656c63e92eff1cbb3976f46da6df526ff7
rpc-anywhere
github_2023
DaniGuardiola
typescript
removeMessageListener
function removeMessageListener< Message extends keyof RemoteSchema["messages"], >( /** * The name of the message to remove the listener for. Use "*" to * remove a listener for all messages. */ message: "*" | Message, /** * The listener function that will be removed. */ listener: | WildcardRPCMessageHandlerFn<RemoteSchema["messages"]> | RPCMessageHandlerFn<RemoteSchema["messages"], Message>, ): void { if (message === "*") { wildcardMessageListeners.delete(listener as any); return; } messageListeners.get(message)?.delete(listener as any); if (messageListeners.get(message)?.size === 0) messageListeners.delete(message); }
/** * Removes a listener for a message (or all if "*" is used) from the * remote RPC endpoint. */
https://github.com/DaniGuardiola/rpc-anywhere/blob/7ec394656c63e92eff1cbb3976f46da6df526ff7/src/rpc.ts#L370-L392
7ec394656c63e92eff1cbb3976f46da6df526ff7
rpc-anywhere
github_2023
DaniGuardiola
typescript
handler
async function handler( message: | _RPCRequestPacketFromSchema<Schema["requests"]> | _RPCResponsePacketFromSchema<RemoteSchema["requests"]> | _RPCMessagePacketFromSchema<RemoteSchema["messages"]>, ) { debugHooks.onReceive?.(message); if (!("type" in message)) throw new Error("Message does not contain a type."); if (message.type === "request") { if (!transport.send || !requestHandler) throw missingTransportMethodError( ["send", "requestHandler"], "handle requests", ); const { id, method, params } = message; let response: _RPCResponsePacket; try { response = { type: "response", id, success: true, payload: await requestHandler(method, params), }; } catch (error) { if (!(error instanceof Error)) throw error; response = { type: "response", id, success: false, error: error.message, }; } debugHooks.onSend?.(response); transport.send(response); return; } if (message.type === "response") { const timeout = requestTimeouts.get(message.id); if (timeout != null) clearTimeout(timeout); const { resolve, reject } = requestListeners.get(message.id) ?? {}; if (!message.success) reject?.(new Error(message.error)); else resolve?.(message.payload); return; } if (message.type === "message") { for (const listener of wildcardMessageListeners) listener(message.id, message.payload); const listeners = messageListeners.get(message.id); if (!listeners) return; for (const listener of listeners) listener(message.payload); return; } throw new Error(`Unexpected RPC message type: ${(message as any).type}`); }
// message handling
https://github.com/DaniGuardiola/rpc-anywhere/blob/7ec394656c63e92eff1cbb3976f46da6df526ff7/src/rpc.ts#L397-L451
7ec394656c63e92eff1cbb3976f46da6df526ff7
stan-js
github_2023
codemask-labs
typescript
getAction
const getAction = <K extends TKey>(key: K) => store.actions[getActionKey(key)] as (value: unknown) => void
// @ts-expect-error - TS doesn't know that all keys are in actions object
https://github.com/codemask-labs/stan-js/blob/2bee695bc462a15d4fc5f4fe610ddabbe81ae3b2/src/createStore.ts#L94-L94
2bee695bc462a15d4fc5f4fe610ddabbe81ae3b2