├── .editorconfig
├── .eslintignore
├── .eslintrc
├── .github
└── workflows
│ ├── ci.yml
│ └── publish.yml
├── .gitignore
├── .stylelintrc.json
├── LICENSE
├── README.md
├── esbuild.config.mjs
├── jest.config.js
├── manifest.json
├── package.json
├── src
├── IconAdder.ts
├── OverwrittenIconModal.ts
├── PostProcessor.ts
├── ProviderTestModal.ts
├── SchemaSuggest.ts
├── decoration
│ ├── Decoration.ts
│ ├── TokenSpec.ts
│ ├── icon
│ │ ├── IconDecorationSet.ts
│ │ ├── IconDecorations.ts
│ │ └── IconWidget.ts
│ └── text
│ │ ├── TextDecorationSet.ts
│ │ ├── TextRemovingDecoration.ts
│ │ └── TextWidget.ts
├── functions.ts
├── main.ts
├── provider.ts
├── settings.ts
├── styles.scss
├── suggest.ts
└── types.ts
├── test
└── functions.test.ts
├── tsconfig.json
└── versions.json
/.editorconfig:
--------------------------------------------------------------------------------
1 | # top-most EditorConfig file
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | insert_final_newline = true
7 | indent_style = tab
8 | indent_size = 4
9 | tab_width = 4
10 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | npm node_modules
2 | build
--------------------------------------------------------------------------------
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "root": true,
3 | "parser": "@typescript-eslint/parser",
4 | "plugins": [
5 | "@typescript-eslint"
6 | ],
7 | "extends": [
8 | "eslint:recommended",
9 | "plugin:@typescript-eslint/eslint-recommended",
10 | "plugin:@typescript-eslint/recommended"
11 | ],
12 | "parserOptions": {
13 | "sourceType": "module"
14 | },
15 | "rules": {
16 | "no-unused-vars": "off",
17 | "@typescript-eslint/no-unused-vars": ["error", { "args": "none" }],
18 | "@typescript-eslint/ban-ts-comment": "off",
19 | "no-prototype-builtins": "off",
20 | "@typescript-eslint/no-empty-function": "off"
21 | }
22 | }
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches: [master]
6 | pull_request:
7 | branches: [master]
8 |
9 | jobs:
10 | lint-and-test:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v2
14 | - name: Install modules
15 | run: npm install
16 | - name: Lint
17 | run: npm run lint
18 | - name: Lint CSS
19 | run: npm run lint-css
20 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Build plugin
2 |
3 | on:
4 | push:
5 | # Sequence of patterns matched against refs/tags
6 | tags:
7 | - "*" # Push events to matching any tag format, i.e. 1.0, 20.15.10
8 |
9 | env:
10 | PLUGIN_NAME: link-favicon
11 |
12 | jobs:
13 | build:
14 | runs-on: ubuntu-latest
15 |
16 | steps:
17 | - uses: actions/checkout@v2
18 | - name: Use Node.js
19 | uses: actions/setup-node@v1
20 | with:
21 | node-version: "14.x" # You might need to adjust this value to your own version
22 | - name: Build
23 | id: build
24 | run: |
25 | sudo apt install jq wget python3 --yes
26 | wget https://www.iana.org/assignments/uri-schemes/uri-schemes-1.csv
27 | cat uri-schemes-1.csv | python -c 'import csv, json, sys; print(json.dumps([dict(r) for r in csv.DictReader(sys.stdin)]))' > test.json
28 | jq 'map(.schema = .["URI Scheme"])' test.json > schemas.json
29 | npm install
30 | npm run build
31 | mkdir ${{ env.PLUGIN_NAME }}
32 | cp build/main.js build/manifest.json build/styles.css ${{ env.PLUGIN_NAME }}
33 | zip -r ${{ env.PLUGIN_NAME }}.zip ${{ env.PLUGIN_NAME }}
34 | ls
35 | echo "::set-output name=tag_name::$(git tag --sort version:refname | tail -n 1)"
36 | - name: Create Release
37 | id: create_release
38 | uses: actions/create-release@v1
39 | env:
40 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
41 | VERSION: ${{ github.ref }}
42 | with:
43 | tag_name: ${{ github.ref }}
44 | release_name: ${{ github.ref }}
45 | draft: false
46 | prerelease: false
47 | - name: Upload zip file
48 | id: upload-zip
49 | uses: actions/upload-release-asset@v1
50 | env:
51 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
52 | with:
53 | upload_url: ${{ steps.create_release.outputs.upload_url }}
54 | asset_path: ./${{ env.PLUGIN_NAME }}.zip
55 | asset_name: ${{ env.PLUGIN_NAME }}-${{ steps.build.outputs.tag_name }}.zip
56 | asset_content_type: application/zip
57 | - name: Upload main.js
58 | id: upload-main
59 | uses: actions/upload-release-asset@v1
60 | env:
61 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
62 | with:
63 | upload_url: ${{ steps.create_release.outputs.upload_url }}
64 | asset_path: ./build/main.js
65 | asset_name: main.js
66 | asset_content_type: text/javascript
67 | - name: Upload manifest.json
68 | id: upload-manifest
69 | uses: actions/upload-release-asset@v1
70 | env:
71 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
72 | with:
73 | upload_url: ${{ steps.create_release.outputs.upload_url }}
74 | asset_path: ./build/manifest.json
75 | asset_name: manifest.json
76 | asset_content_type: application/json
77 | - name: Upload styles.scss
78 | id: upload-styles
79 | uses: actions/upload-release-asset@v1
80 | env:
81 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
82 | with:
83 | upload_url: ${{ steps.create_release.outputs.upload_url }}
84 | asset_path: ./build/styles.css
85 | asset_name: styles.css
86 | asset_content_type: text/css
87 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # vscode
2 | .vscode
3 |
4 | # Intellij
5 | *.iml
6 | .idea
7 |
8 | # npm
9 | node_modules
10 | package-lock.json
11 |
12 | # Don't include the compiled main.js file in the repo.
13 | # They should be uploaded to GitHub releases instead.
14 | main.js
15 |
16 | # Exclude sourcemaps
17 | *.map
18 |
19 | # obsidian
20 | build/data.json
21 | test.json
22 | schemas.json
23 | *.csv
24 | *.lock
25 | cache
26 | build
27 | coverage
28 |
--------------------------------------------------------------------------------
/.stylelintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": ["stylelint-config-recommended", "stylelint-config-standard-scss"],
3 | "rules": {
4 | "font-family-no-missing-generic-family-keyword": null,
5 | "no-descending-specificity": null,
6 | "indentation": "tab",
7 | "value-no-vendor-prefix": null
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/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 | ## Link Favicons
2 |
3 | Plugin for [Obsidian](https://obsidian.md)
4 |
5 | 
6 | 
7 | 
8 | [](https://liberamanifesto.com)
9 | ---
10 |
11 | With this plugin you can see the favicon for a linked website without using any custom CSS.
12 |
13 | 
14 |
15 | Works with: [Admonition](https://github.com/valentine195/obsidian-admonition)
16 | , [RSS Reader](https://github.com/joethei/obsidian-rss) and many more plugins.
17 |
18 | Also check out [Link Favicons for Firefox & Chromium based browsers](https://github.com/joethei/browser-favicon-links)
19 |
20 | ## Icon Providers
21 | You can select between these providers in the settings:
22 |
23 | | Provider | Max Size | Fallback | max requests |
24 | |--------------------------------------------------------------------|-----------|-------------------------|-----------------|
25 | | Google | 16x16px | default icon | no limit️ |
26 | | DuckDuckGo | none | default icon | no limit |
27 | | [Favicon Grabber](https://favicongrabber.com/) | none | none | 100 per minute |
28 | | [The Favicon Finder](https://github.com/mat/besticon) (selfhosted) | 256x256px | automatically generated | no limit️ |
29 | | [Icon Horse](https://icon.horse/) | none | automatically generated | fair use policy |
30 | | [Splitbee](https://github.com/splitbee/favicon-resolver) | none | yes (from Google) | unknown |
31 |
32 | Depending on which provider you choose the icons might look different.
33 |
34 | The Icon Provider will only receive the hostname your links, so `forum.obsidian.md` instead
35 | of `https://forum.obsidian.md/t/custom-link-favicons-hiding-in-community-plugins/24112/5?u=joethei`
36 |
37 |
38 | ## Overwriting icons
39 | > Requires the [Icon Shortcodes](https://github.com/aidenlx/obsidian-icon-shortcodes) plugin
40 |
41 | You can overwrite any domain favicon with an icon of your choosing in the settings.
42 | (See the demo gif below)
43 |
44 | ## Defining Icons for URI Schemes
45 | > Requires the [Icon Shortcodes](https://github.com/aidenlx/obsidian-icon-shortcodes) plugin
46 |
47 | You can also add icons for uri schemes such as `mailto://`, `obsidian://` or `calculator://`.
48 | To do this specify the name of the uri scheme(without `://`) in the settings.
49 | (See the demo gif below)
50 |
51 | 
52 |
53 | ## Disabling on specific links
54 | If you have a link where you do not want to see the favicon, add `|nofavicon` to the link alias.
55 | ```md
56 | [Display text|nofavicon](https://example.org)
57 | ```
58 |
59 | ## For Designers
60 | For help with styling you can also check out the `#appearance` channel on
61 | the [Obsidian Members Group Discord](https://obsidian.md/community)
62 |
63 | If you want to style the favicons you can use a CSS snippet similar to the one below, which makes all favicons appear in
64 | grayscale.
65 |
66 | ```css
67 | body .link-favicon[data-is-readable-a-a] {
68 | filter: grayscale(100%);
69 | }
70 | ```
71 |
72 | If you want to disable your own styling for favicons you can check if the `data-favicon` Attribute is "true". The
73 | example below removes the external link
74 | icon
75 | .
76 |
77 | ```css
78 | .external-link::after {
79 | display: none;
80 | content: '';
81 | }
82 |
83 | .external-link {
84 | background-image: none;
85 | }
86 | ```
87 |
88 | #### Color Inversion
89 |
90 | By default, icons that are perceived as unreadable will have a color filter applied to help with readability.
91 | There are multiple metrics that could be used to decide if an icon is readable or not:
92 | - `is-dark`, `is-light`: whether the icon's color perceived brightness is dark/light.
93 | - `is-readable-a-a`: according to the [W3C AA specification](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html)
94 | - `is-readable-a-a-a`: according to the [W3C AAA specification](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast7.html)
95 |
96 | By default, the AA value is used.
97 |
98 | using the `is-dark`, `is-light` values is not recommended as they don't take the background color into account.
99 |
100 | These values are calculated from the average color.
101 | Using the most dominant color would be more accurate, but is not implemented currently.
102 |
103 | ### For Developers
104 |
105 | As long as you use
106 | the [renderMarkdown](https://marcus.se.net/obsidian-plugin-docs/api/classes/MarkdownRenderer#rendermarkdown)
107 | Method this plugin will add favicons to your external links.
108 | If you want no link favicons in your plugin either add `no-favicon` to your source path when calling the method.
109 | Or specify the Attribute `data-no-favicon` on your link element.
110 |
--------------------------------------------------------------------------------
/esbuild.config.mjs:
--------------------------------------------------------------------------------
1 | import esbuild from "esbuild";
2 | import fs from 'fs';
3 | import process from "process";
4 | import builtins from 'builtin-modules';
5 | import sass from "sass";
6 | import minify from "css-minify";
7 |
8 | const banner =
9 | `/*
10 | THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
11 | if you want to view the source, please visit the github repository of this plugin
12 | https://github.com/joethei/obisidian-link-favicon
13 | */
14 | `;
15 |
16 | const prod = (process.argv[2] === 'production');
17 |
18 | const copyMinifiedCSS = {
19 | name: 'minify-css',
20 | setup: (build) => {
21 | build.onEnd(async () => {
22 | const {css} = sass.compile('src/styles.scss');
23 | let content;
24 | if(prod) {
25 | const minCss = await minify(css);
26 | content = `${banner}\n${minCss}`;
27 | }else {
28 | content = `${banner}\n${css}`;
29 | }
30 | fs.writeFileSync('build/styles.css', content, {encoding: 'utf-8'});
31 | })
32 | }
33 | }
34 |
35 | const copyManifest = {
36 | name: 'copy-manifest',
37 | setup: (build) => {
38 | build.onEnd(() => {
39 | fs.copyFileSync('manifest.json', 'build/manifest.json');
40 | });
41 | },
42 | };
43 |
44 | esbuild.build({
45 | banner: {
46 | js: banner,
47 | },
48 | entryPoints: ['src/main.ts'],
49 | bundle: true,
50 | external: ['obsidian', 'electron', '@codemirror/language', '@codemirror/rangeset', '@codemirror/state', '@codemirror/stream-parser', '@codemirror/view', ...builtins],
51 | format: 'cjs',
52 | watch: !prod,
53 | minify: prod,
54 | target: 'es2016',
55 | logLevel: "info",
56 | sourcemap: prod ? false : 'inline',
57 | treeShaking: true,
58 | outfile: 'build/main.js',
59 | plugins: [copyManifest, copyMinifiedCSS]
60 | }).catch(() => process.exit(1));
61 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | preset: "ts-jest",
3 | transform: {"\\.ts$": ['ts-jest']},
4 | collectCoverage: true,
5 | testEnvironment: "jsdom",
6 | moduleDirectories: ["node_modules", "src", "test"],
7 | coverageReporters: ["lcov", "text"],
8 | testMatch: ["**/test/**/*.ts"]
9 | };
10 |
--------------------------------------------------------------------------------
/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "link-favicon",
3 | "name": "Link Favicons",
4 | "version": "1.8.4",
5 | "minAppVersion": "1.3.0",
6 | "description": "See the favicon for a linked website. ",
7 | "author": "Johannes Theiner",
8 | "authorUrl": "https://github.com/joethei",
9 | "isDesktopOnly": false
10 | }
11 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "link-favicon",
3 | "version": "1.8.1",
4 | "description": "See the favicon for a linked website. ",
5 | "main": "src/main.js",
6 | "scripts": {
7 | "dev": "node esbuild.config.mjs",
8 | "build": "node esbuild.config.mjs production",
9 | "lint": "eslint . --ext .ts",
10 | "lint-css": "stylelint src/styles.scss",
11 | "test": "jest"
12 | },
13 | "keywords": [],
14 | "author": "Johannes Theiner",
15 | "license": "GPL-3.0",
16 | "devDependencies": {
17 | "@typescript-eslint/eslint-plugin": "5.5.0",
18 | "@typescript-eslint/parser": "5.5.0",
19 | "esbuild": "0.13.12",
20 | "eslint": "8.4.1",
21 | "sass": "1.49.9",
22 | "css-minify": "2.0.0",
23 | "stylelint": "14.9.1",
24 | "stylelint-config-standard": "26.0.0",
25 | "stylelint-config-standard-scss": "3.0.0",
26 | "jest": "28.1.3",
27 | "@types/jest": "28.1.6",
28 | "ts-jest": "28.0.7",
29 | "jsdom": "20.0.0",
30 | "@types/jsdom": "20.0.0",
31 | "jsdom-global": "3.0.2",
32 | "jest-environment-jsdom": "28.1.3"
33 | },
34 | "dependencies": {
35 | "@aidenlx/obsidian-icon-shortcodes": "0.9.0",
36 | "@codemirror/language": "https://github.com/lishid/cm-language",
37 | "@codemirror/state": "6.0.0",
38 | "@codemirror/view": "6.0.0",
39 | "@types/node": "16.11.11",
40 | "obsidian": "0.15.0",
41 | "tslib": "2.3.1",
42 | "typescript": "4.4.4",
43 | "fast-average-color": "9.4.0",
44 | "@popperjs/core": "2.11.2",
45 | "tinycolor2": "1.6.0",
46 | "@types/tinycolor2": "1.4.4",
47 | "localstorage-slim": "2.3.0",
48 | "builtin-modules": "3.2.0",
49 | "localforage": "1.10.0"
50 | },
51 | "overrides": {
52 | "obsidian": "$obsidian"
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/IconAdder.ts:
--------------------------------------------------------------------------------
1 | import FaviconPlugin from "./main";
2 | import {IconElement} from "./types";
3 | import ls from "localstorage-slim";
4 | import {arrayBufferToBase64, requestUrl} from "obsidian";
5 | import tinycolor from "tinycolor2";
6 | import {FastAverageColor} from "fast-average-color";
7 |
8 | /**
9 | *
10 | * @since 1.8
11 | */
12 | export class IconAdder {
13 |
14 | private fac = new FastAverageColor();
15 | private readonly plugin: FaviconPlugin;
16 |
17 | constructor(plugin: FaviconPlugin) {
18 | this.plugin = plugin;
19 | }
20 |
21 | destruct() {
22 | this.fac.destroy();
23 | }
24 |
25 | public constructURL(link: string): URL | undefined {
26 | try {
27 | return new URL(link);
28 | } catch (e) {
29 | //we have a link without a protocol for some reason
30 | if(!link.startsWith("http")) return this.constructURL("http://" + link);
31 | return undefined;
32 | }
33 | }
34 |
35 | public async addFavicon(el: HTMLElement, icon: IconElement, fallbackIcon: IconElement, url: URL) {
36 | if ((!icon || icon === "") && (!fallbackIcon || fallbackIcon === "")) {
37 | console.log("no icon for " + url.href);
38 | return;
39 | }
40 |
41 | if (!icon || icon === "") {
42 | await this.useDownloadedIcon(fallbackIcon, el, url);
43 | return;
44 | }
45 |
46 | if (typeof icon === "string") {
47 | //any unicode symbols
48 | if (!icon.startsWith("http")) {
49 | this.addIcon(el, icon);
50 | return;
51 | }
52 |
53 | const objEl = await this.getImageEl(icon, url);
54 | this.addIcon(el, objEl);
55 |
56 | return;
57 | }
58 |
59 | this.addIcon(el, icon);
60 | }
61 |
62 | public async getImageEl(icon: string, qualifier: string | URL): Promise {
63 | if (typeof qualifier === "string") {
64 | const url = this.constructURL(qualifier);
65 | if (!url) return Promise.reject("could not get Object for " + icon + " " + qualifier);
66 | return this.getImageElFromUrl(icon, url);
67 |
68 | } else {
69 | return this.getImageElFromUrl(icon, qualifier);
70 | }
71 | }
72 |
73 | private async getImageElFromUrl(icon: string, url: URL): Promise {
74 | const el = activeDocument.createElement("img");
75 | el.addClass("link-favicon");
76 |
77 | el.dataset.host = url.hostname;
78 |
79 | el.src = await this.getEncodedIcon(icon, url.hostname);
80 |
81 | await this.setColorAttributes(el);
82 |
83 | //making sure these styles will not be overwritten by any other theme/plugin
84 | //i.e. page preview sets height: auto, which creates huge icons.
85 | el.style.height = "0.8em";
86 | el.style.display = "inline-block";
87 |
88 | return el;
89 | }
90 |
91 |
92 | private async useDownloadedIcon(icon: IconElement, el: HTMLElement, url: URL) {
93 | if (!icon || icon === "") return;
94 |
95 | if (typeof icon === "string") {
96 | const imgEl = activeDocument.createElement("img");
97 | imgEl.addClass("link-favicon");
98 | imgEl.src = await this.getEncodedIcon(icon, url.hostname);
99 |
100 | await this.setColorAttributes(imgEl);
101 | this.addIcon(el, imgEl);
102 | }
103 |
104 | }
105 |
106 | /**
107 | * add icon to link element in the page
108 | * @param el
109 | * @param link
110 | * @private
111 | */
112 | private addIcon(el: HTMLElement, link: string | HTMLElement) {
113 | if (!link || link === "undefined") return;
114 | if (this.plugin.settings.iconPosition === "front") {
115 | el.prepend(link);
116 | }
117 | if (this.plugin.settings.iconPosition === "back") {
118 | el.append(link);
119 | }
120 | }
121 |
122 | /**
123 | * get icon from cache or download.
124 | * @param icon web location for the icon
125 | * @param hostname hostname for which the icon is.
126 | * @returns Icon base64 encoded.
127 | * @private
128 | */
129 | private async getEncodedIcon(icon: string, hostname: string): Promise {
130 | if (icon === "") return "";
131 | const parts = icon.split(".");
132 | let extension = parts[parts.length - 1];
133 |
134 | //default to png if there is no extension.
135 | if (!extension) {
136 | extension = "png";
137 | }
138 |
139 | const name = "lf-" + hostname + "." + extension;
140 |
141 | const entry = ls.get(name);
142 | if (entry) {
143 | return entry;
144 | }
145 |
146 | const downloaded = await this.downloadIcon(icon);
147 |
148 | //cache for one month
149 | ls.set(name, downloaded, {ttl: 30 * 24 * 60 * 60});
150 |
151 | return downloaded;
152 | }
153 |
154 | /**
155 | * Download the icon from the web and encode it
156 | * @param iconUrl
157 | * @returns Icon base64 encoded
158 | * @private
159 | */
160 | private async downloadIcon(iconUrl: string): Promise {
161 | const request = await requestUrl({url: iconUrl});
162 | if (request.status !== 200) {
163 | return Promise.reject("server returned status code" + request.status + " for " + iconUrl);
164 | }
165 | return "data:image/png;base64," + arrayBufferToBase64(request.arrayBuffer);
166 | }
167 |
168 | /**
169 | * retrieve color data about icon and add it as CSS attributes.
170 | * The CSS will then change the coloring based on these values.
171 | * @param img image element
172 | * @private
173 | */
174 | private async setColorAttributes(img: HTMLImageElement) {
175 | const darkEl = activeDocument.getElementsByClassName("theme-dark")[0];
176 | const lightEl = activeDocument.getElementsByClassName("theme-light")[0];
177 |
178 |
179 | let background: string;
180 |
181 | if (darkEl !== undefined) {
182 | try {
183 | const style = activeWindow.getComputedStyle(darkEl);
184 | background = style.getPropertyValue('--background-primary');
185 | } catch (e) {
186 | background = "000000";
187 | }
188 |
189 | } else {
190 | try {
191 | const style = activeWindow.getComputedStyle(lightEl);
192 | background = style.getPropertyValue('--background-primary');
193 | } catch (e) {
194 | background = "FFFFFF";
195 | }
196 | }
197 | try {
198 | const color = await this.fac.getColorAsync(img);
199 |
200 | img.dataset.averageColorHex = color.hex;
201 | img.dataset.isDark = String(color.isDark);
202 | img.dataset.isLight = String(color.isLight);
203 | const backgroundColor = tinycolor(background);
204 | img.dataset.colorInversion = String(this.plugin.settings.colorInversion);
205 | img.dataset.readable = tinycolor.readability(color.hex, backgroundColor).toString();
206 | img.dataset.isReadableAA = String(tinycolor.isReadable(color.hex, backgroundColor));
207 | img.dataset.isReadableAAA = String(tinycolor.isReadable(color.hex, backgroundColor, {level: "AAA"}));
208 |
209 | } catch (e) {
210 | console.error("could not extract color information from icon");
211 | console.error(img);
212 | console.error(e);
213 | }
214 | }
215 |
216 |
217 | }
218 |
--------------------------------------------------------------------------------
/src/OverwrittenIconModal.ts:
--------------------------------------------------------------------------------
1 | import FaviconPlugin from "./main";
2 | import {Modal, Notice, Setting} from "obsidian";
3 | import {OverwrittenFavicon} from "./settings";
4 | import {getApi, isPluginEnabled} from "@aidenlx/obsidian-icon-shortcodes";
5 | import {SchemaSuggest} from "./SchemaSuggest";
6 |
7 |
8 | export class OverwrittenIconModal extends Modal {
9 | plugin: FaviconPlugin;
10 | domain: string;
11 | icon: string;
12 | name = "Domain";
13 |
14 | saved: boolean;
15 |
16 | constructor(plugin: FaviconPlugin, map?: OverwrittenFavicon, name?: string) {
17 | super(plugin.app);
18 | this.plugin = plugin;
19 |
20 | if(name) {
21 | this.name = name;
22 | }
23 |
24 | if(map) {
25 | this.domain = map.domain;
26 | this.icon = map.icon;
27 | }
28 | }
29 |
30 | async displayPreview(contentEl: HTMLElement) : Promise {
31 | if(isPluginEnabled(this.plugin) && this.icon) {
32 | contentEl.empty();
33 | const iconPreview = contentEl.createDiv("preview");
34 | iconPreview.addClass("link-favicon-preview");
35 | const iconApi = getApi(this.plugin);
36 | const icon = iconApi.getIcon(this.icon, false);
37 | if(icon !== null)
38 | iconPreview.append(icon);
39 | }
40 | }
41 |
42 | async display() : Promise {
43 |
44 | const { contentEl } = this;
45 |
46 | contentEl.empty();
47 |
48 | //eslint-disable-next-line prefer-const
49 | let previewEL: HTMLElement;
50 |
51 | const nameSetting = new Setting(contentEl).setName(this.name);
52 |
53 | if(this.name !== "Domain") {
54 | //eslint-disable-next-line @typescript-eslint/no-var-requires
55 | let schemas: {schema: string, Description: string}[] = require("../schemas.json");
56 | //we don't need http/https to show up, they would not work here
57 | schemas = schemas.filter(item => !item.schema.contains("http"));
58 | const schemaNames = Object.values(schemas).map(schema => schema.schema);
59 | const descriptions = Object.values(schemas).map(schema => {
60 | return {name: schema.schema, description: schema.Description}
61 | });
62 | nameSetting.addSearch(search => {
63 | new SchemaSuggest(this.plugin.app, search.inputEl, new Set(schemaNames), new Set<{name: string, description: string}>(descriptions));
64 | search.setValue(this.domain)
65 | .onChange(value => {
66 | this.domain = value;
67 | });
68 | });
69 | }else {
70 | nameSetting.addText((text) => {
71 | text
72 | .setValue(this.domain)
73 | .onChange((value) => {
74 | this.domain = value;
75 | });
76 | });
77 | }
78 |
79 |
80 |
81 | const api = getApi(this.plugin);
82 | if (api) {
83 | if (api.version.compare(">=", "0.6.1")) {
84 |
85 | new Setting(contentEl)
86 | .setName("Icon")
87 | .addButton((button) => {
88 | button
89 | .setButtonText("Choose")
90 | .onClick(async() => {
91 | const icon = await api.getIconFromUser();
92 | if(icon) {
93 | this.icon = icon.id;
94 | if(previewEL) {
95 | await this.displayPreview(previewEL);
96 | }
97 | }
98 | });
99 | });
100 |
101 | }else {
102 | new Setting(contentEl)
103 | .setName("Icon")
104 | .addText((text) => {
105 | text
106 | .setValue(this.icon)
107 | .onChange(async(value) => {
108 | this.icon = value;
109 | if(previewEL) {
110 | await this.displayPreview(previewEL);
111 | }
112 | });
113 | });
114 | }
115 | }
116 |
117 | previewEL = contentEl.createDiv("preview");
118 |
119 | await this.displayPreview(previewEL);
120 |
121 | const footerEl = contentEl.createDiv();
122 | const footerButtons = new Setting(footerEl);
123 | footerButtons.addButton((b) => {
124 | b.setTooltip("Save")
125 | .setIcon("checkmark")
126 | .onClick(async () => {
127 | if(this.icon && this.domain) {
128 | this.saved = true;
129 | this.close();
130 | }else {
131 | new Notice("Please supply both a " + this.name + " & a icon");
132 | }
133 |
134 | });
135 | return b;
136 | });
137 | footerButtons.addExtraButton((b) => {
138 | b.setIcon("cross")
139 | .setTooltip("Cancel")
140 | .onClick(() => {
141 | this.saved = false;
142 | this.close();
143 | });
144 | return b;
145 | });
146 | }
147 |
148 | async onOpen() : Promise {
149 | await this.display();
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/src/PostProcessor.ts:
--------------------------------------------------------------------------------
1 | import {MarkdownPostProcessorContext, Notice} from "obsidian";
2 | import {providers} from "./provider";
3 | import FaviconPlugin from "./main";
4 |
5 | export class PostProcessor {
6 | plugin: FaviconPlugin;
7 |
8 | constructor(plugin: FaviconPlugin) {
9 | this.plugin = plugin;
10 | }
11 |
12 | processor = async (element: HTMLElement, context: MarkdownPostProcessorContext) => {
13 | if (!this.plugin.settings.enableReading) {
14 | return;
15 | }
16 |
17 | if (context.sourcePath.contains("no-favicon")) {
18 | return;
19 | }
20 |
21 | let provider = providers[this.plugin.settings.provider];
22 | let fallbackProvider = providers[this.plugin.settings.fallbackProvider];
23 |
24 | //uses providers from frontmatter, if supplied for easier debugging
25 | if (context.frontmatter) {
26 | const fmProvider = providers[context.frontmatter["favicon-provider"]];
27 | const fmFallbackProvider = providers[context.frontmatter["fallback-favicon-provider"]];
28 | if (fmProvider)
29 | provider = fmProvider;
30 |
31 | if (fmFallbackProvider)
32 | fallbackProvider = fmFallbackProvider;
33 | }
34 |
35 |
36 | if (!provider || !fallbackProvider) {
37 | console.error("Link Favicons: misconfigured providers");
38 | new Notice('Link favicons:misconfigured providers, please check the settings');
39 | return;
40 | }
41 |
42 | //delay rendering in Preview, to allow other plugins to finish their stuff(like dataview for issue #13)
43 | const timeout = 50;
44 | setTimeout(async () => {
45 | const links = element.querySelectorAll("a.external-link:not([data-favicon])");
46 | for (let index = 0; index < links.length; index++) {
47 | const link = links.item(index) as HTMLAnchorElement;
48 | link.dataset.disabled = String(this.isDisabled(link));
49 | if (!this.isDisabled(link)) {
50 | if (link.textContent?.includes("|nofavicon")) {
51 | link.href = link.href.replace("%7Cnofavicon", "");
52 | link.ariaLabel = link.ariaLabel.replace("%7Cnofavicon", "");
53 | link.textContent = link.textContent.replace("|nofavicon", "");
54 | continue;
55 | }
56 |
57 |
58 | link.dataset.favicon = "true";
59 |
60 | const icon = await this.plugin.getIcon(link.href, provider);
61 | const fallbackIcon = await this.plugin.getIcon(link.href, fallbackProvider);
62 |
63 | const url = this.plugin.iconAdder.constructURL(link.href);
64 | if(!url) return;
65 |
66 | try {
67 | await this.plugin.iconAdder.addFavicon(link, icon, fallbackIcon, url);
68 | } catch(e) {
69 | console.error(e);
70 | }
71 |
72 | }
73 | }
74 | }, timeout);
75 | }
76 |
77 |
78 | isDisabled = (el: Element) => {
79 | if (el.getAttribute("data-no-favicon")) return true;
80 | if (el.getAttribute("data-favicon")) return true;
81 | if (!this.plugin.settings.showLink && el.textContent === el.getAttribute("href")) return true;
82 | if (!this.plugin.settings.showAliased && el.textContent !== el.getAttribute("href")) return true;
83 |
84 | return false;
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/ProviderTestModal.ts:
--------------------------------------------------------------------------------
1 | import FaviconPlugin from "./main";
2 | import {Modal, Setting} from "obsidian";
3 | import {providers} from "./provider";
4 |
5 | export class ProviderTestModal extends Modal {
6 | plugin: FaviconPlugin;
7 | link: string;
8 |
9 | constructor(plugin: FaviconPlugin) {
10 | super(plugin.app);
11 | this.plugin = plugin;
12 | }
13 |
14 | async display(): Promise {
15 | const {contentEl} = this;
16 | contentEl.empty();
17 | contentEl.addClass("link-favicon-scrollable-content");
18 |
19 | new Setting(contentEl).setName("Link").addText(text => {
20 | text
21 | .setValue(this.link)
22 | .onChange(value => {
23 | this.link = value;
24 | });
25 | text.inputEl.addEventListener('keydown', (event) => {
26 | if (event.key === 'Enter') {
27 | this.display();
28 | }
29 | });
30 | });
31 | new Setting(contentEl).setName("").addButton(button => {
32 | button
33 | .setButtonText("Test")
34 | .onClick(() => {
35 | this.display();
36 | });
37 | });
38 |
39 | if(this.link) {
40 | if(!this.link.startsWith("http")) {
41 | this.link = "http://" + this.link;
42 | }
43 | try {
44 | const url = new URL(this.link);
45 |
46 | for (const provider of Object.values(providers)) {
47 | contentEl.createEl("h3", {text: provider.name});
48 | const preview = contentEl.createEl("img", {cls: "provider-preview"});
49 | preview.setAttribute("src", await provider.url(url.hostname, this.plugin.settings));
50 | }
51 | }catch (e) {
52 | contentEl.createSpan({text: "Could not generate favicon, check your settings"});
53 | }
54 |
55 | }
56 |
57 |
58 | }
59 |
60 | override async onOpen() {
61 | await this.display();
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/SchemaSuggest.ts:
--------------------------------------------------------------------------------
1 | import {App} from "obsidian";
2 | import {TextInputSuggest} from "./suggest";
3 |
4 | export class SchemaSuggest extends TextInputSuggest {
5 |
6 | content: Set;
7 | descriptions: Set<{name: string, description: string}>;
8 |
9 | constructor(app: App, input: HTMLInputElement, content: Set, descriptions: Set<{name: string, description: string}>) {
10 | super(app, input);
11 | this.content = content;
12 | this.descriptions = descriptions;
13 | }
14 |
15 | getSuggestions(inputStr: string): string[] {
16 | const lowerCaseInputStr = inputStr.toLowerCase();
17 | const schemas = [...this.descriptions].filter(schema => {
18 | return schema.name.toLowerCase().contains(lowerCaseInputStr) || schema.description.toLowerCase().contains(lowerCaseInputStr);
19 | });
20 | return Object.values(schemas).map(value => value.name);
21 | }
22 |
23 | renderSuggestion(content: string, el: HTMLElement): void {
24 | el.createSpan().setText(content + " ");
25 | const description = [...this.descriptions].filter((item) => content === item.name)[0].description;
26 | if(description !== content) {
27 | el.createEl("small").setText(description);
28 | }
29 | }
30 |
31 | selectSuggestion(content: string): void {
32 | this.inputEl.value = content;
33 | this.inputEl.trigger("input");
34 | this.close();
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/decoration/Decoration.ts:
--------------------------------------------------------------------------------
1 | // Generic helper for creating pairs of editor state fields and
2 | // effects to model imperatively updated decorations.
3 | // source: https://github.com/ChromeDevTools/devtools-frontend/blob/8f098d33cda3dd94b53e9506cd3883d0dccc339e/front_end/panels/sources/DebuggerPlugin.ts#L1722
4 | import {StateEffect, StateEffectType, StateField} from "@codemirror/state";
5 | import {Decoration, DecorationSet, EditorView} from "@codemirror/view";
6 |
7 | export function defineStatefulDecoration(): { update: StateEffectType; field: StateField; } {
8 | const update = StateEffect.define();
9 | const field = StateField.define({
10 | create(): DecorationSet {
11 | return Decoration.none;
12 | },
13 | update(deco, tr): DecorationSet {
14 | return tr.effects.reduce((deco, effect) => (effect.is(update) ? effect.value : deco), deco.map(tr.changes));
15 | },
16 | provide: field => EditorView.decorations.from(field),
17 | });
18 | return { update, field };
19 | }
20 |
--------------------------------------------------------------------------------
/src/decoration/TokenSpec.ts:
--------------------------------------------------------------------------------
1 | export interface TokenSpec {
2 | from: number;
3 | to: number;
4 | value: string;
5 | }
6 |
--------------------------------------------------------------------------------
/src/decoration/icon/IconDecorationSet.ts:
--------------------------------------------------------------------------------
1 | import {Decoration, DecorationSet, EditorView} from "@codemirror/view";
2 | import FaviconPlugin from "../../main";
3 | import {debounce, Debouncer} from "obsidian";
4 | import {TokenSpec} from "../TokenSpec";
5 | import {Range} from "@codemirror/state";
6 | import {providers} from "../../provider";
7 | import {IconWidget} from "./IconWidget";
8 | import {iconDecorations} from "./IconDecorations";
9 |
10 | export class IconDecorationSet {
11 | editor: EditorView;
12 | plugin: FaviconPlugin;
13 | decoCache: { [cls: string]: Decoration } = Object.create(null);
14 | debouncedUpdate: Debouncer<[tokens: TokenSpec[]]>;
15 |
16 | constructor(editor: EditorView, plugin: FaviconPlugin) {
17 | this.editor = editor;
18 | this.plugin = plugin;
19 | this.debouncedUpdate = debounce(this.updateAsyncDecorations, this.plugin.settings.debounce, true);
20 | }
21 |
22 | async computeAsyncDecorations(tokens: TokenSpec[]): Promise {
23 | const decorations: Range[] = [];
24 | for (const token of tokens) {
25 | let deco = this.decoCache[token.value];
26 | if (!deco) {
27 |
28 | const provider = providers[this.plugin.settings.provider];
29 | const fallbackProvider = providers[this.plugin.settings.fallbackProvider];
30 |
31 | const icon = await this.plugin.getIcon(token.value, provider);
32 | const fallbackIcon = await this.plugin.getIcon(token.value, fallbackProvider);
33 | const url = this.plugin.iconAdder.constructURL(token.value);
34 | if (url) {
35 | const domain = url.protocol.contains("http") ? url.hostname : url.protocol;
36 |
37 | deco = this.decoCache[token.value] = Decoration.widget({widget: new IconWidget(this.plugin, icon, fallbackIcon, domain, token)});
38 | }
39 |
40 | }
41 | decorations.push(deco.range(token.from, token.from));
42 | }
43 | return Decoration.set(decorations, true);
44 | }
45 |
46 | async updateAsyncDecorations(tokens: TokenSpec[]): Promise {
47 | const decorations = await this.computeAsyncDecorations(tokens);
48 | // if our compute function returned nothing and the state field still has decorations, clear them out
49 | if (decorations || this.editor.state.field(iconDecorations.field).size) {
50 | this.editor.dispatch({effects: iconDecorations.update.of(decorations || Decoration.none)});
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/decoration/icon/IconDecorations.ts:
--------------------------------------------------------------------------------
1 | import {EditorView, ViewPlugin, ViewUpdate} from "@codemirror/view";
2 | import {syntaxTree, tokenClassNodeProp} from "@codemirror/language";
3 | import FaviconPlugin from "../../main";
4 | import {TokenSpec} from "../TokenSpec";
5 | import {IconDecorationSet} from "./IconDecorationSet";
6 | import {findOpenParen} from "../../functions";
7 | import {editorLivePreviewField} from "obsidian";
8 | import {defineStatefulDecoration} from "../Decoration";
9 |
10 | //based on: https://gist.github.com/nothingislost/faa89aa723254883d37f45fd16162337
11 |
12 | export const iconDecorations = defineStatefulDecoration();
13 |
14 | function buildViewPlugin(plugin: FaviconPlugin) {
15 | return ViewPlugin.fromClass(
16 | class {
17 | decoManager: IconDecorationSet;
18 |
19 | constructor(view: EditorView) {
20 | this.decoManager = new IconDecorationSet(view, plugin);
21 | this.buildAsyncDecorations(view);
22 | }
23 |
24 | update(update: ViewUpdate) {
25 | const differentModes = update.startState.field(editorLivePreviewField) != update.state.field(editorLivePreviewField);
26 | if (update.docChanged || update.viewportChanged || differentModes) {
27 | this.buildAsyncDecorations(update.view);
28 | }
29 | }
30 |
31 | destroy() {
32 | }
33 |
34 | buildAsyncDecorations(view: EditorView) {
35 | const targetElements: TokenSpec[] = [];
36 | //live preview
37 | if (view.state.field(editorLivePreviewField) && !plugin.settings.enableLivePreview) {
38 | this.decoManager.debouncedUpdate(targetElements);
39 | return;
40 | }
41 | //source mode
42 | if (!view.state.field(editorLivePreviewField) && !plugin.settings.enableSource) {
43 | this.decoManager.debouncedUpdate(targetElements);
44 | return;
45 |
46 | }
47 | for (const {from, to} of view.visibleRanges) {
48 | const tree = syntaxTree(view.state);
49 | tree.iterate({
50 | from,
51 | to,
52 | enter: (node) => {
53 | const tokenProps = node.type.prop(tokenClassNodeProp);
54 | if (tokenProps) {
55 | const props = new Set(tokenProps.split(" "));
56 | const isExternalLink = props.has("url");
57 | let linkText = view.state.sliceDoc(node.from, node.to);
58 | if (isExternalLink && linkText.includes(":")) {
59 | linkText = linkText.replace(/[<>]/g, '');
60 | const before = view.state.doc.sliceString(node.from - 1, node.from);
61 | if (before !== "(") {
62 | if (!plugin.settings.showLink) return;
63 | if (plugin.settings.iconPosition === "front") {
64 | targetElements.push({from: node.from, to: node.to, value: linkText});
65 | }
66 | if (plugin.settings.iconPosition === "back") {
67 | targetElements.push({from: node.to, to: node.to + 1, value: linkText});
68 | }
69 | return;
70 | }
71 |
72 | if (!plugin.settings.showAliased) return;
73 |
74 | //scanning for the matching opening bracket of the alias, to get the correct position for the icon
75 | const line = view.state.doc.lineAt(node.from);
76 | const toLine = line.to - node.to;
77 | const toLineT = line.length - toLine;
78 | const lastIndex = line.text.lastIndexOf("]", toLineT);
79 | const open = findOpenParen(line.text, lastIndex);
80 | if (open === -1) {
81 | return;
82 | }
83 |
84 | const fromTarget = line.from + open;
85 | const fullText = view.state.sliceDoc(fromTarget, node.to);
86 | if (fullText.contains("|nofavicon")) return;
87 |
88 | if (plugin.settings.iconPosition === "front") {
89 | targetElements.push({from: fromTarget, to: node.to, value: linkText});
90 | }
91 | if (plugin.settings.iconPosition === "back") {
92 | targetElements.push({from: node.to, to: node.to + 1, value: linkText});
93 | }
94 | }
95 | }
96 | },
97 | });
98 | }
99 | this.decoManager.debouncedUpdate(targetElements);
100 | }
101 | }
102 | );
103 | }
104 |
105 | export function asyncDecoBuilderExt(plugin: FaviconPlugin) {
106 | return [iconDecorations.field, buildViewPlugin(plugin)];
107 | }
108 |
--------------------------------------------------------------------------------
/src/decoration/icon/IconWidget.ts:
--------------------------------------------------------------------------------
1 | import {WidgetType} from "@codemirror/view";
2 | import FaviconPlugin from "../../main";
3 | import {TokenSpec} from "../TokenSpec";
4 | import {IconElement} from "../../types";
5 |
6 | export class IconWidget extends WidgetType {
7 | qualifier: string;
8 | icon: IconElement;
9 | fallbackIcon: IconElement;
10 | plugin: FaviconPlugin;
11 | token: TokenSpec;
12 |
13 | constructor(plugin: FaviconPlugin, icon: IconElement, fallbackIcon: IconElement, qualifier: string, token: TokenSpec) {
14 | super();
15 | this.plugin = plugin;
16 | this.icon = icon;
17 | this.fallbackIcon = fallbackIcon;
18 | this.qualifier = qualifier;
19 | this.token = token;
20 | }
21 |
22 | override eq(other: IconWidget) {
23 | return other === this;
24 | }
25 |
26 | toDOM() {
27 | if (!this.icon || this.icon === "") {
28 | console.log("empty icon for " + this.qualifier);
29 | return activeDocument.createElement("span");
30 | }
31 |
32 | if (typeof this.icon !== "string") {
33 | return this.icon.cloneNode(true) as HTMLSpanElement;
34 | }
35 |
36 | if (!this.icon.startsWith("http")) {
37 | const span = activeDocument.createElement("span");
38 | span.textContent = this.icon;
39 | return span;
40 | }
41 |
42 | const span = activeDocument.createElement("span");
43 | this.plugin.iconAdder.getImageEl(this.icon, this.qualifier).then((obj) => {
44 | span.append(obj);
45 | }).catch((e) => {
46 | console.error(e);
47 | })
48 |
49 | return span;
50 |
51 | }
52 |
53 | override ignoreEvent(): boolean {
54 | return true;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/decoration/text/TextDecorationSet.ts:
--------------------------------------------------------------------------------
1 | import {Decoration, DecorationSet, EditorView} from "@codemirror/view";
2 | import FaviconPlugin from "../../main";
3 | import {debounce, Debouncer} from "obsidian";
4 | import {TokenSpec} from "../TokenSpec";
5 | import {Range} from "@codemirror/state";
6 | import {textRemovingDecorations} from "./TextRemovingDecoration";
7 |
8 | export class TextDecorationSet {
9 | editor: EditorView;
10 | plugin: FaviconPlugin;
11 | decoCache: { [cls: string]: Decoration } = Object.create(null);
12 | debouncedUpdate: Debouncer<[tokens: TokenSpec[]]>;
13 |
14 | constructor(editor: EditorView, plugin: FaviconPlugin) {
15 | this.editor = editor;
16 | this.plugin = plugin;
17 | this.debouncedUpdate = debounce(this.updateAsyncDecorations, this.plugin.settings.debounce, true);
18 | }
19 |
20 | async computeAsyncDecorations(tokens: TokenSpec[]): Promise {
21 | const decorations: Range[] = [];
22 | for (const token of tokens) {
23 | let deco = this.decoCache[token.value];
24 | if (!deco) {
25 | deco = this.decoCache[token.value] = Decoration.replace({});
26 | }
27 | decorations.push(deco.range(token.from, token.to));
28 | }
29 | return Decoration.set(decorations, true);
30 | }
31 |
32 | async updateAsyncDecorations(tokens: TokenSpec[]): Promise {
33 | const decorations = await this.computeAsyncDecorations(tokens);
34 | // if our compute function returned nothing and the state field still has decorations, clear them out
35 | if (decorations || this.editor.state.field(textRemovingDecorations.field).size) {
36 | this.editor.dispatch({ effects: textRemovingDecorations.update.of(decorations || Decoration.none) });
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/decoration/text/TextRemovingDecoration.ts:
--------------------------------------------------------------------------------
1 | import {EditorView, ViewPlugin, ViewUpdate} from "@codemirror/view";
2 | import {IconDecorationSet} from "../icon/IconDecorationSet";
3 | import {TokenSpec} from "../TokenSpec";
4 | import FaviconPlugin from "../../main";
5 | import {defineStatefulDecoration} from "../Decoration";
6 | import {TextDecorationSet} from "./TextDecorationSet";
7 | import {editorLivePreviewField} from "obsidian";
8 |
9 | export const textRemovingDecorations = defineStatefulDecoration();
10 |
11 | function buildViewPlugin(plugin: FaviconPlugin) {
12 | return ViewPlugin.fromClass(
13 | class {
14 | decoManager: IconDecorationSet;
15 |
16 |
17 | constructor(public view: EditorView) {
18 | this.decoManager = new TextDecorationSet(view, plugin);
19 |
20 | }
21 |
22 | update(update: ViewUpdate) {
23 | if (update.docChanged || update.viewportChanged || update.selectionSet) {
24 | this.buildAsyncDecorations(update.view);
25 | }
26 | }
27 |
28 | buildAsyncDecorations(view: EditorView) {
29 | const targetElements: TokenSpec[] = [];
30 | if (!view.state.field(editorLivePreviewField)) {
31 | this.decoManager.debouncedUpdate(targetElements);
32 | return;
33 | }
34 |
35 | for (const {from, to} of view.visibleRanges) {
36 | const text = view.state.sliceDoc(from, to);
37 | for (const match of text.matchAll(/\|nofavicon/g)) {
38 | const matchFrom = match.index;
39 | if (!matchFrom) continue;
40 | const matchTo = matchFrom + match[0].length;
41 | let inSelection = false;
42 | for (const range of view.state.selection.ranges) {
43 | if ((range.from <= matchFrom && range.to >= matchTo) || (range.from >= matchFrom && range.to <= matchTo)) {
44 | inSelection = true;
45 | }
46 | }
47 | if(!inSelection)
48 | targetElements.push({from: matchFrom, to: matchTo, value: ""});
49 | }
50 | }
51 | this.decoManager.debouncedUpdate(targetElements);
52 | }
53 | }
54 | );
55 | }
56 |
57 | export function textRemovingDecoration(plugin: FaviconPlugin) {
58 | return [textRemovingDecorations.field, buildViewPlugin(plugin)];
59 | }
60 |
--------------------------------------------------------------------------------
/src/decoration/text/TextWidget.ts:
--------------------------------------------------------------------------------
1 | import {EditorView, WidgetType} from "@codemirror/view";
2 |
3 | export class TextWidget extends WidgetType {
4 |
5 | private readonly text: string;
6 |
7 | constructor(text: string) {
8 | super();
9 | this.text = text;
10 | }
11 |
12 | toDOM(view: EditorView): HTMLElement {
13 | const el = document.createElement("span");
14 | el.setText(this.text);
15 | return el;
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/functions.ts:
--------------------------------------------------------------------------------
1 | export function findOpenParen(text: string, closePos: number): number {
2 | return findMatchingSymbol(text, closePos, "[", "]");
3 | }
4 |
5 | export function findMatchingSymbol(text: string, closePos: number, openSymbol: string, closingSymbol: string): number {
6 | if (!text.includes(openSymbol)) return 0;
7 | let openPos = closePos;
8 | let counter = 1;
9 | while (counter > 0) {
10 | const c = text[--openPos];
11 | if (c === undefined) break;
12 | if (c == openSymbol) {
13 | counter--;
14 | } else if (c == closingSymbol) {
15 | counter++;
16 | }
17 | }
18 | return openPos;
19 | }
20 |
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | import {Plugin} from 'obsidian';
2 | import {DEFAULT_SETTINGS, FaviconPluginSettings, FaviconSettings, OverwrittenFavicon} from "./settings";
3 | import {IconProvider} from "./provider";
4 | import {getApi} from "@aidenlx/obsidian-icon-shortcodes";
5 | import {PostProcessor} from "./PostProcessor";
6 | import {textRemovingDecoration} from "./decoration/text/TextRemovingDecoration";
7 | import {IconElement} from "./types";
8 | import {IconAdder} from "./IconAdder";
9 |
10 | export default class FaviconPlugin extends Plugin {
11 | settings!: FaviconPluginSettings;
12 | iconAdder!: IconAdder;
13 |
14 | private async getOverwrittenFavicon(favicons: OverwrittenFavicon[]) {
15 | const iconApi = getApi(this);
16 | if (!iconApi) return Promise.reject("No IconAPI loaded");
17 | if (favicons.length === 0) return Promise.reject("No icons");
18 |
19 | const icon = favicons[0].icon;
20 | if (iconApi.version.satisfies("^0.9.0")) {
21 | const result = await iconApi.getSVGIcon(icon);
22 | if (result) return result;
23 | return Promise.reject();
24 | }
25 | const result = await iconApi.getIcon(icon);
26 | if (result) return result;
27 | return Promise.reject();
28 |
29 | }
30 |
31 | async getCustomDomainIcon(domain: string): Promise {
32 | const icons = this.settings.overwritten.filter(value => domain.match(value.domain));
33 | return this.getOverwrittenFavicon(icons).then(res => res).catch(e => undefined);
34 | }
35 |
36 | async getCustomSchemeIcon(scheme: string): Promise {
37 | const icons = this.settings.protocol.filter(value => scheme.substr(0, scheme.length - 1).match(value.domain));
38 | return this.getOverwrittenFavicon(icons).then(res => res).catch(e => undefined);
39 |
40 | }
41 |
42 | async getIcon(link: string, provider: IconProvider): Promise {
43 |
44 | let url: URL;
45 | try {
46 | url = new URL(link);
47 | } catch (e) {
48 | return Promise.reject();
49 | }
50 |
51 | //custom protocols
52 | const customSchemeIcon = await this.getCustomSchemeIcon(url.protocol);
53 | if (customSchemeIcon) {
54 | if (typeof customSchemeIcon !== "string") {
55 | customSchemeIcon.addClass("link-favicon");
56 | customSchemeIcon.dataset.target = url.href;
57 | customSchemeIcon.dataset.protocol = url.protocol;
58 | }
59 | return customSchemeIcon;
60 | }
61 |
62 |
63 | //filtering out any empty values(otherwise no icons would show up ever)
64 | const ignoredDomains = this.settings.ignored.split("\n").filter(value => value.length > 0);
65 | if (ignoredDomains.some(value => url.hostname.match(new RegExp(value)))) {
66 | return Promise.reject();
67 | }
68 |
69 | //custom domain icons
70 | const customDomainIcon = await this.getCustomDomainIcon(url.hostname);
71 | if (customDomainIcon) {
72 | if (typeof customDomainIcon !== "string") {
73 | customDomainIcon.addClass("link-favicon");
74 | customDomainIcon.dataset.target = url.href;
75 | customDomainIcon.dataset.host = url.hostname;
76 | }
77 | return customDomainIcon;
78 | }
79 |
80 | try {
81 | return await provider.url(url.hostname, this.settings);
82 | } catch (e) {
83 | console.error(e);
84 | return Promise.reject();
85 | }
86 | return "";
87 | }
88 |
89 | /**
90 | * @returns true if Live Preview is supported
91 | */
92 | isUsingLivePreviewEnabledEditor(): boolean {
93 | //@ts-ignore
94 | return !app.vault.getConfig('legacyEditor');
95 | }
96 |
97 | override async onload() {
98 | console.log("enabling plugin: link favicons");
99 | await this.loadSettings();
100 | this.iconAdder = new IconAdder(this);
101 |
102 | const dir = this.app.vault.configDir + "/favicons/";
103 | if (await this.app.vault.adapter.exists(dir)) {
104 | await this.app.vault.adapter.rmdir(dir, true);
105 | }
106 |
107 | //respond to app events to fix #37
108 | this.registerEvent(this.app.workspace.on('css-change', () => {
109 | this.app.workspace.updateOptions();
110 | }));
111 |
112 | this.addSettingTab(new FaviconSettings(this.app, this));
113 |
114 | if (this.isUsingLivePreviewEnabledEditor()) {
115 | //eslint-disable-next-line @typescript-eslint/no-var-requires
116 | const asyncDecoBuilderExt = require('./decoration/icon/IconDecorations').asyncDecoBuilderExt;
117 | //eslint-disable-next-line @typescript-eslint/no-var-requires
118 | const Prec = require("@codemirror/state").Prec;
119 | this.registerEditorExtension(Prec.lowest(asyncDecoBuilderExt(this)));
120 | this.registerEditorExtension(Prec.lowest(textRemovingDecoration(this)));
121 | }
122 |
123 | const processor = new PostProcessor(this);
124 | this.registerMarkdownPostProcessor(processor.processor);
125 | this.app.workspace.updateOptions();
126 | }
127 |
128 | override onunload() {
129 | this.iconAdder.destruct();
130 | console.log("disabling plugin: link favicons");
131 | }
132 |
133 | async loadSettings() {
134 | this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
135 | }
136 |
137 | async saveSettings() {
138 | await this.saveData(this.settings);
139 | this.app.workspace.updateOptions();
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/src/provider.ts:
--------------------------------------------------------------------------------
1 | import {requestUrl} from "obsidian";
2 | import {FaviconPluginSettings} from "./settings";
3 |
4 | export interface IconProvider {
5 | name: string;
6 | url: (domain: string, settings: FaviconPluginSettings) => Promise;
7 | }
8 |
9 | export const providers: Record = {
10 | 'google': {name: 'Google', url: domain => Promise.resolve("https://www.google.com/s2/favicons?domain=" + domain)},
11 | 'duckduckgo': {
12 | name: 'DuckDuckGo',
13 | url: domain => Promise.resolve("https://icons.duckduckgo.com/ip3/" + domain + ".ico")
14 | },
15 | 'iconhorse': {name: 'Icon Horse', url: domain => Promise.resolve("https://icon.horse/icon/" + domain)},
16 | 'splitbee': {name: 'Splitbee', url: domain => Promise.resolve("https://favicon.splitbee.io/?url=" + domain)},
17 | 'besticon': {
18 | name: 'The Favicon Finder', url: async (domain, settings) => {
19 | try {
20 | const host = settings.provider === "besticon" ? settings.providerDomain : settings.fallbackProviderDomain;
21 | const result = await requestUrl({url: host + "/allicons.json?url=" + domain});
22 | if (result.json.icons.length === 0) return Promise.reject("besticon: no icons for domain " + domain);
23 | return Promise.resolve(result.json.icons[0].url);
24 | } catch (e) {
25 | console.error(e);
26 | return Promise.reject("besticon: failed to retrieve icon for " + domain);
27 | }
28 | }
29 | },
30 | 'favicongrabber': {
31 | name: 'Favicon Grabber', url: (async (domain) => {
32 | try {
33 | const result = await requestUrl({url: "https://favicongrabber.com/api/grab/" + domain});
34 | if (result.json.length === 0) return Promise.resolve("");
35 | return Promise.resolve(result.json.icons[0].src);
36 | } catch (e) {
37 | console.error(e);
38 | return Promise.reject("favicongrabber: failed to retrieve icon for domain " + domain);
39 | }
40 | }
41 | )
42 | },
43 | }
44 |
--------------------------------------------------------------------------------
/src/settings.ts:
--------------------------------------------------------------------------------
1 | import {App, ButtonComponent, Notice, PluginSettingTab, Setting} from "obsidian";
2 | import FaviconPlugin from "./main";
3 | import {providers} from "./provider";
4 | import {OverwrittenIconModal} from "./OverwrittenIconModal";
5 | import {getApi, isPluginEnabled} from "@aidenlx/obsidian-icon-shortcodes";
6 | import {ProviderTestModal} from "./ProviderTestModal";
7 | import ls from "localstorage-slim";
8 |
9 | export interface OverwrittenFavicon {
10 | domain: string,
11 | icon: string,
12 | }
13 |
14 | export interface FaviconPluginSettings {
15 | provider: string;
16 | fallbackProvider: string;
17 | providerDomain: string;
18 | fallbackProviderDomain: string;
19 | ignored: string;
20 | overwritten: OverwrittenFavicon[];
21 | protocol: OverwrittenFavicon[];
22 | showAliased: boolean;
23 | showLink: boolean;
24 | enableReading: boolean,
25 | enableSource: boolean,
26 | enableLivePreview: boolean,
27 | debounce: number,
28 | iconPosition: string,
29 | colorInversion: boolean,
30 | }
31 |
32 | export const DEFAULT_SETTINGS: FaviconPluginSettings = {
33 | provider: 'duckduckgo',
34 | fallbackProvider: 'google',
35 | providerDomain: '',
36 | fallbackProviderDomain: '',
37 | ignored: '',
38 | overwritten: [],
39 | protocol: [],
40 | showAliased: true,
41 | showLink: true,
42 | enableReading: true,
43 | enableSource: true,
44 | enableLivePreview: true,
45 | debounce: 500,
46 | iconPosition: 'front',
47 | colorInversion: true,
48 | }
49 |
50 | export class FaviconSettings extends PluginSettingTab {
51 | plugin: FaviconPlugin;
52 |
53 | constructor(app: App, plugin: FaviconPlugin) {
54 | super(app, plugin);
55 | this.plugin = plugin;
56 | }
57 |
58 | display(): void {
59 | const {containerEl} = this;
60 |
61 | containerEl.empty();
62 |
63 | new Setting(containerEl)
64 | .setName("Icon provider")
65 | .addDropdown((dropdown) => {
66 | for (const id in providers) {
67 | if (providers.hasOwnProperty(id)) {
68 | dropdown.addOption(id, providers[id].name);
69 | }
70 | }
71 | dropdown
72 | .setValue(this.plugin.settings.provider)
73 | .onChange(async (value) => {
74 | this.plugin.settings.provider = value;
75 | await this.plugin.saveSettings();
76 | this.display();
77 | })
78 | });
79 |
80 | if (Array.of("besticon").includes(this.plugin.settings.provider)) {
81 | new Setting(containerEl)
82 | .setName('Provider domain')
83 | .setDesc('This Provider is selfhosted, please specify your deployment url. Refer to the readme of the provider for deployment instructions.')
84 | .addText(text => text
85 | .setValue(this.plugin.settings.providerDomain)
86 | .onChange(async (value) => {
87 | this.plugin.settings.providerDomain = value;
88 | await this.plugin.saveSettings();
89 | }));
90 | }
91 |
92 | new Setting(containerEl)
93 | .setName("Fallback icon provider")
94 | .addDropdown((dropdown) => {
95 | for (const id in providers) {
96 | if (providers.hasOwnProperty(id)) {
97 | dropdown.addOption(id, providers[id].name);
98 | }
99 | }
100 | dropdown
101 | .setValue(this.plugin.settings.fallbackProvider)
102 | .onChange(async (value) => {
103 | this.plugin.settings.fallbackProvider = value;
104 | await this.plugin.saveSettings();
105 | this.display();
106 | })
107 | });
108 |
109 | if (Array.of("besticon").includes(this.plugin.settings.fallbackProvider)) {
110 | new Setting(containerEl)
111 | .setName('Fallback provider domain')
112 | .setDesc('This Provider is be selfhosted, please specify your deployment url. Refer to the readme of the provider for deployment instructions.')
113 | .addText(text => text
114 | .setValue(this.plugin.settings.fallbackProviderDomain)
115 | .onChange(async (value) => {
116 | this.plugin.settings.fallbackProviderDomain = value;
117 | await this.plugin.saveSettings();
118 | }));
119 | }
120 |
121 | new Setting(containerEl)
122 | .setName('Not sure which provider to choose?')
123 | .addButton(button =>
124 | button.setButtonText("Test Providers")
125 | .onClick(() => {
126 | new ProviderTestModal(this.plugin).open();
127 | })
128 | );
129 |
130 |
131 | new Setting(containerEl)
132 | .setName('Ignored domains')
133 | .setDesc("Don't show an favicon for these domains(one per line)")
134 | .addTextArea(text => {
135 | text
136 | .setValue(this.plugin.settings.ignored)
137 | .onChange(async (value) => {
138 | this.plugin.settings.ignored = value;
139 | await this.plugin.saveSettings();
140 | })
141 | text.inputEl.setAttr("rows", 8);
142 | }
143 | );
144 |
145 | containerEl.createEl("h2", {text: "Design"});
146 |
147 | new Setting(containerEl)
148 | .setName('Show icon when link has alias')
149 | .setDesc('When link is formatted like: [Obsidian](https://obsidian.md/)')
150 | .addToggle(toggle => {
151 | toggle
152 | .setValue(this.plugin.settings.showAliased)
153 | .onChange(async (value) => {
154 | this.plugin.settings.showAliased = value;
155 | await this.plugin.saveSettings();
156 | });
157 | });
158 |
159 | new Setting(containerEl)
160 | .setName('Show icon when link has no alias')
161 | .setDesc('When link is formatted like: https://obsidian.md/')
162 | .addToggle(toggle => {
163 | toggle
164 | .setValue(this.plugin.settings.showLink)
165 | .onChange(async (value) => {
166 | this.plugin.settings.showLink = value;
167 | await this.plugin.saveSettings();
168 | });
169 | });
170 |
171 | containerEl.createEl("hr");
172 |
173 | new Setting(containerEl)
174 | .setName('Show in Reading mode')
175 | .addToggle(toggle => {
176 | toggle
177 | .setValue(this.plugin.settings.enableReading)
178 | .onChange(async (value) => {
179 | this.plugin.settings.enableReading = value;
180 | await this.plugin.saveSettings();
181 | });
182 | });
183 |
184 | new Setting(containerEl)
185 | .setName('Show in Source mode')
186 | .addToggle(toggle => {
187 | toggle
188 | .setValue(this.plugin.settings.enableSource)
189 | .onChange(async (value) => {
190 | this.plugin.settings.enableSource = value;
191 | await this.plugin.saveSettings();
192 | });
193 | });
194 |
195 | new Setting(containerEl)
196 | .setName('Show in live preview')
197 | .addToggle(toggle => {
198 | toggle
199 | .setValue(this.plugin.settings.enableLivePreview)
200 | .onChange(async (value) => {
201 | this.plugin.settings.enableLivePreview = value;
202 | await this.plugin.saveSettings();
203 | });
204 | });
205 |
206 | new Setting(containerEl)
207 | .setName("Icon Position")
208 | .addDropdown(dropdown => {
209 | dropdown
210 | .addOption('front', "Before the link")
211 | .addOption('back', "After the link")
212 | .setValue(this.plugin.settings.iconPosition)
213 | .onChange(async(value) => {
214 | this.plugin.settings.iconPosition = value;
215 | await this.plugin.saveSettings();
216 | });
217 | });
218 |
219 | new Setting(containerEl)
220 | .setName('Color inversion')
221 | .setDesc('Favicon colors will be automatically inverted if the icon is detected to be less readable')
222 | .addToggle(toggle => {
223 | toggle
224 | .setValue(this.plugin.settings.colorInversion)
225 | .onChange(async value => {
226 | this.plugin.settings.colorInversion = value;
227 | await this.plugin.saveSettings();
228 | });
229 | });
230 |
231 | if (isPluginEnabled(this.plugin)) {
232 | const iconAPI = getApi(this.plugin)!;
233 | containerEl.createEl("h2", {text: "Custom icons"});
234 |
235 | containerEl.createEl("h3", {text: "for domains"});
236 |
237 | new Setting(containerEl)
238 | .setName("Add new")
239 | .setDesc("Add custom icon")
240 | .addButton((button: ButtonComponent): ButtonComponent => {
241 | return button
242 | .setTooltip("add custom icon")
243 | .setIcon("plus-with-circle")
244 | .onClick(async () => {
245 | const modal = new OverwrittenIconModal(this.plugin);
246 |
247 | modal.onClose = async () => {
248 | if (modal.saved) {
249 | this.plugin.settings.overwritten.push({
250 | domain: modal.domain,
251 | icon: modal.icon
252 | });
253 | await this.plugin.saveSettings();
254 |
255 | this.display();
256 | }
257 | };
258 |
259 | modal.open();
260 | });
261 | });
262 |
263 |
264 | const overwrittenContainer = containerEl.createDiv("overwritten");
265 |
266 | const overwrittenDiv = overwrittenContainer.createDiv("overwritten");
267 | for (const overwritten of this.plugin.settings.overwritten) {
268 | const setting = new Setting(overwrittenDiv);
269 |
270 | const desc = new DocumentFragment();
271 | desc.createEl("p", {text: " " + overwritten.icon}).prepend(iconAPI.getIcon(overwritten.icon)!);
272 |
273 | setting
274 | .setName(overwritten.domain)
275 | .setDesc(desc)
276 | .addExtraButton((b) => {
277 | b.setIcon("pencil")
278 | .setTooltip("Edit")
279 | .onClick(() => {
280 | const modal = new OverwrittenIconModal(this.plugin, overwritten);
281 |
282 | modal.onClose = async () => {
283 | if (modal.saved) {
284 | const setting = this.plugin.settings.overwritten.filter((overwritten) => {
285 | return overwritten.domain !== modal.domain;
286 | })
287 | setting.push({domain: modal.domain, icon: modal.icon});
288 | this.plugin.settings.overwritten = setting;
289 | await this.plugin.saveSettings();
290 |
291 | this.display();
292 | }
293 | };
294 |
295 | modal.open();
296 | });
297 | })
298 | .addExtraButton((b) => {
299 | b.setIcon("trash")
300 | .setTooltip("Delete")
301 | .onClick(async () => {
302 | this.plugin.settings.overwritten = this.plugin.settings.overwritten.filter((tmp) => {
303 | return overwritten.domain !== tmp.domain;
304 | });
305 | await this.plugin.saveSettings();
306 | this.display();
307 | });
308 | });
309 |
310 |
311 | }
312 |
313 |
314 | containerEl.createEl("h3", {text: "for URI schemas"});
315 |
316 | new Setting(containerEl)
317 | .setName("Add new")
318 | .setDesc("Add custom icon")
319 | .addButton((button: ButtonComponent): ButtonComponent => {
320 | return button
321 | .setTooltip("add custom icon")
322 | .setIcon("plus-with-circle")
323 | .onClick(async () => {
324 | const modal = new OverwrittenIconModal(this.plugin, null, "URI Schema");
325 |
326 | modal.onClose = async () => {
327 | if (modal.saved) {
328 | this.plugin.settings.protocol.push({
329 | domain: modal.domain,
330 | icon: modal.icon
331 | });
332 | await this.plugin.saveSettings();
333 |
334 | this.display();
335 | }
336 | };
337 |
338 | modal.open();
339 | });
340 | });
341 |
342 |
343 | const protocolContainer = containerEl.createDiv("overwritten");
344 |
345 | const protocolDiv = protocolContainer.createDiv("overwritten");
346 | for (const protocol of this.plugin.settings.protocol) {
347 | const setting = new Setting(protocolDiv);
348 |
349 | const desc = new DocumentFragment();
350 | desc.createEl("p", {text: " " + protocol.icon}).prepend(iconAPI.getIcon(protocol.icon)!);
351 |
352 | setting
353 | .setName(protocol.domain)
354 | .setDesc(desc)
355 | .addExtraButton((b) => {
356 | b.setIcon("pencil")
357 | .setTooltip("Edit")
358 | .onClick(() => {
359 | const modal = new OverwrittenIconModal(this.plugin, protocol, "URI Schema");
360 |
361 | modal.onClose = async () => {
362 | if (modal.saved) {
363 | const setting = this.plugin.settings.protocol.filter((overwritten) => {
364 | return overwritten.domain !== modal.domain;
365 | })
366 | setting.push({domain: modal.domain, icon: modal.icon});
367 | this.plugin.settings.protocol = setting;
368 | await this.plugin.saveSettings();
369 | this.display();
370 | }
371 | };
372 |
373 | modal.open();
374 | });
375 | })
376 | .addExtraButton((b) => {
377 | b.setIcon("trash")
378 | .setTooltip("Delete")
379 | .onClick(async () => {
380 | this.plugin.settings.protocol = this.plugin.settings.protocol.filter((overwritten) => {
381 | return overwritten.domain !== protocol.domain;
382 | });
383 | await this.plugin.saveSettings();
384 | this.display();
385 | });
386 | });
387 |
388 |
389 | }
390 |
391 | const details = containerEl.createEl("details");
392 | details.createEl("summary", {text: 'Advanced'});
393 | const advanced = details.createDiv("advanced");
394 |
395 | new Setting(advanced)
396 | .setName('Debounce')
397 | .setDesc('How fast after editing a link should a icon be displayed(in milliseconds)?')
398 | .addSlider(slider => {
399 | slider
400 | .setLimits(1, 2500, 1)
401 | .setDynamicTooltip()
402 | .setValue(this.plugin.settings.debounce)
403 | .onChange(async (value) => {
404 | this.plugin.settings.debounce = value;
405 | await this.plugin.saveSettings();
406 | });
407 | });
408 |
409 | }
410 |
411 | if(localStorage.getItem('debug-plugin') === '1') {
412 | containerEl.createEl('h1', {text: 'Debugging tools'});
413 | containerEl.createEl('p', {text: 'Only use these tools if you know what you are doing'});
414 |
415 | const cachedDetails = containerEl.createEl('details');
416 | cachedDetails.createEl('summary', {text: 'Cached icons'});
417 | const cached = cachedDetails.createDiv('cached');
418 | Object.keys(localStorage).forEach((key) => {
419 | if(key.startsWith("lf-")) {
420 | cached.createEl('p', {text: key});
421 | cached.createEl('img', {attr: {src: ls.get(key)}});
422 | }
423 | });
424 |
425 | new Setting(containerEl)
426 | .setName('Clear icon cache')
427 | .setDesc('Remove all icons from cache')
428 | .addButton(button => {
429 | button.setButtonText('Clear')
430 | .onClick(() => {
431 | Object.keys(localStorage).forEach((key) => {
432 | if(key.startsWith("lf-")) {
433 | localStorage.removeItem(key);
434 | }
435 | });
436 | new Notice("Cleared cache");
437 | this.display();
438 | });
439 | });
440 | }
441 | }
442 | }
443 |
--------------------------------------------------------------------------------
/src/styles.scss:
--------------------------------------------------------------------------------
1 |
2 |
3 | .link-favicon {
4 | vertical-align: bottom;
5 | margin-bottom: 0.3em;
6 | margin-left: 0.1em;
7 | margin-right: 0.1em;
8 | cursor: pointer !important;
9 | image-rendering: -webkit-optimize-contrast;
10 | max-height: 1em;
11 | }
12 |
13 | .link-favicon-preview {
14 | font-size: 50px;
15 | text-align: center;
16 | }
17 |
18 | .link-favicon-preview img {
19 | height: 50px;
20 | }
21 |
22 | .link-favicon[data-color-inversion="true"][data-is-readable-a-a="false"] {
23 | filter: hue-rotate(180deg) invert(1);
24 | }
25 |
26 | .link-favicon-scrollable-content {
27 | overflow: auto;
28 | height: 60vh;
29 | }
30 |
--------------------------------------------------------------------------------
/src/suggest.ts:
--------------------------------------------------------------------------------
1 | // Credits go to Liam's Periodic Notes Plugin: https://github.com/liamcain/obsidian-periodic-notes
2 |
3 | import { App, ISuggestOwner, Scope } from "obsidian";
4 | import { createPopper, Instance as PopperInstance } from "@popperjs/core";
5 |
6 | const wrapAround = (value: number, size: number): number => {
7 | return ((value % size) + size) % size;
8 | };
9 |
10 | class Suggest {
11 | private owner: ISuggestOwner;
12 | private values: T[];
13 | private suggestions: HTMLDivElement[];
14 | private selectedItem: number;
15 | private containerEl: HTMLElement;
16 |
17 | constructor(
18 | owner: ISuggestOwner,
19 | containerEl: HTMLElement,
20 | scope: Scope
21 | ) {
22 | this.owner = owner;
23 | this.containerEl = containerEl;
24 |
25 | containerEl.on(
26 | "click",
27 | ".suggestion-item",
28 | this.onSuggestionClick.bind(this)
29 | );
30 | containerEl.on(
31 | "mousemove",
32 | ".suggestion-item",
33 | this.onSuggestionMouseover.bind(this)
34 | );
35 |
36 | scope.register([], "ArrowUp", (event) => {
37 | if (!event.isComposing) {
38 | this.setSelectedItem(this.selectedItem - 1, true);
39 | return false;
40 | }
41 | });
42 |
43 | scope.register([], "ArrowDown", (event) => {
44 | if (!event.isComposing) {
45 | this.setSelectedItem(this.selectedItem + 1, true);
46 | return false;
47 | }
48 | });
49 |
50 | scope.register([], "Enter", (event) => {
51 | if (!event.isComposing) {
52 | this.useSelectedItem(event);
53 | return false;
54 | }
55 | });
56 | }
57 |
58 | onSuggestionClick(event: MouseEvent, el: HTMLDivElement): void {
59 | event.preventDefault();
60 |
61 | const item = this.suggestions.indexOf(el);
62 | this.setSelectedItem(item, false);
63 | this.useSelectedItem(event);
64 | }
65 |
66 | onSuggestionMouseover(_event: MouseEvent, el: HTMLDivElement): void {
67 | const item = this.suggestions.indexOf(el);
68 | this.setSelectedItem(item, false);
69 | }
70 |
71 | setSuggestions(values: T[]) {
72 | this.containerEl.empty();
73 | const suggestionEls: HTMLDivElement[] = [];
74 |
75 | values.forEach((value) => {
76 | const suggestionEl = this.containerEl.createDiv("suggestion-item");
77 | this.owner.renderSuggestion(value, suggestionEl);
78 | suggestionEls.push(suggestionEl);
79 | });
80 |
81 | this.values = values;
82 | this.suggestions = suggestionEls;
83 | this.setSelectedItem(0, false);
84 | }
85 |
86 | useSelectedItem(event: MouseEvent | KeyboardEvent) {
87 | const currentValue = this.values[this.selectedItem];
88 | if (currentValue) {
89 | this.owner.selectSuggestion(currentValue, event);
90 | }
91 | }
92 |
93 | setSelectedItem(selectedIndex: number, scrollIntoView: boolean) {
94 | const normalizedIndex = wrapAround(
95 | selectedIndex,
96 | this.suggestions.length
97 | );
98 | const prevSelectedSuggestion = this.suggestions[this.selectedItem];
99 | const selectedSuggestion = this.suggestions[normalizedIndex];
100 |
101 | prevSelectedSuggestion?.removeClass("is-selected");
102 | selectedSuggestion?.addClass("is-selected");
103 |
104 | this.selectedItem = normalizedIndex;
105 |
106 | if (scrollIntoView) {
107 | selectedSuggestion.scrollIntoView(false);
108 | }
109 | }
110 | }
111 |
112 | export abstract class TextInputSuggest implements ISuggestOwner {
113 | protected app: App;
114 | protected inputEl: HTMLInputElement | HTMLTextAreaElement;
115 |
116 | private popper: PopperInstance;
117 | private scope: Scope;
118 | private suggestEl: HTMLElement;
119 | private suggest: Suggest;
120 |
121 | constructor(app: App, inputEl: HTMLInputElement | HTMLTextAreaElement) {
122 | this.app = app;
123 | this.inputEl = inputEl;
124 | this.scope = new Scope();
125 |
126 | this.suggestEl = createDiv("suggestion-container");
127 | const suggestion = this.suggestEl.createDiv("suggestion");
128 | this.suggest = new Suggest(this, suggestion, this.scope);
129 |
130 | this.scope.register([], "Escape", this.close.bind(this));
131 |
132 | this.inputEl.addEventListener("input", this.onInputChanged.bind(this));
133 | this.inputEl.addEventListener("focus", this.onInputChanged.bind(this));
134 | this.inputEl.addEventListener("blur", this.close.bind(this));
135 | this.suggestEl.on(
136 | "mousedown",
137 | ".suggestion-container",
138 | (event: MouseEvent) => {
139 | event.preventDefault();
140 | }
141 | );
142 | }
143 |
144 | onInputChanged(): void {
145 | const inputStr = this.inputEl.value;
146 | const suggestions = this.getSuggestions(inputStr);
147 |
148 | if (!suggestions) {
149 | this.close();
150 | return;
151 | }
152 |
153 | if (suggestions.length > 0) {
154 | this.suggest.setSuggestions(suggestions);
155 | // eslint-disable-next-line @typescript-eslint/no-explicit-any
156 | this.open((this.app).dom.appContainerEl, this.inputEl);
157 | } else {
158 | this.close();
159 | }
160 | }
161 |
162 | open(container: HTMLElement, inputEl: HTMLElement): void {
163 | // eslint-disable-next-line @typescript-eslint/no-explicit-any
164 | (this.app).keymap.pushScope(this.scope);
165 |
166 | container.appendChild(this.suggestEl);
167 | this.popper = createPopper(inputEl, this.suggestEl, {
168 | placement: "bottom-start",
169 | modifiers: [
170 | {
171 | name: "sameWidth",
172 | enabled: true,
173 | fn: ({ state, instance }) => {
174 | // Note: positioning needs to be calculated twice -
175 | // first pass - positioning it according to the width of the popper
176 | // second pass - position it with the width bound to the reference element
177 | // we need to early exit to avoid an infinite loop
178 | const targetWidth = `${state.rects.reference.width}px`;
179 | if (state.styles.popper.width === targetWidth) {
180 | return;
181 | }
182 | state.styles.popper.width = targetWidth;
183 | instance.update();
184 | },
185 | phase: "beforeWrite",
186 | requires: ["computeStyles"],
187 | },
188 | ],
189 | });
190 | }
191 |
192 | close(): void {
193 | // eslint-disable-next-line @typescript-eslint/no-explicit-any
194 | (this.app).keymap.popScope(this.scope);
195 |
196 | this.suggest.setSuggestions([]);
197 | if (this.popper) this.popper.destroy();
198 | this.suggestEl.detach();
199 | }
200 |
201 | abstract getSuggestions(inputStr: string): { name: string; description: string }[];
202 | abstract renderSuggestion(item: T, el: HTMLElement): void;
203 | abstract selectSuggestion(item: T): void;
204 | }
205 |
--------------------------------------------------------------------------------
/src/types.ts:
--------------------------------------------------------------------------------
1 | export type IconElement = string | HTMLImageElement | HTMLSpanElement;
2 |
--------------------------------------------------------------------------------
/test/functions.test.ts:
--------------------------------------------------------------------------------
1 | import {findMatchingSymbol} from "../src/functions";
2 |
3 | test('find matching symbol', () => {
4 | expect(findMatchingSymbol("test test", 5, "(", ")")).toBe(-1);
5 | expect(findMatchingSymbol("test( test)", 11, "(", ")")).toBe(4);
6 | });
7 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": ".",
4 | "inlineSourceMap": true,
5 | "inlineSources": true,
6 | "module": "ESNext",
7 | "target": "ES6",
8 | "allowJs": false,
9 | "noImplicitAny": true,
10 | "strictNullChecks": true,
11 | "strictFunctionTypes": true,
12 | "strictBindCallApply": true,
13 | "noImplicitOverride": true,
14 | "noImplicitReturns": true,
15 | "noImplicitThis": true,
16 | "alwaysStrict": true,
17 | "strictPropertyInitialization": true,
18 | "moduleResolution": "node",
19 | "importHelpers": true,
20 | "resolveJsonModule": true,
21 | "esModuleInterop": true,
22 | "lib": [
23 | "DOM",
24 | "ES5",
25 | "ES6",
26 | "ES7"
27 | ]
28 | },
29 | "include": [
30 | "**/*.ts"
31 | ]
32 | }
33 |
--------------------------------------------------------------------------------
/versions.json:
--------------------------------------------------------------------------------
1 | {
2 | "1.0.0": "0.12.0",
3 | "1.1.0": "0.12.0",
4 | "1.2.0": "0.12.0",
5 | "1.2.1": "0.12.0",
6 | "1.2.2": "0.12.0",
7 | "1.3.0": "0.13.14",
8 | "1.3.1": "0.13.14",
9 | "1.3.2": "0.13.14",
10 | "1.3.3": "0.13.14",
11 | "1.4.0": "0.13.14",
12 | "1.4.1": "0.13.14",
13 | "1.4.2": "0.13.14",
14 | "1.4.3": "0.13.14",
15 | "1.4.4": "0.13.14",
16 | "1.5.0": "0.13.14",
17 | "1.6.0": "0.13.14",
18 | "1.6.1": "0.13.14",
19 | "1.6.2": "0.13.14",
20 | "1.6.3": "0.13.14",
21 | "1.7.0": "0.13.30",
22 | "1.7.1": "0.13.30",
23 | "1.7.2": "0.13.30",
24 | "1.7.3": "0.13.30",
25 | "1.7.4": "0.15.0",
26 | "1.8.0": "0.15.0",
27 | "1.8.1": "0.15.0",
28 | "1.8.2": "1.3.0",
29 | "1.8.3": "1.3.0"
30 | }
31 |
--------------------------------------------------------------------------------