├── .npmrc ├── styles.css ├── doc └── screenshot.png ├── .prettierrc ├── manifest.json ├── manifest-beta.json ├── .github └── workflows │ ├── lint.yml │ ├── test.yml │ └── release.yml ├── .gitignore ├── tsconfig.json ├── versions.json ├── version-bump.mjs ├── LICENSE ├── eslint.config.mjs ├── esbuild.config.mjs ├── README.md ├── package.json ├── src ├── search │ ├── search.grammar │ ├── search.ts │ └── search.test.ts ├── view.ts ├── main.ts ├── settings.ts ├── utils │ ├── previewContent.test.ts │ └── previewContent.ts └── components │ ├── store.ts │ ├── Card.svelte │ └── Root.svelte └── CONTRIBUTING.md /.npmrc: -------------------------------------------------------------------------------- 1 | tag-version-prefix="" -------------------------------------------------------------------------------- /styles.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Required by Obsidian to load the plugin 3 | */ 4 | -------------------------------------------------------------------------------- /doc/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jillro/obsidian-cards-view-plugin/HEAD/doc/screenshot.png -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": ["prettier-plugin-svelte"], 3 | "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }] 4 | } 5 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "cards-view", 3 | "name": "Cards View", 4 | "version": "1.9.3", 5 | "minAppVersion": "1.6.5", 6 | "description": "Displays a card view of your notes.", 7 | "author": "Maud Royer", 8 | "authorUrl": "https://maudroyer.fr", 9 | "isDesktopOnly": false 10 | } -------------------------------------------------------------------------------- /manifest-beta.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "cards-view", 3 | "name": "Cards View", 4 | "version": "1.9.0-rc1", 5 | "minAppVersion": "1.6.5", 6 | "description": "Displays a card view of your notes.", 7 | "author": "Maud Royer", 8 | "authorUrl": "https://maudroyer.fr", 9 | "isDesktopOnly": false 10 | } -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | on: push 2 | 3 | jobs: 4 | lint: 5 | runs-on: ubuntu-latest 6 | 7 | steps: 8 | - uses: actions/checkout@v3 9 | 10 | - name: Use Node.js 11 | uses: actions/setup-node@v3 12 | with: 13 | node-version: "24.x" 14 | 15 | - name: Install dependencies 16 | run: npm install 17 | 18 | - name: Lint plugin 19 | run: npm run lint -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | on: push 2 | 3 | jobs: 4 | test: 5 | runs-on: ubuntu-latest 6 | 7 | steps: 8 | - uses: actions/checkout@v3 9 | 10 | - name: Use Node.js 11 | uses: actions/setup-node@v3 12 | with: 13 | node-version: "24.x" 14 | 15 | - name: Install dependencies 16 | run: npm install 17 | 18 | - name: Run tests 19 | run: npm run test -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # vscode 2 | .vscode 3 | 4 | # Intellij 5 | *.iml 6 | .idea 7 | 8 | # npm 9 | node_modules 10 | 11 | # Don't include the compiled main.js file in the repo. 12 | # They should be uploaded to GitHub releases instead. 13 | main.js 14 | 15 | # Exclude sourcemaps 16 | *.map 17 | 18 | # obsidian 19 | data.json 20 | 21 | # Exclude macOS Finder (System Explorer) View States 22 | .DS_Store 23 | 24 | # Generated by Lezer 25 | src/search/grammar*.js -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@tsconfig/svelte/tsconfig.json", 3 | "compilerOptions": { 4 | "types": ["svelte", "node"], 5 | "baseUrl": ".", 6 | "inlineSources": true, 7 | "module": "ESNext", 8 | "target": "ES6", 9 | "allowJs": true, 10 | "noImplicitAny": true, 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "isolatedModules": true, 14 | "strictNullChecks": true, 15 | "lib": [ 16 | "DOM", 17 | "ES5", 18 | "ES6", 19 | "ES7" 20 | ], 21 | }, 22 | "include": [ 23 | "**/*.ts" 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /versions.json: -------------------------------------------------------------------------------- 1 | { 2 | "1.0.0": "0.15.0", 3 | "1.1.0": "0.15.0", 4 | "1.2.0": "0.15.0", 5 | "1.2.1": "0.15.0", 6 | "1.2.2": "0.15.0", 7 | "1.2.3": "0.15.0", 8 | "1.2.4": "0.15.0", 9 | "1.3.0": "0.15.0", 10 | "1.3.1": "0.15.0", 11 | "1.3.2": "0.15.0", 12 | "1.3.3": "0.15.0", 13 | "1.3.4": "0.15.0", 14 | "1.4.0": "0.15.0", 15 | "1.4.1": "0.15.0", 16 | "1.5.0": "0.15.0", 17 | "1.6.0": "0.15.0", 18 | "1.7.0": "0.15.0", 19 | "1.8.0": "1.6.5", 20 | "1.8.1": "1.6.5", 21 | "1.9.0": "1.6.5", 22 | "1.9.1": "1.6.5", 23 | "1.9.2": "1.6.5", 24 | "1.9.3-beta.0": "1.6.5", 25 | "1.9.3-beta.1": "1.6.5", 26 | "1.9.3-beta.2": "1.6.5", 27 | "1.9.3": "1.6.5" 28 | } -------------------------------------------------------------------------------- /version-bump.mjs: -------------------------------------------------------------------------------- 1 | import { readFileSync, writeFileSync } from "fs"; 2 | 3 | const targetVersion = process.env.npm_package_version; 4 | 5 | // read minAppVersion from manifest.json and bump version to target version 6 | let manifest = JSON.parse(readFileSync("manifest.json", "utf8")); 7 | const { minAppVersion } = manifest; 8 | manifest.version = targetVersion; 9 | writeFileSync("manifest.json", JSON.stringify(manifest, null, "\t")); 10 | 11 | // update versions.json with target version and minAppVersion from manifest.json 12 | let versions = JSON.parse(readFileSync("versions.json", "utf8")); 13 | versions[targetVersion] = minAppVersion; 14 | writeFileSync("versions.json", JSON.stringify(versions, null, "\t")); 15 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release Obsidian plugin 2 | 3 | on: 4 | push: 5 | tags: 6 | - "*" 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v3 14 | 15 | - name: Use Node.js 16 | uses: actions/setup-node@v3 17 | with: 18 | node-version: "24.x" 19 | 20 | - name: Build plugin 21 | run: | 22 | npm install 23 | npm run build 24 | 25 | - name: Create release 26 | env: 27 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 28 | run: | 29 | tag="${GITHUB_REF#refs/tags/}" 30 | 31 | gh release create "$tag" \ 32 | --title="$tag" \ 33 | --draft \ 34 | main.js manifest.json styles.css 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Maud Royer 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import globals from "globals"; 2 | import js from "@eslint/js"; 3 | import tseslint from "typescript-eslint"; 4 | import svelte from "eslint-plugin-svelte"; 5 | import tsPlugin from "@typescript-eslint/eslint-plugin"; 6 | import svelteParser from "svelte-eslint-parser"; 7 | import tsParser from "@typescript-eslint/parser"; 8 | 9 | export default [ 10 | js.configs.recommended, 11 | tseslint.configs.eslintRecommended, 12 | ...tseslint.configs.recommended, 13 | ...svelte.configs["flat/prettier"], 14 | { 15 | files: ["**/*.ts", "**/*.svelte", "**/*.mjs", "**/*.js"], 16 | languageOptions: { 17 | parser: tsParser, 18 | globals: { ...globals.node }, 19 | sourceType: "module", 20 | }, 21 | plugins: { "@typescript-eslint": tsPlugin }, 22 | rules: { 23 | "no-undef": "off", 24 | "no-unused-vars": "off", 25 | "@typescript-eslint/no-unused-vars": ["error", { args: "none" }], 26 | "@typescript-eslint/ban-ts-comment": "off", 27 | "no-prototype-builtins": "off", 28 | "@typescript-eslint/no-empty-function": "off", 29 | }, 30 | }, 31 | { 32 | files: ["**/*.svelte"], 33 | languageOptions: { 34 | parser: svelteParser, 35 | parserOptions: { 36 | parser: "@typescript-eslint/parser", 37 | }, 38 | }, 39 | }, 40 | { 41 | ignores: ["node_modules", "main.js"], 42 | }, 43 | ]; 44 | -------------------------------------------------------------------------------- /esbuild.config.mjs: -------------------------------------------------------------------------------- 1 | import esbuildSvelte from "esbuild-svelte"; 2 | import { sveltePreprocess } from "svelte-preprocess"; 3 | import esbuild from "esbuild"; 4 | import { builtinModules } from "node:module"; 5 | 6 | const banner = `/* 7 | THIS IS A GENERATED/BUNDLED FILE BY ESBUILD 8 | if you want to view the source, please visit the github repository of this plugin 9 | */ 10 | `; 11 | 12 | const prod = process.argv[2] === "production"; 13 | 14 | const context = await esbuild.context({ 15 | plugins: [ 16 | esbuildSvelte({ 17 | compilerOptions: { css: "injected" }, 18 | preprocess: sveltePreprocess(), 19 | sourceMap: !prod, 20 | filterWarnings: (warning) => warning.code !== "css-unused-selector", 21 | }), 22 | ], 23 | banner: { 24 | js: banner, 25 | }, 26 | entryPoints: ["src/main.ts"], 27 | bundle: true, 28 | external: [ 29 | "obsidian", 30 | "electron", 31 | "@codemirror/autocomplete", 32 | "@codemirror/collab", 33 | "@codemirror/commands", 34 | "@codemirror/language", 35 | "@codemirror/lint", 36 | "@codemirror/search", 37 | "@codemirror/state", 38 | "@codemirror/view", 39 | "@lezer/common", 40 | "@lezer/highlight", 41 | "@lezer/lr", 42 | ...builtinModules, 43 | ], 44 | format: "cjs", 45 | target: "es2018", 46 | logLevel: "info", 47 | sourcemap: prod ? false : "inline", 48 | treeShaking: true, 49 | outfile: "main.js", 50 | minify: prod, 51 | }); 52 | 53 | if (prod) { 54 | await context.rebuild(); 55 | process.exit(0); 56 | } else { 57 | await context.watch(); 58 | } 59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cards View 2 | 3 | This is a plugin for Obsidian.md that displays a card view of your notes. 4 | 5 | ![Screenshot](doc/screenshot.png) 6 | 7 | ## Features 8 | 9 | - Display notes in a card view 10 | - Sorts by last modified or created date 11 | - Pin notes to top 12 | - Supports same [search syntax](https://help.obsidian.md/Plugins/Search#Search+terms) as Obsidian official 13 | search plugin (except `block:`, `section:` and `task*:` operators) 14 | - Quick access to filtering by tags 15 | - Settings to exclude some notes from the view 16 | 17 | ## Installation 18 | 19 | 1. Navigate to Obsidian's settings 20 | 2. Click on "Third-party plugin" 21 | 3. Turn off the Safe mode 22 | 4. Click on "Browse" and search for "Obsidian Cards View Plugin" 23 | 5. Click install 24 | 6. Toggle the plugin on in the "Installed plugins" tab 25 | 26 | ## Beta version 27 | 28 | This plugin offers beta versions that can be installed with [BRAT](https://github.com/TfTHacker/obsidian42-brat?tab=readme-ov-file). 29 | 30 | Please be aware that this versions may be unstable and have bugs, but you will have access to new features earlier. 31 | 32 | ## Contributing 33 | 34 | For major changes, please open an issue first to discuss what you would like to change. 35 | Pull requests are welcome. Please read [CONTRIBUTING.md](https://github.com/jillro/obsidian-cards-view-plugin/blob/main/CONTRIBUTING.md) for details. 36 | 37 | ## License 38 | 39 | [MIT](https://choosealicense.com/licenses/mit/) 40 | 41 | ## Credits 42 | 43 | This project uses the following dependencies: 44 | 45 | - [Masonry](https://masonry.desandro.com/). Licensed under the [MIT License](https://desandro.mit-license.org/). 46 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cards-view", 3 | "version": "1.9.3", 4 | "description": "Plugin for Obsidian.md. Displays a card view of your notes.", 5 | "main": "main.js", 6 | "scripts": { 7 | "dev": "node esbuild.config.mjs", 8 | "prebuild": "npm run lezer", 9 | "postinstall": "npm run lezer", 10 | "lezer": "lezer-generator src/search/search.grammar -o src/search/grammar.js", 11 | "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", 12 | "version": "node version-bump.mjs && git add manifest.json versions.json", 13 | "lint": "eslint && prettier --check **/*.mjs **/*.ts **/*.svelte && svelte-check", 14 | "test": "node --test --require tsx/cjs $(find . -name \"*.test.ts\")" 15 | }, 16 | "keywords": [], 17 | "author": "Maud Royer ", 18 | "license": "MIT", 19 | "devDependencies": { 20 | "@eslint/js": "^9.16.0", 21 | "@tsconfig/svelte": "^5.0.2", 22 | "@types/masonry-layout": "^4.2.7", 23 | "@types/minimasonry": "^1.3.5", 24 | "@types/node": "^24.10.4", 25 | "@typescript-eslint/eslint-plugin": "^8.18.0", 26 | "@typescript-eslint/parser": "^8.18.0", 27 | "builtin-modules": "^5.0.0", 28 | "esbuild": "^0.27.1", 29 | "esbuild-svelte": "^0.9.4", 30 | "eslint-config-prettier": "^10.1.8", 31 | "eslint-plugin-svelte": "^3.13.1", 32 | "globals": "^16.5.0", 33 | "lezer-generator": "^0.13.4", 34 | "obsidian": "latest", 35 | "prettier": "^3.3.3", 36 | "prettier-plugin-svelte": "^3.2.6", 37 | "svelte": "^5.0.0", 38 | "svelte-check": "^4.3.4", 39 | "svelte-eslint-parser": "^1.4.1", 40 | "svelte-preprocess": "^6.0.3", 41 | "tsafe": "^1.8.5", 42 | "tslib": "^2.6.2", 43 | "tsx": "^4.19.2", 44 | "typescript": "^5.5.0", 45 | "typescript-eslint": "^8.18.0", 46 | "vitest": "^4.0.15" 47 | }, 48 | "dependencies": { 49 | "minimasonry": "^1.3.2" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/search/search.grammar: -------------------------------------------------------------------------------- 1 | @precedence { 2 | Not 3 | subExpression 4 | or @left 5 | SearchOperator @left 6 | } 7 | 8 | @top Program { expression } 9 | 10 | expression { And | Or } 11 | 12 | And { subExpressionOrNot+ } 13 | Or { expression !or orOperator expression } 14 | Not { "-" subExpression } 15 | subExpressionOrNot { subExpression | Not } 16 | subExpression { term | "(" expression ")" } 17 | term { text | searchOperator | PropertyOperator } 18 | text { Word | Quote | Regex } 19 | searchOperator { 20 | FileOperator | 21 | PathOperator | 22 | ContentOperator | 23 | MatchCaseOperator | 24 | IgnoreCaseOperator | 25 | TagOperator | 26 | LineOperator 27 | } 28 | FileOperator { "file:" text } 29 | PathOperator { "path:" text } 30 | ContentOperator { "content:" text } 31 | MatchCaseOperator { "match-case:" text } 32 | IgnoreCaseOperator { "ignore-case:" text } 33 | TagOperator { "tag:" Word } 34 | LineOperator { "line:" subExpression } 35 | 36 | PropertyOperator { ("[" PropertyName "]") | ("[" PropertyName ":" PropertyValueExpression "]") } 37 | PropertyValueExpression { text | PropertyValueOr | "(" PropertyValueExpression ")" } 38 | PropertyValueOr { PropertyValueExpression !or orOperator PropertyValueExpression } 39 | 40 | @tokens { 41 | orOperator { "OR" } 42 | Quote { '"' (!["\\] | "\\" _)* '"' } 43 | Regex { '/' (![/\\] | "\\" _)* '/' } 44 | Word { ![\["/ \t\n\r\:\-()] ![ \t\n\r\:\-()\]]+ } 45 | PropertyName { ![\[" \t\n\r\:\]]+ } 46 | space { $[ \t\n\r]+ } 47 | @precedence { 48 | orOperator, 49 | Quote, 50 | Regex, 51 | "file:", 52 | "path:", 53 | "content:", 54 | "match-case:", 55 | "ignore-case:", 56 | "tag:", 57 | "line:", 58 | "]", 59 | ")", 60 | Word, 61 | space 62 | } 63 | } 64 | 65 | @skip { space } 66 | 67 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution guidelines 2 | 3 | You use this plugin and want to contribute ? First off, thank you for considering contributing to Cards View. 4 | 5 | Cards View have been increasing in popularity since its first release, and I am very happy to see that people are using it. I am also very happy 6 | to see that people are contributing to it. I am always looking for ways to improve the plugin and make it more useful. 7 | 8 | However, maintaining a plugin like this takes time and effort. I want this plugin to mature, but also to 9 | stay stable and viable. For this reason, I will be very careful in accepting contributions that I can maintain 10 | and that are in line with the vision I have for the plugin. 11 | 12 | ## Bugfixes 13 | 14 | All bug fixes are welcome. Be aware that because Cards View should be able to handle thousands of files, performance 15 | is often a key issue. Sometimes, you might be tempted to reimplement a feature in a more simple way in order 16 | to fix a bug, but it might be the case that they are implemented the way they are for the sake of performance. 17 | Of course, contributions that improve performance are always welcome. 18 | 19 | ## Features 20 | 21 | If you want to add a feature, please open an issue first to discuss it. This is to avoid wasting time on a feature that 22 | might not be accepted. 23 | 24 | ## General guidelines on pull requests 25 | 26 | Please make sure that your code is clean and well documented. If you are not sure about something, feel free to ask. Please 27 | also make sure that your code is tested. 28 | 29 | Please keep a clean commit history and follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) 30 | guidelines for your commit messages. This will male it easier to understand what your pull request is about, 31 | and to generate a changelog. 32 | 33 | Do not add changes in your pull request that are not directly related to the issue you are working on. 34 | Do not move files, add dependencies, or change the structure of the project in any way without first discussing it. 35 | -------------------------------------------------------------------------------- /src/view.ts: -------------------------------------------------------------------------------- 1 | import { ItemView, TAbstractFile, TFile } from "obsidian"; 2 | import Root from "./components/Root.svelte"; 3 | import store, { Sort } from "./components/store"; 4 | import { get } from "svelte/store"; 5 | import { mount } from "svelte"; 6 | 7 | export const VIEW_TYPE = "cards-view"; 8 | 9 | export class CardsViewPluginView extends ItemView { 10 | root: ReturnType | undefined; 11 | 12 | getViewType() { 13 | return VIEW_TYPE; 14 | } 15 | 16 | getDisplayText() { 17 | return "Cards View"; 18 | } 19 | 20 | onResize() { 21 | this.root?.updateLayoutNextTick(); 22 | } 23 | 24 | async onOpen() { 25 | const viewContent = this.containerEl.children[1]; 26 | store.view.set(this); 27 | 28 | store.files.set(this.app.vault.getMarkdownFiles()); 29 | this.registerEvent( 30 | this.app.vault.on("create", async (file: TAbstractFile) => { 31 | if (!this.app.workspace.layoutReady) { 32 | return; 33 | } 34 | if (file instanceof TFile && file.extension === "md") { 35 | store.files.update((files) => files?.concat(file)); 36 | } 37 | }), 38 | ); 39 | this.registerEvent( 40 | this.app.vault.on("delete", async (file: TAbstractFile) => { 41 | if (file instanceof TFile && file.extension === "md") { 42 | store.files.update((files) => 43 | files?.filter((f) => f.path !== file.path), 44 | ); 45 | } 46 | }), 47 | ); 48 | this.registerEvent( 49 | this.app.vault.on("modify", async (file: TAbstractFile) => { 50 | if (file instanceof TFile && file.extension === "md") { 51 | store.files.update((files) => 52 | files?.map((f) => (f.path === file.path ? file : f)), 53 | ); 54 | } 55 | }), 56 | ); 57 | this.registerEvent( 58 | this.app.vault.on( 59 | "rename", 60 | async (file: TAbstractFile, oldPath: string) => { 61 | if (file instanceof TFile && file.extension === "md") { 62 | store.files.update((files) => 63 | files?.map((f) => (f.path === oldPath ? file : f)), 64 | ); 65 | } 66 | }, 67 | ), 68 | ); 69 | 70 | this.root = mount(Root, { 71 | target: viewContent, 72 | }); 73 | 74 | // On scroll 80% of viewContent, load more cards 75 | viewContent.addEventListener("scroll", async () => { 76 | if ( 77 | viewContent.scrollTop + viewContent.clientHeight > 78 | viewContent.scrollHeight - 500 79 | ) { 80 | store.displayedCount.set(get(store.displayedFiles).length + 50); 81 | } 82 | }); 83 | } 84 | 85 | async onClose() { 86 | store.searchQuery.set(""); 87 | store.displayedCount.set(50); 88 | store.sort.set(Sort.Modified); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { 2 | type CachedMetadata, 3 | getAllTags, 4 | Plugin, 5 | WorkspaceLeaf, 6 | } from "obsidian"; 7 | 8 | import { 9 | type CardsViewSettings, 10 | CardsViewSettingsTab, 11 | DEFAULT_SETTINGS, 12 | } from "./settings"; 13 | import { CardsViewPluginView, VIEW_TYPE } from "./view"; 14 | import store from "./components/store"; 15 | 16 | export default class CardsViewPlugin extends Plugin { 17 | settings: CardsViewSettings = Object.assign({}, DEFAULT_SETTINGS); 18 | async onload() { 19 | this.settings = Object.assign(this.settings, await this.loadData()); 20 | if (!this.settings.savedSearch) { 21 | this.settings.savedSearch = await this.getTags(); 22 | } 23 | store.settings.subscribe(async () => await this.saveSettings()); 24 | store.app.set(this.app); 25 | store.settings.set(this.settings); 26 | store.settings.subscribe(async (settings) => { 27 | this.settings = settings; 28 | await this.saveSettings(); 29 | }); 30 | store.appCache.set(this.app.metadataCache); 31 | this.registerEvent( 32 | this.app.metadataCache.on("resolved", async () => 33 | store.appCache.update(() => this.app.metadataCache), 34 | ), 35 | ); 36 | 37 | this.addSettingTab(new CardsViewSettingsTab(this.app, this)); 38 | this.addRibbonIcon("align-start-horizontal", "Card view", () => { 39 | this.activateView(); 40 | }); 41 | 42 | this.addCommand({ 43 | id: "cards-view-plugin", 44 | name: "Open card view", 45 | callback: () => { 46 | this.activateView(); 47 | }, 48 | }); 49 | 50 | this.registerView(VIEW_TYPE, (leaf) => new CardsViewPluginView(leaf)); 51 | 52 | this.app.workspace.onLayoutReady(() => { 53 | if (this.settings.launchOnStart) { 54 | this.activateView(); 55 | } 56 | }); 57 | } 58 | 59 | onunload() {} 60 | 61 | async activateView() { 62 | const { workspace } = this.app; 63 | 64 | let leaf: WorkspaceLeaf | null; 65 | const leaves = workspace.getLeavesOfType(VIEW_TYPE); 66 | 67 | if (leaves.length) { 68 | leaf = leaves[0]; 69 | } else { 70 | leaf = workspace.getLeaf("tab"); 71 | } 72 | 73 | await leaf.setViewState({ type: VIEW_TYPE, active: true }); 74 | } 75 | 76 | async saveSettings() { 77 | await this.saveData(this.settings); 78 | } 79 | 80 | async getTags() { 81 | const tags = this.app.vault 82 | .getMarkdownFiles() 83 | .map( 84 | (file) => 85 | getAllTags( 86 | this.app.metadataCache.getFileCache(file) as CachedMetadata, 87 | ) || [], 88 | ) 89 | .flat(); 90 | 91 | const tagCounts = tags.reduce( 92 | (acc, tag) => { 93 | acc[tag] = (acc[tag] || 0) + 1; 94 | return acc; 95 | }, 96 | {} as Record, 97 | ); 98 | 99 | return Object.keys(tagCounts).sort((a, b) => tagCounts[b] - tagCounts[a]); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/settings.ts: -------------------------------------------------------------------------------- 1 | import CardsViewPlugin from "./main"; 2 | import { App, Notice, PluginSettingTab, Setting } from "obsidian"; 3 | import { settings } from "./components/store"; 4 | 5 | export enum TitleDisplayMode { 6 | Both = "Both", 7 | Title = "Title", 8 | Filename = "Filename", 9 | } 10 | 11 | export interface CardsViewSettings { 12 | baseQuery: string; 13 | minCardWidth: number; 14 | launchOnStart: boolean; 15 | displayTitle: TitleDisplayMode; 16 | pinnedFiles: string[]; 17 | savedSearch?: string[]; 18 | } 19 | 20 | export const DEFAULT_SETTINGS: CardsViewSettings = { 21 | baseQuery: "", 22 | minCardWidth: 200, 23 | launchOnStart: false, 24 | displayTitle: TitleDisplayMode.Both, 25 | pinnedFiles: [], 26 | }; 27 | 28 | export class CardsViewSettingsTab extends PluginSettingTab { 29 | plugin: CardsViewPlugin; 30 | 31 | constructor(app: App, plugin: CardsViewPlugin) { 32 | super(app, plugin); 33 | this.plugin = plugin; 34 | } 35 | 36 | display(): void { 37 | const { containerEl } = this; 38 | containerEl.empty(); 39 | 40 | new Setting(containerEl) 41 | .setName("Base search query") 42 | .setDesc( 43 | "Use this for example to exclude tags, folders or keywords from the view.", 44 | ) 45 | .addText((text) => 46 | text 47 | .setPlaceholder('-path:"Folder name/" -tag:hidden') 48 | .setValue(this.plugin.settings.baseQuery) 49 | .onChange((value) => { 50 | settings.update((s) => ({ 51 | ...s, 52 | baseQuery: value, 53 | })); 54 | }), 55 | ); 56 | 57 | new Setting(containerEl) 58 | .setName("Minimum card width") 59 | .setDesc("Cards will not be smaller than this width (in pixels)") 60 | .addText((text) => 61 | text 62 | .setPlaceholder("200") 63 | .setValue(this.plugin.settings.minCardWidth.toString()) 64 | .onChange((value) => { 65 | if (isNaN(parseInt(value))) { 66 | new Notice("Invalid number"); 67 | return; 68 | } 69 | 70 | settings.update((s) => ({ 71 | ...s, 72 | minCardWidth: parseInt(value), 73 | })); 74 | }), 75 | ); 76 | 77 | new Setting(containerEl) 78 | .setName("Title display mode") 79 | .setDesc("What to display on cards starting with a # Level 1 title") 80 | .addDropdown((dropdown) => 81 | dropdown 82 | .addOptions({ 83 | [TitleDisplayMode.Both]: "Both title and filename", 84 | [TitleDisplayMode.Title]: "Title", 85 | [TitleDisplayMode.Filename]: "Filename", 86 | }) 87 | .setValue(this.plugin.settings.displayTitle) 88 | .onChange((value) => { 89 | settings.update((s) => ({ 90 | ...s, 91 | displayTitle: value as TitleDisplayMode, 92 | })); 93 | }), 94 | ); 95 | 96 | new Setting(containerEl) 97 | .setName("Launch on start") 98 | .setDesc("Open the cards view when Obsidian starts") 99 | .addToggle((toggle) => 100 | toggle 101 | .setValue(this.plugin.settings.launchOnStart) 102 | .onChange((value) => { 103 | settings.update((s) => ({ 104 | ...s, 105 | launchOnStart: value, 106 | })); 107 | }), 108 | ); 109 | 110 | new Setting(containerEl) 111 | .setName("Reset settings") 112 | .setDesc("Reset all settings to default") 113 | .addButton((button) => 114 | button.setButtonText("Reset").onClick(() => { 115 | settings.set(DEFAULT_SETTINGS); 116 | }), 117 | ); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/utils/previewContent.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, test } from "node:test"; 2 | import assert from "assert"; 3 | import { extractPreviewContent } from "./previewContent"; 4 | 5 | describe("extractPreviewContent", async () => { 6 | await describe("table handling", async () => { 7 | await test("includes at least 10 lines of table regardless of char limit", () => { 8 | const content = `# Header 9 | 10 | Some intro text. 11 | 12 | | Column 1 | Column 2 | Column 3 | 13 | |----------|----------|----------| 14 | | Row 1 | Data 1 | Value 1 | 15 | | Row 2 | Data 2 | Value 2 | 16 | | Row 3 | Data 3 | Value 3 | 17 | | Row 4 | Data 4 | Value 4 | 18 | | Row 5 | Data 5 | Value 5 | 19 | | Row 6 | Data 6 | Value 6 | 20 | | Row 7 | Data 7 | Value 7 | 21 | | Row 8 | Data 8 | Value 8 | 22 | | Row 9 | Data 9 | Value 9 | 23 | | Row 10 | Data 10 | Value 10 | 24 | | Row 11 | Data 11 | Value 11 | 25 | | Row 12 | Data 12 | Value 12 | 26 | 27 | More text after table.`; 28 | 29 | // Use a char limit that cuts off inside the table (after ~5 rows) 30 | const result = extractPreviewContent(content, 200); 31 | 32 | // Count table lines in result (lines with |) 33 | const tableLines = result.split("\n").filter((line) => line.includes("|")); 34 | 35 | // Should have at least 10 table lines (header + separator + 8+ data rows) 36 | assert.ok( 37 | tableLines.length >= 10, 38 | `Expected at least 10 table lines, got ${tableLines.length}`, 39 | ); 40 | }); 41 | 42 | await test("preserves full table when less than 10 lines", () => { 43 | const content = `# Header 44 | 45 | | Column 1 | Column 2 | 46 | |----------|----------| 47 | | Row 1 | Data 1 | 48 | | Row 2 | Data 2 | 49 | | Row 3 | Data 3 | 50 | 51 | More text after.`; 52 | 53 | const result = extractPreviewContent(content, 150); 54 | 55 | // Should include all table lines 56 | const tableLines = result.split("\n").filter((line) => line.includes("|")); 57 | assert.equal(tableLines.length, 5); // header + separator + 3 rows 58 | }); 59 | 60 | await test("handles table at start of content", () => { 61 | const content = `| Column 1 | Column 2 | 62 | |----------|----------| 63 | | Row 1 | Data 1 | 64 | | Row 2 | Data 2 | 65 | | Row 3 | Data 3 | 66 | | Row 4 | Data 4 | 67 | | Row 5 | Data 5 | 68 | | Row 6 | Data 6 | 69 | | Row 7 | Data 7 | 70 | | Row 8 | Data 8 | 71 | | Row 9 | Data 9 | 72 | | Row 10 | Data 10 | 73 | | Row 11 | Data 11 | 74 | 75 | Text after table.`; 76 | 77 | const result = extractPreviewContent(content, 100); 78 | const tableLines = result.split("\n").filter((line) => line.includes("|")); 79 | 80 | assert.ok( 81 | tableLines.length >= 10, 82 | `Expected at least 10 table lines, got ${tableLines.length}`, 83 | ); 84 | }); 85 | 86 | await test("does not extend beyond table end", () => { 87 | const content = `# Header 88 | 89 | | Column 1 | Column 2 | 90 | |----------|----------| 91 | | Row 1 | Data 1 | 92 | | Row 2 | Data 2 | 93 | 94 | This should not be included in table extension.`; 95 | 96 | const result = extractPreviewContent(content, 100); 97 | 98 | // Should not include the text after the table when extending 99 | assert.ok(!result.includes("This should not be included")); 100 | }); 101 | 102 | await test("handles content without tables normally", () => { 103 | const content = `# Header 104 | 105 | This is some regular content without any tables. 106 | It should be truncated normally. 107 | 108 | More paragraphs here. 109 | And more text.`; 110 | 111 | const result = extractPreviewContent(content, 50); 112 | 113 | // Should truncate normally without table logic interfering 114 | assert.ok(result.length <= 100); // Should be reasonably short 115 | assert.ok(!result.includes("More paragraphs")); // Should be truncated 116 | }); 117 | 118 | await test("handles empty content", () => { 119 | const result = extractPreviewContent("", 100); 120 | assert.equal(result, ""); 121 | }); 122 | 123 | await test("skips YAML frontmatter", () => { 124 | const content = `--- 125 | title: Test 126 | tags: [test] 127 | --- 128 | 129 | | Column 1 | Column 2 | 130 | |----------|----------| 131 | | Row 1 | Data 1 |`; 132 | 133 | const result = extractPreviewContent(content, 100); 134 | 135 | // Should not include frontmatter 136 | assert.ok(!result.includes("title: Test")); 137 | assert.ok(!result.includes("tags: [test]")); 138 | 139 | // Should include table 140 | assert.ok(result.includes("Column 1")); 141 | }); 142 | 143 | await test("handles tables with different formatting", () => { 144 | const content = `# Header 145 | 146 | | Left | Center | Right | 147 | |:-----|:------:|------:| 148 | | L1 | C1 | R1 | 149 | | L2 | C2 | R2 | 150 | | L3 | C3 | R3 | 151 | | L4 | C4 | R4 | 152 | | L5 | C5 | R5 | 153 | | L6 | C6 | R6 | 154 | | L7 | C7 | R7 | 155 | | L8 | C8 | R8 | 156 | | L9 | C9 | R9 | 157 | | L10 | C10 | R10 | 158 | | L11 | C11 | R11 |`; 159 | 160 | const result = extractPreviewContent(content, 150); 161 | const tableLines = result.split("\n").filter((line) => line.includes("|")); 162 | 163 | assert.ok( 164 | tableLines.length >= 10, 165 | `Expected at least 10 table lines, got ${tableLines.length}`, 166 | ); 167 | }); 168 | }); 169 | }); -------------------------------------------------------------------------------- /src/utils/previewContent.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Extracts preview content from markdown, optimized for card display. 3 | * Truncates content at a safe boundary while preserving valid markdown syntax. 4 | */ 5 | 6 | /** 7 | * Extracts a preview of the markdown content for efficient card rendering. 8 | * 9 | * @param content - Full markdown content from the file 10 | * @param charLimit - Maximum number of characters to extract (default: 700) 11 | * @returns Truncated content ready for markdown rendering 12 | */ 13 | export function extractPreviewContent( 14 | content: string, 15 | charLimit: number = 1200, 16 | ): string { 17 | if (!content || content.length === 0) { 18 | return ""; 19 | } 20 | 21 | // Skip YAML frontmatter if present 22 | let startIndex = 0; 23 | if (content.startsWith("---")) { 24 | const frontmatterEnd = content.indexOf("\n---", 3); 25 | if (frontmatterEnd !== -1) { 26 | // Skip past the closing --- and newline 27 | startIndex = frontmatterEnd + 4; 28 | } 29 | } 30 | 31 | // If content after frontmatter is empty or very short, return it as-is 32 | const contentAfterFrontmatter = content.slice(startIndex); 33 | if (contentAfterFrontmatter.length <= charLimit) { 34 | return contentAfterFrontmatter.trim(); 35 | } 36 | 37 | // Extract up to charLimit characters 38 | let truncated = contentAfterFrontmatter.slice(0, charLimit); 39 | 40 | // Find a safe truncation point 41 | truncated = findSafeTruncationPoint(truncated); 42 | 43 | // If we're inside a table, ensure at least 10 lines of the table are included 44 | truncated = ensureMinTableLines(truncated, contentAfterFrontmatter); 45 | 46 | // Check if we're inside a code block and close it if needed 47 | truncated = closeUnclosedCodeBlocks(truncated); 48 | 49 | // Add ellipsis if we actually truncated content 50 | if (startIndex + truncated.length < content.length) { 51 | truncated = truncated.trimEnd() + " ..."; 52 | } 53 | 54 | return truncated.trim(); 55 | } 56 | 57 | /** 58 | * Finds a safe place to truncate content (word or sentence boundary). 59 | * Prioritizes: sentence end > paragraph end > word boundary > char limit 60 | */ 61 | function findSafeTruncationPoint(text: string): string { 62 | // Try to find the last sentence ending within the last 100 chars 63 | const sentencePattern = /[.!?]\s/g; 64 | let lastSentenceEnd = -1; 65 | let match; 66 | 67 | while ((match = sentencePattern.exec(text)) !== null) { 68 | lastSentenceEnd = match.index + 1; // Include the punctuation 69 | } 70 | 71 | // If we found a sentence ending in the last 100 chars, use it 72 | if (lastSentenceEnd > text.length - 100 && lastSentenceEnd > 0) { 73 | return text.slice(0, lastSentenceEnd); 74 | } 75 | 76 | // Try to find the last double newline (paragraph boundary) 77 | const lastParagraph = text.lastIndexOf("\n\n"); 78 | if (lastParagraph > text.length - 100 && lastParagraph > 0) { 79 | return text.slice(0, lastParagraph); 80 | } 81 | 82 | // Fall back to last word boundary (space or newline) 83 | const lastSpace = Math.max(text.lastIndexOf(" "), text.lastIndexOf("\n")); 84 | 85 | if (lastSpace > text.length - 50 && lastSpace > 0) { 86 | return text.slice(0, lastSpace); 87 | } 88 | 89 | // If no good boundary found, just use the full text 90 | return text; 91 | } 92 | 93 | /** 94 | * Ensures that if we're truncating inside a table, at least 10 lines of the table are included. 95 | * @param truncated - The currently truncated content 96 | * @param fullContent - The full content to potentially extend from 97 | * @returns Extended content if inside a table with fewer than 10 lines, otherwise original truncated content 98 | */ 99 | function ensureMinTableLines(truncated: string, fullContent: string): string { 100 | const MIN_TABLE_LINES = 10; 101 | 102 | // Find the last table in the truncated content 103 | const truncatedLines = truncated.split("\n"); 104 | let lastTableEndIndex = -1; 105 | let tableStartIndex = -1; 106 | 107 | // Scan backwards to find if we're inside a table 108 | for (let i = truncatedLines.length - 1; i >= 0; i--) { 109 | const line = truncatedLines[i].trim(); 110 | // Table rows contain pipes (|) 111 | if (line.includes("|")) { 112 | if (lastTableEndIndex === -1) { 113 | lastTableEndIndex = i; 114 | } 115 | tableStartIndex = i; 116 | } else if (lastTableEndIndex !== -1 && line.length > 0) { 117 | // We've found a non-empty, non-table line after finding table content 118 | // This means the table has ended 119 | break; 120 | } 121 | } 122 | 123 | // If we're not in a table, return as-is 124 | if (tableStartIndex === -1 || lastTableEndIndex === -1) { 125 | return truncated; 126 | } 127 | 128 | // Count table lines we currently have 129 | const currentTableLines = lastTableEndIndex - tableStartIndex + 1; 130 | 131 | // If we already have at least MIN_TABLE_LINES, return as-is 132 | if (currentTableLines >= MIN_TABLE_LINES) { 133 | return truncated; 134 | } 135 | 136 | // We need to extend to include more table lines 137 | // Strategy: Find the table start in full content, extract MIN_TABLE_LINES from there, 138 | // and replace the partial table in truncated content 139 | 140 | const fullContentLines = fullContent.split("\n"); 141 | 142 | // Find where the table starts in the full content by matching the first table line 143 | const firstTableLine = truncatedLines[tableStartIndex]; 144 | let fullTableStartIndex = -1; 145 | 146 | for (let i = 0; i < fullContentLines.length; i++) { 147 | if (fullContentLines[i] === firstTableLine) { 148 | fullTableStartIndex = i; 149 | break; 150 | } 151 | } 152 | 153 | // If we can't find the table in full content, return as-is 154 | if (fullTableStartIndex === -1) { 155 | return truncated; 156 | } 157 | 158 | // Collect MIN_TABLE_LINES from the full content 159 | const tableLines: string[] = []; 160 | for (let i = fullTableStartIndex; i < fullContentLines.length; i++) { 161 | const line = fullContentLines[i]; 162 | 163 | // Stop if we hit a non-table line 164 | if (!line.trim().includes("|") && line.trim().length > 0) { 165 | break; 166 | } 167 | 168 | if (line.trim().includes("|")) { 169 | tableLines.push(line); 170 | if (tableLines.length >= MIN_TABLE_LINES) { 171 | break; 172 | } 173 | } 174 | } 175 | 176 | // Build the result: content before table + complete table lines 177 | const contentBeforeTable = truncatedLines.slice(0, tableStartIndex); 178 | return contentBeforeTable.join("\n") + "\n" + tableLines.join("\n"); 179 | } 180 | 181 | /** 182 | * Checks for unclosed code blocks and closes them properly. 183 | * Handles both triple-backtick code blocks and inline code. 184 | */ 185 | function closeUnclosedCodeBlocks(text: string): string { 186 | // Count triple-backtick code blocks 187 | const tripleBacktickCount = (text.match(/```/g) || []).length; 188 | 189 | // If odd number of triple backticks, we're inside a code block 190 | if (tripleBacktickCount % 2 === 1) { 191 | // Close the code block 192 | return text + "\n```"; 193 | } 194 | 195 | return text; 196 | } 197 | -------------------------------------------------------------------------------- /src/components/store.ts: -------------------------------------------------------------------------------- 1 | import { 2 | type App, 3 | type CachedMetadata, 4 | getAllTags, 5 | ItemView, 6 | MetadataCache, 7 | TFile, 8 | } from "obsidian"; 9 | import { derived, get, writable } from "svelte/store"; 10 | import type { CardsViewSettings } from "../settings"; 11 | import generateFilter from "../search/search"; 12 | 13 | export enum Sort { 14 | Created = "ctime", 15 | Modified = "mtime", 16 | } 17 | 18 | /** 19 | * Stores for obsidian data (updated mainly from main.ts) 20 | */ 21 | 22 | export const app = writable(); 23 | export const view = writable(); 24 | export const appCache = writable(); 25 | export const files = writable([]); 26 | 27 | /** 28 | * Stores for user input (updated mainly from settings.ts, view.ts, Root.svelte) 29 | */ 30 | 31 | export const settings = writable(); 32 | export const sort = writable(Sort.Modified); 33 | const pinnedFiles = derived(settings, ($settings) => $settings?.pinnedFiles); 34 | const sortedFiles = derived( 35 | [sort, files, pinnedFiles], 36 | ([$sort, $files, $pinnedFiles]) => 37 | [...$files].sort( 38 | (a: TFile, b: TFile) => 39 | ($pinnedFiles.includes(b.path) ? 1 : 0) - 40 | ($pinnedFiles.includes(a.path) ? 1 : 0) || 41 | b.stat[$sort] - a.stat[$sort], 42 | ), 43 | [] as TFile[], 44 | ); 45 | export const searchQuery = writable(""); 46 | export const searchCaseSensitive = writable(false); 47 | 48 | /** 49 | * Search logic 50 | */ 51 | 52 | const baseQuery = derived(settings, ($settings) => $settings?.baseQuery); 53 | const searchFilter = derived( 54 | [baseQuery, searchQuery], 55 | ([$baseQuery, $searchQuery]) => { 56 | const query = $baseQuery ? $baseQuery + " " + $searchQuery : $searchQuery; 57 | 58 | if (query === "") { 59 | return null; 60 | } 61 | 62 | return generateFilter(query); 63 | }, 64 | ); 65 | const searchResultCache = writable>(new Map()); 66 | searchFilter.subscribe(() => searchResultCache.set(new Map())); 67 | const cacheKey = (file: TFile) => file.path + file.stat.mtime; 68 | /** 69 | * This is not derived from searchResultCache because we want incremental update 70 | * and not full invalidation when cache is invalidated 71 | */ 72 | const searchResultsExcluded = writable>(new Set()); 73 | export const searchResultLoadingState = writable(1); 74 | 75 | async function updateSearchResults() { 76 | const $sortedFiles = get(sortedFiles); 77 | const $searchQuery = get(searchQuery); 78 | const $searchFilter = get(searchFilter); 79 | const $appCache = get(appCache); 80 | const $app = get(app); 81 | const $searchCaseSensitive = get(searchCaseSensitive); 82 | if ($searchFilter === null) { 83 | searchResultsExcluded.set(new Set()); 84 | searchResultLoadingState.set(1); 85 | return; 86 | } 87 | 88 | let batch: Map = new Map(); 89 | let lastBatch = { date: new Date(), index: 0 }; 90 | for (let i = 0; i < $sortedFiles.length; i++) { 91 | const file = $sortedFiles[i]; 92 | const cachedResult = get(searchResultCache).get(cacheKey($sortedFiles[i])); 93 | if (cachedResult !== undefined) { 94 | batch.set(file, cachedResult); 95 | } else { 96 | const content = await file.vault.cachedRead(file); 97 | const tags = ( 98 | getAllTags($appCache.getFileCache(file) as CachedMetadata) || [] 99 | ).map((t) => t.replace(/^#/, "")); 100 | let frontmatter; 101 | await $app.fileManager.processFrontMatter(file, (fm) => { 102 | frontmatter = fm; 103 | }); 104 | 105 | const match = await $searchFilter({ 106 | file, 107 | content, 108 | tags, 109 | frontmatter, 110 | caseSensitive: $searchCaseSensitive, 111 | }); 112 | 113 | if ($searchQuery !== get(searchQuery)) return; 114 | batch.set(file, match); 115 | searchResultCache.update((cache) => cache.set(cacheKey(file), match)); 116 | } 117 | 118 | if ($searchQuery !== get(searchQuery)) return; 119 | 120 | if (i % 10 === 0) { 121 | searchResultLoadingState.set(i / $sortedFiles.length); 122 | } 123 | 124 | if ( 125 | lastBatch.date.getTime() + 200 < new Date().getTime() || 126 | i === $sortedFiles.length - 1 127 | ) { 128 | searchResultLoadingState.set((i + 1) / $sortedFiles.length); 129 | searchResultsExcluded.update((set) => { 130 | batch.forEach((match, file) => 131 | match ? set.delete(file) : set.add(file), 132 | ); 133 | return set; 134 | }); 135 | batch = new Map(); 136 | lastBatch = { date: new Date(), index: i + 1 }; 137 | } 138 | } 139 | } 140 | searchFilter.subscribe(() => updateSearchResults()); 141 | files.subscribe(() => updateSearchResults()); 142 | searchCaseSensitive.subscribe(() => updateSearchResults()); 143 | 144 | /** 145 | * Display logic 146 | */ 147 | 148 | export const displayedCount = writable(0); 149 | export const displayedFiles = writable([]); 150 | const lastDisplayed = derived(displayedFiles, ($displayedFiles) => { 151 | const lastFile = $displayedFiles.last(); 152 | return lastFile ? get(sortedFiles).indexOf(lastFile) : 0; 153 | }); 154 | searchResultsExcluded.subscribe((excludedFiles) => { 155 | // When the search results changes, and we have less files to display, we want 156 | // to keep the same file as current end of infinite scroll 157 | // event if it means that we reduce the number of files displayed. 158 | // This is to avoid the infinite scroll to be triggered when the user 159 | // is typing in search 160 | const $sortedFiles = get(sortedFiles); 161 | const $lastDisplayed = get(lastDisplayed); 162 | const beforeCurrentLast = $sortedFiles.slice(0, $lastDisplayed + 1); 163 | const filteredBeforeCurrentLast = beforeCurrentLast.filter( 164 | (f) => !excludedFiles.has(f), 165 | ); 166 | 167 | if (filteredBeforeCurrentLast.length > 50) { 168 | // We only want to keep same last file if the list is shorter, 169 | // if it is longer, we keep same length 170 | displayedFiles.set( 171 | filteredBeforeCurrentLast.slice(0, get(displayedFiles).length), 172 | ); 173 | return; 174 | } 175 | 176 | // If we have not enough files to reach 50, we add some new ones 177 | const filteredAfterCurrentLast = $sortedFiles 178 | .slice( 179 | $lastDisplayed, 180 | Math.floor($sortedFiles.length * get(searchResultLoadingState)) - 181 | $lastDisplayed - 182 | 1, 183 | ) // If search results are updating, exclude files which have not been filtered yet 184 | .filter((f) => !excludedFiles.has(f)); 185 | const toAdd = 50 - filteredBeforeCurrentLast.length; 186 | displayedFiles.set([ 187 | ...filteredBeforeCurrentLast, 188 | ...filteredAfterCurrentLast.slice(0, toAdd), 189 | ]); 190 | }); 191 | // When the user scrolls, we add more files to the display 192 | displayedCount.subscribe((count) => { 193 | displayedFiles.set( 194 | get(sortedFiles) 195 | .filter((f) => !get(searchResultsExcluded).has(f)) 196 | .slice(0, count), 197 | ); 198 | }); 199 | // When sort order changes, we want to reset display with same number of files 200 | sortedFiles.subscribe(($sortedFiles) => { 201 | displayedFiles.set( 202 | $sortedFiles 203 | .filter((f) => !get(searchResultsExcluded).has(f)) 204 | .slice(0, get(displayedFiles).length), 205 | ); 206 | }); 207 | 208 | export default { 209 | files, 210 | sort, 211 | searchQuery, 212 | searchCaseSensitive, 213 | displayedCount, 214 | displayedFiles, 215 | app, 216 | view, 217 | settings, 218 | appCache, 219 | }; 220 | -------------------------------------------------------------------------------- /src/components/Card.svelte: -------------------------------------------------------------------------------- 1 | 110 | 111 |
120 | {#if displayFilename}

{file.basename}

{/if} 121 |
122 |
123 | 130 | {#if file.parent != null && file.parent.path !== "/"} 131 |
132 | {file.parent.path} 133 |
134 | {/if} 135 | 141 |
142 |
143 | 144 | 277 | -------------------------------------------------------------------------------- /src/components/Root.svelte: -------------------------------------------------------------------------------- 1 | 126 | 127 |
128 | 134 | 189 |
190 |
191 | {#each $settings.savedSearch || [] as savedSearch} 192 | 196 | {/each} 197 |
198 |
199 |
200 |
205 | {#each $displayedFiles as file (file.path + file.stat.mtime)} 206 | 207 | {/each} 208 |
209 | 210 | 325 | -------------------------------------------------------------------------------- /src/search/search.ts: -------------------------------------------------------------------------------- 1 | import { parser } from "./grammar.js"; 2 | import { type Tree, TreeCursor } from "lezer-tree"; 3 | import assert from "assert"; 4 | import type { TFile } from "obsidian"; 5 | 6 | type FilterFn = (params: { 7 | file?: TFile; 8 | content?: string; 9 | tags?: string[]; // Without the # prefix 10 | frontmatter?: object; 11 | caseSensitive?: boolean; 12 | }) => Promise; 13 | 14 | type PropertyFilterFn = (params: { 15 | key: K; 16 | frontmatter?: Record; 17 | caseSensitive?: boolean; 18 | }) => Promise; 19 | 20 | function getAndFilter(input: string, cursor: TreeCursor): FilterFn { 21 | const filters: FilterFn[] = []; 22 | if (!cursor.firstChild()) { 23 | return async () => true; 24 | } 25 | filters.push(getExpressionFilter(input, cursor)); 26 | while (cursor.nextSibling()) { 27 | filters.push(getExpressionFilter(input, cursor)); 28 | } 29 | 30 | cursor.parent(); 31 | return async (params) => 32 | (await Promise.all(filters.map((filter) => filter(params)))).every(Boolean); 33 | } 34 | 35 | function getOrFilter(input: string, cursor: TreeCursor): FilterFn { 36 | const filters: FilterFn[] = []; 37 | if (!cursor.firstChild()) { 38 | return async () => true; 39 | } 40 | filters.push(getExpressionFilter(input, cursor)); 41 | while (cursor.nextSibling()) { 42 | filters.push(getExpressionFilter(input, cursor)); 43 | } 44 | 45 | cursor.parent(); 46 | return async (params) => 47 | (await Promise.all(filters.map((filter) => filter(params)))).some(Boolean); 48 | } 49 | 50 | function getPropertyValueFilter( 51 | input: string, 52 | cursor: TreeCursor, 53 | ): PropertyFilterFn { 54 | cursor.firstChild(); 55 | if (cursor.node.type.name === "PropertyValueOr") { 56 | const filters: PropertyFilterFn[] = []; 57 | cursor.firstChild(); 58 | filters.push(getPropertyValueFilter(input, cursor)); 59 | while (cursor.nextSibling()) { 60 | filters.push(getPropertyValueFilter(input, cursor)); 61 | } 62 | cursor.parent(); 63 | cursor.parent(); 64 | return async (params) => 65 | (await Promise.all(filters.map((filter) => filter(params)))).some( 66 | Boolean, 67 | ); 68 | } 69 | 70 | if (cursor.node.type.name === "PropertyValueExpression") { 71 | const filter = getPropertyValueFilter(input, cursor); 72 | cursor.parent(); 73 | return filter; 74 | } 75 | 76 | // type is text 77 | const termFilter = getTermFilter(input, cursor); 78 | cursor.parent(); 79 | return async ({ 80 | key, 81 | frontmatter, 82 | caseSensitive, 83 | }: { 84 | key: K; 85 | frontmatter?: Record; 86 | caseSensitive?: boolean; 87 | }) => 88 | Boolean( 89 | frontmatter && 90 | (await termFilter({ content: frontmatter[key], caseSensitive })), 91 | ); 92 | } 93 | 94 | function getTermFilter(input: string, cursor: TreeCursor): FilterFn { 95 | if (cursor.node.type.name === "Word" || cursor.node.type.name === "Quote") { 96 | const value = 97 | cursor.node.type.name === "Quote" 98 | ? input.slice(cursor.node.from + 1, cursor.node.to - 1) 99 | : input.slice(cursor.node.from, cursor.node.to); 100 | return async ({ 101 | file, 102 | content, 103 | caseSensitive, 104 | }: { 105 | file?: TFile; 106 | content?: string; 107 | caseSensitive?: boolean; 108 | }) => 109 | Boolean( 110 | content && 111 | (caseSensitive 112 | ? content.includes(value) 113 | : content.toLowerCase().includes(value.toLowerCase())), 114 | ) || 115 | Boolean( 116 | file && 117 | file.name && 118 | (caseSensitive 119 | ? file.name.includes(value) 120 | : file.name.toLowerCase().includes(value.toLowerCase())), 121 | ); 122 | } 123 | 124 | if (cursor.node.type.name === "Regex") { 125 | const value = input.slice(cursor.node.from + 1, cursor.node.to - 1); 126 | const regex = new RegExp(value); 127 | return async ({ file, content }: { file?: TFile; content?: string }) => 128 | Boolean(content && regex.test(content)) || 129 | Boolean(file && file.name && regex.test(file.name)); 130 | } 131 | 132 | if (cursor.node.type.name === "FileOperator") { 133 | if (!cursor.firstChild()) { 134 | return async () => true; 135 | } 136 | const termFilter = getTermFilter(input, cursor); 137 | cursor.parent(); 138 | return async ({ 139 | file, 140 | caseSensitive, 141 | }: { 142 | file?: TFile; 143 | caseSensitive?: boolean; 144 | }) => 145 | Boolean( 146 | file && 147 | file.name && 148 | (await termFilter({ content: file.name, caseSensitive })), 149 | ); 150 | } 151 | 152 | if (cursor.node.type.name === "PathOperator") { 153 | if (!cursor.firstChild()) { 154 | return async () => true; 155 | } 156 | const termFilter = getTermFilter(input, cursor); 157 | cursor.parent(); 158 | return async ({ 159 | file, 160 | caseSensitive, 161 | }: { 162 | file?: TFile; 163 | caseSensitive?: boolean; 164 | }) => 165 | Boolean( 166 | file && 167 | file.path && 168 | (await termFilter({ content: file.path, caseSensitive })), 169 | ); 170 | } 171 | 172 | if (cursor.node.type.name === "ContentOperator") { 173 | if (!cursor.firstChild()) { 174 | return async () => true; 175 | } 176 | const termFilter = getTermFilter(input, cursor); 177 | cursor.parent(); 178 | return async ({ 179 | content, 180 | caseSensitive, 181 | }: { 182 | content?: string; 183 | caseSensitive?: boolean; 184 | }) => Boolean(content && (await termFilter({ content, caseSensitive }))); 185 | } 186 | 187 | if (cursor.node.type.name === "MatchCaseOperator") { 188 | if (!cursor.firstChild()) { 189 | return async () => true; 190 | } 191 | const termFilter = getTermFilter(input, cursor); 192 | cursor.parent(); 193 | return async ({ content }: { content?: string }) => 194 | Boolean(content && (await termFilter({ content, caseSensitive: true }))); 195 | } 196 | 197 | if (cursor.node.type.name === "IgnoreCaseOperator") { 198 | if (!cursor.firstChild()) { 199 | return async () => true; 200 | } 201 | const termFilter = getTermFilter(input.toLowerCase(), cursor); 202 | cursor.parent(); 203 | return async ({ content }: { content?: string }) => 204 | Boolean(content && termFilter({ content: content.toLowerCase() })); 205 | } 206 | 207 | if (cursor.node.type.name === "TagOperator") { 208 | const value = input 209 | .slice(cursor.node.from, cursor.node.to) 210 | .replace(/^tag:/, "") 211 | .replace(/^#/, ""); 212 | return async ({ 213 | tags, 214 | caseSensitive, 215 | }: { 216 | tags?: string[]; 217 | caseSensitive?: boolean; 218 | }) => { 219 | return Boolean( 220 | tags && 221 | (caseSensitive 222 | ? tags.includes(value) 223 | : tags.map((t) => t.toLowerCase()).includes(value.toLowerCase())), 224 | ); 225 | }; 226 | } 227 | 228 | if (cursor.node.type.name === "LineOperator") { 229 | if (!cursor.firstChild()) { 230 | return async () => true; 231 | } 232 | const termFilter = getExpressionFilter(input, cursor); 233 | cursor.parent(); 234 | return async ({ 235 | content, 236 | caseSensitive, 237 | }: { 238 | content?: string; 239 | caseSensitive?: boolean; 240 | }) => 241 | Boolean( 242 | content && 243 | ( 244 | await Promise.all( 245 | content 246 | .split("\n") 247 | .map((line) => termFilter({ content: line, caseSensitive })), 248 | ) 249 | ).some(Boolean), 250 | ); 251 | } 252 | 253 | if (cursor.node.type.name === "PropertyOperator") { 254 | if (!cursor.firstChild()) { 255 | return async () => true; 256 | } 257 | // @ts-ignore 258 | assert(cursor.node.type.name === "PropertyName"); 259 | const propertyName = input.slice(cursor.node.from, cursor.node.to); 260 | 261 | // d'abord filter toutes les propriétés qui matchent 262 | // puis filter par leurs valeurs 263 | 264 | let propertyValueFilter: PropertyFilterFn = async () => 265 | true; 266 | if (cursor.nextSibling()) { 267 | assert(cursor.node.type.name === "PropertyValueExpression"); 268 | propertyValueFilter = getPropertyValueFilter(input, cursor); 269 | } 270 | 271 | cursor.parent(); 272 | return async ({ 273 | frontmatter, 274 | caseSensitive, 275 | }: { 276 | frontmatter?: object; 277 | caseSensitive?: boolean; 278 | }) => { 279 | if (!frontmatter) return false; 280 | 281 | const matchingProperties = Object.keys(frontmatter).filter((k) => 282 | caseSensitive 283 | ? k.includes(propertyName) 284 | : k.toLowerCase().includes(propertyName.toLowerCase()), 285 | ); 286 | 287 | if (matchingProperties.length === 0) return false; 288 | 289 | return ( 290 | await Promise.all( 291 | matchingProperties.map(async (k) => 292 | propertyValueFilter({ 293 | key: k, 294 | frontmatter: frontmatter as Record, 295 | caseSensitive, 296 | }), 297 | ), 298 | ) 299 | ).some(Boolean); 300 | }; 301 | } 302 | 303 | cursor.parent(); 304 | return async () => true; 305 | } 306 | 307 | function getExpressionFilter(input: string, cursor: TreeCursor): FilterFn { 308 | if (cursor.node.type.name === "And") { 309 | return getAndFilter(input, cursor); 310 | } 311 | 312 | if (cursor.node.type.name === "Or") { 313 | return getOrFilter(input, cursor); 314 | } 315 | 316 | if (cursor.node.type.name === "Not") { 317 | cursor.firstChild(); 318 | const filter = getExpressionFilter(input, cursor); 319 | cursor.parent(); 320 | return async (params) => !(await filter(params)); 321 | } 322 | 323 | return getTermFilter(input, cursor); 324 | } 325 | 326 | export default function generateFilter(input: string): FilterFn { 327 | const tree: Tree = parser.parse(input); 328 | const cursor = tree.cursor(); 329 | if (!cursor.firstChild()) { 330 | return async () => true; 331 | } 332 | 333 | return getExpressionFilter(input, cursor); 334 | } 335 | -------------------------------------------------------------------------------- /src/search/search.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, test } from "node:test"; 2 | import assert from "assert"; 3 | import { parser } from "./grammar.js"; 4 | import type { Tree } from "lezer-tree"; 5 | import generateFilter from "./search"; 6 | import type { TFile } from "obsidian"; 7 | 8 | describe("search", async () => { 9 | await describe("parser", async () => { 10 | await test("lorem", () => { 11 | const query = "lorem"; 12 | const tree: Tree = parser.parse(query); 13 | const cursor = tree.cursor(); 14 | assert.equal(cursor.type.name, "Program"); 15 | assert.equal(cursor.firstChild(), true); 16 | assert.equal(cursor.node.type.name, "And"); 17 | assert.equal(cursor.firstChild(), true); 18 | assert.equal(cursor.node.type.name, "Word"); 19 | assert.equal(query.slice(cursor.node.from, cursor.node.to), "lorem"); 20 | }); 21 | 22 | await test("lorem OR ipsum", () => { 23 | const query = "lorem OR ipsum"; 24 | const tree: Tree = parser.parse(query); 25 | const cursor = tree.cursor(); 26 | assert.equal(cursor.type.name, "Program"); 27 | assert.equal(cursor.firstChild(), true); 28 | assert.equal(cursor.node.type.name, "Or"); 29 | assert.equal(cursor.firstChild(), true); 30 | assert.equal(cursor.node.type.name, "And"); 31 | assert.equal(cursor.firstChild(), true); 32 | assert.equal(cursor.node.type.name, "Word"); 33 | assert.equal(query.slice(cursor.node.from, cursor.node.to), "lorem"); 34 | assert.equal(cursor.parent(), true); 35 | assert.equal(cursor.nextSibling(), true); 36 | assert.equal(cursor.node.type.name, "And"); 37 | assert.equal(cursor.firstChild(), true); 38 | assert.equal(cursor.node.type.name, "Word"); 39 | assert.equal(query.slice(cursor.node.from, cursor.node.to), "ipsum"); 40 | }); 41 | }); 42 | 43 | await describe("generateFilter", async () => { 44 | await test("lorem", async () => { 45 | const query = "lorem"; 46 | const filter = generateFilter(query); 47 | assert.equal(await filter({ content: "lorem ipsum" }), true); 48 | assert.equal(await filter({ content: "Lorem" }), true); 49 | assert.equal(await filter({ content: "ipsum" }), false); 50 | }); 51 | 52 | await test("-lorem", async () => { 53 | const query = "-lorem"; 54 | const filter = generateFilter(query); 55 | assert.equal(await filter({ content: "lorem ipsum" }), false); 56 | assert.equal(await filter({ content: "Lorem" }), false); 57 | assert.equal(await filter({ content: "ipsum" }), true); 58 | }); 59 | 60 | await test("lorem ipsum OR dolor sic", async () => { 61 | const query = "lorem ipsum OR dolor sic"; 62 | const filter = generateFilter(query); 63 | assert.equal(await filter({ content: "lorem ipsum" }), true); 64 | assert.equal(await filter({ content: "dolor sic" }), true); 65 | }); 66 | 67 | await test("lorem in filename", async () => { 68 | const query = "lorem"; 69 | const filter = generateFilter(query); 70 | assert.equal( 71 | await filter({ file: { name: "lorem ipsum" } as TFile, content: "" }), 72 | true, 73 | ); 74 | }); 75 | 76 | await test("lorem ipsum", async () => { 77 | const query = "lorem ipsum"; 78 | const filter = generateFilter(query); 79 | assert.equal(await filter({ content: "ipsum lorem" }), true); 80 | assert.equal(await filter({ content: "lorem" }), false); 81 | }); 82 | 83 | await test("lorem OR ipsum", async () => { 84 | const query = "lorem OR ipsum"; 85 | const filter = generateFilter(query); 86 | assert.equal(await filter({ content: "lorem ipsum" }), true); 87 | assert.equal(await filter({ content: "ipsum" }), true); 88 | assert.equal(await filter({ content: "lorem" }), true); 89 | assert.equal(await filter({ content: "dolor" }), false); 90 | }); 91 | 92 | await test("-(lorem OR ipsum)", async () => { 93 | const query = "-(lorem OR ipsum)"; 94 | const filter = generateFilter(query); 95 | assert.equal(await filter({ content: "lorem ipsum" }), false); 96 | assert.equal(await filter({ content: "ipsum" }), false); 97 | assert.equal(await filter({ content: "lorem" }), false); 98 | assert.equal(await filter({ content: "dolor" }), true); 99 | }); 100 | 101 | await test("lorem -(ipsum OR dolor)", async () => { 102 | const query = "lorem -(ipsum OR dolor)"; 103 | const filter = generateFilter(query); 104 | assert.equal(await filter({ content: "lorem" }), true); 105 | assert.equal(await filter({ content: "lorem ipsum" }), false); 106 | assert.equal(await filter({ content: "lorem dolor" }), false); 107 | assert.equal(await filter({ content: "sic amet" }), false); 108 | }); 109 | 110 | await test("lorem ipsum OR dolor", async () => { 111 | const query = "lorem ipsum OR dolor"; 112 | const filter = generateFilter(query); 113 | assert.equal(await filter({ content: "ipsum lorem" }), true); 114 | assert.equal(await filter({ content: "dolor" }), true); 115 | assert.equal(await filter({ content: "lorem" }), false); 116 | }); 117 | 118 | await test('"lorem ipsum"', async () => { 119 | const query = '"lorem ipsum"'; 120 | const filter = generateFilter(query); 121 | assert.equal(await filter({ content: "lorem ipsum" }), true); 122 | assert.equal(await filter({ content: "ipsum lorem" }), false); 123 | }); 124 | 125 | await test('"lorem ipsum" OR dolor', async () => { 126 | const query = '"lorem ipsum" OR dolor'; 127 | const filter = generateFilter(query); 128 | assert.equal(await filter({ content: "lorem ipsum" }), true); 129 | assert.equal(await filter({ content: "dolor" }), true); 130 | assert.equal(await filter({ content: "ipsum lorem" }), false); 131 | }); 132 | 133 | await test("/(lorem|ipsum)/", async () => { 134 | const query = "/(lorem|ipsum)/"; 135 | const filter = generateFilter(query); 136 | assert.equal(await filter({ content: "lorem ipsum" }), true); 137 | assert.equal(await filter({ content: "ipsum lorem" }), true); 138 | assert.equal(await filter({ content: "dolor" }), false); 139 | }); 140 | 141 | await test("file:.jpg", async () => { 142 | const query = "file:.jpg"; 143 | const filter = generateFilter(query); 144 | assert.equal( 145 | await filter({ file: { name: "lorem.jpg" } as TFile, content: "" }), 146 | true, 147 | ); 148 | assert.equal( 149 | await filter({ file: { name: "lorem.png" } as TFile, content: "" }), 150 | false, 151 | ); 152 | }); 153 | 154 | await test("file:.jpg OR lorem", async () => { 155 | const query = "file:.jpg OR lorem"; 156 | const filter = generateFilter(query); 157 | assert.equal( 158 | await filter({ file: { name: "dolor.jpg" } as TFile, content: "" }), 159 | true, 160 | ); 161 | assert.equal( 162 | await filter({ file: { name: "dolor.png" } as TFile, content: "" }), 163 | false, 164 | ); 165 | assert.equal( 166 | await filter({ 167 | file: { name: "dolor.png" } as TFile, 168 | content: "lorem", 169 | }), 170 | true, 171 | ); 172 | }); 173 | 174 | await test("path:lorem/ipsum", async () => { 175 | const query = "path:lorem/ipsum"; 176 | const filter = generateFilter(query); 177 | assert.equal( 178 | await filter({ file: { path: "lorem/ipsum/" } as TFile, content: "" }), 179 | true, 180 | ); 181 | assert.equal( 182 | await filter({ file: { path: "lorem/dolor" } as TFile, content: "" }), 183 | false, 184 | ); 185 | }); 186 | 187 | await test('path:"lorem ipsum"', async () => { 188 | const query = 'path:"lorem ipsum"'; 189 | const filter = generateFilter(query); 190 | assert.equal( 191 | await filter({ file: { path: "lorem ipsum/" } as TFile, content: "" }), 192 | true, 193 | ); 194 | assert.equal( 195 | await filter({ file: { path: "/lorem/dolor" } as TFile, content: "" }), 196 | false, 197 | ); 198 | }); 199 | 200 | await test('content:"lorem ipsum"', async () => { 201 | const query = 'content:"lorem ipsum"'; 202 | const filter = generateFilter(query); 203 | assert.equal(await filter({ content: "lorem ipsum" }), true); 204 | assert.equal(await filter({ content: "ipsum lorem" }), false); 205 | }); 206 | 207 | await test("match-case:Lorem", async () => { 208 | const query = "match-case:Lorem"; 209 | const filter = generateFilter(query); 210 | assert.equal(await filter({ content: "Lorem ipsum" }), true); 211 | assert.equal(await filter({ content: "lorem ipsum" }), false); 212 | }); 213 | 214 | await test("ignore-case:Lorem", async () => { 215 | const query = "ignore-case:Lorem"; 216 | const filter = generateFilter(query); 217 | assert.equal(await filter({ content: "Lorem ipsum" }), true); 218 | assert.equal(await filter({ content: "lorem ipsum" }), true); 219 | }); 220 | 221 | await test("line:(lorem ipsum)", async () => { 222 | const query = "line:(lorem ipsum)"; 223 | const filter = generateFilter(query); 224 | assert.equal(await filter({ content: "lorem ipsum" }), true); 225 | assert.equal(await filter({ content: "lorem\nipsum" }), false); 226 | }); 227 | 228 | await test("tag:lorem", async () => { 229 | const query = "tag:lorem"; 230 | const filter = generateFilter(query); 231 | assert.equal(await filter({ tags: ["lorem"] }), true); 232 | assert.equal(await filter({ tags: ["ipsum"] }), false); 233 | }); 234 | 235 | await test("tag:#lorem", async () => { 236 | const query = "tag:#lorem"; 237 | const filter = generateFilter(query); 238 | assert.equal(await filter({ tags: ["lorem"] }), true); 239 | assert.equal(await filter({ tags: ["ipsum"] }), false); 240 | }); 241 | 242 | await test("[lorem]", async () => { 243 | const query = "[lorem]"; 244 | const filter = generateFilter(query); 245 | assert.equal(await filter({ frontmatter: { lorem: true } }), true); 246 | assert.equal(await filter({ frontmatter: { ipsum: true } }), false); 247 | }); 248 | 249 | await test("[lorem:ipsum]", async () => { 250 | const query = "[lorem:ipsum]"; 251 | const filter = generateFilter(query); 252 | assert.equal(await filter({ frontmatter: { lorem: "ipsum" } }), true); 253 | assert.equal(await filter({ frontmatter: { lorem: "lorem" } }), false); 254 | assert.equal(await filter({ frontmatter: { lorem: "dolor" } }), false); 255 | assert.equal(await filter({ frontmatter: { ipsum: "ipsum" } }), false); 256 | }); 257 | 258 | await test("[lorem:ipsum OR dolor]", async () => { 259 | const query = "[lorem:ipsum OR dolor]"; 260 | const filter = generateFilter(query); 261 | assert.equal(await filter({ frontmatter: { lorem: "ipsum" } }), true); 262 | assert.equal(await filter({ frontmatter: { lorem: "dolor" } }), true); 263 | assert.equal(await filter({ frontmatter: { lorem: "lorem" } }), false); 264 | }); 265 | 266 | await test("lorem OR (ipsum -tag:#Tag1)", async () => { 267 | const query = "lorem OR (ipsum -tag:#Tag1)"; 268 | const filter = generateFilter(query); 269 | assert.equal(await filter({ content: "lorem" }), true); 270 | assert.equal(await filter({ content: "ipsum" }), true); 271 | assert.equal(await filter({ tags: ["Tag1"], content: "ipsum" }), false); 272 | }); 273 | }); 274 | }); 275 | --------------------------------------------------------------------------------