├── .editorconfig
├── .eslintignore
├── .eslintrc
├── .gitignore
├── .npmrc
├── LICENSE
├── README.md
├── assets
├── coffee.png
├── eaglefolderid.gif
├── fromeagle.gif
├── imagesize.gif
├── menu.png
├── menucall.gif
├── searchid.gif
├── searchname.gif
├── setting.png
├── synch.gif
├── upload.gif
├── url.gif
├── urlfromeagle.gif
└── zoom.gif
├── doc
├── ReadmeZH.md
├── Tutorial.md
└── TutorialZH.md
├── esbuild.config.mjs
├── manifest.json
├── package-lock.json
├── package.json
├── src
├── Leftclickimage.ts
├── addCommand-config.ts
├── eaglejumpobsidian.ts
├── embed-state-field.ts
├── embed-widget.ts
├── embed.ts
├── main.ts
├── menucall.ts
├── onElement.ts
├── server.ts
├── setting.ts
├── synchronizedpagetabs.ts
└── urlHandler.ts
├── styles.css
├── tsconfig.json
├── typings
└── a.d.ts
├── version-bump.mjs
└── versions.json
/.editorconfig:
--------------------------------------------------------------------------------
1 | # top-most EditorConfig file
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | end_of_line = lf
7 | insert_final_newline = true
8 | indent_style = tab
9 | indent_size = 4
10 | tab_width = 4
11 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 |
3 | main.js
4 |
--------------------------------------------------------------------------------
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "root": true,
3 | "parser": "@typescript-eslint/parser",
4 | "env": { "node": true },
5 | "plugins": [
6 | "@typescript-eslint"
7 | ],
8 | "extends": [
9 | "eslint:recommended",
10 | "plugin:@typescript-eslint/eslint-recommended",
11 | "plugin:@typescript-eslint/recommended"
12 | ],
13 | "parserOptions": {
14 | "sourceType": "module"
15 | },
16 | "rules": {
17 | "no-unused-vars": "off",
18 | "@typescript-eslint/no-unused-vars": ["error", { "args": "none" }],
19 | "@typescript-eslint/ban-ts-comment": "off",
20 | "no-prototype-builtins": "off",
21 | "@typescript-eslint/no-empty-function": "off"
22 | }
23 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # vscode
2 | .vscode
3 |
4 | # Intellij
5 | *.iml
6 | .idea
7 |
8 | # npm
9 | node_modules
10 |
11 | # Don't include the compiled main.js file in the repo.
12 | # They should be uploaded to GitHub releases instead.
13 | main.js
14 |
15 | # Exclude sourcemaps
16 | *.map
17 |
18 | # obsidian
19 | data.json
20 |
21 | # Exclude macOS Finder (System Explorer) View States
22 | .DS_Store
23 |
--------------------------------------------------------------------------------
/.npmrc:
--------------------------------------------------------------------------------
1 | tag-version-prefix=""
--------------------------------------------------------------------------------
/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 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Obsidian EagleBridge
2 |
3 | 【[中文](./doc/ReadmeZH.md) / EN】
4 |
5 | This is a sample plugin for Obsidian, designed to integrate Obsidian with the Eagle software.
6 |
7 | [eagle](https://eagle.cool) is a powerful attachment management software that allows for easy management of large quantities of images, videos, and audio materials, suitable for various scenarios such as collection, organization, and search. It supports Windows systems.
8 |
9 | ## Features Overview
10 |
11 | This plugin includes the following functionalities:
12 |
13 | - Quick eagle attachment navigation in Obsidian
14 | - Tag synchronization
15 | - File viewing
16 | - Attachment management
17 |
18 | [](https://github.com/zyjGraphein/Obsidian-EagleBridge/stargazers)
19 | [](https://github.com/zyjGraphein/Obsidian-EagleBridge/releases)
20 | [](https://github.com/zyjGraphein/Obsidian-EagleBridge/releases/latest)
21 | 
22 | 
23 | [](https://github.com/zyjGraphein/Obsidian-EagleBridge/blob/master/LICENSE)
24 | [](https://github.com/zyjGraphein/Obsidian-EagleBridge/issues)
25 | [](https://github.com/zyjGraphein/Obsidian-EagleBridge/commits/master)
26 |
27 | ## Initial Setup Instructions
28 |
29 | 1. **Configure the Listening Port**: Set a four-digit, complex value between 1000 and 9999 (e.g., 6060) to avoid conflicts with common port numbers. Once set, it is recommended not to change it to ensure stable attachment links.
30 |
31 | 2. **Set Eagle Library Location**: Select the library in the top left corner of the Eagle software and copy its path, for example: `D:\onedrive\eagle\Library`.
32 |
33 | You need to restart Obsidian after completing these configurations, and then you can start using the plugin.
34 |
35 |
36 | ## Showcase
37 |
38 | ### Load Attachments from Eagle
39 |
40 |
41 |
42 | ### Upload Local Attachments to Eagle via EagleBridge and View in Obsidian
43 |
44 |
45 |
46 |
47 | ## Installation Instructions
48 |
49 | ### Install via BRAT
50 |
51 | Add `https://github.com/zyjGraphein/Obsidian-EagleBridge` to [BRAT](https://github.com/TfTHacker/obsidian42-brat).
52 |
53 | ### Manual Installation
54 |
55 | Visit the latest release page, download `main.js`, `manifest.json`, and `style.css`, then place them into `/.obsidian/plugins/EagleBridge/`.
56 |
57 |
58 | ## Usage Guide
59 |
60 | - Text Tutorial ([中文](./doc/TutorialZH.md) / [EN](./doc/Tutorial.md))
61 | - Video Tutorial ([Obsidian EagleBridge -bilibili](https://www.bilibili.com/video/BV1voQsYaE5W/?share_source=copy_web&vd_source=491bedf306ddb53a3baa114332c02b93))
62 |
63 |
64 | ### Notes
65 | - When using the plugin, Eagle must be running in the background, and the open state should correspond to the repository at the specified path.
66 | - If Eagle is not running or is not in the target path repository, you can still view images, but the context menu functions and attachment uploads to Eagle will not work.
67 | - When exporting notes as a PDF, images will display correctly, but other links (URLs, PDFs, MP4s) will still be clickable. However, when shared with others (outside the local environment), these links may not open.
68 |
69 | ## Development Guide
70 |
71 | This plugin follows the structure of the [Obsidian Sample Plugin](https://github.com/obsidianmd/obsidian-sample-plugin). More details can be found there.
72 |
73 | - Clone this repository
74 | - Ensure your NodeJS is at least v16 (`node --version`)
75 | - Run `npm i` or `yarn` to install dependencies
76 | - Run `npm run dev` to start the compiler in watch mode
77 |
78 |
79 | ## To-Do List
80 |
81 | - [x] Support embedded previews for various file formats (e.g., PDF, MP4, PSD, OBJ, etc.)
82 | - [ ] Add support for macOS.
83 | - [ ] Support updating position when dragging.
84 | - [ ] When exporting, replace all attachment links and export all attachments to a folder.
85 |
86 | ## Known Limitations
87 |
88 | Currently, there is no effective method to prevent accidental deletion of attachments when traversing all file references. It is recommended to delete within Eagle and use ID retrieval to remove links in `.md` files.
89 |
90 |
91 | ## Issues and Suggestions
92 |
93 | You are welcome to submit issues for:
94 |
95 | - Bug reports
96 | - Ideas for new features
97 | - Optimizations for existing features
98 |
99 | If you are considering developing a large feature, please contact me first so we can determine if it is a good fit for this plugin.
100 |
101 |
102 | ## Credits
103 | This plugin also utilizes API calls from [eagle](https://api.eagle.cool/) to enable viewing, editing, and uploading of Eagle content.
104 |
105 | The right-click functionality and image zooming in this plugin draw inspiration from [AttachFlow](https://github.com/Yaozhuwa/AttachFlow)
106 |
107 | Video and PDF external link embedding previews are inspired by the corresponding features of [auto-embed](https://github.com/GnoxNahte/obsidian-auto-embed).
108 |
109 | Additionally, it is also inspired by some features from[PicGo+Eagle+Python](https://zhuanlan.zhihu.com/p/695526765), [obsidian-auto-link-title](https://github.com/zolrath/obsidian-auto-link-title) and [obsidian-image-auto-upload-plugin](https://github.com/renmu123/obsidian-image-auto-upload-plugin).
110 |
111 | Additionally, support from the Obsidian forum ([get-the-source-path-when-drag-and-drop-or-copying-a-file-image-from-outside](https://forum.obsidian.md/t/how-to-get-the-source-path-when-drag-and-drop-or-copying-a-file-image-from-outside/96437)) helped in implementing the ability to capture file sources via copying or dragging.
112 |
113 |
114 | ## License
115 |
116 | This project is licensed under the [GNU General Public License v3 (GPL-3.0)](https://github.com/zyjGraphein/EagleBridge/blob/master/LICENSE).
117 |
118 |
119 | ## Support
120 |
121 | If you appreciate this plugin and want to say thanks, you can buy me a coffee!
122 |
123 |
--------------------------------------------------------------------------------
/assets/coffee.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/coffee.png
--------------------------------------------------------------------------------
/assets/eaglefolderid.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/eaglefolderid.gif
--------------------------------------------------------------------------------
/assets/fromeagle.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/fromeagle.gif
--------------------------------------------------------------------------------
/assets/imagesize.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/imagesize.gif
--------------------------------------------------------------------------------
/assets/menu.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/menu.png
--------------------------------------------------------------------------------
/assets/menucall.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/menucall.gif
--------------------------------------------------------------------------------
/assets/searchid.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/searchid.gif
--------------------------------------------------------------------------------
/assets/searchname.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/searchname.gif
--------------------------------------------------------------------------------
/assets/setting.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/setting.png
--------------------------------------------------------------------------------
/assets/synch.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/synch.gif
--------------------------------------------------------------------------------
/assets/upload.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/upload.gif
--------------------------------------------------------------------------------
/assets/url.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/url.gif
--------------------------------------------------------------------------------
/assets/urlfromeagle.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/urlfromeagle.gif
--------------------------------------------------------------------------------
/assets/zoom.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyjGraphein/Obsidian-EagleBridge/749eeaeb759279761e3c5fe0931ce8f8a80b1f1c/assets/zoom.gif
--------------------------------------------------------------------------------
/doc/ReadmeZH.md:
--------------------------------------------------------------------------------
1 | # Obsidian EagleBridge
2 |
3 | 这是一个用于 Obsidian 的示例插件,主要用于连接 Obsidian 与 Eagle 软件。
4 |
5 | [eagle](https://eagle.cool) 是一款强大的附件管理软件,可以轻松管理大量图片、视频、音频素材,满足“收藏、整理、查找”的各类场景需求,支持 Windows 系统。
6 |
7 | ## 功能概述
8 |
9 | 本插件的功能包括:
10 |
11 | - 在 Obsidian 中快速跳转 eagle 附件
12 | - 标签同步
13 | - 文件查看
14 | - 附件管理
15 |
16 | ## 初次使用配置说明
17 |
18 | 1. **配置监听端口号**:需要设置一个 1000 到 9999 之间的四位复杂数值(例如 6060),以避免与常用端口号重复。为了保持附件链接的稳定性,该数值一旦设置好后,不建议进行修改。
19 |
20 | 2. **设置 Eagle 仓库位置**:通过 Eagle 软件的左上角选择仓库,并复制其路径,例如:`D:\onedrive\eagle\仓库.Library`。
21 |
22 | 完成这些操作后您需要重启obsidian,然后就可以开始使用该插件了。
23 |
24 | ## 示例展示
25 |
26 | ### 从 Eagle 中加载附件
27 |
28 |
29 |
30 | ### 从本地文件上传附件至 Eagle,并在 Obsidian 中查看
31 |
32 |
33 |
34 |
35 | ## 安装指南
36 |
37 | ### 通过 BRAT 安装
38 |
39 | 将 `https://github.com/zyjGraphein/Obsidian-EagleBridge` 添加到 [BRAT](https://github.com/TfTHacker/obsidian42-brat)。
40 |
41 | ### 手动安装
42 |
43 | 访问最新发布页面,下载 `main.js`、`manifest.json`、`style.css`,然后将它们放入 `/.obsidian/plugins/EagleBridge/`。
44 |
45 |
46 | ## 使用指南
47 |
48 | - 文字教程([中文](../doc/TutorialZH.md) / [EN](../doc/Tutorial.md))
49 | - 视频教程([Obsidian EagleBridge -bilibili](https://www.bilibili.com/video/BV1voQsYaE5W/?share_source=copy_web&vd_source=491bedf306ddb53a3baa114332c02b93))
50 |
51 | ### 注意事项
52 | - 在使用该插件时,需要 eagle 在后台保持运行,并且打开状态是对应填写路径的仓库。
53 | - 如果 eagle 没有运行,或不处于目标路径的仓库。依旧能够查看图片,但右键的功能菜单,以及附件上传eagle会无法上传。
54 | - 笔记导出为 pdf,图片能够正常显示,但其他的链接(url, pdf, mp4)依旧能够正常点击打开,但分享给其他人(脱离本地)会无法打开。
55 |
56 | ## 开发指南
57 |
58 | 此插件遵循 [Obsidian Sample Plugin](https://github.com/obsidianmd/obsidian-sample-plugin) 的结构,更多详情请参阅。
59 |
60 | - 克隆此仓库
61 | - 确保你的 NodeJS 版本至少为 v16 (`node --version`)
62 | - 运行 `npm i` 或 `yarn` 安装依赖
63 | - 运行 `npm run dev` 启动编译并进入观察模式
64 |
65 | ## 待办事项
66 |
67 | - [x] 支持多种格式文件的嵌入预览(如 PDF,MP4,PSD,OBJ 等)
68 | - [ ] 支持 macOS 系统
69 | - [ ] 支持拖拽时更新位置
70 | - [ ] 导出时,替换所有附件的链接,并导出所有附件在一个文件夹中。
71 |
72 |
73 | ## 已知限制
74 |
75 | 为防止误删附件,删除源文件时遍历所有文件的引用目前没有好的方法。建议在 Eagle 内部删除并检索 ID 对 `.md` 文档中的链接进行删除。
76 |
77 |
78 | ## 问题或建议
79 |
80 | 欢迎提交 issue:
81 |
82 | - Bug 反馈
83 | - 新功能的想法
84 | - 现有功能的优化
85 |
86 | 如果你计划实现一个大型功能,请提前与我联系,我们可以确认它是否适合此插件。
87 |
88 |
89 | ## 鸣谢
90 |
91 | 该插件主要基于 [eagle](https://api.eagle.cool) 的 API 调用,实现 Eagle 的查看、编辑、上传功能。
92 |
93 | 该插件的右键功能及图片放大参考了 [AttachFlow](https://github.com/Yaozhuwa/AttachFlow)对应的功能。
94 |
95 | 视频与PDF等外链嵌入式预览参考了[auto-embed](https://github.com/GnoxNahte/obsidian-auto-embed)对应的功能。
96 |
97 | 此外,受到[PicGo+Eagle+Python实现本地免费图床](https://zhuanlan.zhihu.com/p/695526765) ,[obsidian-auto-link-title](https://github.com/zolrath/obsidian-auto-link-title),[obsidian-image-auto-upload-plugin](https://github.com/renmu123/obsidian-image-auto-upload-plugin) 一些功能的启发。
98 |
99 | 以及感谢来自 Obsidian 论坛回答 ([get-the-source-path-when-drag-and-drop-or-copying-a-file-image-from-outside](https://forum.obsidian.md/t/how-to-get-the-source-path-when-drag-and-drop-or-copying-a-file-image-from-outside/96437)) 的帮助,实现了通过复制或拖拽获得文件来源的功能。
100 |
101 |
102 |
103 | ## 许可证
104 |
105 | 该项目依据 [GNU 通用公共许可证 v3 (GPL-3.0)](https://github.com/zyjGraphein/EagleBridge/blob/master/LICENSE) 授权。
106 |
107 |
108 | ## 支持
109 |
110 | 如果你喜欢这个插件并想表示感谢,可以请我喝杯咖啡!
111 |
112 |
--------------------------------------------------------------------------------
/doc/Tutorial.md:
--------------------------------------------------------------------------------
1 | # Port Number and Library Path Configuration
2 |
3 | When using for the first time, you need to configure the listening port number, which should be a complex four-digit number ranging from `1000` to `9999` (e.g., `6060`) to avoid conflicts with commonly used port numbers. Once set, it is not recommended to change this to ensure the stability of attachment links.
4 |
5 | Additionally, you should configure the location of the Eagle library. Select the library in the top-left corner of the Eagle application and copy the path, for example: ```D:\onedrive\eagle\Library```.
6 |
7 | Since Obsidian and Eagle might exist on different computers via sync methods like OneDrive, Nut Cloud, or hard drives, to ensure effective linking and avoid repeatedly changing settings, this plugin supports multiple addresses for Eagle libraries.
8 |
9 | For instance, on Computer A, the Eagle library might be located at ```H:\directory\example.Library```, and on Computer B, it might be at ```E:\xxxx\example.Library```. The content is the same, but they are located at different addresses.
10 |
11 | Once set up, the system will automatically map the local server to ```D:\xxxx\eagle\Library``` when using Computer A, and to ```E:\xxxx\Library``` when using Computer B, ensuring better maintenance of attachment links.
12 |
13 |
14 |
15 | # From Eagle to Obsidian
16 |
17 | Currently, attachments can be moved from Eagle to Obsidian through copying and dragging.
18 |
19 |
20 |
21 | This is applicable to attachments of all formats, such as `pdf`, `png`, `mp4`, `url`, etc. For image files like `png` and `jpg`, the copied format will be ``````, allowing preview in Obsidian. Other file types will appear as link formats like ```[image.png|700](http://localhost:6060/images/M7G6FALW4.info)```.
22 |
23 | ## Locating Eagle Images in Obsidian
24 |
25 | Right-click on an image in Eagle, choose to copy the link, then open Obsidian. Use ```Ctrl+P``` to activate the ```EagleBridge:eagle-jump-obsidian``` functionality (which can be assigned a shortcut key) and paste the link to locate the image.
26 |
27 |
28 |
29 | ## Alternative Retrieval Method
30 |
31 | See the section on integration with Obsidian Advanced URI.
32 |
33 | # From Obsidian to Eagle
34 |
35 | Currently, attachments can be copied and dragged from a local source into Obsidian, and the plugin will automatically upload them to Eagle. Images can be previewed directly; occasionally, due to loading issues, images might not display immediately. Press enter after the link to display them normally.
36 |
37 |
38 |
39 | You can set the ```Eagle Folder ID``` option to specify a folder in Eagle to upload the local files to.
40 |
41 |
42 |
43 | URLs can also be uploaded and managed, an optional feature that can be toggled on or off in the settings.
44 |
45 |
46 |
47 | - **Advantages**:
48 | - Uploading URLs allows for managing online resources within Obsidian, achieving an all-in-one management for all types of resources.
49 | - **Disadvantages**:
50 | - These links become local server links, which might be lost when sharing documents (similarly, links for PDFs, MP4s, etc., cannot be opened. Future plans include a new feature to export all attachments (including URLs) associated with a `.md` document as individual folders, replacing links with ones that are easier to share).
51 | - There is a delay of about 10 seconds as Eagle parses the URL for fetching cover images, during which performing other tasks may cause errors.
52 | - Users may prefer not all URLs to be managed.
53 | - **Additional Notes**:
54 | - The switch affects only URL uploads from Obsidian to Eagle. Links from Eagle to Obsidian can be loaded directly and aren't affected by this option. Since covers have already been fetched, the process is faster and smoother. It is recommended to turn off URL uploads and only paste links that need to be managed into Obsidian via Eagle.
55 |
56 |
57 |
58 | # Operations in Obsidian
59 |
60 | ## Image Zoom Preview
61 |
62 | Clicking the right half of an image allows for zoomed preview.
63 |
64 |
65 |
66 | ## Default Image Size Adjustment
67 |
68 | Default image insertion size can be adjusted in the settings under ```image size```.
69 |
70 |
71 |
72 | ## Options Menu
73 |
74 | For images in format ``````, right-clicking and holding opens the options menu. For link format ```[image.png|700](http://localhost:6060/images/M7G6FALW5.info)```, click to open options.
75 |
76 |
77 |
78 | ### Option Descriptions
79 |
80 | - **Open in Obsidian**: Opens the attachment in Obsidian's default way. With the core plugin Web Viewer enabled, URLs can be opened in Obsidian, supporting previews for images, videos, audio, and PDFs. Unsupported formats (like PPT, Word) can't be previewed.
81 | - **Open in Eagle**: Previews the attachment in Eagle, aiding quick and convenient image modifications and operations through Eagle's other plugins.
82 | - **Open in the default app**: Opens the attachment using the system's default opening method.
83 | - **Open in other apps**: Opt to open the attachment with other apps, like Photoshop.
84 | - **Copy source file**: Copies the attachment for sharing or moving.
85 | - **Eagle Name**: Shows and copies the attachment name. It also displays annotation, URL, and tags.
86 | - **Modify properties**: Modify attachment annotation, URL, and tags. Use a comma `,` to separate tags.
87 | - **Copy markdown link**: Makes it easy to reference links in other documents.
88 | - **Clear markdown link**: Quickly removes the attachment link.
89 |
90 |
91 |
92 | ## Attachment Synchronization and `.md` Tags
93 |
94 | After finishing an article, use ```Ctrl+P``` to search for ```EagleBridge: synchronized-page-tabs``` (or bind to a hotkey) and synchronize attachment tags with those in the `.md` file.
95 |
96 |
97 |
98 | # Integration with Obsidian Advanced URI
99 |
100 | ## Manage all attachments in the current `.md` document
101 |
102 | Set Obsidian Advanced URI’s vault to ID by obtaining the current vault's ID link, e.g., ```obsidian://adv-uri?vault=adbba5532cfb5f8d&uid=c5b638b9-253b-4491-891d-3d3b3633e634```, where the vault ID is ```adbba5532cfb5f8d``` and the `.md` file's ID is ```c5b638b9-253b-4491-891d-3d3b3633e634```. Enter the vault ID into the settings under ```Obsidian Store ID```. Later, enable ```Synchronizing advanced URL as a tag``` in settings and execute ```EagleBridge: synchronized-page-tabs``` to have the `.md` file's ID as ```c5b638b9-253b-4491-891d-3d3b3633e634``` a tag. This allows searching in Eagle for projects with that tag, displaying all related attachments.
103 |
104 | ## Locate Eagle Images in Obsidian (Alternative Method)
105 |
106 | If using Obsidian Advanced URI and storing the URI as the image tag, you can copy the `.md` file ID from the image tag and paste it into ```EagleBridge:eagle-jump-obsidian``` to locate the corresponding `.md` document.
107 |
108 |
--------------------------------------------------------------------------------
/doc/TutorialZH.md:
--------------------------------------------------------------------------------
1 | # 填写端口号和库路径配置
2 |
3 | 在首次使用时,需要配置监听端口号,范围在 `1000` 到 `9999` 之间,并尽量选择复杂的数值(例如 `6060`)以避免重复。一旦设置,该数值不建议修改以确保附件链接的稳定性。
4 |
5 | 此外,还需设置 Eagle 软件库的位置。在 Eagle 软件中选择左上角的库,复制路径,例如:```D:\onedrive\eagle\Library```。
6 |
7 | 由于 Obsidian 和 Eagle 可能通过同步、OneDrive、坚果云或硬盘存在于不同的电脑上,为了确保能够有效链接并避免重复修改设置,该插件支持 Eagle 库的多地址设置。
8 |
9 | 例如,在 A 电脑上,Eagle 库位于 ```H:\directory\example.Library```,而在 B 电脑上,Eagle 位于 ```E:\xxxx\example.Library```,两个库内容相同但位于不同地址。
10 |
11 | 配置完成后,当使用 A 电脑时,系统将自动将本地服务器映射到 ```D:\xxxx\eagle\Library```;当使用 B 电脑时,系统将映射到 ```E:\xxxx\Library```,从而更好地维护附件链接。
12 |
13 |
14 |
15 | # 从 Eagle 到 Obsidian
16 |
17 | 当前支持复制和拖拽两种方式将附件从 Eagle 移动到 Obsidian。
18 |
19 |
20 |
21 | 适用于所有格式的附件,例如 `pdf`、`png`、`mp4`、`url` 等。对于图片类文件(`png`、`jpg`),复制后格式为 ``````,可在 Obsidian 中嵌入预览。而其他文件类型会显示为链接形式 ```[image.png|700](http://localhost:6060/images/M7G6FALW4.info)```。
22 |
23 | ## 检索 Eagle 图片在 Obsidian 中的位置
24 |
25 | 在 Eagle 中右键图片,选择复制链接,然后在 Obsidian 中使用 ```Ctrl+P``` 并选择功能 ```EagleBridge:eagle-jump-obsidian```(可以绑定快捷键),粘贴对应链接,找到图片。
26 |
27 |
28 |
29 | ## 另一种检索方式
30 |
31 | 参考本文后的 Obsidian Advanced URI 联动介绍。
32 |
33 | # 从 Obsidian 到 Eagle
34 |
35 | 当前支持通过复制和拖拽将附件从本地直接导入 Obsidian,插件会自动上传到 Eagle。图片可直接预览,有时因加载问题可能不会立即显示,需在链接后按回车即显示正常。
36 |
37 |
38 |
39 | 您可以设置 ```Eagle Folder ID``` 选项,将本地上传的文件指定到 Eagle 的特定文件夹。
40 |
41 |
42 |
43 | 对于 URL,也可以进行上传管理,这是一项可选设置,可以在设置中打开或关闭。
44 |
45 |
46 |
47 | - **优势**:
48 | - 上传 URL 的优点是可以在 Obsidian 中管理在线资源,实现对所有类型资源的统一管理。
49 | - **缺点**:
50 | - 这种链接转换为本地服务器链接后,共享文档时链接会丢失。(类似地,PDF、MP4等的链接也无法访问。计划未来推出新功能,实现导出带有所有相关附件(包括 URL)的 `.md` 文档至独立文件夹,并替换链接为更便于共享的形式。)
51 | - 上传 URL 后,Eagle 解析以获取封面会有约 10 秒的延时,可能导致错误。
52 | - 用户可能不希望所有 URL 都被管理。
53 | - **补充说明**:
54 | - 此开关仅针对 URL 从 Obsidian 上传到 Eagle。在 Eagle 中的链接可以直接加载到 Obsidian,不受这一开关影响。由于已经加载过封面,过程快速流畅。建议关闭 URL 上传,仅将需要管理的链接从 Eagle 加载到 Obsidian。
55 |
56 |
57 |
58 | # 在 Obsidian 中的操作
59 |
60 | ## 图片放大预览
61 |
62 | 点击图片右半部分可实现放大预览。
63 |
64 |
65 |
66 | ## 默认图片尺寸调整
67 |
68 | 可通过设置中的 ```image size``` 调整插入图片的默认尺寸。
69 |
70 |
71 |
72 | ## 选项菜单
73 |
74 | 对于 `````` 格式的图片,通过右键持续按住可打开选项菜单。对于链接格式 ```[image.png|700](http://localhost:6060/images/M7G6FALW5.info)```,通过左键点击可打开选项菜单。
75 |
76 |
77 |
78 | ### 选项说明
79 |
80 | - **Open in Obsidian**: 使用 Obsidian 默认方式打开附件。启用 Obsidian 核心插件 Web Viewer 时,可在 Obsidian 中打开网址,并预览图片、视频、音频、PDF。对于 Web 不支持的格式(如 PPT、Word 等),将无法预览。
81 | - **Open in Eagle**: 在 Eagle 中预览附件,有助于利用其他插件,例如 AI 去背景和放大等快速修改图片,实时同步 Obsidian 中对应显示。
82 | - **Open in the default app**: 根据系统默认打开方式打开附件。
83 | - **Open in other apps**: 选择其他应用打开附件,例如 Photoshop。
84 | - **Copy source file**: 复制附件以便分享或移动。
85 | - **Eagle Name**: 显示并复制附件名称。同时显示附件的注释、URL、标签等信息。
86 | - **Modify properties**: 修改附件的注释、URL 和标签。标签用英文`,`分隔。
87 | - **Copy markdown link**: 便于在其他文档中调用附件链接。
88 | - **Clear markdown link**: 快速删除附件链接。
89 |
90 |
91 |
92 | ## 附件同步和`.md`中的标签
93 |
94 | 文章撰写完成后,可通过```Ctrl+P```搜索```EagleBridge: synchronized-page-tabs```(或绑定快捷键)实现附件标签与`.md`中标签的一致。
95 |
96 |
97 |
98 | # 与 Obsidian Advanced URI 联动
99 |
100 | ## 管理当前`.md`文档中的所有附件
101 |
102 | 将 Obsidian Advanced URI 的 Vault 设置为 ID,通过获取当前仓库的 ID 链接,例如 ```obsidian://adv-uri?vault=adbba5532cfb5f8d&uid=c5b638b9-253b-4491-891d-3d3b3633e634```,其中仓库 ID 为```adbba5532cfb5f8d```和`.md`文件的 ID 为```c5b638b9-253b-4491-891d-3d3b3633e634```。将仓库 ID 填入设置栏```Obsidian Store ID```后,打开设置中的```Synchronizing advanced URL as a tag```选项,执行```EagleBridge: synchronized-page-tabs```,可在 Eagle 中搜索含有该标签的项目,以展示`.md`中的所有相关附件。
103 |
104 | ## 检索 Eagle 图片在 Obsidian 中的位置(另一种方式)
105 |
106 | 如果使用了 Obsidian Advanced URI 并将 URI 作为图片标签储存,可复制图片标签中的`.md`文件 ID ,然后在```EagleBridge:eagle-jump-obsidian```中粘贴 ID,实现跳转到对应的`.md`文档。
107 |
108 |
--------------------------------------------------------------------------------
/esbuild.config.mjs:
--------------------------------------------------------------------------------
1 | import esbuild from "esbuild";
2 | import process from "process";
3 | import builtins from "builtin-modules";
4 |
5 | const banner =
6 | `/*
7 | THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
8 | if you want to view the source, please visit the github repository of this plugin
9 | */
10 | `;
11 |
12 | const prod = (process.argv[2] === "production");
13 |
14 | const context = await esbuild.context({
15 | banner: {
16 | js: banner,
17 | },
18 | entryPoints: ["src/main.ts"],
19 | bundle: true,
20 | external: [
21 | "obsidian",
22 | "electron",
23 | "@codemirror/autocomplete",
24 | "@codemirror/collab",
25 | "@codemirror/commands",
26 | "@codemirror/language",
27 | "@codemirror/lint",
28 | "@codemirror/search",
29 | "@codemirror/state",
30 | "@codemirror/view",
31 | "@lezer/common",
32 | "@lezer/highlight",
33 | "@lezer/lr",
34 | ...builtins],
35 | format: "cjs",
36 | target: "es2018",
37 | logLevel: "info",
38 | sourcemap: prod ? false : "inline",
39 | treeShaking: true,
40 | outfile: "main.js",
41 | minify: prod,
42 | });
43 |
44 | if (prod) {
45 | await context.rebuild();
46 | process.exit(0);
47 | } else {
48 | await context.watch();
49 | }
50 |
--------------------------------------------------------------------------------
/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "EagleBridge",
3 | "name": "EagleBridge",
4 | "version": "0.3.3",
5 | "minAppVersion": "0.15.0",
6 | "description": "EagleBridge is a plugin for Obsidian that allows you to connect to the Eagle.",
7 | "author": "zyjGraphein",
8 | "authorUrl": "https://github.com/zyjGraphein",
9 | "fundingUrl": "https://github.com/sponsors/zyjGraphein",
10 | "isDesktopOnly": false
11 | }
12 |
13 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "obsidian-sample-plugin",
3 | "version": "1.0.0",
4 | "description": "This is a sample plugin for Obsidian (https://obsidian.md)",
5 | "main": "main.js",
6 | "scripts": {
7 | "dev": "node esbuild.config.mjs",
8 | "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
9 | "version": "node version-bump.mjs && git add manifest.json versions.json"
10 | },
11 | "keywords": [],
12 | "author": "",
13 | "license": "MIT",
14 | "devDependencies": {
15 | "@types/node": "^16.11.6",
16 | "@typescript-eslint/eslint-plugin": "5.29.0",
17 | "@typescript-eslint/parser": "5.29.0",
18 | "builtin-modules": "3.3.0",
19 | "esbuild": "0.17.3",
20 | "obsidian": "latest",
21 | "tslib": "2.4.0",
22 | "typescript": "4.7.4"
23 | },
24 | "dependencies": {
25 | "@codemirror/language": "^6.10.8",
26 | "chokidar": "^4.0.3"
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/Leftclickimage.ts:
--------------------------------------------------------------------------------
1 | //from [AttachFlow](https://github.com/Yaozhuwa/AttachFlow)
2 | export async function handleImageClick(evt: MouseEvent, adaptiveRatio: number) {
3 | const target = evt.target as HTMLElement;
4 |
5 | if (target.tagName !== 'IMG') {
6 | removeZoomedImage();
7 | return;
8 | }
9 |
10 | const rect = target.getBoundingClientRect();
11 | const imageCenter = rect.left + rect.width / 2;
12 |
13 | if (evt.clientX <= imageCenter || document.getElementById('af-zoomed-image')) return;
14 |
15 | evt.preventDefault();
16 |
17 | const mask = createZoomMask();
18 | const { zoomedImage, originalWidth, originalHeight } = await createZoomedImage((target as HTMLImageElement).src, adaptiveRatio);
19 | const scaleDiv = createZoomScaleDiv(zoomedImage, originalWidth, originalHeight);
20 |
21 | zoomedImage.addEventListener('wheel', (e) => handleZoomMouseWheel(e, zoomedImage, originalWidth, originalHeight, scaleDiv));
22 | zoomedImage.addEventListener('contextmenu', (e) => handleZoomContextMenu(e, zoomedImage, originalWidth, originalHeight, scaleDiv));
23 | zoomedImage.addEventListener('mousedown', (e) => handleZoomDragStart(e, zoomedImage));
24 | zoomedImage.addEventListener('dblclick', (e) => {
25 | adaptivelyDisplayImage(zoomedImage, originalWidth, originalHeight, adaptiveRatio);
26 | updateZoomScaleDiv(scaleDiv, zoomedImage, originalWidth, originalHeight);
27 | });
28 | }
29 |
30 | export function removeZoomedImage() {
31 | const zoomedImage = document.getElementById('af-zoomed-image');
32 | if (zoomedImage) document.body.removeChild(zoomedImage);
33 | const scaleDiv = document.getElementById('af-scale-div');
34 | if (scaleDiv) document.body.removeChild(scaleDiv);
35 | const mask = document.getElementById('af-mask');
36 | if (mask) document.body.removeChild(mask);
37 | }
38 |
39 | // ... existing functions like createZoomMask, createZoomedImage, adaptivelyDisplayImage, etc. ...
40 | // 创建放大图片的遮罩层
41 | function createZoomMask(): HTMLDivElement {
42 | const mask = document.createElement('div');
43 | mask.id = 'af-mask';
44 | mask.style.position = 'fixed';
45 | mask.style.top = '0';
46 | mask.style.left = '0';
47 | mask.style.width = '100%';
48 | mask.style.height = '100%';
49 | mask.style.background = 'rgba(0, 0, 0, 0.5)';
50 | mask.style.zIndex = '9998';
51 | document.body.appendChild(mask);
52 | return mask;
53 | }
54 |
55 |
56 | // 创建放大图片
57 | async function createZoomedImage(src: string, adaptive_ratio: number): Promise<{ zoomedImage: HTMLImageElement, originalWidth: number, originalHeight: number }> {
58 | const zoomedImage = document.createElement('img');
59 | zoomedImage.id = 'af-zoomed-image';
60 | zoomedImage.src = src;
61 | zoomedImage.style.position = 'fixed';
62 | zoomedImage.style.zIndex = '9999';
63 | zoomedImage.style.top = '50%';
64 | zoomedImage.style.left = '50%';
65 | zoomedImage.style.transform = 'translate(-50%, -50%)';
66 | document.body.appendChild(zoomedImage);
67 |
68 | let originalWidth = zoomedImage.naturalWidth;
69 | let originalHeight = zoomedImage.naturalHeight;
70 |
71 | adaptivelyDisplayImage(zoomedImage, originalWidth, originalHeight, adaptive_ratio);
72 |
73 | return {
74 | zoomedImage,
75 | originalWidth,
76 | originalHeight
77 | };
78 | }
79 |
80 |
81 | // 自适应图片大小
82 | function adaptivelyDisplayImage(zoomedImage: HTMLImageElement, originalWidth: number, originalHeight: number, adaptive_ratio: number) {
83 | zoomedImage.style.left = `50%`;
84 | zoomedImage.style.top = `50%`;
85 | // 如果图片的尺寸大于屏幕尺寸,使其大小为屏幕尺寸的 adaptive_ratio
86 | let screenRatio = adaptive_ratio; // 屏幕尺寸比例
87 | let screenWidth = window.innerWidth;
88 | let screenHeight = window.innerHeight;
89 |
90 | // Adjust initial size of the image if it exceeds screen size
91 | if (originalWidth > screenWidth || originalHeight > screenHeight) {
92 | if (originalWidth / screenWidth > originalHeight / screenHeight) {
93 | zoomedImage.style.width = `${screenWidth * screenRatio}px`;
94 | zoomedImage.style.height = 'auto';
95 | } else {
96 | zoomedImage.style.height = `${screenHeight * screenRatio}px`;
97 | zoomedImage.style.width = 'auto';
98 | }
99 | } else {
100 | zoomedImage.style.width = `${originalWidth}px`;
101 | zoomedImage.style.height = `${originalHeight}px`;
102 | }
103 | }
104 |
105 | // 创建百分比指示元素
106 | function createZoomScaleDiv(zoomedImage: HTMLImageElement, originalWidth: number, originalHeight: number): HTMLDivElement {
107 | const scaleDiv = document.createElement('div');
108 | scaleDiv.id = 'af-scale-div';
109 | scaleDiv.classList.add('af-scale-div');
110 | scaleDiv.style.zIndex = '10000';
111 | updateZoomScaleDiv(scaleDiv, zoomedImage, originalWidth, originalHeight);
112 | document.body.appendChild(scaleDiv);
113 | return scaleDiv;
114 | }
115 | // 更新百分比指示元素
116 | function updateZoomScaleDiv(scaleDiv: HTMLDivElement, zoomedImage: HTMLImageElement, originalWidth: number, originalHeight: number) {
117 | // 获取当前的宽度和高度
118 | const width = zoomedImage.offsetWidth;
119 | const height = zoomedImage.offsetHeight;
120 | let scalePercent = width / originalWidth * 100;
121 | scaleDiv.innerText = `${width}×${height} (${scalePercent.toFixed(1)}%)`;
122 | }
123 |
124 | // 滚轮事件处理器
125 | function handleZoomMouseWheel(e: WheelEvent, zoomedImage: HTMLImageElement, originalWidth: number, originalHeight: number, scaleDiv: HTMLDivElement) {
126 | e.preventDefault();
127 | const mouseX = e.clientX;
128 | const mouseY = e.clientY;
129 | const scale = e.deltaY > 0 ? 0.95 : 1.05;
130 | const newWidth = scale * zoomedImage.offsetWidth;
131 | const newHeight = scale * zoomedImage.offsetHeight;
132 | const newLeft = mouseX - (mouseX - zoomedImage.offsetLeft) * scale;
133 | const newTop = mouseY - (mouseY - zoomedImage.offsetTop) * scale;
134 | zoomedImage.style.width = `${newWidth}px`;
135 | zoomedImage.style.height = `${newHeight}px`;
136 | zoomedImage.style.left = `${newLeft}px`;
137 | zoomedImage.style.top = `${newTop}px`;
138 | updateZoomScaleDiv(scaleDiv, zoomedImage, originalWidth, originalHeight);
139 | }
140 | // 鼠标右键点击事件处理器
141 | function handleZoomContextMenu(e: MouseEvent, zoomedImage: HTMLImageElement, originalWidth: number, originalHeight: number, scaleDiv: HTMLDivElement) {
142 | e.preventDefault();
143 | zoomedImage.style.width = `${originalWidth}px`;
144 | zoomedImage.style.height = `${originalHeight}px`;
145 | zoomedImage.style.left = `50%`;
146 | zoomedImage.style.top = `50%`;
147 | updateZoomScaleDiv(scaleDiv, zoomedImage, originalWidth, originalHeight);
148 | }
149 |
150 | // 拖动事件处理器
151 | function handleZoomDragStart(e: MouseEvent, zoomedImage: HTMLImageElement) {
152 | // 事件处理的代码 ...
153 | // 阻止浏览器默认的拖动事件
154 | e.preventDefault();
155 |
156 | // 记录点击位置
157 | let clickX = e.clientX;
158 | let clickY = e.clientY;
159 |
160 | // 更新元素位置的回调函数
161 | const updatePosition = (moveEvt: MouseEvent) => {
162 | // 计算鼠标移动距离
163 | let moveX = moveEvt.clientX - clickX;
164 | let moveY = moveEvt.clientY - clickY;
165 |
166 | // 定位图片位置
167 | zoomedImage.style.left = `${zoomedImage.offsetLeft + moveX}px`;
168 | zoomedImage.style.top = `${zoomedImage.offsetTop + moveY}px`;
169 |
170 | // 更新点击位置
171 | clickX = moveEvt.clientX;
172 | clickY = moveEvt.clientY;
173 | }
174 |
175 | // 鼠标移动事件
176 | document.addEventListener('mousemove', updatePosition);
177 |
178 | // 鼠标松开事件
179 | document.addEventListener('mouseup', function listener() {
180 | // 移除鼠标移动和鼠标松开的监听器
181 | document.removeEventListener('mousemove', updatePosition);
182 | document.removeEventListener('mouseup', listener);
183 | }, { once: true });
184 | }
--------------------------------------------------------------------------------
/src/addCommand-config.ts:
--------------------------------------------------------------------------------
1 | import MyPlugin from './main';
2 | import { syncTags } from "./synchronizedpagetabs";
3 | import { jumpModal } from "./eaglejumpobsidian";
4 |
5 | export const addCommandSynchronizedPageTabs = (myPlugin: MyPlugin) => {
6 | myPlugin.addCommand({
7 | id: "synchronized-page-tabs",
8 | name: "synchronized-page-tabs",
9 | callback: async () => {
10 | syncTags(myPlugin.app, myPlugin.settings);
11 | },
12 | });
13 | };
14 |
15 | export const addCommandEagleJump = (myPlugin: MyPlugin) => {
16 | myPlugin.addCommand({
17 | id: "eagle-jump-obsidian",
18 | name: "eagle-jump-obsidian",
19 | callback: async () => {
20 | jumpModal(myPlugin.app, myPlugin.settings);
21 | },
22 | });
23 | };
--------------------------------------------------------------------------------
/src/eaglejumpobsidian.ts:
--------------------------------------------------------------------------------
1 | import { App, Modal, Notice, Setting, MarkdownView } from 'obsidian';
2 | import { MyPluginSettings } from './setting';
3 | import { print, setDebug } from './main';
4 |
5 | export class EagleJumpModal extends Modal {
6 | private onSubmit: (link: string) => void;
7 | private settings: MyPluginSettings;
8 |
9 | constructor(app: App, settings: MyPluginSettings, onSubmit: (link: string) => void) {
10 | super(app);
11 | this.settings = settings;
12 | this.onSubmit = onSubmit;
13 | }
14 |
15 | onOpen() {
16 | const { contentEl } = this;
17 | contentEl.createEl('h3', { text: 'Please enter Page id or Eagle image link' });
18 |
19 | let linkInput: HTMLInputElement;
20 |
21 | new Setting(contentEl)
22 | .addText(text => {
23 | linkInput = text.inputEl;
24 | text.setPlaceholder('link...');
25 | linkInput.style.width = '400px'; // 设置文本框宽度为400
26 | });
27 |
28 | const buttonContainer = contentEl.createDiv();
29 | buttonContainer.style.display = 'flex';
30 | // buttonContainer.style.gap = '10px'; // 设置按钮之间的间距
31 | buttonContainer.style.alignItems = 'end'; // 确保按钮在同一行上
32 | buttonContainer.style.justifyContent = 'center'; // 确保按钮在同一行上
33 |
34 | new Setting(buttonContainer)
35 | .addButton(btn => btn
36 | .setButtonText('Jump')
37 | .setCta()
38 | .onClick(() => {
39 | const link = linkInput.value.trim();
40 | if (link) {
41 | // 检查链接格式
42 | const eaglePattern = /^eagle:\/\/item\/([A-Z0-9]+)$/;
43 | const uuidPattern = /^.+$/; // 匹配任意非空字符串
44 | const imagePattern = /http:\/\/localhost:\d+\/images\/([A-Z0-9]+)\.info/;
45 |
46 | const eagleMatch = link.match(eaglePattern);
47 | const uuidMatch = link.match(uuidPattern);
48 | const imageMatch = link.match(imagePattern);
49 |
50 | if (eagleMatch || imageMatch) {
51 | // 如果是 eagle://item/ 或者图片链接格式,使用 Obsidian 的搜索功能
52 | const itemId = eagleMatch ? eagleMatch[1] : (imageMatch ? imageMatch[1] : null);
53 | if (itemId) {
54 | print(`Search ID in Obsidian: ${itemId}`);
55 | // 打开搜索面板
56 | let searchLeaf = this.app.workspace.getLeavesOfType('search')[0];
57 | if (!searchLeaf) {
58 | searchLeaf = this.app.workspace.getLeaf(true); // 获取一个新的叶子
59 | searchLeaf.setViewState({ type: 'search' }); // 设置视图类型为搜索
60 | }
61 | this.app.workspace.revealLeaf(searchLeaf);
62 | const searchView = searchLeaf.view;
63 | if (searchView && typeof (searchView as any).setQuery === 'function') {
64 | (searchView as any).setQuery(itemId);
65 | } else {
66 | new Notice('Search view does not support setQuery');
67 | }
68 | } else {
69 | new Notice('Cannot extract a valid ID');
70 | }
71 | } else if (uuidMatch) {
72 | // 如果是 UUID 格式,构建 obsidian://adv-uri 链接
73 | const obsidianStoreId = this.settings.obsidianStoreId;
74 | const advUri = `obsidian://adv-uri?vault=${obsidianStoreId}&uid=${link}`;
75 | print(`Run link: ${advUri}`);
76 | window.open(advUri, '_blank');
77 | } else {
78 | new Notice('Please enter a valid link');
79 | }
80 | this.close();
81 | } else {
82 | new Notice('Please enter a valid link');
83 | }
84 | }));
85 |
86 | new Setting(buttonContainer)
87 | .addButton(btn => btn
88 | .setButtonText('Cancel')
89 | .onClick(() => {
90 | this.close();
91 | }));
92 | }
93 |
94 | onClose() {
95 | const { contentEl } = this;
96 | contentEl.empty();
97 | }
98 | }
99 |
100 | // 使用示例
101 | export function jumpModal(app: App, settings: MyPluginSettings) {
102 | new EagleJumpModal(app, settings, (link) => {
103 | print(`User input link: ${link}`);
104 | }).open();
105 | }
--------------------------------------------------------------------------------
/src/embed-state-field.ts:
--------------------------------------------------------------------------------
1 | import { syntaxTree } from "@codemirror/language";
2 | import { Extension, RangeSetBuilder, StateField, Transaction } from "@codemirror/state";
3 | import { Decoration, DecorationSet, EditorView } from "@codemirror/view";
4 | import { editorLivePreviewField } from "obsidian";
5 | import { EmbedWidget } from "./embed-widget";
6 | import { isURL, isLocalHostLink, embedManager, isAltTextImage } from "./embed";
7 |
8 | // 使用与参考代码完全一致的正则表达式
9 | const formattingImageMarkerRegex = /formatting_formatting-image_image_image-marker(?:_list-\d*)?$/;
10 | const stringUrlRegex = /^(?:list-\d*_)?string_url$/;
11 |
12 | // 调试函数
13 | function debugLog(message: string, ...args: any[]) {
14 | // console.log(`[Eagle-Embed-Debug] ${message}`, ...args); // 删除冗余
15 | }
16 |
17 | // 检查Alt文本是否表示图片类型(与embed.ts保持一致)
18 | // function isAltTextImage(alt: string): boolean {
19 | // // 首先处理可能包含尺寸的情况,如 "image.png|700"
20 | // const mainPart = alt.split('|')[0].trim();
21 | // debugLog(`检查alt文本: ${alt}, 主要部分: ${mainPart}`);
22 | // return /\.(jpg|jpeg|png|gif|webp|svg|avif|bmp|ico)$/i.test(mainPart);
23 | // }
24 |
25 | // 定义编辑器状态字段
26 | export const embedField = StateField.define({
27 | create(): DecorationSet {
28 | // print("创建初始装饰集");
29 | return Decoration.none;
30 | },
31 |
32 | update(oldState: DecorationSet, transaction: Transaction): DecorationSet {
33 | const builder = new RangeSetBuilder();
34 |
35 | // 检查是否在实时预览模式下
36 | if (!transaction.state.field(editorLivePreviewField, false)) {
37 | // print("不在实时预览模式,跳过");
38 | return builder.finish();
39 | }
40 |
41 | // print("处理编辑器状态更新");
42 |
43 | // 追踪alt文本的开始位置
44 | let altTextStartPos: number | null = null;
45 |
46 | // 遍历语法树查找图像链接
47 | syntaxTree(transaction.state).iterate({
48 | enter(node) {
49 | // 调试节点类型
50 | debugLog(`节点类型: ${node.type.name}`);
51 |
52 | // 查找图像标记
53 | if (formattingImageMarkerRegex.test(node.type.name)) {
54 | altTextStartPos = node.to + 1;
55 | // print(`找到图像标记,alt文本开始位置: ${altTextStartPos}`);
56 | }
57 | // 查找URL
58 | else if (stringUrlRegex.test(node.type.name)) {
59 | if (altTextStartPos === null) {
60 | // print("未找到对应的图像标记,跳过URL");
61 | return;
62 | }
63 |
64 | // 获取URL和alt文本
65 | const url = transaction.state.sliceDoc(node.from, node.to);
66 | const alt = transaction.state.sliceDoc(altTextStartPos, node.from - 2);
67 |
68 | // print(`提取的URL: ${url}`);
69 | // print(`提取的alt文本: ${alt}`);
70 |
71 | // 重置alt文本开始位置
72 | altTextStartPos = null;
73 |
74 | // 检查是否应该嵌入
75 | if (!isURL(url)) {
76 | // print(`不是有效URL: ${url}`);
77 | return;
78 | }
79 |
80 | // 检查alt文本是否表示图片类型
81 | if (isAltTextImage(alt)) {
82 | // print(`根据alt文本识别为图片,跳过: ${alt}`);
83 | return;
84 | }
85 |
86 | // 检查是否为本地链接且不是图片链接
87 | if (!isLocalHostLink(url) || isAltTextImage(url)) {
88 | // print(`不是本地链接或是图片链接: ${url}`);
89 | return;
90 | }
91 |
92 | if (!embedManager.shouldEmbed(url)) {
93 | // print(`不应该嵌入此URL: ${url}`);
94 | return;
95 | }
96 |
97 | // print(`创建嵌入内容: ${url}`);
98 |
99 | // 添加替换装饰
100 | const replaceFrom = node.to + 1;
101 | builder.add(
102 | replaceFrom,
103 | replaceFrom,
104 | Decoration.replace({
105 | widget: new EmbedWidget(url, alt),
106 | block: true
107 | })
108 | );
109 | }
110 | }
111 | });
112 |
113 | return builder.finish();
114 | },
115 |
116 | provide(field: StateField): Extension {
117 | return EditorView.decorations.from(field);
118 | }
119 | });
--------------------------------------------------------------------------------
/src/embed-widget.ts:
--------------------------------------------------------------------------------
1 | import { WidgetType } from "@codemirror/view";
2 | import { embedManager } from "./embed";
3 |
4 | // 调试函数
5 | function debugLog(message: string, ...args: any[]) {
6 | console.log(`[Eagle-Embed-Widget] ${message}`, ...args);
7 | }
8 |
9 | export class EmbedWidget extends WidgetType {
10 | private url: string;
11 | private alt: string;
12 | private container: HTMLElement | null = null;
13 |
14 | constructor(url: string, alt: string = "") {
15 | super();
16 | this.url = url;
17 | this.alt = alt;
18 | // print(`创建嵌入部件: ${url}`);
19 | }
20 |
21 | eq(other: EmbedWidget): boolean {
22 | return other.url === this.url && other.alt === this.alt;
23 | }
24 |
25 | toDOM(): HTMLElement {
26 | // print(`渲染嵌入部件: ${this.url}`);
27 |
28 | // 如果已经有容器,返回现有容器
29 | if (this.container) {
30 | return this.container;
31 | }
32 |
33 | this.container = document.createElement('div');
34 | this.container.className = "eagle-embed-container cm-embed-block";
35 |
36 | // // 检查是否有noembed标记
37 | // if (this.alt && /noembed/i.test(this.alt)) {
38 | // // print(`跳过嵌入,发现noembed标记: ${this.url}`);
39 | // this.container.classList.add("eagle-embed-placeholder");
40 | // this.container.textContent = `已禁用嵌入 (noembed): ${this.url.substring(0, 50)}...`;
41 | // return this.container;
42 | // }
43 |
44 | try {
45 | if (embedManager.shouldEmbed(this.url)) {
46 | // print(`创建嵌入内容: ${this.url}`);
47 | const result = embedManager.create(this.url);
48 | this.container = result.containerEl;
49 |
50 | // 添加编辑模式特定样式
51 | this.container.classList.add("cm-embed-block");
52 |
53 | // 添加编辑模式特定样式
54 | this.container.classList.add("cm-embed-block");
55 | // 在插入DOM后,检查前一个同级元素是否为与当前URL匹配的图片
56 | setTimeout(() => {
57 | if (this.container && this.container.parentElement) {
58 | const prevSibling = this.container.previousSibling;
59 |
60 | if (prevSibling && prevSibling.nodeName === 'IMG') {
61 | const imgElement = prevSibling as HTMLImageElement;
62 |
63 | imgElement.classList.add("auto-embed-hide-display");
64 | // this.container.parentElement?.removeChild(this.container);
65 | // this.container.parentElement?.removeChild(imgElement);
66 | }
67 | }
68 | }, 0);
69 | // 添加加载事件处理
70 | if (result.iframeEl) {
71 | const iframe = result.iframeEl;
72 | // 设置iframe事件处理
73 | iframe.onerror = () => {
74 | // print(`嵌入加载失败: ${this.url}`);
75 | this.showError(`加载失败: ${this.url}`);
76 | };
77 |
78 | iframe.onload = () => {
79 | // print(`嵌入加载成功: ${this.url}`);
80 | };
81 | }
82 | } else {
83 | // print(`不应该嵌入此URL: ${this.url}`);
84 | this.container.classList.add("eagle-embed-placeholder");
85 | this.container.textContent = `不支持的嵌入内容: ${this.url.substring(0, 50)}...`;
86 | }
87 | } catch (error) {
88 | // print(`处理嵌入时出错: ${error}`);
89 | this.showError(`处理嵌入时出错: ${error}`);
90 | }
91 |
92 | return this.container;
93 | }
94 |
95 | // 显示错误信息
96 | private showError(message: string): void {
97 | if (!this.container) return;
98 |
99 | this.container.innerHTML = '';
100 | this.container.classList.add("eagle-embed-error");
101 | this.container.textContent = message;
102 | }
103 |
104 | ignoreEvent(): boolean {
105 | return false;
106 | }
107 | }
--------------------------------------------------------------------------------
/src/embed.ts:
--------------------------------------------------------------------------------
1 | // URL 检测函数
2 | export function isURL(str: string): boolean {
3 | let url: URL;
4 |
5 | try {
6 | url = new URL(str);
7 | } catch {
8 | return false;
9 | }
10 |
11 | return url.protocol === "http:" || url.protocol === "https:";
12 | }
13 |
14 |
15 | // 检查是否为本地主机链接
16 | export function isLocalHostLink(str: string): boolean {
17 | try {
18 | const url = new URL(str);
19 | return url.hostname === "localhost" || url.hostname === "127.0.0.1";
20 | } catch {
21 | return false;
22 | }
23 | }
24 |
25 |
26 | // 检查Alt文本是否表示图片类型(增强版)
27 | export function isAltTextImage(alt: string): boolean {
28 | // 首先处理可能包含尺寸的情况,如 "image.png|700"
29 | const mainPart = alt.split('|')[0].trim();
30 | return /\.(jpg|jpeg|png|gif|webp|svg|avif|bmp|ico)$/i.test(mainPart);
31 | }
32 |
33 | // 基本嵌入数据结构
34 | export interface EmbedResult {
35 | containerEl: HTMLElement;
36 | iframeEl?: HTMLIFrameElement;
37 | }
38 |
39 | // 本地链接嵌入处理器
40 | export class LocalHostEmbedder {
41 | // 创建嵌入内容
42 | create(src: string): EmbedResult {
43 | const container = document.createElement('div');
44 | container.className = "eagle-embed-container";
45 |
46 | // 创建 iframe 元素
47 | const iframe = document.createElement('iframe');
48 | iframe.src = src;
49 | iframe.width = "100%";
50 | iframe.height = "500px"; // 增加高度以适应更多内容
51 | iframe.style.border = "none";
52 | iframe.setAttribute("allowfullscreen", "true");
53 | iframe.setAttribute("loading", "lazy");
54 |
55 | container.appendChild(iframe);
56 |
57 | return {
58 | containerEl: container,
59 | iframeEl: iframe
60 | };
61 | }
62 |
63 | // 检查是否应该嵌入此链接
64 | shouldEmbed(src: string, alt?: string): boolean {
65 | // 如果提供了alt文本且表示图片,跳过嵌入
66 | if (alt && isAltTextImage(alt)) {
67 | console.log(`[Eagle-Embed] 跳过图片嵌入: ${alt}, URL: ${src}`);
68 | return false;
69 | }
70 |
71 | // 确认是localhost链接
72 | return isLocalHostLink(src);
73 | }
74 | }
75 |
76 | // 嵌入管理器
77 | export const embedManager = new LocalHostEmbedder();
78 |
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | import { Menu,MenuItem,App, Editor, MarkdownView, Modal, Notice, Plugin, Setting,TFile, Platform, FileStats } from 'obsidian';
2 | import { startServer, refreshServer, stopServer } from './server';
3 | import { handlePasteEvent, handleDropEvent } from './urlHandler';
4 | import { onElement } from './onElement';
5 | import { exec, spawn, execSync } from 'child_process';
6 | import * as path from 'path';
7 | import { addCommandSynchronizedPageTabs,addCommandEagleJump } from "./addCommand-config";
8 | import { existsSync } from 'fs';
9 | import { MyPluginSettings, DEFAULT_SETTINGS, SampleSettingTab } from './setting';
10 | import { handleImageClick, removeZoomedImage } from './Leftclickimage';
11 | import { handleLinkClick, eagleImageContextMenuCall, registerEscapeButton, addEagleImageMenuSourceMode, addEagleImageMenuPreviewMode, fetchImageInfo } from './menucall';
12 | import { isAltTextImage, isURL, isLocalHostLink} from './embed';
13 | import { embedManager } from './embed';
14 | import { embedField } from './embed-state-field';
15 | import { Extension } from "@codemirror/state";
16 |
17 |
18 | let DEBUG = false;
19 |
20 | export const print = (message?: any, ...optionalParams: any[]) => {
21 | // console.log('DEBUG status:', DEBUG); // 调试输出
22 | if (DEBUG) {
23 | console.log(message, ...optionalParams);
24 | }
25 | }
26 |
27 | export function setDebug(value: boolean) {
28 | DEBUG = value;
29 | }
30 |
31 | export default class MyPlugin extends Plugin {
32 | settings: MyPluginSettings;
33 |
34 | async onload() {
35 | console.log('加载 Eagle-Embed 插件');
36 |
37 | await this.loadSettings();
38 |
39 | // 注册编辑器扩展,务必正确导入和注册
40 | this.registerEditorExtension([embedField]);
41 |
42 | // 处理预览模式
43 | this.registerMarkdownPostProcessor((el, ctx) => {
44 | const images = el.querySelectorAll('img');
45 | images.forEach((image) => {
46 | if (embedManager.shouldEmbed(image.src)) {
47 | print(`MarkdownPostProcessor 找到可嵌入图像: ${image.src}`);
48 | this.handleImage(image);
49 | }
50 | });
51 | });
52 |
53 | // 注册外部文件支持
54 | // 注册图片右键菜单事件
55 | this.registerDocument(document);
56 | this.app.workspace.on("window-open", (workspaceWindow, window) => {
57 | this.registerDocument(window.document);
58 | });
59 | // 在插件加载时启动服务器
60 | startServer(this.settings.libraryPath, this.settings.port);
61 | // 添加设置面板
62 | this.addSettingTab(new SampleSettingTab(this.app, this));
63 | // await this.loadSettings();
64 | // 注册粘贴事件
65 | this.registerEvent(
66 | this.app.workspace.on('editor-paste', (clipboard: ClipboardEvent, editor: Editor) => {
67 | handlePasteEvent(clipboard, editor, this.settings.port, this);
68 | })
69 | );
70 | // 注册拖拽事件
71 | this.registerEvent(
72 | this.app.workspace.on('editor-drop', (event: DragEvent, editor: Editor) => {
73 | handleDropEvent(event, editor, this.settings.port, this);
74 | })
75 | );
76 | // 在插件加载时设置 DEBUG 状态
77 | // console.log('Debug setting:', this.settings.debug);
78 | setDebug(this.settings.debug);
79 |
80 | this.registerDomEvent(document, "click", async (event: MouseEvent) => {
81 | const target = event.target as HTMLElement;
82 | const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
83 | if (!activeView) {
84 | print('Cannot find the active view');
85 | return;
86 | }
87 |
88 | const inPreview = activeView.getMode() === "preview";
89 | let url: string | null = null;
90 |
91 | if (inPreview) {
92 | if (!target.matches("a.external-link")) {
93 | return;
94 | }
95 |
96 | const linkElement = target as HTMLAnchorElement;
97 | if (linkElement && linkElement.href) {
98 | url = linkElement.href;
99 | print(`Preview mode link: ${url}`);
100 | }
101 | } else {
102 | if (!target.matches("span.external-link, .cm-link, a.cm-underline")) {
103 | return;
104 | }
105 |
106 | const editor = activeView.editor;
107 | const cursor = editor.getCursor();
108 | const lineText = editor.getLine(cursor.line);
109 | const urlMatches = Array.from(lineText.matchAll(/\bhttps?:\/\/[^\s)]+/g));
110 | print(urlMatches);
111 | let closestUrl = null;
112 | let minDistance = Infinity;
113 | const cursorPos = cursor.ch;
114 | print(cursorPos);
115 |
116 | for (let i = 0; i < urlMatches.length; i++) {
117 | const match = urlMatches[i];
118 | const end = (match.index || 0) + match[0].length + 1;
119 | if (cursorPos <= end) {
120 | closestUrl = match[0];
121 | print(`Cursor is in the link interval: ${i + 1}`);
122 | break;
123 | }
124 | }
125 |
126 | if (closestUrl) {
127 | url = closestUrl;
128 | print(`Edit mode link: ${url}`);
129 | }
130 | }
131 |
132 | if (url && url.match(/^http:\/\/localhost:\d+\/images\/[^.]+\.info$/)) {
133 | event.preventDefault();
134 | event.stopPropagation();
135 | print(`Prevented link: ${url}`);
136 | handleLinkClick(this, event, url);
137 | } else {
138 | return;
139 | }
140 | }, { capture: true });
141 | // 注册点击事件(参考AttachFlow)
142 | this.registerDomEvent(document, 'click', async (evt: MouseEvent) => {
143 | if (!this.settings.clickView) return;
144 | handleImageClick(evt, this.settings.adaptiveRatio);
145 | });
146 |
147 | this.registerDomEvent(document, 'keydown', (evt: KeyboardEvent) => {
148 | if (evt.key === 'Escape') {
149 | removeZoomedImage();
150 | }
151 | });
152 | // register all commands in addCommand function
153 | addCommandSynchronizedPageTabs(this);
154 | addCommandEagleJump(this);
155 | // 添加自定义样式,确保样式包含编辑模式特定样式
156 | const style = document.createElement('style');
157 | style.textContent = `
158 | .menu-item {
159 | max-width: 800px; /* 设置最大宽度 */
160 | white-space: normal; /* 允许换行 */
161 | word-wrap: break-word; /* 自动换行 */
162 | }
163 |
164 | .eagle-embed-hide {
165 | display: none !important;
166 | }
167 |
168 | .eagle-embed-container {
169 | margin: 10px 0;
170 | border-radius: 5px;
171 | overflow: hidden;
172 | background: var(--background-primary);
173 | border: 1px solid var(--background-modifier-border);
174 | width: 100%;
175 | }
176 |
177 | .eagle-embed-container iframe {
178 | display: block;
179 | width: 100%;
180 | height: 500px;
181 | border: none;
182 | }
183 |
184 | /* 编辑模式样式 */
185 | .cm-embed-block {
186 | margin: 0.5em 0;
187 | width: 100%;
188 | }
189 |
190 | /* 占位符样式 */
191 | .eagle-embed-placeholder {
192 | background: var(--background-secondary);
193 | border-radius: 5px;
194 | padding: 1em;
195 | text-align: center;
196 | margin: 0.5em 0;
197 | }
198 |
199 | /* 错误样式 */
200 | .eagle-embed-error {
201 | background: rgba(255, 0, 0, 0.1);
202 | border: 1px solid rgba(255, 0, 0, 0.3);
203 | color: #ff0000;
204 | padding: 1em;
205 | text-align: center;
206 | margin: 0.5em 0;
207 | border-radius: 5px;
208 | }
209 | `;
210 | document.head.appendChild(style);
211 |
212 | }
213 |
214 |
215 | onunload() {
216 | // 在插件卸载时停止服务器
217 | stopServer();
218 | // this.app.vault.getResourcePath = this.originalGetResourcePath;
219 | // this.app.metadataCache.getFirstLinkpathDest = this.originalGetFirstLinkpathDest;
220 | }
221 |
222 | async loadSettings() {
223 | this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
224 | this.updateLibraryPath(); // 更新Library Path
225 | }
226 |
227 | async updateLibraryPath() {
228 | for (const path of this.settings.libraryPaths) {
229 | if (existsSync(path)) { // 检查路径是否存在
230 | this.settings.libraryPath = path;
231 | break;
232 | }
233 | }
234 | await this.saveSettings();
235 | }
236 |
237 | async saveSettings() {
238 | await this.saveData(this.settings);
239 | }
240 | // 注册图片右键菜单事件
241 | registerDocument(document: Document) {
242 | this.register(
243 | onElement(
244 | document,
245 | "contextmenu",
246 | "img",
247 | eagleImageContextMenuCall.bind(this),
248 | { capture: true }
249 | )
250 | );
251 | }
252 | handleImage(img: HTMLImageElement): HTMLElement | null {
253 | try {
254 | const alt = img.alt || "";
255 | const src = img.src;
256 |
257 | // print(`处理图像: ${src} 替代文本: ${alt}`);
258 |
259 | // 检查是否有 noembed 标记
260 | if (/noembed/i.test(alt)) {
261 | img.alt = alt.replace(/noembed/i, "").trim();
262 | // print("跳过嵌入: 图像标记为noembed");
263 | return null;
264 | }
265 |
266 | // 检查alt文本是否表示图片类型
267 | if (isAltTextImage(alt)) {
268 | // print(`根据alt文本识别为图片,跳过: ${alt}`);
269 | return null;
270 | }
271 |
272 | // 检查是否应该嵌入
273 | if (!isURL(src) || !embedManager.shouldEmbed(src, alt)) {
274 | // print("跳过嵌入: 不是有效URL或不应嵌入");
275 | return null;
276 | }
277 |
278 | // print(`创建嵌入内容: ${src}`);
279 | const embedResult = embedManager.create(src);
280 | const container = embedResult.containerEl;
281 |
282 | if (!img.parentElement) {
283 | // print("错误: 图像没有父元素");
284 | return null;
285 | }
286 |
287 | // 使用替换方法
288 | img.parentElement.replaceChild(container, img);
289 |
290 |
291 | return container;
292 | } catch (error) {
293 | console.error("处理图像时出错:", error);
294 | return null;
295 | }
296 | }
297 | }
298 |
299 |
--------------------------------------------------------------------------------
/src/menucall.ts:
--------------------------------------------------------------------------------
1 | import { Menu, MenuItem, MarkdownView, Notice, Modal, App, Setting } from 'obsidian';
2 | import MyPlugin from './main';
3 | import * as path from 'path';
4 | import { onElement } from './onElement';
5 | import { print, setDebug } from './main';
6 | import { exec, spawn, execSync } from 'child_process';
7 | import { existsSync } from 'fs';
8 | import { EditorView} from '@codemirror/view';
9 |
10 | export function handleLinkClick(plugin: MyPlugin, event: MouseEvent, url: string) {
11 | const menu = new Menu();
12 | const inPreview = plugin.app.workspace.getActiveViewOfType(MarkdownView)?.getMode() == "preview";
13 | if (inPreview) {
14 | addEagleImageMenuPreviewMode(plugin, menu, url, event);
15 | } else {
16 | addEagleImageMenuSourceMode(plugin, menu, url, event);
17 | }
18 | registerEscapeButton(plugin, menu);
19 | let offset = 0;
20 | menu.showAtPosition({ x: event.pageX, y: event.pageY + offset });
21 | }
22 |
23 | export function eagleImageContextMenuCall(this: MyPlugin, event: MouseEvent) {
24 | const img = event.target as HTMLImageElement;
25 | const inTable: boolean = img.closest('table') != null;
26 | const inCallout: boolean = img.closest('.callout') != null;
27 | if (img.id == 'af-zoomed-image') return;
28 | if (!img.src.startsWith('http')) return;
29 | event.preventDefault();
30 | event.stopPropagation();
31 | this.app.workspace.getActiveViewOfType(MarkdownView)?.editor?.blur();
32 | img.classList.remove('image-ready-click-view', 'image-ready-resize');
33 | const url = img.src;
34 | const menu = new Menu();
35 | const inPreview = this.app.workspace.getActiveViewOfType(MarkdownView)?.getMode() == "preview";
36 | if (inPreview) {
37 | addEagleImageMenuPreviewMode(this, menu, url, event);
38 | } else {
39 | addEagleImageMenuSourceMode(this, menu, url, event);
40 | }
41 | registerEscapeButton(this, menu);
42 | let offset = 0;
43 | if (!inPreview && (inTable || inCallout)) offset = -138;
44 | menu.showAtPosition({ x: event.pageX, y: event.pageY + offset });
45 | }
46 |
47 | export function registerEscapeButton(plugin: MyPlugin, menu: Menu, document: Document = activeDocument) {
48 | menu.register(
49 | onElement(
50 | document,
51 | "keydown" as keyof HTMLElementEventMap,
52 | "*",
53 | (e: KeyboardEvent) => {
54 | if (e.key === "Escape") {
55 | e.preventDefault();
56 | e.stopPropagation();
57 | menu.hide();
58 | }
59 | }
60 | )
61 | );
62 | }
63 |
64 | export async function addEagleImageMenuPreviewMode(plugin: MyPlugin, menu: Menu, oburl: string, event: MouseEvent) {
65 | const imageInfo = await fetchImageInfo(oburl);
66 |
67 | if (imageInfo) {
68 | const { id, name, ext, annotation, tags, url } = imageInfo;
69 | // const infoToCopy = `ID: ${id}, Name: ${name}, Ext: ${ext}, Annotation: ${annotation}, Tags: ${tags}, URL: ${url}`;
70 | // navigator.clipboard.writeText(infoToCopy);
71 | // new Notice(`Copied: ${infoToCopy}`);
72 | menu.addItem((item: MenuItem) =>
73 | item
74 | .setIcon("file-symlink")
75 | .setTitle("Open in obsidian")
76 | .onClick(async (event: MouseEvent) => {
77 | // 根据设置决定如何打开链接
78 | const openMethod = plugin.settings.openInObsidian || 'newPage';
79 |
80 | if (openMethod === 'newPage') {
81 | // 在新页面打开(默认行为)
82 | window.open(oburl, '_blank');
83 | } else if (openMethod === 'popup') {
84 | // 使用 Obsidian 的独立窗口打开
85 | const leaf = plugin.app.workspace.getLeaf('window');
86 | await leaf.setViewState({
87 | type: 'webviewer',
88 | state: {
89 | url: oburl,
90 | navigate: true,
91 | },
92 | active: true,
93 | });
94 | } else if (openMethod === 'rightPane') {
95 | // 在右侧新栏中打开
96 | const leaf = plugin.app.workspace.getLeaf('split', 'vertical');
97 | await leaf.setViewState({
98 | type: 'webviewer',
99 | state: {
100 | url: oburl,
101 | navigate: true,
102 | },
103 | active: true,
104 | });
105 | }
106 | })
107 | );
108 |
109 |
110 |
111 | menu.addItem((item: MenuItem) =>
112 | item
113 | .setIcon("file-symlink")
114 | .setTitle("Open in eagle")
115 | .onClick(() => {
116 | const eagleLink = `eagle://item/${id}`;
117 | navigator.clipboard.writeText(eagleLink);
118 | window.open(eagleLink, '_self'); // 直接运行跳转到 eagle:// 链接
119 | })
120 | );
121 |
122 | menu.addItem((item: MenuItem) =>
123 | item
124 | .setIcon("square-arrow-out-up-right")
125 | .setTitle("Open in the default app")
126 | .onClick(() => {
127 | const libraryPath = plugin.settings.libraryPath;
128 | const localFilePath = path.join(
129 | libraryPath,
130 | "images",
131 | `${id}.info`,
132 | `${name}.${ext}`
133 | );
134 |
135 | // 打印路径用于调试
136 | new Notice(`File real path: ${localFilePath}`);
137 | // print(`文件的真实路径是: ${localFilePath}`);
138 |
139 | // 使用 spawn 调用 explorer.exe 打开文件
140 | const child = spawn('explorer.exe', [localFilePath], { shell: true });
141 | child.on('error', (error) => {
142 | print('Error opening file:', error);
143 | new Notice('Cannot open the file, please check if the path is correct');
144 | });
145 |
146 | child.on('exit', (code) => {
147 | if (code === 0) {
148 | print('The file has been opened successfully');
149 | } else {
150 | print(`The file cannot be opened normally, exit code: ${code}`);
151 | }
152 | });
153 | })
154 | );
155 | menu.addItem((item: MenuItem) =>
156 | item
157 | .setIcon("external-link")
158 | .setTitle("Open in other apps")
159 | .onClick(() => {
160 | const libraryPath = plugin.settings.libraryPath;
161 | const localFilePath = path.join(
162 | libraryPath,
163 | "images",
164 | `${id}.info`,
165 | `${name}.${ext}`
166 | );
167 |
168 | // 打印路径用于调试
169 | new Notice(`File real path: ${localFilePath}`);
170 | // print(`文件的真实路径是: ${localFilePath}`);
171 |
172 | // 使用 rundll32 调用系统的"打开方式"对话框
173 | const child = spawn('rundll32', ['shell32.dll,OpenAs_RunDLL', localFilePath], { shell: true });
174 |
175 | child.on('error', (error) => {
176 | print('Error opening file:', error);
177 | new Notice('Cannot open the file, please check if the path is correct');
178 | });
179 |
180 | child.on('exit', (code) => {
181 | if (code === 0) {
182 | print('The file has been opened successfully');
183 | } else {
184 | print(`The file cannot be opened normally, exit code: ${code}`);
185 | }
186 | });
187 | })
188 | );
189 | // 复制源文件
190 | menu.addItem((item: MenuItem) =>
191 | item
192 | .setIcon("copy")
193 | .setTitle("Copy source file")
194 | .onClick(() => {
195 | const libraryPath = plugin.settings.libraryPath;
196 | const localFilePath = path.join(
197 | libraryPath,
198 | "images",
199 | `${id}.info`,
200 | `${name}.${ext}`
201 | );
202 | try {
203 | copyFileToClipboardCMD(localFilePath);
204 | new Notice("Copied to clipboard!", 3000);
205 | } catch (error) {
206 | console.error(error);
207 | new Notice("Failed to copy the file!", 3000);
208 | }
209 | })
210 | );
211 | menu.addItem((item: MenuItem) =>
212 | item
213 | .setIcon("case-sensitive")
214 | .setTitle(`Eagle Name: ${name}`)
215 | .onClick(() => {
216 | navigator.clipboard.writeText(name);
217 | new Notice(`Copied: ${name}`);
218 | })
219 | );
220 |
221 | menu.addItem((item: MenuItem) =>
222 | item
223 | .setIcon("letter-text")
224 | .setTitle(`Eagle Annotation: ${annotation}`)
225 | .onClick(() => {
226 | navigator.clipboard.writeText(annotation);
227 | new Notice(`Copied: ${annotation}`);
228 | })
229 | );
230 |
231 | menu.addItem((item: MenuItem) =>
232 | item
233 | .setIcon("link-2")
234 | .setTitle(`Eagle url: ${url}`)
235 | .onClick(() => {
236 | // navigator.clipboard.writeText(url);
237 | window.open(url, '_self');
238 | new Notice(`Copied: ${url}`);
239 | })
240 | );
241 | // 确保 tags 是一个数组
242 | const tagsArray = Array.isArray(tags) ? tags : tags.split(',').map(tag => tag.trim());
243 |
244 | menu.addItem((item: MenuItem) =>
245 | item
246 | .setIcon("tags")
247 | .setTitle(`Eagle tag: ${tagsArray.join(', ')}`)
248 | .onClick(() => {
249 | const tagsString = tagsArray.join(', ');
250 | navigator.clipboard.writeText(tagsString)
251 | .then(() => new Notice(`Copied: ${tagsString}`))
252 | .catch(err => new Notice('Failed to copy tags'));
253 | })
254 | );
255 | menu.addItem((item: MenuItem) =>
256 | item
257 | .setIcon("wrench")
258 | .setTitle("Modify properties")
259 | .onClick(() => {
260 | new ModifyPropertiesModal(this.app, id, name, annotation, url, tagsArray, (newId, newName, newAnnotation, newUrl, newTags) => {
261 | // new Notice(`Name changed to: ${newName}`);
262 | // 在这里处理保存逻辑
263 | }).open();
264 | })
265 | );
266 | // 其他菜单项可以继续使用 { id, name, ext } 数据
267 | }
268 |
269 | menu.showAtPosition({ x: event.pageX, y: event.pageY });
270 | }
271 |
272 | export async function addEagleImageMenuSourceMode(plugin: MyPlugin, menu: Menu, url: string, event: MouseEvent) {
273 | await addEagleImageMenuPreviewMode(plugin, menu, url, event);
274 |
275 | menu.addItem((item: MenuItem) =>
276 | item
277 | .setIcon("copy")
278 | .setTitle("Copy markdown link")
279 | .onClick(async () => {
280 | const editor = this.app.workspace.getActiveViewOfType(MarkdownView)?.editor;
281 | if (!editor) {
282 | new Notice('Cannot find the active editor');
283 | return;
284 | }
285 |
286 | const doc = editor.getDoc();
287 | const lineCount = doc.lineCount();
288 |
289 | let linkFound = false;
290 |
291 | for (let line = 0; line < lineCount; line++) {
292 | const lineText = doc.getLine(line);
293 |
294 | // 使用正则表达式查找 Markdown 链接,匹配带叹号和不带叹号的链接
295 | const regex = new RegExp(`(!?\\[.*?\\]\\(${url}\\))`, 'g');
296 | const match = regex.exec(lineText);
297 |
298 | if (match) {
299 | const linkText = match[1]; // 获取完整的匹配文本
300 | navigator.clipboard.writeText(linkText);
301 | new Notice('Link copied');
302 | linkFound = true;
303 | break; // 找到并复制后退出循环
304 | }
305 | }
306 |
307 | if (!linkFound) {
308 | new Notice('Cannot find the link');
309 | }
310 |
311 | })
312 | );
313 | menu.addItem((item: MenuItem) =>
314 | item
315 | .setIcon("trash-2")
316 | .setTitle("Clear markdown link")
317 | .onClick(() => {
318 | try {
319 | // Util.handlerDelFile(FileBaseName, currentMd, this);
320 | const target = getMouseEventTarget(event);
321 | const editor = this.app.workspace.getActiveViewOfType(MarkdownView)?.editor;
322 | const editorView = editor.cm as EditorView;
323 | const target_pos = editorView.posAtDOM(target);
324 | deleteCurTargetLink(url, plugin, target_pos);
325 | } catch {
326 | new Notice("Error, could not clear the file!");
327 | }
328 | })
329 | );
330 | menu.showAtPosition({ x: event.pageX, y: event.pageY });
331 | }
332 |
333 | // 修改eagle属性中的annotation,url,tags
334 | class ModifyPropertiesModal extends Modal {
335 | id: string;
336 | name: string;
337 | annotation: string;
338 | url: string;
339 | tags: string[];
340 | onSubmit: (id: string, name: string, annotation: string, url: string, tags: string[]) => void;
341 |
342 | constructor(app: App, id: string, name: string, annotation: string, url: string, tags: string[], onSubmit: (id: string, name: string, annotation: string, url: string, tags: string[]) => void) {
343 | super(app);
344 | this.id = id;
345 | this.name = name;
346 | this.annotation = annotation;
347 | this.url = url;
348 | this.tags = tags;
349 | this.onSubmit = onSubmit;
350 | }
351 |
352 | onOpen() {
353 | const { contentEl } = this;
354 | contentEl.createEl('h2', { text: 'Modify Properties' });
355 |
356 | new Setting(contentEl)
357 | .setName('Annotation')
358 | .addText(text => text
359 | .setValue(this.annotation)
360 | .onChange(value => {
361 | this.annotation = value;
362 | })
363 | .inputEl.style.width = '400px'
364 | );
365 |
366 | new Setting(contentEl)
367 | .setName('URL')
368 | .addText(text => text
369 | .setValue(this.url)
370 | .onChange(value => {
371 | this.url = value;
372 | })
373 | .inputEl.style.width = '400px'
374 | );
375 |
376 | new Setting(contentEl)
377 | .setName('Tags')
378 | .setDesc('Separate tags use ,')
379 | .addText(text => text
380 | .setValue(this.tags.join(', '))
381 | .onChange(value => {
382 | this.tags = value.split(',').map(tag => tag.trim());
383 | })
384 | .inputEl.style.width = '400px'
385 | );
386 |
387 | new Setting(contentEl)
388 | .addButton(btn => btn
389 | .setButtonText('Save')
390 | .setCta()
391 | .onClick(() => {
392 | // 构建数据对象
393 | const data = {
394 | id: this.id,
395 | // name: this.name,
396 | tags: this.tags,
397 | annotation: this.annotation,
398 | url: this.url,
399 | };
400 |
401 | // 设置请求选项
402 | const requestOptions: RequestInit = {
403 | method: 'POST',
404 | body: JSON.stringify(data),
405 | redirect: 'follow' as RequestRedirect
406 | };
407 |
408 | // 发送请求
409 | fetch("http://localhost:41595/api/item/update", requestOptions)
410 | .then(response => response.json())
411 | .then(result => {
412 | print(result);
413 | new Notice('Data uploaded successfully');
414 | })
415 | .catch(error => {
416 | print('error', error);
417 | new Notice('Failed to upload data');
418 | });
419 |
420 | // 调用 onSubmit 回调
421 | this.onSubmit(this.id, this.name, this.annotation, this.url, this.tags);
422 | this.close();
423 | }));
424 | }
425 |
426 | onClose() {
427 | const { contentEl } = this;
428 | contentEl.empty();
429 | }
430 | }
431 |
432 |
433 | function copyFileToClipboardCMD(filePath: string) {
434 |
435 | if (!existsSync(filePath)) {
436 | console.error(`File ${filePath} does not exist`);
437 | return;
438 | }
439 |
440 | const callback = (error: Error | null, stdout: string, stderr: string) => {
441 | if (error) {
442 | new Notice(`Error executing command: ${error.message}`, 3000);
443 | console.error(`Error executing command: ${error.message}`);
444 | return;
445 | }
446 | };
447 |
448 | if (process.platform === 'darwin') {
449 | execSync(`open -R "${filePath}"`);
450 | execSync(`osascript -e 'tell application "System Events" to keystroke "c" using command down'`);
451 | execSync(`osascript -e 'tell application "System Events" to keystroke "w" using command down'`);
452 | execSync(`open -a "Obsidian.app"`);
453 | } else if (process.platform === 'linux') {
454 | } else if (process.platform === 'win32') {
455 | let safeFilePath = filePath.replace(/'/g, "''");
456 | exec(`powershell -command "Set-Clipboard -Path '${safeFilePath}'"`, callback);
457 | }
458 | }
459 |
460 | export async function fetchImageInfo(url: string): Promise<{ id: string, name: string, ext: string, annotation: string, tags: string, url: string } | null> {
461 | const match = url.match(/\/images\/(.*)\.info/);
462 | if (match && match[1]) {
463 | const requestOptions: RequestInit = {
464 | method: 'GET',
465 | redirect: 'follow' as RequestRedirect
466 | };
467 |
468 | try {
469 | const response = await fetch(`http://localhost:41595/api/item/info?id=${match[1]}`, requestOptions);
470 | const result = await response.json();
471 |
472 | if (result.status === "success" && result.data) {
473 | return result.data;
474 | } else {
475 | print('Failed to fetch item info');
476 | }
477 | } catch (error) {
478 | print('Error fetching item info', error);
479 | }
480 | } else {
481 | print('Invalid image source format');
482 | }
483 | return null;
484 | }
485 |
486 | export const getMouseEventTarget = (event: MouseEvent): HTMLElement => {
487 | event.preventDefault();
488 | const target = event.target as HTMLElement;
489 | return target;
490 | }
491 |
492 | export function deleteCurTargetLink(
493 | url: string,
494 | plugin: MyPlugin,
495 | target_pos: number,
496 | ) {
497 | const activeView = plugin.app.workspace.getActiveViewOfType(MarkdownView);
498 | if (!activeView) {
499 | new Notice("无法获取活动视图!", 3000);
500 | return;
501 | }
502 | const editor = activeView.editor;
503 | const editorView = (editor as any).cm as EditorView;
504 |
505 | // 获取目标行和文本
506 | const target_line = editorView.state.doc.lineAt(target_pos);
507 | const line_text = target_line.text;
508 |
509 | // 检查是否在表格或callout中
510 | const target = editorView.domAtPos(target_pos).node as HTMLElement;
511 | const inTable = !!target.closest('table');
512 | const inCallout = !!target.closest('.callout');
513 |
514 | if (!inTable && !inCallout) {
515 | // 普通文本中的链接
516 | const finds = findLinkInLine(url, line_text);
517 | if (finds.length === 0) {
518 | new Notice("无法找到链接文本,请手动删除!", 3000);
519 | return;
520 | }
521 | else if (finds.length !== 1) {
522 | new Notice("当前行中发现多个相同的链接,请手动删除!", 3000);
523 | return;
524 | }
525 | else {
526 | editor.replaceRange('',
527 | {line: target_line.number-1, ch: finds[0][0]},
528 | {line: target_line.number-1, ch: finds[0][1]}
529 | );
530 | return;
531 | }
532 | }
533 |
534 | // 处理表格或callout中的链接
535 | const startReg: {[key: string]: RegExp} = {
536 | 'table': /^\s*\|/,
537 | 'callout': /^>/,
538 | };
539 |
540 | const mode = inTable ? 'table' : 'callout';
541 | let finds_lines: number[] = [];
542 | let finds_all: [number, number][] = [];
543 |
544 | // 向下搜索
545 | for (let i = target_line.number; i <= editor.lineCount(); i++) {
546 | const line_text = editor.getLine(i-1);
547 | if (!startReg[mode].test(line_text)) break;
548 |
549 | const finds = findLinkInLine(url, line_text);
550 | if (finds.length > 0) {
551 | finds_lines.push(...new Array(finds.length).fill(i));
552 | finds_all.push(...finds);
553 | }
554 | }
555 |
556 | // 向上搜索
557 | for (let i = target_line.number-1; i >= 1; i--) {
558 | const line_text = editor.getLine(i-1);
559 | if (!startReg[mode].test(line_text)) break;
560 |
561 | const finds = findLinkInLine(url, line_text);
562 | if (finds.length > 0) {
563 | finds_lines.push(...new Array(finds.length).fill(i));
564 | finds_all.push(...finds);
565 | }
566 | }
567 |
568 | if (finds_all.length === 0) {
569 | new Notice(`无法在${mode}中找到链接文本,请手动删除!`, 3000);
570 | return;
571 | }
572 | else if (finds_all.length !== 1) {
573 | new Notice(`在${mode}中找到多个相同的链接,请手动删除!`, 3000);
574 | return;
575 | }
576 | else {
577 | editor.replaceRange('',
578 | {line: finds_lines[0]-1, ch: finds_all[0][0]},
579 | {line: finds_lines[0]-1, ch: finds_all[0][1]}
580 | );
581 | }
582 |
583 | editor.focus();
584 | }
585 |
586 | // 查找一行中包含特定URL的链接
587 | function findLinkInLine(url: string, line: string): [number, number][] {
588 | const results: [number, number][] = [];
589 |
590 | // 匹配Markdown链接:  或 [text](url)
591 | const regex = new RegExp(`(!?\\[[^\\]]*\\]\\(${escapeRegExp(url)}[^)]*\\))`, 'g');
592 |
593 | let match;
594 | while ((match = regex.exec(line)) !== null) {
595 | results.push([match.index, match.index + match[0].length]);
596 | }
597 |
598 | return results;
599 | }
600 |
601 | // 转义正则表达式特殊字符
602 | function escapeRegExp(string: string): string {
603 | return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
604 | }
--------------------------------------------------------------------------------
/src/onElement.ts:
--------------------------------------------------------------------------------
1 | // 这段代码定义了一个名为 `onElement` 的函数和一个 `Listener` 接口。
2 |
3 | // `onElement` 函数用于在指定的文档元素上注册事件监听器,并返回一个函数以便稍后移除该监听器。它接受以下参数:
4 | // - `el`: 要注册事件的文档元素。
5 | // - `event`: 要监听的事件类型。
6 | // - `selector`: 选择器字符串,用于匹配要监听的子元素。
7 | // - `listener`: 事件触发时要调用的回调函数。
8 | // - `options`: 可选参数,用于指定事件监听器的选项(例如是否在捕获阶段触发)。
9 |
10 | // `Listener` 接口定义了一个回调函数类型,该函数在事件触发时被调用。
11 |
12 | // 具体实现中,`el.on` 方法用于注册事件监听器,`el.off` 方法用于移除事件监听器。
13 |
14 | export function onElement(
15 | el: Document,
16 | event: keyof HTMLElementEventMap,
17 | selector: string,
18 | listener: Listener,
19 | options?: { capture?: boolean; }
20 | ) {
21 | el.on(event, selector, listener, options);
22 | return () => el.off(event, selector, listener, options);
23 | }
24 |
25 | export interface Listener {
26 | // eslint-disable-next-line @typescript-eslint/no-explicit-any
27 | (this: Document, ev: Event): any;
28 | }
29 |
30 | // 如果是 type 是 "img",就准确删除图片引用链接的部分,如果是其他类型,直接删除整行
31 | // target_line (1-based) 和 target_ch 是指示附件所在的位置
32 | // export const deleteCurTargetLink = (
33 | // file_base_name: string,
34 | // plugin: AttachFlowPlugin,
35 | // target_type: string,
36 | // target_pos: number,
37 | // in_table: boolean,
38 | // in_callout: boolean
39 | // ) => {
40 | // file_base_name = file_base_name.startsWith('/') ? file_base_name.substring(1):file_base_name;
41 | // const activeView = plugin.app.workspace.getActiveViewOfType(MarkdownView) as MarkdownView;
42 | // const editor = activeView.editor;
43 | // // @ts-expect-error, not typed
44 | // const editorView = editor.cm as EditorView;
45 |
46 | // let target_line = editorView.state.doc.lineAt(target_pos);
47 | // let line_text = target_line.text;
48 |
49 | // if (!in_table && !in_callout){
50 | // let finds = findLinkInLine(file_base_name, line_text);
51 | // if (finds.length == 0){
52 | // new Notice("Fail to find the link-text, please delete it manually!", 0);
53 | // return;
54 | // }
55 | // else if(finds.length != 1){
56 | // new Notice("Find multiple same Link in current line, please delete it manually!", 0);
57 | // return;
58 | // }
59 | // else{
60 | // // editorView.dispatch({changes: {from: target_line.from + finds[0][0], to: target_line.from + finds[0][1], insert: ''}});
61 | // editor.replaceRange('', {line: target_line.number-1, ch: finds[0][0]}, {line: target_line.number-1, ch: finds[0][1]});
62 | // return;
63 | // }
64 | // }
65 |
66 | // type RegDictionary = {
67 | // [key: string]: RegExp;
68 | // };
69 |
70 | // let startReg: RegDictionary = {
71 | // 'table': /^\s*\|/,
72 | // 'callout': /^>/,
73 | // };
74 |
75 | // let mode = in_table ? 'table' : 'callout';
76 | // let finds_lines: number[] = [];
77 | // let finds_all: [from:number, to:number][] = [];
78 | // for (let i=target_line.number; i<=editor.lineCount(); i++){
79 | // let line_text = editor.getLine(i-1);
80 | // if (!startReg[mode].test(line_text)) break;
81 | // print(`line_${i}_text:`, line_text)
82 | // let finds = findLinkInLine(file_base_name, line_text);
83 | // if (finds.length > 0){
84 | // finds_lines.push(...new Array(finds.length).fill(i));
85 | // finds_all.push(...finds);
86 | // }
87 | // }
88 |
89 | // for (let i=target_line.number-1; i>=1; i--){
90 | // let line_text = editor.getLine(i-1);
91 | // if (!startReg[mode].test(line_text)) break;
92 | // print(`line_${i}_text:`, line_text)
93 | // let finds = findLinkInLine(file_base_name, line_text);
94 | // if (finds.length > 0){
95 | // finds_lines.push(...new Array(finds.length).fill(i));
96 | // finds_all.push(...finds);
97 | // }
98 | // }
99 |
100 | // if (finds_all.length == 0){
101 | // new Notice(`Fail to find the link-text (for links in ${mode}), please delete it manually!`, 0);
102 | // return;
103 | // }
104 | // else if(finds_all.length != 1){
105 | // new Notice(`Find multiple same Link in current ${mode}, please delete it manually!`, 0);
106 | // return;
107 | // }
108 | // else{
109 | // editor.replaceRange('', {line: finds_lines[0]-1, ch: finds_all[0][0]}, {line: finds_lines[0]-1, ch: finds_all[0][1]});
110 | // }
111 |
112 | // editor.focus();
113 | // }
--------------------------------------------------------------------------------
/src/server.ts:
--------------------------------------------------------------------------------
1 | import * as http from 'http';
2 | import * as fs from 'fs';
3 | import * as path from 'path';
4 | import chokidar from 'chokidar';
5 | import { EventEmitter } from 'events';
6 | import { print, setDebug } from './main';
7 |
8 | let server: http.Server;
9 | let isServerRunning = false;
10 | let latestDirUrl: string | null = null;
11 |
12 | const urlEmitter = new EventEmitter();
13 |
14 | // let exportedData: { imageName?: string; annotation?: string } = {};
15 |
16 | function getContentType(ext: string): string | null {
17 | switch (ext) {
18 | case '.jpg':
19 | case '.jpeg':
20 | return 'image/jpeg';
21 | case '.png':
22 | return 'image/png';
23 | case '.gif':
24 | return 'image/gif';
25 | case '.webp':
26 | return 'image/webp';
27 | case '.svg':
28 | return 'image/svg+xml';
29 | case '.pdf':
30 | return 'application/pdf';
31 | case '.mp4':
32 | return 'video/mp4';
33 | case '.mp3':
34 | return 'audio/mpeg';
35 | case '.ogg':
36 | return 'audio/ogg';
37 | case '.wav':
38 | return 'audio/wav';
39 | case '.json':
40 | return 'application/json';
41 | case '.xml':
42 | return 'application/xml';
43 | case '.ico':
44 | return 'image/x-icon';
45 | case '.txt':
46 | return 'text/plain';
47 | case '.csv':
48 | return 'text/csv';
49 | case '.html':
50 | return 'text/html';
51 | case '.css':
52 | return 'text/css';
53 | case '.js':
54 | return 'application/javascript';
55 | // case '.pptx':
56 | // return 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
57 | // case '.url':
58 | // return 'text/plain';
59 | default:
60 | return null;
61 | }
62 | }
63 |
64 | export function startServer(libraryPath: string, port: number) {
65 | if (isServerRunning) return;
66 |
67 | const imagesPath = path.join(libraryPath, 'images');
68 |
69 | // 使用 chokidar 监控 images 目录中新建的文件夹
70 | const watcher = chokidar.watch(imagesPath, {
71 | ignored: /(^|[\/\\])\../, // 忽略隐藏文件
72 | persistent: true,
73 | depth: 1, // 只监控一级目录
74 | ignoreInitial: true // 忽略初始添加的文件和文件夹
75 | });
76 |
77 | watcher.on('addDir', (dirPath) => {
78 | const relativePath = path.relative(libraryPath, dirPath).replace(/\\/g, '/');
79 | latestDirUrl = `http://localhost:${port}/${relativePath}`;
80 | // console.log(`新建文件夹路径: ${latestDirUrl}`);
81 | urlEmitter.emit('urlUpdated', latestDirUrl);
82 | });
83 |
84 | server = http.createServer((req, res) => {
85 | res.setHeader('Access-Control-Allow-Origin', '*');
86 | res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
87 | res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
88 | res.setHeader('Access-Control-Allow-Credentials', 'true');
89 |
90 | const filePath = path.join(libraryPath, req.url || '');
91 |
92 | // 解析 URL 查询参数
93 | const url = new URL(req.url || '/', `http://${req.headers.host}`);
94 | const noAutoplay = url.searchParams.has('noautoplay');
95 |
96 | // 将参数存储在请求对象中,以便后续处理时使用
97 | (req as any).noAutoplay = noAutoplay;
98 |
99 | // 新增:提前验证请求路径是否在 images 目录下
100 | if (!filePath.startsWith(path.join(libraryPath, 'images') + path.sep)) {
101 | res.writeHead(404);
102 | res.end();
103 | return;
104 | }
105 |
106 | fs.stat(filePath, (err, stats) => {
107 | if (err) {
108 | // 修改:静默处理 ENOENT 错误
109 | if (err.code === 'ENOENT') {
110 | res.writeHead(404).end();
111 | } else {
112 | res.writeHead(500).end('Internal Error');
113 | }
114 | return;
115 | }
116 |
117 | if (stats.isDirectory()) {
118 | const jsonFilePath = path.join(filePath, 'metadata.json');
119 |
120 | // 新增:检查 metadata.json 是否存在
121 | if (!fs.existsSync(jsonFilePath)) {
122 | res.writeHead(404).end();
123 | return;
124 | }
125 |
126 | fs.readFile(jsonFilePath, 'utf8', (err, data) => {
127 | if (err) {
128 | console.error('Error reading JSON file:', err);
129 | res.writeHead(500, {'Content-Type': 'text/plain'});
130 | res.end('Internal Server Error');
131 | } else {
132 | try {
133 | const info = JSON.parse(data);
134 | const imageName = info.name;
135 | // exportedData.imageName = imageName;
136 | // const annotation = info.annotation;
137 | // exportedData.annotation = annotation;
138 | const imageExt = info.ext;
139 | const imageFile = `${imageName}.${imageExt}`;
140 | const imagePath = path.join(filePath, imageFile);
141 |
142 | fs.readFile(imagePath, (err, data) => {
143 | if (err) {
144 | console.error('Error reading file:', err);
145 | res.writeHead(404, {'Content-Type': 'text/plain'});
146 | res.end('File not found');
147 | } else {
148 | if (imageExt === 'url') {
149 | const content = data.toString('utf8');
150 | const urlMatch = content.match(/URL=(.+)/i);
151 | if (urlMatch && urlMatch[1]) {
152 | res.writeHead(302, { 'Location': urlMatch[1] });
153 | res.end();
154 | return;
155 | }
156 | }
157 | const contentType = getContentType(`.${imageExt}`);
158 | if (contentType === null) {
159 | res.writeHead(204);
160 | res.end();
161 | return;
162 | }
163 | res.writeHead(200, {'Content-Type': contentType});
164 | res.end(data);
165 | }
166 | });
167 | } catch (parseErr) {
168 | console.error('Error parsing JSON:', parseErr);
169 | res.writeHead(500, {'Content-Type': 'text/plain'});
170 | res.end('Error parsing JSON');
171 | }
172 | }
173 | });
174 | } else {
175 | // 新增:缓存验证头
176 | res.setHeader('Cache-Control', 'public, max-age=604800'); // 1 week
177 |
178 | fs.readFile(filePath, (err, data) => {
179 | if (err) {
180 | // console.error('Error reading file:', err);
181 | res.writeHead(500, {'Content-Type': 'text/plain'});
182 | res.end('Internal Server Error');
183 | } else {
184 | const ext = path.extname(filePath).toLowerCase();
185 | const contentType = getContentType(ext);
186 | if (contentType === null) {
187 | res.writeHead(204);
188 | res.end();
189 | return;
190 | }
191 | if (ext === '.url') {
192 | const content = data.toString('utf8');
193 | const urlMatch = content.match(/URL=(.+)/i);
194 | if (urlMatch && urlMatch[1]) {
195 | res.writeHead(302, { 'Location': urlMatch[1] });
196 | res.end();
197 | return;
198 | }
199 | }
200 | res.writeHead(200, {'Content-Type': contentType});
201 | res.end(data);
202 | }
203 | });
204 | }
205 | });
206 | });
207 |
208 |
209 | server.listen(port, () => {
210 | isServerRunning = true;
211 | print(`Server is running at http://localhost:${port}/`);
212 | });
213 | }
214 |
215 | export function refreshServer(libraryPath: string, port: number) {
216 | if (!isServerRunning) return;
217 | server.close(() => {
218 | isServerRunning = false;
219 | print('Server stopped for refresh.');
220 | startServer(libraryPath, port);
221 | });
222 | }
223 |
224 | export function stopServer() {
225 | if (isServerRunning) {
226 | server.close(() => {
227 | isServerRunning = false;
228 | print('Server stopped.');
229 | });
230 | }
231 | }
232 |
233 | export function getLatestDirUrl(): string | null {
234 | return latestDirUrl;
235 | }
236 |
237 | export { urlEmitter };
238 |
239 | // export { exportedData };
240 |
--------------------------------------------------------------------------------
/src/setting.ts:
--------------------------------------------------------------------------------
1 | import { App, PluginSettingTab, Setting, Notice } from 'obsidian';
2 | import MyPlugin from './main';
3 | import { startServer, refreshServer, stopServer } from './server';
4 |
5 | export interface MyPluginSettings {
6 | mySetting: string;
7 | port: number;
8 | libraryPath: string;
9 | folderId?: string;
10 | clickView: boolean;
11 | adaptiveRatio: number;
12 | advancedID: boolean;
13 | obsidianStoreId: string;
14 | imageSize: number | undefined;
15 | websiteUpload: boolean;
16 | libraryPaths: string[];
17 | debug: boolean;
18 | openInObsidian: string;
19 | }
20 |
21 | export const DEFAULT_SETTINGS: MyPluginSettings = {
22 | mySetting: 'default',
23 | port: 6060,
24 | libraryPath: '',
25 | folderId: '',
26 | clickView: false,
27 | adaptiveRatio: 0.8,
28 | advancedID: false,
29 | obsidianStoreId: '',
30 | imageSize: undefined,
31 | websiteUpload: false,
32 | libraryPaths: [],
33 | debug: false,
34 | openInObsidian: 'newPage',
35 | }
36 |
37 |
38 | export class SampleSettingTab extends PluginSettingTab {
39 | plugin: MyPlugin;
40 |
41 | constructor(app: App, plugin: MyPlugin) {
42 | super(app, plugin);
43 | this.plugin = plugin;
44 | }
45 |
46 | display(): void {
47 | const { containerEl } = this;
48 |
49 | containerEl.empty();
50 |
51 | new Setting(containerEl)
52 | .setName('Port')
53 | .setDesc('Enter the port number of the server, ranging from 1000 to 9999, and do not modify it after setting.')
54 | .addText(text => text
55 | .setPlaceholder('Enter port number')
56 | .setValue(this.plugin.settings.port.toString())
57 | .onChange(async (value) => {
58 | this.plugin.settings.port = parseInt(value);
59 | await this.plugin.saveSettings();
60 | }));
61 |
62 | new Setting(containerEl)
63 | .setName('Library Paths')
64 | .setDesc(`Enter multiple library paths for the server. Current valid path: ${this.plugin.settings.libraryPath}`)
65 | .addButton(button => {
66 | button.setButtonText('+')
67 | .setCta()
68 | .onClick(() => {
69 | this.plugin.settings.libraryPaths.push('');
70 | this.plugin.saveSettings();
71 | this.display(); // 重新渲染设置界面
72 | });
73 | });
74 |
75 | this.plugin.settings.libraryPaths.forEach((path, index) => {
76 | new Setting(containerEl)
77 | .addText(text => text
78 | .setPlaceholder('Enter library path')
79 | .setValue(path)
80 | .onChange(async (value) => {
81 | this.plugin.settings.libraryPaths[index] = value;
82 | await this.plugin.saveSettings();
83 | await this.plugin.updateLibraryPath(); // 更新Library Path
84 | this.display(); // 重新渲染设置界面
85 | }))
86 | .addExtraButton(button => {
87 | button.setIcon('cross')
88 | .setTooltip('Remove')
89 | .onClick(async () => {
90 | this.plugin.settings.libraryPaths.splice(index, 1);
91 | await this.plugin.saveSettings();
92 | await this.plugin.updateLibraryPath(); // 更新Library Path
93 | this.display(); // 重新渲染设置界面
94 | });
95 | });
96 | });
97 | // new Setting(containerEl)
98 | // .setName('Current Library Path')
99 | // .setDesc('The first valid library path')
100 | // .addText(text => text
101 | // .setValue(this.plugin.settings.libraryPath)
102 | // .setDisabled(true)); // 禁用输入框,只显示有效路径
103 |
104 | new Setting(containerEl)
105 | .setName('Eagle Folder ID')
106 | .setDesc('Enter the folder ID for Eagle')
107 | .addText(text => text
108 | .setPlaceholder('Enter folder ID')
109 | .setValue(this.plugin.settings.folderId || '')
110 | .onChange(async (value) => {
111 | this.plugin.settings.folderId = value;
112 | await this.plugin.saveSettings();
113 | }));
114 |
115 | new Setting(containerEl)
116 | .setName('Image size')
117 | .setDesc('Default size for image import')
118 | .addText(text => text
119 | .setPlaceholder('Enter image size')
120 | .setValue(this.plugin.settings.imageSize?.toString() || '')
121 | .onChange(async (value) => {
122 | this.plugin.settings.imageSize = value ? parseInt(value) : undefined;
123 | await this.plugin.saveSettings();
124 | }));
125 |
126 | new Setting(containerEl)
127 | .setName("Click to view images")
128 | .setDesc("Click the right half of the image to view the image in detail.")
129 | .addToggle((toggle) => {
130 | toggle.setValue(this.plugin.settings.clickView)
131 | .onChange(async (value) => {
132 | this.plugin.settings.clickView = value;
133 | await this.plugin.saveSettings();
134 | });
135 | });
136 |
137 | new Setting(containerEl)
138 | .setName('Adaptive image display ratio based on window size')
139 | .setDesc('When the image exceeds the window size, the image is displayed adaptively according to the window size.')
140 | .addSlider((slider) => {
141 | slider.setLimits(0.1, 1, 0.05);
142 | slider.setValue(this.plugin.settings.adaptiveRatio);
143 | slider.onChange(async (value) => {
144 | this.plugin.settings.adaptiveRatio = value;
145 | new Notice(`Adaptive ratio: ${value}`);
146 | await this.plugin.saveSettings();
147 | });
148 | slider.setDynamicTooltip();
149 | });
150 |
151 | new Setting(containerEl)
152 | .setName("Synchronizing advanced URI as a tag")
153 | .setDesc("Synchronize advanced URI as a tag when page ids exist.")
154 | .addToggle((toggle) => {
155 | toggle.setValue(this.plugin.settings.advancedID)
156 | .onChange(async (value) => {
157 | this.plugin.settings.advancedID = value;
158 | await this.plugin.saveSettings();
159 | });
160 | });
161 |
162 | new Setting(containerEl)
163 | .setName('Obsidian store ID')
164 | .setDesc('Enter the Obsidian store ID')
165 | .addText(text => text
166 | .setPlaceholder('Enter Obsidian store ID')
167 | .setValue(this.plugin.settings.obsidianStoreId)
168 | .onChange(async (value) => {
169 | this.plugin.settings.obsidianStoreId = value;
170 | await this.plugin.saveSettings();
171 | }));
172 | new Setting(containerEl)
173 | .setName('Open in obsidian')
174 | .setDesc('Default opening of attachments in obsidian')
175 | .addDropdown(dropdown => {
176 | dropdown.addOption('newPage', 'Open in new page')
177 | .addOption('popup', 'Open in popup')
178 | .addOption('rightPane', 'Open in right pane')
179 | .setValue(this.plugin.settings.openInObsidian || 'newPage')
180 | .onChange(async (value) => {
181 | this.plugin.settings.openInObsidian = value;
182 | await this.plugin.saveSettings();
183 | });
184 | });
185 |
186 | new Setting(containerEl)
187 | .setName('Website upload')
188 | .setDesc('URL uploaded to eagle. note: 1. eagle will automatically get the cover, with a certain delay. 2. when exporting notes to share, may not be able to jump effectively. 3.This option does not affect links dragged/copied from eagle to obsidian.')
189 | .addToggle((toggle) => {
190 | toggle.setValue(this.plugin.settings.websiteUpload)
191 | .onChange(async (value) => {
192 | this.plugin.settings.websiteUpload = value;
193 | await this.plugin.saveSettings();
194 | });
195 | });
196 |
197 | new Setting(containerEl)
198 | .setName('Refresh Server')
199 | .setDesc('Refresh the server with the new settings')
200 | .addButton(button => button
201 | .setButtonText('Refresh')
202 | .onClick(() => {
203 | refreshServer(this.plugin.settings.libraryPath, this.plugin.settings.port);
204 | }));
205 |
206 | new Setting(containerEl)
207 | .setName('Debug Mode')
208 | .setDesc('Enable or disable debug mode')
209 | .addToggle(toggle => toggle
210 | .setValue(this.plugin.settings.debug)
211 | .onChange(async (value) => {
212 | this.plugin.settings.debug = value;
213 | await this.plugin.saveSettings();
214 | }));
215 |
216 | }
217 | }
--------------------------------------------------------------------------------
/src/synchronizedpagetabs.ts:
--------------------------------------------------------------------------------
1 | import { App, Notice, TFile } from 'obsidian';
2 | import { MyPluginSettings } from './setting';
3 | import { print, setDebug } from './main';
4 |
5 | export async function syncTags(app: App, settings: MyPluginSettings) {
6 | try {
7 | // 获取当前 Markdown 文件的 YAML 标签
8 | const yamlTags = getYamlTagsFromCurrentFile(app); // 例如:['tag1', 'tag2']
9 |
10 | // 检查 advancedID 设置
11 | let additionalTags: string[] = [];
12 | if (settings.advancedID) {
13 | const yamlId = getYamlIdFromCurrentFile(app);
14 | if (yamlId) {
15 | additionalTags.push(yamlId);
16 | }
17 | }
18 |
19 | // 获取当前文件中所有的 .info 文件 ID
20 | const infoFileIds = await getInfoFileIdsFromCurrentFile(app); // 例如:['M5U5BORKN1LNW', 'KBHG6KA0Y5S9W']
21 |
22 | for (const id of infoFileIds) {
23 | // 获取当前 .info 文件的标签
24 | const currentTags = await fetchTagsForInfoFile(id);
25 |
26 | // 合并并去重标签
27 | const newTags = Array.from(new Set([...currentTags, ...yamlTags, ...additionalTags]));
28 |
29 | // 发送更新后的标签
30 | await updateTagsForInfoFile(id, newTags);
31 | new Notice('Tags synced successfully');
32 | }
33 | } catch (error) {
34 | print('Error syncing tags:', error);
35 | new Notice('Error syncing tags. Check console for details.');
36 | }
37 | }
38 |
39 | async function fetchTagsForInfoFile(id: string): Promise {
40 | const requestOptions: RequestInit = {
41 | method: 'GET',
42 | redirect: 'follow' as RequestRedirect
43 | };
44 |
45 | const response = await fetch(`http://localhost:41595/api/item/info?token=YOUR_API_TOKEN&id=${id}`, requestOptions);
46 | const result = await response.json();
47 | return result.data.tags || [];
48 | }
49 |
50 | async function updateTagsForInfoFile(id: string, tags: string[]) {
51 | const data = {
52 | id: id,
53 | tags: tags
54 | };
55 |
56 | const requestOptions: RequestInit = {
57 | method: 'POST',
58 | body: JSON.stringify(data),
59 | redirect: 'follow' as RequestRedirect
60 | };
61 |
62 | const response = await fetch("http://localhost:41595/api/item/update", requestOptions);
63 | const result = await response.json();
64 | print(`Updated tags for ${id}:`, result);
65 | }
66 |
67 | function getYamlTagsFromCurrentFile(app: App): string[] {
68 | const activeFile = app.workspace.getActiveFile();
69 | if (!activeFile) {
70 | new Notice('No active file found.');
71 | return [];
72 | }
73 |
74 | const fileCache = app.metadataCache.getFileCache(activeFile);
75 | if (!fileCache || !fileCache.frontmatter) {
76 | new Notice('No YAML frontmatter found.');
77 | return [];
78 | }
79 |
80 | return fileCache.frontmatter.tags || [];
81 | }
82 |
83 | async function getInfoFileIdsFromCurrentFile(app: App): Promise {
84 | const activeFile = app.workspace.getActiveFile();
85 | if (!activeFile) {
86 | new Notice('No active file found.');
87 | return [];
88 | }
89 |
90 | const fileContent = await app.vault.read(activeFile);
91 | const regex = /http:\/\/localhost:\d+\/images\/([A-Z0-9]+)\.info/g;
92 | let match;
93 | const ids = new Set();
94 |
95 | while ((match = regex.exec(fileContent)) !== null) {
96 | ids.add(match[1]); // match[1] 是正则表达式中捕获的 ID
97 | }
98 |
99 | return Array.from(ids);
100 | }
101 |
102 | function getYamlIdFromCurrentFile(app: App): string | null {
103 | const activeFile = app.workspace.getActiveFile();
104 | if (!activeFile) {
105 | new Notice('No active file found.');
106 | return null;
107 | }
108 |
109 | const fileCache = app.metadataCache.getFileCache(activeFile);
110 | if (!fileCache || !fileCache.frontmatter) {
111 | new Notice('No YAML frontmatter found.');
112 | return null;
113 | }
114 |
115 | return fileCache.frontmatter.id || null;
116 | }
117 |
--------------------------------------------------------------------------------
/src/urlHandler.ts:
--------------------------------------------------------------------------------
1 | import { Editor , Notice , FileSystemAdapter} from 'obsidian';
2 | import * as fs from 'fs';
3 | import * as path from 'path';
4 | import * as os from 'os';
5 | import { getLatestDirUrl, urlEmitter } from './server';
6 | import MyPlugin from './main';
7 | import { print, setDebug } from './main';
8 | const electron = require('electron')
9 | const clipboard = electron.clipboard;
10 |
11 | // import { clipboard } from 'electron';
12 | // const { remote } = require('electron');
13 | // declare const app: any; // 声明全局 app 变量
14 |
15 | // 处理粘贴事件的函数
16 | export async function handlePasteEvent(clipboardEvent: ClipboardEvent, editor: Editor, port: number, pluginInstance: MyPlugin) {
17 | // 获取剪贴板中的纯文本内容
18 | let clipboardText = clipboardEvent.clipboardData?.getData('text/plain');
19 | let filePath = "";
20 |
21 | if (clipboardEvent.clipboardData?.files.length) {
22 | clipboardEvent.preventDefault();
23 | const file = clipboardEvent.clipboardData.files[0];
24 | filePath = electron.webUtils.getPathForFile(file);
25 |
26 | if (!filePath) { // 如果 filePath 不存在
27 | const tempDir = os.tmpdir(); // 使用 os.tmpdir() 获取临时目录
28 | const uploadDir = path.join(tempDir, 'obsidian-uploads');
29 | if (!fs.existsSync(uploadDir)) {
30 | fs.mkdirSync(uploadDir);
31 | }
32 |
33 | // 将文件保存到临时目录
34 | filePath = path.join(uploadDir, file.name);
35 | // console.log('File path2:', filePath); // 在控制台打印文件路径
36 | const buffer = await file.arrayBuffer();
37 | fs.writeFileSync(filePath, Buffer.from(buffer));
38 | }
39 | }
40 |
41 | if (clipboardText && /^https?:\/\/[^\s]+$/.test(clipboardText) && !clipboardText.startsWith('http://localhost')) {
42 | // 如果文本内容为 URL 且不以 http://localhost 开头
43 |
44 | if (pluginInstance.settings.websiteUpload) {
45 | clipboardEvent.preventDefault();
46 | try {
47 | const url = `${clipboardText}`;
48 | await uploadByUrl(url, pluginInstance, editor);
49 | new Notice('URL uploaded successfully, please wait for Eagle link update', 12000);
50 | } catch (error) {
51 | new Notice('URL upload failed');
52 | }
53 | print(`Clipboard has text: ${clipboardText}`);
54 | } else {
55 | return;
56 | }
57 | } else if (filePath) {
58 | // 如果 filePath 存在
59 | clipboardEvent.preventDefault();
60 | if (!filePath.startsWith(pluginInstance.settings.libraryPath)) {
61 | print('filePath1:', filePath);
62 | // 如果 filePath 不属于 pluginInstance.settings.libraryPath 的子文件
63 | try {
64 | await uploadByClipboard(filePath, pluginInstance);
65 | new Notice('File uploaded successfully');
66 |
67 | // 监听 URL 更新事件
68 | urlEmitter.once('urlUpdated', (latestDirUrl: string) => {
69 | const fileName = path.basename(filePath);
70 | const fileExt = path.extname(filePath).toLowerCase();
71 |
72 | if (['.png', '.jpg', '.jpeg', '.gif', '.webp'].includes(fileExt)) {
73 | editor.replaceSelection(``);
74 | new Notice('Eagle link converted');
75 | } else {
76 | editor.replaceSelection(`[${fileName}](${latestDirUrl})`);
77 | }
78 | });
79 | } catch (error) {
80 | new Notice('File upload failed, check if Eagle is running');
81 | }
82 | } else {
83 | // 检查 filePath 中是否包含 'images\xxxxxx.info' 模式
84 | const match = filePath.match(/images\\[^\\]+\.info/);
85 | if (match) {
86 | const fileName = path.basename(filePath);
87 | const fileExt = path.extname(filePath).toLowerCase();
88 |
89 | let updatedText;
90 | const urlPath = match[0].replace(/\\/g, '/'); // 将反斜杠替换为正斜杠
91 |
92 | if (['.png', '.jpg', '.jpeg'].includes(fileExt)) {
93 | clipboardEvent.preventDefault();
94 | updatedText = ``;
95 | } else {
96 | clipboardEvent.preventDefault();
97 | updatedText = `[${fileName}](http://localhost:${port}/${urlPath})`;
98 | }
99 | editor.replaceSelection(updatedText);
100 | new Notice('Eagle link converted');
101 | } else {
102 | new Notice('Non-Eagle link');
103 | }
104 | }
105 | }
106 | }
107 | // 检查剪贴板内容是否为Eagle链接
108 | // if (/eagle:\/\/item\/(\w+)/.test(clipboardText)) {
109 | // clipboard.preventDefault();
110 | // const updatedText = clipboardText.replace(/eagle:\/\/item\/(\w+)/g, (match, p1) => {
111 | // return ``;
112 | // });
113 | // editor.replaceSelection(updatedText);
114 | // new Notice('Eagle链接已转换');
115 | // }
116 | // 如果是非局域网的URL
117 |
118 | // 获取剪贴板内容
119 | // else if (os === "win32") {
120 | // const rawFilePath = clipboard.readBuffer("FileNameW");
121 | // filePath = rawFilePath.toString('ucs2').replace(new RegExp(String.fromCharCode(0), "g"), "");
122 | // } else if (os === "darwin") {
123 | // filePath = clipboard.read("public.file-url").replace("file://", "");
124 | // } else {
125 | // filePath = ""; // Linux 或其他系统的处理
126 | // }
127 | // 检查剪贴板内容
128 |
129 | // 使用API上传剪贴板中的图片
130 | async function uploadByClipboard(filePath: string, pluginInstance: MyPlugin): Promise {
131 | // 从插件实例的 settings 中获取 folderId
132 | const folderId = pluginInstance.settings.folderId || "";
133 |
134 | // 构建请求数据
135 | const data = {
136 | "path": filePath, // 直接使用传入的文件路径
137 | "name": path.basename(filePath), // 从路径中提取文件名
138 | "folderId": folderId,
139 | // "token": "58f7ecda-250f-4043-8ae0-cd11d673f680" // 请替换为实际的API令牌
140 | };
141 |
142 | // 构建请求选项
143 | const requestOptions = {
144 | method: 'POST',
145 | body: JSON.stringify(data),
146 | redirect: 'follow' as RequestRedirect
147 | };
148 |
149 | // 发送请求到指定的API端点
150 | const response = await fetch("http://localhost:41595/api/item/addFromPath", requestOptions);
151 |
152 | if (!response.ok) {
153 | throw new Error('Upload Failed');
154 | }
155 |
156 | // 不需要处理返回值,直接返回
157 | return; // 或者 return null; 如果需要返回一个值
158 | }
159 |
160 |
161 | async function uploadByUrl(url: string, pluginInstance: MyPlugin, editor: Editor): Promise {
162 | const folderId = pluginInstance.settings.folderId || "";
163 | const data = {
164 | "url": url,
165 | // "name": "アルトリア・キャスター",
166 | // "tags": ["FGO", "アルトリア・キャスター"],
167 | "folderId": folderId
168 | };
169 |
170 | print('Request data:', data); // 调试输出请求数据
171 |
172 | const requestOptions = {
173 | method: 'POST',
174 | body: JSON.stringify(data),
175 | redirect: 'follow' as RequestRedirect
176 | };
177 |
178 | try {
179 | const response = await fetch("http://localhost:41595/api/item/addBookmark", requestOptions);
180 |
181 | if (!response.ok) {
182 | const errorResult = await response.json();
183 | console.error('Error response:', errorResult); // 输出错误响应
184 | throw new Error('Upload Failed');
185 | }
186 |
187 | // 添加延时等待
188 | // await new Promise(resolve => setTimeout(resolve, 2000)); // 延时2秒
189 |
190 | // 监听 URL 更新事件
191 | urlEmitter.once('urlUpdated', async (latestDirUrl: string) => {
192 | // 提取 ID
193 | print('latestDirUrl:', latestDirUrl);
194 | const match = latestDirUrl.match(/images\/([^/]+)\.info/);
195 |
196 | if (match && match[1]) {
197 | const fileId = match[1];
198 | await new Promise(resolve => setTimeout(resolve, 2000));
199 | // 设置请求选项
200 | const requestOptions = {
201 | method: 'GET',
202 | redirect: 'follow' as RequestRedirect
203 | };
204 |
205 | try {
206 | // 发送请求以获取文件信息
207 | const response = await fetch(`http://localhost:41595/api/item/info?id=${fileId}`, requestOptions);
208 | const result = await response.json();
209 |
210 | if (result.status === "success" && result.data) {
211 | const fileName = result.data.name + "." + result.data.ext;
212 | // const fileName = path.basename(filePath);
213 | // 更新编辑器中的链接
214 | editor.replaceSelection(`[${fileName}](${latestDirUrl})`);
215 | } else {
216 | print(`Failed to get file information: ${result}`);
217 | }
218 | } catch (error) {
219 | print(`Request error: ${error}`);
220 | }
221 | } else {
222 | print('Cannot extract file ID');
223 | }
224 | });
225 | } catch (error) {
226 | console.error('Fetch error:', error);
227 | throw error;
228 | }
229 | }
230 |
231 |
232 |
233 |
234 |
235 | // export async function handleDropEvent(dropEvent: DragEvent, editor: Editor, port: number, pluginInstance: MyPlugin) {
236 | // dropEvent.preventDefault();
237 |
238 | // // 在代码中添加详细日志
239 | // console.log('原始拖拽数据:', {
240 | // types: dropEvent.dataTransfer?.types,
241 | // files: dropEvent.dataTransfer?.files,
242 | // items: Array.from(dropEvent.dataTransfer?.items || []).map(i => ({
243 | // kind: i.kind,
244 | // type: i.type,
245 | // getAsFile: i.getAsFile()
246 | // }))
247 |
248 | // });
249 |
250 | // // 获取系统平台信息
251 | // const os = process.platform;
252 | // const filePaths: string[] = [];
253 |
254 |
255 | // // 遍历拖拽项
256 | // if (dropEvent.dataTransfer?.items) {
257 | // const items = Array.from(dropEvent.dataTransfer.items); // 将 items 转换为数组
258 | // for (const item of items) {
259 | // if (item.kind === 'file') {
260 | // // 系统级路径获取逻辑
261 | // let filePath = "";
262 |
263 | // // Windows 系统处理
264 | // if (os === "win32") {
265 | // try {
266 | // // 通过私有 API 获取 NTFS 路径
267 | // const file = item.getAsFile() as any;
268 | // if (file?.path) {
269 | // filePath = file.path.replace(/\\/g, '/');
270 | // }
271 | // } catch (error) {
272 | // console.error('Windows路径获取失败:', error);
273 | // }
274 | // }
275 | // // macOS 系统处理
276 | // else if (os === "darwin") {
277 | // try {
278 | // // 通过私有数据格式获取路径
279 | // const uri = dropEvent.dataTransfer.getData('text/uri-list');
280 | // if (uri) {
281 | // filePath = decodeURIComponent(uri)
282 | // .replace('file://', '')
283 | // .replace(/\/([^/]+)$/, '$1'); // 安全解码
284 | // }
285 | // } catch (error) {
286 | // console.error('macOS路径获取失败:', error);
287 | // }
288 | // }
289 |
290 | // // 备用方案:使用传统方式获取
291 | // if (!filePath) {
292 | // const file = item.getAsFile();
293 | // if (file) {
294 | // filePath = (file as any).path || `/${file.name}`;
295 | // }
296 | // }
297 |
298 | // if (filePath) {
299 | // filePaths.push(filePath);
300 | // }
301 | // }
302 | // }
303 | // }
304 |
305 | // // 处理所有获取到的文件路径
306 | // if (filePaths.length > 0) {
307 | // for (const filePath of filePaths) {
308 | // console.log('解析后的完整路径:', filePath);
309 |
310 | // try {
311 | // const file = new File([], filePath); // 创建一个空的 File 对象
312 | // await uploadByClipboard(file, pluginInstance);
313 | // new Notice('文件上传成功');
314 |
315 | // urlEmitter.once('urlUpdated', (latestDirUrl: string) => {
316 | // const extension = filePath.split('.').pop()?.toLowerCase() || '';
317 | // const isImage = ['png', 'jpg', 'jpeg', 'gif', 'webp'].includes(extension);
318 |
319 | // const fileName = filePath.split('/').pop() || filePath;
320 | // if (isImage) {
321 | // editor.replaceSelection(``);
322 | // } else {
323 | // editor.replaceSelection(`[${fileName}](${latestDirUrl})`);
324 | // }
325 | // new Notice('链接已插入');
326 | // });
327 | // } catch (error) {
328 | // console.error('上传失败:', error);
329 | // new Notice(`上传失败: ${error.message}`);
330 | // }
331 | // }
332 | // }
333 | // }
334 |
335 | // // 新增工具函数
336 | // function getFilePath(file: File): string {
337 | // // 类型安全的路径获取方式
338 | // const anyFile = file as any;
339 | // return anyFile.path ||
340 | // anyFile.filepath || // 某些环境下可能使用不同属性名
341 | // (anyFile.name && `/${anyFile.name}`) || // 备用方案
342 | // 'unknown_path';
343 | // }
344 |
345 | // function getFileExtension(path: string): string {
346 | // return path.split('.').pop() || '';
347 | // }
348 |
349 |
350 | // 添加拖动事件处理
351 | export async function handleDropEvent(dropEvent: DragEvent, editor: Editor, port: number, pluginInstance: MyPlugin) {
352 | // 阻止默认行为,这样我们可以自己处理拖放
353 | dropEvent.preventDefault();
354 |
355 |
356 | // 检查拖拽事件中的文件
357 | if (dropEvent.dataTransfer?.files.length) {
358 | const files = dropEvent.dataTransfer.files;
359 | for (let i = 0; i < files.length; i++) {
360 | const file = files[i];
361 | // 使用 electron.webUtils.getPathForFile 获取文件路径
362 | const filePath = electron.webUtils.getPathForFile(file);
363 |
364 | print(`Drag file path: ${filePath}`);
365 |
366 | if (!filePath.startsWith(pluginInstance.settings.libraryPath)) {
367 | // 如果 filePath 不属于 pluginInstance.settings.libraryPath 的子文件
368 | try {
369 | await uploadByClipboard(filePath, pluginInstance);
370 | new Notice('File uploaded successfully');
371 |
372 | // 监听 URL 更新事件
373 | urlEmitter.once('urlUpdated', (latestDirUrl: string) => {
374 | const fileName = path.basename(filePath);
375 | const fileExt = path.extname(filePath).toLowerCase();
376 |
377 | // 准备插入的文本
378 | let insertText;
379 | if (['.png', '.jpg', '.jpeg', '.gif', '.webp'].includes(fileExt)) {
380 | insertText = ``;
381 | new Notice('Eagle link converted');
382 | } else {
383 | insertText = `[${fileName}](${latestDirUrl})`;
384 | }
385 |
386 | // 在拖放位置插入内容
387 | // 注意:Obsidian会自动处理拖放位置,我们只需要使用replaceSelection
388 | editor.replaceSelection(insertText);
389 | new Notice('Eagle链接已转换');
390 | });
391 | } catch (error) {
392 | new Notice('File upload failed, check if Eagle is running');
393 | }
394 | } else {
395 | // 检查 filePath 中是否包含 'images\xxxxxx.info' 模式
396 | const match = filePath.match(/images\\[^\\]+\.info/);
397 | if (match) {
398 | const fileName = path.basename(filePath);
399 | const fileExt = path.extname(filePath).toLowerCase();
400 |
401 | let updatedText;
402 | const urlPath = match[0].replace(/\\/g, '/'); // 将反斜杠替换为正斜杠
403 |
404 | if (['.png', '.jpg', '.jpeg'].includes(fileExt)) {
405 | updatedText = ``;
406 | } else {
407 | updatedText = `[${fileName}](http://localhost:${port}/${urlPath})`;
408 | }
409 | editor.replaceSelection(updatedText);
410 | new Notice('Eagle链接已转换');
411 | } else {
412 | new Notice('非Eagle链接');
413 | }
414 | }
415 | }
416 | }
417 | }
--------------------------------------------------------------------------------
/styles.css:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | This CSS file will be included with your plugin, and
4 | available in the app when your plugin is enabled.
5 |
6 | If your plugin does not need CSS, delete this file.
7 |
8 | */
9 | /* Normal / default when pasting without any other content */
10 |
11 | .auto-embed-hide-display {
12 | display: none !important;
13 | }
14 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": ".",
4 | "inlineSourceMap": true,
5 | "inlineSources": true,
6 | "module": "ESNext",
7 | "target": "ES6",
8 | "allowJs": true,
9 | "noImplicitAny": true,
10 | "moduleResolution": "node",
11 | "importHelpers": true,
12 | "isolatedModules": true,
13 | "strictNullChecks": true,
14 | "lib": [
15 | "DOM",
16 | "ES5",
17 | "ES6",
18 | "ES7"
19 | ]
20 | },
21 | "include": [
22 | "src/**/*.ts",
23 | "typings/**/*.d.ts"
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------
/typings/a.d.ts:
--------------------------------------------------------------------------------
1 | import * as Obsidian from 'obsidian';
2 | // 在文件的顶部或合适的位置添加接口扩展
3 | declare module 'obsidian' {
4 | interface TFile {
5 | cache?: () => {};
6 | }
7 | }
--------------------------------------------------------------------------------
/version-bump.mjs:
--------------------------------------------------------------------------------
1 | import { readFileSync, writeFileSync } from "fs";
2 |
3 | const targetVersion = process.env.npm_package_version;
4 |
5 | // read minAppVersion from manifest.json and bump version to target version
6 | let manifest = JSON.parse(readFileSync("manifest.json", "utf8"));
7 | const { minAppVersion } = manifest;
8 | manifest.version = targetVersion;
9 | writeFileSync("manifest.json", JSON.stringify(manifest, null, "\t"));
10 |
11 | // update versions.json with target version and minAppVersion from manifest.json
12 | let versions = JSON.parse(readFileSync("versions.json", "utf8"));
13 | versions[targetVersion] = minAppVersion;
14 | writeFileSync("versions.json", JSON.stringify(versions, null, "\t"));
15 |
--------------------------------------------------------------------------------
/versions.json:
--------------------------------------------------------------------------------
1 | {
2 | "1.0.0": "0.15.0"
3 | }
4 |
--------------------------------------------------------------------------------