├── .eslintignore
├── .eslintrc.js
├── .github
└── workflows
│ ├── main.yml
│ └── release.yml
├── .gitignore
├── .prettierrc.js
├── DemoVault
├── .obsidian
│ ├── app.json
│ ├── appearance.json
│ ├── community-plugins.json
│ ├── core-plugins.json
│ ├── daily-notes.json
│ └── hotkeys.json
├── Daily Notes
│ ├── 2022-02-11.md
│ └── Not a daily note.md
├── Projects
│ ├── Home improvements.md
│ └── Obsidian GTD plugin.md
└── TODO.md
├── LICENSE
├── README.md
├── assets
├── inbox.png
├── scheduled.png
├── someday.png
└── today.png
├── constants.ts
├── jest.config.js
├── main.ts
├── manifest.json
├── model
├── TodoIndex.ts
├── TodoItem.ts
├── TodoParser.test.ts
├── TodoParser.ts
└── TodoPluginSettings.ts
├── package.json
├── rollup.config.js
├── styles.css
├── sync.sh
├── tsconfig.json
├── ui
├── SettingsTab.ts
├── TodoItemView.ts
└── icons.ts
├── util
├── DailyNoteParser.ts
├── DateFormatter.test.ts
├── DateFormatter.ts
├── DateParser.test.ts
├── DateParser.ts
└── __mocks__
│ └── DailyNoteParser.ts
├── versions.json
└── yarn.lock
/.eslintignore:
--------------------------------------------------------------------------------
1 | main.js
2 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | parser: '@typescript-eslint/parser',
3 | parserOptions: {
4 | ecmaVersion: 2020,
5 | sourceType: 'module',
6 | },
7 | extends: [
8 | 'plugin:@typescript-eslint/recommended',
9 | 'prettier/@typescript-eslint',
10 | 'plugin:prettier/recommended', // Should be last
11 | ],
12 | rules: {},
13 | };
14 |
--------------------------------------------------------------------------------
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on:
3 | push:
4 | branches: [ main ]
5 | pull_request:
6 | branches: [ main ]
7 |
8 | jobs:
9 | test:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: actions/checkout@v2
13 | - name: Install dependencies
14 | run: yarn install
15 | - name: Run tests
16 | run: yarn test
17 | - name: Lint
18 | run: yarn lint-on-ci
19 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Cut release
2 | on:
3 | workflow_dispatch:
4 | inputs:
5 | version_number:
6 | description: 'Version Number'
7 | required: true
8 |
9 | jobs:
10 | release:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v2
14 | - name: Install dependencies
15 | run: yarn install
16 | - name: Run the tests
17 | run: yarn test
18 | - name: Update manifest
19 | run: |
20 | git config --global user.email "lars.lockefeer@gmail.com"
21 | git config --global user.name "Lars Lockefeer"
22 | tmp=$(mktemp) && jq --arg VERSION_NUMBER "$VERSION_NUMBER" '.version = $VERSION_NUMBER' manifest.json > "$tmp" && mv "$tmp" manifest.json
23 | git add manifest.json && git commit -m "Bump version to $VERSION_NUMBER"
24 | git push
25 | env:
26 | VERSION_NUMBER: ${{ github.event.inputs.version_number }}
27 | - name: Build the release artifacts
28 | run: yarn build
29 | - name: Create the release
30 | run: gh release create $VERSION_NUMBER main.js styles.css manifest.json --title $VERSION_NUMBER --draft
31 | env:
32 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
33 | VERSION_NUMBER: ${{ github.event.inputs.version_number }}
34 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # OS X
2 | .DS_Store
3 |
4 | # Intellij
5 | *.iml
6 | .idea
7 |
8 | # npm / yarn
9 | node_modules
10 | package-lock.json
11 | yarn-error.log
12 |
13 | # build
14 | main.js
15 | *.js.map
16 |
17 | # Demo vault
18 | DemoVault/.obsidian/plugins/obsidian-plugin-todo
19 | DemoVault/.obsidian/workspace
20 |
--------------------------------------------------------------------------------
/.prettierrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | semi: true,
3 | trailingComma: "all",
4 | singleQuote: true,
5 | printWidth: 120,
6 | tabWidth: 2,
7 | };
8 |
--------------------------------------------------------------------------------
/DemoVault/.obsidian/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "legacyEditor": false,
3 | "livePreview": true
4 | }
--------------------------------------------------------------------------------
/DemoVault/.obsidian/appearance.json:
--------------------------------------------------------------------------------
1 | {
2 | "theme": "moonstone",
3 | "baseFontSize": 16
4 | }
--------------------------------------------------------------------------------
/DemoVault/.obsidian/community-plugins.json:
--------------------------------------------------------------------------------
1 | [
2 | "obsidian-plugin-todo"
3 | ]
--------------------------------------------------------------------------------
/DemoVault/.obsidian/core-plugins.json:
--------------------------------------------------------------------------------
1 | [
2 | "file-explorer",
3 | "global-search",
4 | "switcher",
5 | "graph",
6 | "backlink",
7 | "page-preview",
8 | "daily-notes",
9 | "note-composer",
10 | "command-palette",
11 | "markdown-importer",
12 | "word-count",
13 | "open-with-default-app",
14 | "file-recovery"
15 | ]
--------------------------------------------------------------------------------
/DemoVault/.obsidian/daily-notes.json:
--------------------------------------------------------------------------------
1 | {
2 | "folder": "Daily Notes"
3 | }
--------------------------------------------------------------------------------
/DemoVault/.obsidian/hotkeys.json:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/DemoVault/Daily Notes/2022-02-11.md:
--------------------------------------------------------------------------------
1 | - [ ] Do something on the date of this daily note
2 | - [ ] Do something in 2099 #2099-01-01
3 | - [ ] Do something, some day #someday
--------------------------------------------------------------------------------
/DemoVault/Daily Notes/Not a daily note.md:
--------------------------------------------------------------------------------
1 | - [ ] This is a task in a file in the daily note folder without a date
2 |
--------------------------------------------------------------------------------
/DemoVault/Projects/Home improvements.md:
--------------------------------------------------------------------------------
1 | # Home improvements
2 | - [ ] Fix broken window #2021-02-20
--------------------------------------------------------------------------------
/DemoVault/Projects/Obsidian GTD plugin.md:
--------------------------------------------------------------------------------
1 | # Obsidian GTD plugin
2 | ## Roadmap
3 | - [ ] Add setting to prevent files at specific paths from being indexed
4 | - [ ] Allow filtering in the list views via a freeform query
5 | - [ ] Group tasks in the list views by file
6 |
7 | ## Version 0.2.3
8 | - [x] Integrate with Daily Notes plugin, assume tasks in a daily note without a due date are scheduled for that day
9 |
10 | ## Version 0.2.2
11 | - [x] Add Demo Vault, showing off all features
12 |
13 | ## Version 0.2.1
14 | - [x] Render due dates in list view
15 |
16 | ## Version 0.2.0
17 | - [x] Fix timezone issues
18 | - [x] Add settings tab
19 | - [x] Add setting to change the date format
20 | - [x] Add setting to change the format of the date tag
21 | - [x] Add setting to open files in new leaf
22 |
23 | ## Pre-release M2 | Support full GTD flow
24 | - [x] Add "Inbox"-view
25 | - [x] Define syntax for scheduling
26 | - [x] Add "Today"-view / "Scheduled"-view
27 | - [x] Add "Someday/Maybe"-view
28 |
29 | ## Pre-release M1 | List all TODOs in a single list
30 | - [x] Get item view to render as side panel
31 | - [x] Write parser to parse all TODOs from all files
32 | - [x] Create index with all results from above
33 | - [x] Subscribe index to file edit/delete events, reindex file
34 | - [x] List all outstanding todos in item view
35 | - [x] Create simple UI
36 | - [x] Allow for completion of TODOs, remove them from list
37 | - [x] It seems events are not always firing, causing delays in the view on the right.
38 | - [x] Add linting pre-commit hook
39 | - See https://www.robertcooper.me/using-eslint-and-prettier-in-a-typescript-project
40 | - [x] Add link to file in which TODO is found
41 | - [x] Render links correctly in list view
42 | - [x] Write README
--------------------------------------------------------------------------------
/DemoVault/TODO.md:
--------------------------------------------------------------------------------
1 | # Things to do
2 |
3 | - [ ] Buy milk #2021-02-16
4 | - [ ] Do sometime far in the future #2023-10-08
5 | - [ ] Do today #2022-02-09
6 | - [ ] Read "Meditations" by Marcus Aurelius #someday
7 | - [ ] Check out "The Queen's Gambit" on [[Netflix]]
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Obsidian TODO Plugin
2 |
3 | Text-based GTD in Obsidian.
4 |
5 | [](https://www.buymeacoffee.com/larslockefeer)
6 |
7 | ### Features
8 | - Aggregates all outstanding TODOs in your vault and lists them in a single view
9 | - Split out TODOs by type ("Today", "Scheduled", "Inbox" and "Someday/Maybe")
10 | - Schedule a TODO for a specific date by adding a tag
11 | - Mark a TODO as Someday/Maybe by adding a tag #someday
12 | - Complete TODOs from the list view
13 | - Quickly jump to the file in which a TODO is found from the list view
14 | - Integrates with the Daily Notes plugin: TODOs without a due date will inherit the date of the daily note as due date
15 |
16 | ### Settings
17 | **Date tag format**: Customise the format you use to add due dates to your tasks. Defaults to `#%date%`.
18 |
19 | **Date format**: Customise the date format. Uses luxon under the hood. See [their documentation](https://moment.github.io/luxon/#/formatting?id=table-of-tokens) for supported tokens. Defaults to `yyyy-MM-dd`.
20 |
21 | **Open files in a new leaf**: When enabled, files opened from within the plugin will open in a new leaf rather than replacing the currently opened file.
22 |
23 | ### Screenshots
24 | 
25 | 
26 | 
27 | 
28 |
29 | ### Roadmap
30 | - [ ] Scroll to correct line in file when jumping from list view
31 | - [ ] (Re)schedule TODOs from the list view
32 | - [ ] Persist cache, on reopening only reindex files changed since Obsidian was closed
33 | - [ ] Filter items list view by tags / freeform search
34 | - [ ] Improve UI and themeability
35 |
--------------------------------------------------------------------------------
/assets/inbox.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/larslockefeer/obsidian-plugin-todo/2d3efd7ea4d1e3102e9ec1cde787e7749c498e1c/assets/inbox.png
--------------------------------------------------------------------------------
/assets/scheduled.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/larslockefeer/obsidian-plugin-todo/2d3efd7ea4d1e3102e9ec1cde787e7749c498e1c/assets/scheduled.png
--------------------------------------------------------------------------------
/assets/someday.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/larslockefeer/obsidian-plugin-todo/2d3efd7ea4d1e3102e9ec1cde787e7749c498e1c/assets/someday.png
--------------------------------------------------------------------------------
/assets/today.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/larslockefeer/obsidian-plugin-todo/2d3efd7ea4d1e3102e9ec1cde787e7749c498e1c/assets/today.png
--------------------------------------------------------------------------------
/constants.ts:
--------------------------------------------------------------------------------
1 | export const VIEW_TYPE_TODO = 'online.larslockefeer.obsidian-plugin-todo';
2 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | preset: 'ts-jest',
3 | testEnvironment: 'node',
4 | };
5 |
--------------------------------------------------------------------------------
/main.ts:
--------------------------------------------------------------------------------
1 | import { App, Plugin, PluginManifest, TFile, WorkspaceLeaf } from 'obsidian';
2 | import { VIEW_TYPE_TODO } from './constants';
3 | import { TodoItemView, TodoItemViewProps } from './ui/TodoItemView';
4 | import { TodoItem, TodoItemStatus } from './model/TodoItem';
5 | import { TodoIndex } from './model/TodoIndex';
6 | import { TodoPluginSettings, DEFAULT_SETTINGS } from './model/TodoPluginSettings';
7 | import { SettingsTab } from './ui/SettingsTab';
8 | import { DateFormatter } from 'util/DateFormatter';
9 | import { DateTime } from 'luxon';
10 |
11 | export default class TodoPlugin extends Plugin {
12 | private dateFormatter: DateFormatter;
13 | private todoIndex: TodoIndex;
14 | private view: TodoItemView;
15 | private settings: TodoPluginSettings;
16 |
17 | constructor(app: App, manifest: PluginManifest) {
18 | super(app, manifest);
19 | this.todoIndex = new TodoIndex(this.app.vault, DEFAULT_SETTINGS, this.tick.bind(this));
20 | }
21 |
22 | async onload(): Promise {
23 | this.settings = Object.assign(DEFAULT_SETTINGS, (await this.loadData()) ?? {});
24 | this.dateFormatter = new DateFormatter(this.settings.dateFormat);
25 | this.addSettingTab(new SettingsTab(this.app, this));
26 |
27 | this.registerView(VIEW_TYPE_TODO, (leaf: WorkspaceLeaf) => {
28 | const todos: TodoItem[] = [];
29 | const props = {
30 | todos: todos,
31 | formatDate: (date: DateTime) => {
32 | return this.dateFormatter.formatDate(date);
33 | },
34 | openFile: (filePath: string) => {
35 | const file = this.app.vault.getAbstractFileByPath(filePath) as TFile;
36 | if (this.settings.openFilesInNewLeaf && this.app.workspace.getActiveFile()) {
37 | this.app.workspace.splitActiveLeaf().openFile(file);
38 | } else {
39 | this.app.workspace.getUnpinnedLeaf().openFile(file);
40 | }
41 | },
42 | toggleTodo: (todo: TodoItem, newStatus: TodoItemStatus) => {
43 | this.todoIndex.setStatus(todo, newStatus);
44 | },
45 | };
46 | this.view = new TodoItemView(leaf, props);
47 | return this.view;
48 | });
49 |
50 | this.app.workspace.onLayoutReady(() => {
51 | this.initLeaf();
52 | this.triggerIndex();
53 | });
54 | }
55 |
56 | onunload(): void {
57 | this.app.workspace.getLeavesOfType(VIEW_TYPE_TODO).forEach((leaf) => leaf.detach());
58 | }
59 |
60 | initLeaf(): void {
61 | if (this.app.workspace.getLeavesOfType(VIEW_TYPE_TODO).length) {
62 | return;
63 | }
64 | this.app.workspace.getRightLeaf(false).setViewState({
65 | type: VIEW_TYPE_TODO,
66 | });
67 | }
68 |
69 | getSettings(): TodoPluginSettings {
70 | return this.settings;
71 | }
72 |
73 | async updateSettings(settings: TodoPluginSettings): Promise {
74 | this.settings = settings;
75 | this.dateFormatter = new DateFormatter(this.settings.dateFormat);
76 | await this.saveData(this.settings);
77 | this.todoIndex.setSettings(settings);
78 | }
79 |
80 | private async triggerIndex(): Promise {
81 | await this.todoIndex.initialize();
82 | }
83 |
84 | tick(todos: TodoItem[]): void {
85 | this.view.setProps((currentProps: TodoItemViewProps) => {
86 | return {
87 | ...currentProps,
88 | todos: todos,
89 | };
90 | });
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "obsidian-plugin-todo",
3 | "name": "Obsidian TODO | Text-based GTD",
4 | "version": "0.2.7",
5 | "minAppVersion": "0.11.0",
6 | "description": "Text-based GTD in Obsidian. Collects all outstanding TODOs from your vault and presents them in lists Today, Scheduled, Inbox and Someday/Maybe.",
7 | "author": "Lars Lockefeer",
8 | "authorUrl": "https://lars.lockefeer.online",
9 | "isDesktopOnly": false
10 | }
11 |
--------------------------------------------------------------------------------
/model/TodoIndex.ts:
--------------------------------------------------------------------------------
1 | import { TAbstractFile, TFile, Vault } from 'obsidian';
2 | import { TodoItem, TodoItemStatus } from '../model/TodoItem';
3 | import { TodoPluginSettings } from '../model/TodoPluginSettings';
4 | import { DateParser } from '../util/DateParser';
5 | import { TodoParser } from '../model/TodoParser';
6 |
7 | export class TodoIndex {
8 | private vault: Vault;
9 | private todos: Map;
10 | private listeners: ((todos: TodoItem[]) => void)[];
11 | private settings: TodoPluginSettings;
12 |
13 | constructor(vault: Vault, settings: TodoPluginSettings, listener: (todos: TodoItem[]) => void) {
14 | this.vault = vault;
15 | this.todos = new Map();
16 | this.listeners = [listener];
17 | this.settings = settings;
18 | }
19 |
20 | async initialize(): Promise {
21 | // TODO: persist index & last sync timestamp; only parse files that changed since then.
22 | const todoMap = new Map();
23 | let numberOfTodos = 0;
24 | const timeStart = new Date().getTime();
25 |
26 | const markdownFiles = this.vault.getMarkdownFiles();
27 | for (const file of markdownFiles) {
28 | const todos = await this.parseTodosInFile(file);
29 | numberOfTodos += todos.length;
30 | if (todos.length > 0) {
31 | todoMap.set(file.path, todos);
32 | }
33 | }
34 |
35 | const totalTimeMs = new Date().getTime() - timeStart;
36 | console.log(
37 | `[obsidian-plugin-todo] Parsed ${numberOfTodos} TODOs from ${markdownFiles.length} markdown files in (${
38 | totalTimeMs / 1000.0
39 | }s)`,
40 | );
41 | this.todos = todoMap;
42 | this.registerEventHandlers();
43 | this.invokeListeners();
44 | }
45 |
46 | setStatus(todo: TodoItem, newStatus: TodoItemStatus): void {
47 | const file = this.vault.getAbstractFileByPath(todo.sourceFilePath) as TFile;
48 | const fileContents = this.vault.read(file);
49 | fileContents.then((c: string) => {
50 | const newTodo = `[${newStatus === TodoItemStatus.Done ? 'x' : ' '}] ${todo.description}`;
51 | const newContents = c.substring(0, todo.startIndex) + newTodo + c.substring(todo.startIndex + todo.length);
52 | this.vault.modify(file, newContents);
53 | });
54 | }
55 |
56 | setSettings(settings: TodoPluginSettings): void {
57 | const oldSettings = this.settings;
58 | this.settings = settings;
59 |
60 | const reIndexRequired =
61 | oldSettings.dateFormat !== settings.dateFormat || oldSettings.dateTagFormat !== settings.dateTagFormat;
62 | if (reIndexRequired) {
63 | this.initialize();
64 | }
65 | }
66 |
67 | private indexAbstractFile(file: TAbstractFile) {
68 | if (!(file instanceof TFile)) {
69 | return;
70 | }
71 | this.indexFile(file as TFile);
72 | }
73 |
74 | private indexFile(file: TFile) {
75 | this.parseTodosInFile(file).then((todos) => {
76 | this.todos.set(file.path, todos);
77 | this.invokeListeners();
78 | });
79 | }
80 |
81 | private clearIndex(path: string, silent = false) {
82 | this.todos.delete(path);
83 | if (!silent) {
84 | this.invokeListeners();
85 | }
86 | }
87 |
88 | private async parseTodosInFile(file: TFile): Promise {
89 | // TODO: Does it make sense to index completed TODOs at all?
90 | const dateParser = new DateParser(this.settings.dateTagFormat, this.settings.dateFormat);
91 | const todoParser = new TodoParser(dateParser);
92 | const fileContents = await this.vault.cachedRead(file);
93 | return todoParser
94 | .parseTasks(file.path, fileContents)
95 | .then((todos) => todos.filter((todo) => todo.status === TodoItemStatus.Todo));
96 | }
97 |
98 | private registerEventHandlers() {
99 | this.vault.on('create', (file: TAbstractFile) => {
100 | this.indexAbstractFile(file);
101 | });
102 | this.vault.on('modify', (file: TAbstractFile) => {
103 | this.indexAbstractFile(file);
104 | });
105 | this.vault.on('delete', (file: TAbstractFile) => {
106 | this.clearIndex(file.path);
107 | });
108 | // We could simply change the references to the old path, but parsing again does the trick as well
109 | this.vault.on('rename', (file: TAbstractFile, oldPath: string) => {
110 | this.clearIndex(oldPath);
111 | this.indexAbstractFile(file);
112 | });
113 | }
114 |
115 | private invokeListeners() {
116 | const todos = ([] as TodoItem[]).concat(...Array.from(this.todos.values()));
117 | this.listeners.forEach((listener) => listener(todos));
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/model/TodoItem.ts:
--------------------------------------------------------------------------------
1 | import { DateTime } from 'luxon';
2 |
3 | export enum TodoItemStatus {
4 | Todo,
5 | Done,
6 | }
7 |
8 | // eslint-disable-next-line @typescript-eslint/no-namespace
9 | export namespace TodoItemStatus {
10 | export function toggleStatus(status: TodoItemStatus): TodoItemStatus {
11 | switch (status) {
12 | case TodoItemStatus.Todo:
13 | return TodoItemStatus.Done;
14 | case TodoItemStatus.Done:
15 | return TodoItemStatus.Todo;
16 | }
17 | }
18 | }
19 |
20 | export class TodoItem {
21 | public sourceFilePath: string;
22 | public startIndex: number;
23 | public length: number;
24 |
25 | public status: TodoItemStatus;
26 | public description: string;
27 | public actionDate?: DateTime;
28 | public isSomedayMaybeNote: boolean;
29 |
30 | constructor(
31 | status: TodoItemStatus,
32 | description: string,
33 | isSomedayMaybeNote: boolean,
34 | sourceFilePath: string,
35 | startIndex: number,
36 | length: number,
37 | actionDate?: DateTime,
38 | ) {
39 | this.status = status;
40 | this.description = description;
41 | this.actionDate = actionDate;
42 | this.isSomedayMaybeNote = isSomedayMaybeNote;
43 | this.sourceFilePath = sourceFilePath;
44 | this.startIndex = startIndex;
45 | this.length = length;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/model/TodoParser.test.ts:
--------------------------------------------------------------------------------
1 | import { TodoItemStatus } from './TodoItem';
2 | import { TodoParser } from './TodoParser';
3 | import { DateParser } from '../util/DateParser';
4 | import { DateTime } from 'luxon';
5 |
6 | jest.mock('../util/DailyNoteParser');
7 |
8 | const dateParser = new DateParser(`#${DateParser.DateToken}`, 'yyyy-MM-dd');
9 | const todoParser = new TodoParser(dateParser);
10 |
11 | test('parsing an outstanding todo', async () => {
12 | const contents = `- [ ] This is something that needs doing`;
13 | const todos = await todoParser.parseTasks('/', contents);
14 | const todo = todos[0];
15 | expect(todo.startIndex).toEqual(2);
16 | expect(todo.length).toEqual(38);
17 | expect(todo.sourceFilePath).toEqual('/');
18 | expect(todo.status).toEqual(TodoItemStatus.Todo);
19 | expect(todo.description).toEqual('This is something that needs doing');
20 | expect(todo.actionDate).toBeUndefined();
21 | expect(todo.isSomedayMaybeNote).toEqual(false);
22 | });
23 |
24 | test('parsing a completed todo', async () => {
25 | const contents = `- [x] This is something that has been completed`;
26 | const todos = await todoParser.parseTasks('/', contents);
27 | const todo = todos[0];
28 | expect(todo.startIndex).toEqual(2);
29 | expect(todo.length).toEqual(45);
30 | expect(todo.sourceFilePath).toEqual('/');
31 | expect(todo.status).toEqual(TodoItemStatus.Done);
32 | expect(todo.description).toEqual('This is something that has been completed');
33 | expect(todo.actionDate).toBeUndefined();
34 | expect(todo.isSomedayMaybeNote).toEqual(false);
35 | });
36 |
37 | test('parsing an outstanding todo with a specific action date', async () => {
38 | const contents = `- [ ] This is something that needs doing #2021-02-16`;
39 | const todos = await todoParser.parseTasks('/', contents);
40 | const todo = todos[0];
41 | expect(todo.startIndex).toEqual(2);
42 | expect(todo.length).toEqual(50);
43 | expect(todo.sourceFilePath).toEqual('/');
44 | expect(todo.status).toEqual(TodoItemStatus.Todo);
45 | expect(todo.description).toEqual('This is something that needs doing');
46 | expect(todo.actionDate.day).toEqual(16);
47 | expect(todo.actionDate.month).toEqual(2);
48 | expect(todo.actionDate.year).toEqual(2021);
49 | expect(todo.isSomedayMaybeNote).toEqual(false);
50 | });
51 |
52 | test('parsing an outstanding someday/maybe todo', async () => {
53 | const contents = `- [ ] This is something that needs doing #someday`;
54 | const todos = await todoParser.parseTasks('/', contents);
55 | const todo = todos[0];
56 | expect(todo.startIndex).toEqual(2);
57 | expect(todo.length).toEqual(47);
58 | expect(todo.sourceFilePath).toEqual('/');
59 | expect(todo.status).toEqual(TodoItemStatus.Todo);
60 | expect(todo.description).toEqual('This is something that needs doing #someday');
61 | expect(todo.actionDate).toBeUndefined();
62 | expect(todo.isSomedayMaybeNote).toEqual(true);
63 | });
64 |
65 | test('parsing a todo in a daily notes file', async () => {
66 | const contents = `- [ ] This is something that needs doing today`;
67 | const todos = await todoParser.parseTasks('/Daily Notes/today.md', contents);
68 | const todo = todos[0];
69 | expect(todo.actionDate.day).toEqual(DateTime.now().day);
70 | expect(todo.actionDate.month).toEqual(DateTime.now().month);
71 | expect(todo.actionDate.year).toEqual(DateTime.now().year);
72 | });
73 |
74 | test('parsing a todo in a daily notes file with a due date', async () => {
75 | const contents = `- [ ] This is something that needs doing #2022-04-01`;
76 | const todos = await todoParser.parseTasks('/Daily Notes/today.md', contents);
77 | const todo = todos[0];
78 | expect(todo.actionDate.day).toEqual(1);
79 | expect(todo.actionDate.month).toEqual(4);
80 | expect(todo.actionDate.year).toEqual(2022);
81 | });
82 |
83 | test('parsing a todo in a daily notes file tagged as someday/maybe', async () => {
84 | const contents = `- [ ] This is something that needs doing #someday`;
85 | const todos = await todoParser.parseTasks('/Daily Notes/today.md', contents);
86 | const todo = todos[0];
87 | expect(todo.actionDate).toBeUndefined();
88 | expect(todo.isSomedayMaybeNote).toEqual(true);
89 | });
90 |
91 | test('parsing an outstanding todo with a specific action date and a someday/maybe tag', async () => {
92 | const contents = `- [ ] This is something that needs doing #2021-02-16 #someday`;
93 | const todos = await todoParser.parseTasks('/', contents);
94 | const todo = todos[0];
95 | expect(todo.status).toEqual(TodoItemStatus.Todo);
96 | expect(todo.actionDate).toBeUndefined();
97 | expect(todo.isSomedayMaybeNote).toEqual(true);
98 | });
99 |
--------------------------------------------------------------------------------
/model/TodoParser.ts:
--------------------------------------------------------------------------------
1 | import { DateParser } from '../util/DateParser';
2 | import { TodoItem, TodoItemStatus } from '../model/TodoItem';
3 | import { DateTime } from 'luxon';
4 | import { extractDueDateFromDailyNotesFile } from '../util/DailyNoteParser';
5 |
6 | export class TodoParser {
7 | private dateParser: DateParser;
8 |
9 | constructor(dateParser: DateParser) {
10 | this.dateParser = dateParser;
11 | }
12 |
13 | async parseTasks(filePath: string, fileContents: string): Promise {
14 | const pattern = /(-|\*) \[(\s|x)?\]\s(.*)/g;
15 | return [...fileContents.matchAll(pattern)].map((task) => this.parseTask(filePath, task));
16 | }
17 |
18 | private parseTask(filePath: string, entry: RegExpMatchArray): TodoItem {
19 | const todoItemOffset = 2; // Strip off `-|* `
20 | const status = entry[2] === 'x' ? TodoItemStatus.Done : TodoItemStatus.Todo;
21 | const description = entry[3];
22 |
23 | const actionDate = this.parseDueDate(description, filePath);
24 | const descriptionWithoutDate = this.dateParser.removeDate(description);
25 | const somedayPattern = /#(someday)/g;
26 | const isSomedayMaybeTask = description.match(somedayPattern) != null;
27 |
28 | return new TodoItem(
29 | status,
30 | descriptionWithoutDate,
31 | isSomedayMaybeTask,
32 | filePath,
33 | (entry.index ?? 0) + todoItemOffset,
34 | entry[0].length - todoItemOffset,
35 | !isSomedayMaybeTask ? actionDate : undefined,
36 | );
37 | }
38 |
39 | private parseDueDate(description: string, filePath: string): DateTime | undefined {
40 | const taggedDueDate = this.dateParser.parseDate(description);
41 | if (taggedDueDate) {
42 | return taggedDueDate;
43 | }
44 | return extractDueDateFromDailyNotesFile(filePath);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/model/TodoPluginSettings.ts:
--------------------------------------------------------------------------------
1 | export interface TodoPluginSettings {
2 | dateFormat: string;
3 | dateTagFormat: string;
4 | openFilesInNewLeaf: boolean;
5 | }
6 |
7 | export const DEFAULT_SETTINGS: TodoPluginSettings = {
8 | dateFormat: 'yyyy-MM-dd',
9 | dateTagFormat: '#%date%',
10 | openFilesInNewLeaf: true,
11 | };
12 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "obsidian-plugin-todo",
3 | "version": "0.2.0",
4 | "description": "Text-based GTD in Obsidian. Collects all outstanding TODOs from your vault and presents them in lists Today, Scheduled, Inbox and Someday/Maybe.",
5 | "main": "main.js",
6 | "scripts": {
7 | "build": "rollup --config rollup.config.js",
8 | "dev": "rollup --config rollup.config.js -w",
9 | "lint": "eslint '**/*.{js,ts}' --fix",
10 | "lint-on-ci": "eslint '**/*.{js,ts}'",
11 | "test": "jest"
12 | },
13 | "keywords": [],
14 | "author": "Lars Lockefeer",
15 | "bugs": {
16 | "url": "https://github.com/larslockefeer/obsidian-plugin-todo/issues"
17 | },
18 | "homepage": "https://github.com/larslockefeer/obsidian-plugin-todo#obsidian-todo-plugin",
19 | "license": "GPL-3.0-only",
20 | "devDependencies": {
21 | "@rollup/plugin-commonjs": "^15.1.0",
22 | "@rollup/plugin-node-resolve": "^9.0.0",
23 | "@rollup/plugin-typescript": "^6.0.0",
24 | "@types/jest": "^26.0.20",
25 | "@types/luxon": "^1.26.0",
26 | "@types/node": "^14.14.2",
27 | "@typescript-eslint/eslint-plugin": "^4.15.0",
28 | "@typescript-eslint/parser": "^4.15.0",
29 | "eslint": "^7.19.0",
30 | "eslint-config-prettier": "^7.2.0",
31 | "eslint-plugin-prettier": "^3.3.1",
32 | "husky": "^5.0.9",
33 | "jest": "^26.6.3",
34 | "lint-staged": "^10.5.4",
35 | "prettier": "^2.2.1",
36 | "rollup": "^2.32.1",
37 | "rollup-plugin-polyfill-node": "^0.8.0",
38 | "ts-jest": "^26.5.1",
39 | "tslib": "^2.0.3",
40 | "typescript": "^4.0.3"
41 | },
42 | "husky": {
43 | "hooks": {
44 | "pre-commit": "lint-staged"
45 | }
46 | },
47 | "lint-staged": {
48 | "*.{js,ts,ts}": [
49 | "eslint --fix"
50 | ]
51 | },
52 | "dependencies": {
53 | "luxon": "^1.26.0",
54 | "obsidian": "^0.12.17",
55 | "obsidian-daily-notes-interface": "^0.9.4"
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import typescript from '@rollup/plugin-typescript';
2 | import { nodeResolve } from '@rollup/plugin-node-resolve';
3 | import commonjs from '@rollup/plugin-commonjs';
4 | import nodePolyfills from 'rollup-plugin-polyfill-node';
5 |
6 | export default {
7 | input: 'main.ts',
8 | output: {
9 | dir: '.',
10 | sourcemap: 'inline',
11 | format: 'cjs',
12 | exports: 'default',
13 | },
14 | external: ['obsidian'],
15 | plugins: [typescript(), nodeResolve({ browser: true }), commonjs(), nodePolyfills()],
16 | };
17 |
--------------------------------------------------------------------------------
/styles.css:
--------------------------------------------------------------------------------
1 | div.todo-item-view-container {
2 | }
3 |
4 | div.todo-item-view-toolbar {
5 | display: flex;
6 | justify-content: center;
7 | align-items: center;
8 | border-bottom: 1px solid #cccccc;
9 | border-top: 1px solid #cccccc;
10 | }
11 |
12 | div.todo-item-view-toolbar-item {
13 | padding-left: 15px;
14 | padding-right: 15px;
15 | padding-top: 8px;
16 | padding-bottom: 2px;
17 | cursor: pointer;
18 | }
19 |
20 | div.todo-item-view-items {
21 | display: flex;
22 | flex-direction: column;
23 | justify-content: flex-start;
24 | }
25 |
26 | div.todo-item-view-item {
27 | display: flex;
28 | padding-top: 10px;
29 | padding-bottom: 10px;
30 | }
31 |
32 | div.todo-item-view-item p {
33 | margin: 0;
34 | }
35 |
36 | div.todo-item-view-item span.due-date {
37 | padding: 5px 8px 5px 8px;
38 | font-size: 0.6em;
39 | border-radius: 12px;
40 | background-color: #fbb034;
41 | border-color: #fbb034;
42 | }
43 |
44 | div.todo-item-view-item span.due-date.overdue {
45 | background-color: #ff2400;
46 | border-color: #ff2400;
47 | }
48 |
49 | div.todo-item-view-item span.due-date.future-due {
50 | background-color: #6fdf94;
51 | border-color: #6fdf94;
52 | }
53 |
54 | div.todo-item-view-item-checkbox {
55 | flex-basis: 25px;
56 | flex-shrink: 0;
57 | }
58 |
59 | div.todo-item-view-item-description {
60 | flex-grow: 1;
61 | padding-left: 4px;
62 | }
63 |
64 | div.todo-item-view-item-link {
65 | flex-basis: 25px;
66 | flex-shrink: 0;
67 | cursor: pointer;
68 | padding-left: 8px;
69 | }
70 |
71 | div.todo-item-view-item-link svg, div.todo-item-view-toolbar-item svg {
72 | fill: #cccccc;
73 | }
74 |
75 | div.todo-item-view-toolbar-item.active svg {
76 | fill: #7f6df2;
77 | }
78 |
--------------------------------------------------------------------------------
/sync.sh:
--------------------------------------------------------------------------------
1 | #! /bin/bash
2 |
3 | BASE_PATH="${1:-./DemoVault}"
4 | yarn build
5 | rm -rf "$BASE_PATH/.obsidian/plugins/obsidian-plugin-todo/"
6 | mkdir -p "$BASE_PATH/.obsidian/plugins/obsidian-plugin-todo/"
7 | cp main.js manifest.json styles.css "$BASE_PATH/.obsidian/plugins/obsidian-plugin-todo/"
8 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": ".",
4 | "esModuleInterop": true,
5 | "inlineSourceMap": true,
6 | "inlineSources": true,
7 | "module": "ESNext",
8 | "target": "es6",
9 | "allowJs": true,
10 | "noImplicitAny": true,
11 | "moduleResolution": "node",
12 | "importHelpers": true,
13 | "lib": [
14 | "dom",
15 | "es5",
16 | "scripthost",
17 | "es2020"
18 | ]
19 | },
20 | "include": [
21 | "**/*.ts"
22 | ]
23 | }
24 |
--------------------------------------------------------------------------------
/ui/SettingsTab.ts:
--------------------------------------------------------------------------------
1 | import { App, PluginSettingTab, Setting } from 'obsidian';
2 | import { DateTime } from 'luxon';
3 | import TodoPlugin from 'main';
4 | import { DEFAULT_SETTINGS } from '../model/TodoPluginSettings';
5 |
6 | export class SettingsTab extends PluginSettingTab {
7 | private plugin: TodoPlugin;
8 |
9 | constructor(app: App, plugin: TodoPlugin) {
10 | super(app, plugin);
11 | this.plugin = plugin;
12 | }
13 |
14 | display(): void {
15 | const { containerEl } = this;
16 | const currentSettings = this.plugin.getSettings();
17 |
18 | containerEl.empty();
19 |
20 | containerEl.createEl('h2', { text: 'Obsidian TODO Settings' });
21 |
22 | const tagFormatSetting = new Setting(containerEl);
23 | tagFormatSetting
24 | .setName('Date tag format')
25 | .setDesc(this.dateTagFormatDescription())
26 | .addText((text) =>
27 | text.setPlaceholder(currentSettings.dateTagFormat).onChange(async (dateTagFormat) => {
28 | // TODO: refactor this
29 | if (dateTagFormat.length === 0) {
30 | dateTagFormat = DEFAULT_SETTINGS.dateTagFormat;
31 | }
32 |
33 | if (!this.validateDateTag(dateTagFormat)) {
34 | tagFormatSetting.descEl.empty();
35 | tagFormatSetting.setDesc(this.dateTagFormatDescription('Date tag must include %date% token.'));
36 | return;
37 | }
38 |
39 | tagFormatSetting.descEl.empty();
40 | tagFormatSetting.setDesc(this.dateTagFormatDescription());
41 |
42 | this.plugin.updateSettings({ ...currentSettings, dateTagFormat });
43 | }),
44 | );
45 |
46 | const dateFormatSetting = new Setting(containerEl);
47 | dateFormatSetting
48 | .setName('Date format')
49 | .setDesc(this.dateFormatDescription())
50 | .addText((text) =>
51 | text.setPlaceholder(currentSettings.dateFormat).onChange(async (dateFormat) => {
52 | // TODO: refactor this
53 | if (dateFormat.length === 0) {
54 | dateFormat = DEFAULT_SETTINGS.dateFormat;
55 | }
56 |
57 | if (!this.validateDateFormat(dateFormat)) {
58 | dateFormatSetting.descEl.empty();
59 | dateFormatSetting.setDesc(this.dateTagFormatDescription('Invalid date format.'));
60 | return;
61 | }
62 |
63 | dateFormatSetting.descEl.empty();
64 | dateFormatSetting.setDesc(this.dateTagFormatDescription());
65 |
66 | this.plugin.updateSettings({ ...currentSettings, dateFormat });
67 | }),
68 | );
69 |
70 | new Setting(containerEl)
71 | .setName('Open files in a new leaf')
72 | .setDesc(
73 | 'If enabled, when opening the file containing a TODO that file will open in a new leaf. If disabled, it will replace the file that you currently have open.',
74 | )
75 | .addToggle((toggle) => {
76 | toggle.setValue(currentSettings.openFilesInNewLeaf);
77 | toggle.onChange(async (openFilesInNewLeaf) => {
78 | this.plugin.updateSettings({ ...currentSettings, openFilesInNewLeaf });
79 | });
80 | });
81 | }
82 |
83 | private dateTagFormatDescription(error?: string): DocumentFragment {
84 | const el = document.createDocumentFragment();
85 | el.appendText('The format in which the due date is included in the task description.');
86 | el.appendChild(document.createElement('br'));
87 | el.appendText('Must include the %date% token.');
88 | el.appendChild(document.createElement('br'));
89 | el.appendText("To configure the format of the date, see 'Date format'.");
90 | if (error != null) {
91 | el.appendChild(document.createElement('br'));
92 | el.appendText(`Error: ${error}`);
93 | }
94 | return el;
95 | }
96 |
97 | private dateFormatDescription(error?: string): DocumentFragment {
98 | const el = document.createDocumentFragment();
99 | el.appendText('Dates in this format will be recognised as due dates.');
100 | el.appendChild(document.createElement('br'));
101 |
102 | const a = document.createElement('a');
103 | a.href = 'https://moment.github.io/luxon/#/formatting?id=table-of-tokens';
104 | a.text = 'See the documentation for supported tokens.';
105 | a.target = '_blank';
106 | el.appendChild(a);
107 |
108 | if (error != null) {
109 | el.appendChild(document.createElement('br'));
110 | el.appendText(`Error: ${error}`);
111 | }
112 | return el;
113 | }
114 |
115 | private validateDateTag(dateTag: string): boolean {
116 | if (dateTag.length === 0) {
117 | return true;
118 | }
119 | return dateTag.includes('%date%');
120 | }
121 |
122 | private validateDateFormat(dateFormat: string): boolean {
123 | if (dateFormat.length === 0) {
124 | return true;
125 | }
126 | const expected = DateTime.fromISO('2020-05-25');
127 | const formatted = expected.toFormat(dateFormat);
128 | const parsed = DateTime.fromFormat(formatted, dateFormat);
129 | return parsed.hasSame(expected, 'day') && parsed.hasSame(expected, 'month') && parsed.hasSame(expected, 'year');
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/ui/TodoItemView.ts:
--------------------------------------------------------------------------------
1 | import { DateTime } from 'luxon';
2 | import { ItemView, MarkdownRenderer, WorkspaceLeaf } from 'obsidian';
3 | import { VIEW_TYPE_TODO } from '../constants';
4 | import { TodoItem, TodoItemStatus } from '../model/TodoItem';
5 | import { RenderIcon, Icon } from '../ui/icons';
6 |
7 | enum TodoItemViewPane {
8 | Today,
9 | Scheduled,
10 | Inbox,
11 | Someday,
12 | }
13 | export interface TodoItemViewProps {
14 | todos: TodoItem[];
15 | formatDate: (date: DateTime) => string;
16 | openFile: (filePath: string) => void;
17 | toggleTodo: (todo: TodoItem, newStatus: TodoItemStatus) => void;
18 | }
19 |
20 | interface TodoItemViewState {
21 | activePane: TodoItemViewPane;
22 | }
23 |
24 | export class TodoItemView extends ItemView {
25 | private props: TodoItemViewProps;
26 | private state: TodoItemViewState;
27 |
28 | constructor(leaf: WorkspaceLeaf, props: TodoItemViewProps) {
29 | super(leaf);
30 | this.props = props;
31 | this.state = {
32 | activePane: TodoItemViewPane.Today,
33 | };
34 | }
35 |
36 | getViewType(): string {
37 | return VIEW_TYPE_TODO;
38 | }
39 |
40 | getDisplayText(): string {
41 | return 'Todo';
42 | }
43 |
44 | getIcon(): string {
45 | return 'checkmark';
46 | }
47 |
48 | onClose(): Promise {
49 | return Promise.resolve();
50 | }
51 |
52 | public setProps(setter: (currentProps: TodoItemViewProps) => TodoItemViewProps): void {
53 | this.props = setter(this.props);
54 | this.render();
55 | }
56 |
57 | private setViewState(newState: TodoItemViewState) {
58 | this.state = newState;
59 | this.render();
60 | }
61 |
62 | private render(): void {
63 | const container = this.containerEl.children[1];
64 | container.empty();
65 | container.createDiv('todo-item-view-container', (el) => {
66 | el.createDiv('todo-item-view-toolbar', (el) => {
67 | this.renderToolBar(el);
68 | });
69 | el.createDiv('todo-item-view-items', (el) => {
70 | this.renderItems(el);
71 | });
72 | });
73 | }
74 |
75 | private renderToolBar(container: HTMLDivElement) {
76 | const activeClass = (pane: TodoItemViewPane) => {
77 | return pane === this.state.activePane ? ' active' : '';
78 | };
79 |
80 | const setActivePane = (pane: TodoItemViewPane) => {
81 | const newState = {
82 | ...this.state,
83 | activePane: pane,
84 | };
85 | this.setViewState(newState);
86 | };
87 |
88 | container.createDiv(`todo-item-view-toolbar-item${activeClass(TodoItemViewPane.Today)}`, (el) => {
89 | el.appendChild(RenderIcon(Icon.Today, 'Today'));
90 | el.onClickEvent(() => setActivePane(TodoItemViewPane.Today));
91 | });
92 | container.createDiv(`todo-item-view-toolbar-item${activeClass(TodoItemViewPane.Scheduled)}`, (el) => {
93 | el.appendChild(RenderIcon(Icon.Scheduled, 'Scheduled'));
94 | el.onClickEvent(() => setActivePane(TodoItemViewPane.Scheduled));
95 | });
96 | container.createDiv(`todo-item-view-toolbar-item${activeClass(TodoItemViewPane.Inbox)}`, (el) => {
97 | el.appendChild(RenderIcon(Icon.Inbox, 'Inbox'));
98 | el.onClickEvent(() => setActivePane(TodoItemViewPane.Inbox));
99 | });
100 | container.createDiv(`todo-item-view-toolbar-item${activeClass(TodoItemViewPane.Someday)}`, (el) => {
101 | el.appendChild(RenderIcon(Icon.Someday, 'Someday / Maybe'));
102 | el.onClickEvent(() => setActivePane(TodoItemViewPane.Someday));
103 | });
104 | }
105 |
106 | private renderItems(container: HTMLDivElement) {
107 | this.props.todos
108 | .filter(this.filterForState, this)
109 | .sort(this.sortByActionDate)
110 | .forEach((todo) => {
111 | container.createDiv('todo-item-view-item', (el) => {
112 | el.createDiv('todo-item-view-item-checkbox', (el) => {
113 | el.createEl('input', { type: 'checkbox' }, (el) => {
114 | el.checked = todo.status === TodoItemStatus.Done;
115 | el.onClickEvent(() => {
116 | this.toggleTodo(todo);
117 | });
118 | });
119 | });
120 | el.createDiv('todo-item-view-item-description', (el) => {
121 | MarkdownRenderer.renderMarkdown(todo.description, el, todo.sourceFilePath, this);
122 | if (todo.actionDate) {
123 | el.createSpan('due-date', (el) => {
124 | if (todo.actionDate.startOf('day') < DateTime.now().startOf('day')) {
125 | el.classList.add('overdue');
126 | } else if (todo.actionDate.startOf('day') > DateTime.now().startOf('day')) {
127 | el.classList.add('future-due');
128 | }
129 | el.setText(this.props.formatDate(todo.actionDate));
130 | });
131 | }
132 | });
133 | el.createDiv('todo-item-view-item-link', (el) => {
134 | el.appendChild(RenderIcon(Icon.Reveal, 'Open file'));
135 | el.onClickEvent(() => {
136 | this.openFile(todo);
137 | });
138 | });
139 | });
140 | });
141 | }
142 |
143 | private filterForState(value: TodoItem, _index: number, _array: TodoItem[]): boolean {
144 | const isToday = (date: DateTime) => {
145 | const today = DateTime.now();
146 | return date.day == today.day && date.month == today.month && date.year == today.year;
147 | };
148 |
149 | const isBeforeToday = (date: DateTime) => {
150 | const today = DateTime.now();
151 | return date < today;
152 | };
153 |
154 | const isTodayNote = value.actionDate && (isToday(value.actionDate) || isBeforeToday(value.actionDate));
155 | const isScheduledNote = !value.isSomedayMaybeNote && value.actionDate && !isTodayNote;
156 |
157 | switch (this.state.activePane) {
158 | case TodoItemViewPane.Inbox:
159 | return !value.isSomedayMaybeNote && !isTodayNote && !isScheduledNote;
160 | case TodoItemViewPane.Scheduled:
161 | return isScheduledNote;
162 | case TodoItemViewPane.Someday:
163 | return value.isSomedayMaybeNote;
164 | case TodoItemViewPane.Today:
165 | return isTodayNote;
166 | }
167 | }
168 |
169 | private sortByActionDate(a: TodoItem, b: TodoItem): number {
170 | if (!a.actionDate && !b.actionDate) {
171 | if (a.isSomedayMaybeNote && !b.isSomedayMaybeNote) {
172 | return -1;
173 | }
174 | if (!a.isSomedayMaybeNote && b.isSomedayMaybeNote) {
175 | return 1;
176 | }
177 | return 0;
178 | }
179 | return a.actionDate < b.actionDate ? -1 : a.actionDate > b.actionDate ? 1 : 0;
180 | }
181 |
182 | private toggleTodo(todo: TodoItem): void {
183 | this.props.toggleTodo(todo, TodoItemStatus.toggleStatus(todo.status));
184 | }
185 |
186 | private openFile(todo: TodoItem): void {
187 | this.props.openFile(todo.sourceFilePath);
188 | }
189 | }
190 |
--------------------------------------------------------------------------------
/ui/icons.ts:
--------------------------------------------------------------------------------
1 | export enum Icon {
2 | Inbox,
3 | Reveal,
4 | Scheduled,
5 | Someday,
6 | Today,
7 | }
8 |
9 | export const RenderIcon = (icon: Icon, title = '', description = ''): HTMLElement => {
10 | const svg = svgForIcon(icon)(title, description);
11 | return parser.parseFromString(svg, 'text/xml').documentElement;
12 | };
13 |
14 | const parser = new DOMParser();
15 |
16 | const svgForIcon = (icon: Icon): ((arg0: string, arg1: string) => string) => {
17 | switch (icon) {
18 | case Icon.Inbox:
19 | return inboxIcon;
20 | case Icon.Reveal:
21 | return revealIcon;
22 | case Icon.Scheduled:
23 | return scheduledIcon;
24 | case Icon.Someday:
25 | return somedayIcon;
26 | case Icon.Today:
27 | return todayIcon;
28 | }
29 | };
30 |
31 | const inboxIcon = (title: string, description: string): string => `
32 |
38 | `;
39 |
40 | const revealIcon = (title: string, description: string): string => `
41 |
48 | `;
49 |
50 | const scheduledIcon = (title: string, description: string): string => `
51 |
57 | `;
58 |
59 | const somedayIcon = (title: string, description: string): string => `
60 |
68 | `;
69 |
70 | const todayIcon = (title: string, description: string): string => `
71 |
77 | `;
78 |
--------------------------------------------------------------------------------
/util/DailyNoteParser.ts:
--------------------------------------------------------------------------------
1 | import { getDailyNoteSettings, getDateFromPath } from 'obsidian-daily-notes-interface';
2 | import { DateTime } from 'luxon';
3 | import path from 'path';
4 |
5 | export const extractDueDateFromDailyNotesFile = (filePath: string): DateTime | undefined => {
6 | const dailyNotesSettings = getDailyNoteSettings();
7 | if (dailyNotesSettings.folder && path.dirname(filePath) == dailyNotesSettings.folder) {
8 | const dueDate = getDateFromPath(filePath, 'day');
9 | if (dueDate != null) {
10 | return DateTime.fromISO(dueDate.toISOString());
11 | }
12 | }
13 | return undefined;
14 | };
15 |
--------------------------------------------------------------------------------
/util/DateFormatter.test.ts:
--------------------------------------------------------------------------------
1 | import { DateTime } from 'luxon';
2 | import { DateFormatter } from './DateFormatter';
3 |
4 | test('Formatting dates works', () => {
5 | const firstDateFormatter = new DateFormatter('yyyy-MM-dd');
6 | const date = DateTime.fromISO('2021-12-29');
7 | expect(firstDateFormatter.formatDate(date)).toBe('2021-12-29');
8 |
9 | const secondDateFormatter = new DateFormatter('yyyy LLL dd');
10 | expect(secondDateFormatter.formatDate(date)).toBe('2021 Dec 29');
11 | });
12 |
--------------------------------------------------------------------------------
/util/DateFormatter.ts:
--------------------------------------------------------------------------------
1 | import { DateTime } from 'luxon';
2 |
3 | export class DateFormatter {
4 | private dateFormat: string;
5 |
6 | constructor(dateFormat: string) {
7 | this.dateFormat = dateFormat;
8 | }
9 |
10 | public formatDate(date: DateTime): string {
11 | return date.toFormat(this.dateFormat);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/util/DateParser.test.ts:
--------------------------------------------------------------------------------
1 | import { DateParser } from './DateParser';
2 |
3 | test('initializing the date parser without the date token', () => {
4 | expect(() => new DateParser('something else', 'yyyy-MM-dd')).toThrow('Tag format must include the %date% token.');
5 | });
6 |
7 | test('initializing the date parser with an invalid date format', () => {
8 | const dateParser = new DateParser('%date%', 'bogus');
9 | const contents = `This is a string that contains a date: 2020-02-16.`;
10 | const date = dateParser.parseDate(contents);
11 | expect(date).toBeUndefined();
12 | });
13 |
14 | test('extracting a date in a valid, simple format', () => {
15 | const dateParser = new DateParser(DateParser.DateToken, 'yyyy-MM-dd');
16 | const contents = `This is a string that contains a date: 2021-02-16.`;
17 | const date = dateParser.parseDate(contents);
18 | expect(date.day).toEqual(16);
19 | expect(date.month).toEqual(2);
20 | expect(date.year).toEqual(2021);
21 | });
22 |
23 | test('removing a date in a valid, simple format', () => {
24 | const dateParser = new DateParser(DateParser.DateToken, 'yyyy-MM-dd');
25 | const contents = `This is a string that contains a date: 2021-02-16.`;
26 | const contentsWithoutDate = dateParser.removeDate(contents);
27 | expect(contentsWithoutDate).toEqual('This is a string that contains a date: .');
28 | });
29 |
30 | test('only the first date is extracted', async () => {
31 | const dateParser = new DateParser(DateParser.DateToken, 'yyyy-MM-dd');
32 | const contents = `This is a string that contains not one date: 2021-02-16 but two: 2020-04-28.`;
33 | const date = dateParser.parseDate(contents);
34 | expect(date.day).toEqual(16);
35 | expect(date.month).toEqual(2);
36 | expect(date.year).toEqual(2021);
37 | });
38 |
39 | test('trying to extract a date that is not there', () => {
40 | const dateParser = new DateParser(DateParser.DateToken, 'yyyy-MM-dd');
41 | const contents = `This is a string that does not contain a date.`;
42 | const date = dateParser.parseDate(contents);
43 | expect(date).toBeUndefined();
44 | });
45 |
46 | test('extracting a date if the tag format contains date special regex characters', async () => {
47 | const dateParser = new DateParser(`[[${DateParser.DateToken}]]`, 'yyyy-MM-dd');
48 | const contents = `This is a string that contains a date: [[2021-02-16]] in a more complex format.`;
49 | const date = dateParser.parseDate(contents);
50 | expect(date.day).toEqual(16);
51 | expect(date.month).toEqual(2);
52 | expect(date.year).toEqual(2021);
53 | });
54 |
55 | test('extracting a date if the tag format contains date format tokens', () => {
56 | const dateParser = new DateParser(`Due:${DateParser.DateToken}`, 'yyyy-MM-dd');
57 | const contents = `A very custom tag. Due:2021-02-16.`;
58 | const date = dateParser.parseDate(contents);
59 | expect(date.day).toEqual(16);
60 | expect(date.month).toEqual(2);
61 | expect(date.year).toEqual(2021);
62 | });
63 |
--------------------------------------------------------------------------------
/util/DateParser.ts:
--------------------------------------------------------------------------------
1 | import { DateTime } from 'luxon';
2 |
3 | export class DateParser {
4 | public static DateToken = '%date%';
5 | private dateFormat: string;
6 | private regexp: RegExp;
7 |
8 | constructor(tagFormat: string, dateFormat: string) {
9 | if (!tagFormat.includes(DateParser.DateToken)) {
10 | throw new Error(`Tag format must include the ${DateParser.DateToken} token.`);
11 | }
12 | this.dateFormat = dateFormat;
13 |
14 | const explanation = DateTime.fromFormatExplain('x', dateFormat);
15 | const pattern = explanation.regex;
16 | const patternString = pattern.toString().replace('/^', '').replace('$/i', '');
17 |
18 | const formatPattern = stringToPattern(tagFormat);
19 | const fullPattern = formatPattern.replace(new RegExp(DateParser.DateToken), `(${patternString})`);
20 | this.regexp = new RegExp(fullPattern);
21 | }
22 |
23 | public parseDate(source: string): DateTime | undefined {
24 | const matches = source.match(this.regexp);
25 | if (!matches) {
26 | return undefined;
27 | }
28 | return DateTime.fromFormat(matches[1], this.dateFormat);
29 | }
30 |
31 | public removeDate(source: string): string {
32 | return source.replace(this.regexp, '').trim();
33 | }
34 | }
35 |
36 | const stringToPattern = (rawString: string) => {
37 | return rawString.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
38 | };
39 |
--------------------------------------------------------------------------------
/util/__mocks__/DailyNoteParser.ts:
--------------------------------------------------------------------------------
1 | import { DateTime } from 'luxon';
2 |
3 | export const extractDueDateFromDailyNotesFile = (filePath: string): DateTime | undefined => {
4 | if (filePath.includes('Daily Notes')) {
5 | return DateTime.now();
6 | }
7 | return undefined;
8 | };
9 |
--------------------------------------------------------------------------------
/versions.json:
--------------------------------------------------------------------------------
1 | {
2 | "0.1.0": "0.10.13",
3 | "0.2.1": "0.11.0"
4 | }
5 |
--------------------------------------------------------------------------------