Update traffic statistics

This commit is contained in:
github-actions[bot]
2026-01-02 07:22:08 +00:00
commit 2b8782a8d4
120 changed files with 17233 additions and 0 deletions
+82
View File
@@ -0,0 +1,82 @@
name: Update Clone Count Badge
on:
schedule:
- cron: '0 0 * * *' # Runs daily at midnight
workflow_dispatch: # Allows manual trigger
jobs:
update-badge:
runs-on: ubuntu-latest
permissions:
contents: write # Needed to push to the branch
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Fetch Traffic Stats and Save JSON
uses: actions/github-script@v6
with:
github-token: ${{ secrets.TRAFFIC_TOKEN }}
script: |
try {
const { owner, repo } = context.repo;
// 1. Fetch Clones
const clones = await github.rest.repos.getClones({
owner,
repo,
});
// 2. Fetch Views (Visitors)
const views = await github.rest.repos.getViews({
owner,
repo,
});
const fs = require('fs');
const data = {
clones: {
count: clones.data.count,
uniques: clones.data.uniques,
},
views: {
count: views.data.count,
uniques: views.data.uniques,
},
timestamp: new Date().toISOString()
};
console.log('Stats fetched:', JSON.stringify(data));
// Write to a generic stats file
fs.writeFileSync('traffic_stats.json', JSON.stringify(data, null, 2));
// Maintain the old file for backward compatibility if needed, or just switch everything
fs.writeFileSync('git_clones.json', JSON.stringify(data.clones, null, 2));
} catch (error) {
console.error('Error fetching stats:', error);
process.exit(1);
}
- name: Push to Badges Branch
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
# Stash the files
mv traffic_stats.json /tmp/traffic_stats.json
mv git_clones.json /tmp/git_clones.json
# Fetch the badges branch or create it
git fetch origin badges:badges || true
git checkout badges || git checkout --orphan badges
# Restore the files
mv /tmp/traffic_stats.json traffic_stats.json
mv /tmp/git_clones.json git_clones.json
# Commit and push
git add traffic_stats.json git_clones.json
git diff --quiet && git diff --staged --quiet || (git commit -m "Update traffic statistics" && git push origin badges)
+20
View File
@@ -0,0 +1,20 @@
name: Publish to Comfy registry
on:
workflow_dispatch:
push:
branches:
- main
paths:
- "pyproject.toml"
jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Publish Custom Node
uses: Comfy-Org/publish-node-action@main
with:
personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} ## Add your own personal access token to your Github Repository secrets and reference it here.
+43
View File
@@ -0,0 +1,43 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
*.egg-info/
.eggs/
# Node.js / TypeScript build tooling
node_modules/
pnpm-lock.yaml
package-lock.json
yarn.lock
# IDE / Editor
.vscode/
.idea/
*.swp
*.swo
*~
.DS_Store
# Build artifacts (optional - see note below)
# Note: The web/ directory contains the compiled JS that ComfyUI serves.
# You should COMMIT web/ so users don't need to build from source.
# But these specific build artifacts can be ignored:
web/node_modules/
# TypeScript build cache
*.tsbuildinfo
# Test artifacts
test-results/
playwright-report/
.playwright/
# Debug files
Broswer_Console_Errors.md
# Environment
.env
.env.local
+56
View File
@@ -0,0 +1,56 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.5.0] - 2024-12-31
### Added
- **Quick Toggle Button**: Integrated Magnify Glass toggle into the main ComfyUI toolbar (bottom-right).
- **Inspector Persistence**: Panel now remembers if it was open or closed when toggling the tool.
- **Glass Preview Toggle**: New specific toggle for the visual glass circle (allowing "Inspector Only" mode).
- **Smart Workflow Logic**:
- Auto-Pin Inspector (Unlocked Mode) when hiding Glass Preview.
- Auto-Lock Inspector (Follow Mode) when showing Glass Preview.
- Professional SVG icons replacing emoji icons throughout the UI
- Full theme support for ComfyUI themes: Dark, Light, Solarized, Arc, Nord, GitHub
- External CSS stylesheet for easier customization
- Click event handlers for all floating control buttons
- Section expand/collapse functionality in info panel
### Improved
- **Drag Safety**: Dragging is now disabled when following the glass to prevent position fighting.
- **Visibility Interlocks**:
- "Unpin" button disabled when glass is hidden (prevents following invisible cursor).
- "Hide Inspector" button disabled when glass is hidden (prevents hiding all UI).
- **Global Toggle**: The 'X' key/button now acts as a master switch, preserving your exact workspace state.
### Changed
- Migrated from inline CSS-in-JS to external `info-panel.css` file
- Improved theme detection using ComfyUI's `Comfy.ColorPalette` setting
- More professional appearance with custom SVG icon set
### Removed
- Vue.js dependency (reduces bundle size)
- Emoji icons (replaced with SVG for better scaling and consistency)
- Inline CSS injection (now uses external stylesheet)
### Fixed
- Button click handlers now properly attached to floating controls
- Theme switching now works across all 6 ComfyUI themes
- Removed stale build artifacts that caused module loading errors
## [1.4.0] - Previous Release
### Added
- TypeScript source code
- WebGL-based magnification
- Info panel with node, media, and inspector sections
- Floating control buttons
- Multiple glass shapes and positions
---
For more information, see the [README](README.md).
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+124
View File
@@ -0,0 +1,124 @@
<div align="center">
# ComfyUI-MagnifyGlass
[![ComfyUI](https://img.shields.io/badge/ComfyUI-Extension-green?style=for-the-badge)](https://github.com/comfyanonymous/ComfyUI)
[![Dependencies](https://img.shields.io/badge/dependencies-none-brightgreen?style=for-the-badge&color=blue)](package.json)
[![License](https://img.shields.io/badge/License-GPLv3-red?style=for-the-badge)](LICENSE)
[![Version](https://img.shields.io/badge/Version-1.5.0-orange?style=for-the-badge)](https://github.com/AEmotionStudio/ComfyUI-MagnifyGlass/releases)
[![Downloads](https://img.shields.io/github/downloads/AEmotionStudio/ComfyUI-MagnifyGlass/total?style=for-the-badge&color=blueviolet)](https://github.com/AEmotionStudio/ComfyUI-MagnifyGlass/releases)
![Visitors](https://img.shields.io/badge/dynamic/json?color=blue&label=Visitors&query=views.uniques&url=https://raw.githubusercontent.com/AEmotionStudio/ComfyUI-MagnifyGlass/badges/traffic_stats.json&style=for-the-badge&logo=github)
[![Clones](https://img.shields.io/badge/dynamic/json?color=success&label=Clones&query=clones.uniques&url=https://raw.githubusercontent.com/AEmotionStudio/ComfyUI-MagnifyGlass/badges/traffic_stats.json&style=for-the-badge&logo=github)](https://github.com/AEmotionStudio/ComfyUI-MagnifyGlass/graphs/traffic)
**A powerful, customizable magnifying glass extension for ComfyUI.**
*Inspect fine details in your generated images, node connections, and canvas with ease.*
[Features](#features) • [Installation](#installation) • [Usage](#usage) • [Configuration](#configuration) • [Changelog](CHANGELOG.md)
</div>
---
## 🚀 Latest Updates (v1.5.0)
I've completely overhauled the UI and workflow for a seamless experience. Major highlights include:
* **Modernized UI**: Professional SVG icons and full support for all ComfyUI themes (Dark, Solarized, Nord, etc.).
* **Smart Workflow**: The Inspector Panel now intelligently pins/unpins based on your usage, allowing for both "Follow Glass" and "Free Floating" modes.
* **Quick Access**: New toolbar toggle for instant access.
> 📄 **See [CHANGELOG.md](CHANGELOG.md) for the complete version history and detailed patch notes.**
---
## ✨ Features
<div align="center">
<img src="https://github.com/AEmotionStudio/ComfyUI-MagnifyGlass/releases/download/assets-v1/magnify_glass_action.webp" width="800" alt="Magnify Glass Demo">
</div>
### 🔍 Magnifying Glass
* **High Performance**: WebGL-powered rendering for smooth zooming.
* **Smart Interactions**: Follows your cursor or stays fixed. Toggles transparently to let you click through to nodes.
* **Customizable**: Adjust zoom level (up to 10x), size, border, and shape (Circle/Square).
### ℹ️ Inspector Panel
* **Deep Analysis**: Hover over any node to see parameters (Seed, CFG, Steps), text content, and image details.
* **Dockable Interface**: Pin the panel to the screen to keep it stable, or let it follow the glass.
* **Inspector Tab**: Technical breakdown of coordinate space and scaling for power users.
---
## 📦 Installation
### Option 1: ComfyUI Manager (Recommended)
1. Open **ComfyUI Manager**.
2. Search for **`ComfyUI-MagnifyGlass`**.
3. Click **Install**.
### Option 2: Manual Install
```bash
cd /path/to/ComfyUI/custom_nodes
git clone https://github.com/AEmotionStudio/ComfyUI-MagnifyGlass.git
```
---
## 🎮 Usage
| Key | Action |
| :--- | :--- |
| **`X`** | **Activate / Toggle Tool** (Master Switch) |
| **`H`** | Toggle Follow Cursor Mode |
| **`I`** | Toggle Inspector Panel Visibility |
| **`G`** | Toggle Glass Preview (Enters "Inspector Only" Mode) |
| **`U`** | Pin/Unpin Inspector Panel |
| **`O`** | Reset Offsets |
| **Arrows** | Nudge Glass Position |
> **Pro Tip:** Toggle the **Glass Preview (`G`)** off to keep the Inspector Panel active but hide the magnifying preview.
---
## ⚙️ Configuration
Access settings via the ComfyUI Settings (⚙️) menu.
**Magnify Glass**
| Setting | Default | Description |
| :--- | :--- | :--- |
| **Zoom Factor** | `300` | Magnification level (300 = 3x). |
| **Glass Size** | `300px` | Diameter of the lens. |
| **Shape** | `Rounded` | Circle, Square, or Rounded Square. |
| **Activation Key** | `X` | Hotkey to toggle the tool. |
**Information Panel**
| Setting | Default | Description |
| :--- | :--- | :--- |
| **Theme** | `Auto` | Syncs with ComfyUI theme automatically. |
| **Opacity** | `100%` | Transparency of the panel background. |
| **Show Hover Controls** | `On` | Displays the quick-action toolbar on the panel. |
---
## 🤝 Contributing
Contributions are welcome! Please submit a Pull Request or open an Issue on GitHub.
1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the Branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
---
<div align="center">
**Developed by [AEmotionStudio](https://aemotionstudio.org/)**
[![YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/@aemotionstudio/videos)
[![Discord](https://img.shields.io/badge/Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/UzC9353mfp)
[![Ko-fi](https://img.shields.io/badge/Ko--fi-F16061?style=for-the-badge&logo=ko-fi&logoColor=white)](https://ko-fi.com/aemotionstudio)
</div>
+15
View File
@@ -0,0 +1,15 @@
# Define the web directory for our extension
WEB_DIRECTORY = "./web"
# Required to register as a ComfyUI extension
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
# List of JS files to be loaded
__js_files__ = ["magnify_glass.js", "magnify_info_panel.js"]
# List of exported elements
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY', '__js_files__']
# Print a message to confirm the extension loaded
print("ComfyUI Magnify Glass extension loaded")
+664
View File
@@ -0,0 +1,664 @@
/**
* ComfyUI MagnifyGlass - Info Panel Styles
*
* Complete CSS styles for the info panel component.
*/
/* SVG Icon Styling */
.magnify-info-panel svg,
.floating-controls svg {
width: 1em;
height: 1em;
vertical-align: middle;
fill: none;
stroke: currentColor;
pointer-events: none;
/* Allow clicks to pass through to button */
}
.header-icon svg {
width: 18px;
height: 18px;
}
.section-icon svg {
width: 18px;
height: 18px;
}
.control-btn svg {
width: 14px;
height: 14px;
}
.expand-icon svg {
width: 12px;
height: 12px;
}
.empty-state-icon svg {
width: 36px;
height: 36px;
stroke-width: 1.5;
}
.magnify-info-panel {
border-radius: 12px;
backdrop-filter: blur(20px);
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3), 0 0 0 1px rgba(255, 255, 255, 0.1);
overflow: hidden;
font-size: 16px;
line-height: 1.6;
pointer-events: auto;
}
.magnify-info-panel * {
pointer-events: auto;
}
.magnify-info-panel.theme-dark {
background: linear-gradient(135deg, rgba(0, 0, 0, 0.96), rgba(10, 10, 15, 0.96));
color: var(--info-panel-text-color, #e0e0e0);
border: 1px solid rgba(100, 100, 120, 0.4);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 2px 16px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(12px);
}
.magnify-info-panel.theme-light {
background: linear-gradient(135deg, rgba(250, 250, 255, 0.96), rgba(240, 240, 250, 0.96));
color: var(--info-panel-text-color, #2a2a2a);
border: 1px solid rgba(200, 200, 220, 0.5);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1), 0 2px 16px rgba(0, 0, 0, 0.05);
backdrop-filter: blur(12px);
}
/* Solarized Theme - warm, muted tones */
.magnify-info-panel.theme-solarized {
background: linear-gradient(135deg, rgba(0, 43, 54, 0.96), rgba(7, 54, 66, 0.96));
color: var(--info-panel-text-color, #839496);
border: 1px solid rgba(88, 110, 117, 0.5);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 2px 16px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(12px);
--info-panel-accent-color: #268bd2;
}
/* Arc Theme - modern blue-gray */
.magnify-info-panel.theme-arc {
background: linear-gradient(135deg, rgba(56, 60, 74, 0.96), rgba(64, 69, 82, 0.96));
color: var(--info-panel-text-color, #d3dae3);
border: 1px solid rgba(90, 100, 120, 0.5);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25), 0 2px 16px rgba(0, 0, 0, 0.15);
backdrop-filter: blur(12px);
--info-panel-accent-color: #5294e2;
}
/* Nord Theme - cool arctic colors */
.magnify-info-panel.theme-nord {
background: linear-gradient(135deg, rgba(46, 52, 64, 0.96), rgba(59, 66, 82, 0.96));
color: var(--info-panel-text-color, #d8dee9);
border: 1px solid rgba(76, 86, 106, 0.5);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25), 0 2px 16px rgba(0, 0, 0, 0.15);
backdrop-filter: blur(12px);
--info-panel-accent-color: #88c0d0;
}
/* GitHub Theme - clean, professional */
.magnify-info-panel.theme-github {
background: linear-gradient(135deg, rgba(255, 255, 255, 0.96), rgba(246, 248, 250, 0.96));
color: var(--info-panel-text-color, #24292e);
border: 1px solid rgba(225, 228, 232, 0.8);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1), 0 2px 16px rgba(0, 0, 0, 0.05);
backdrop-filter: blur(12px);
--info-panel-accent-color: #0366d6;
}
.magnify-info-panel.visible {
transform: translateY(0) !important;
}
.magnify-info-panel.panel-pinned {
cursor: grab;
box-shadow: 0 0 0 2px rgba(255, 215, 0, 0.5), 0 20px 40px rgba(0, 0, 0, 0.3);
}
.magnify-info-panel.panel-locked {
cursor: default !important;
box-shadow: 0 0 0 2px rgba(255, 69, 0, 0.5), 0 20px 40px rgba(0, 0, 0, 0.3);
}
.magnify-info-panel.panel-locked::after {
content: '📌';
position: absolute;
top: 8px;
right: 8px;
font-size: 14px;
opacity: 0.7;
pointer-events: none;
z-index: 1;
}
.magnify-info-panel.panel-pinned.panel-dragging {
cursor: grabbing;
box-shadow: 0 25px 50px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(255, 215, 0, 0.7);
transform: scale(1.02) !important;
z-index: 100001 !important;
transition: none !important;
}
.magnify-info-panel.panel-pinned::before {
content: '';
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background: linear-gradient(45deg, rgba(255, 215, 0, 0.05) 0%, transparent 100%);
pointer-events: none;
border-radius: inherit;
}
.panel-dragging * {
pointer-events: none !important;
user-select: none !important;
transition: none !important;
}
.magnify-info-panel.panel-minimized .panel-content {
max-height: 0 !important;
overflow: hidden;
transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.floating-controls {
position: fixed;
display: none;
/* Hidden initially - JS will show when positioned */
padding: 4px;
background: rgba(40, 40, 50, 0.95);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 4px;
opacity: 1;
z-index: 100000;
backdrop-filter: blur(8px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
}
.floating-controls.vertical-layout {
flex-direction: column;
gap: 4px;
}
.floating-controls.horizontal-layout {
flex-direction: row;
gap: 4px;
}
.control-btn {
background: rgba(60, 60, 70, 0.8);
border: 1px solid rgba(255, 255, 255, 0.2);
width: 28px;
height: 28px;
font-size: 14px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
color: #ddd;
border-radius: 3px;
transition: background-color 0.15s ease;
}
.control-btn:hover {
background: rgba(80, 80, 90, 0.9);
color: white;
}
.control-btn:active {
background: rgba(100, 100, 110, 0.9);
}
.control-btn:disabled {
background: rgba(40, 40, 50, 0.5);
color: #666;
cursor: not-allowed;
opacity: 0.5;
}
.control-btn.active {
background: rgba(255, 200, 50, 0.3);
border-color: rgba(255, 200, 50, 0.6);
color: #ffcc33;
}
.control-btn.lock-btn.active {
background: rgba(255, 69, 0, 0.3);
border-color: rgba(255, 69, 0, 0.6);
color: #ff4500;
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 18px;
background: linear-gradient(135deg, rgba(0, 0, 0, 0.1), rgba(255, 255, 255, 0.05));
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
user-select: none;
cursor: grab;
transition: background 0.15s ease;
}
.panel-header:hover {
background: linear-gradient(135deg, rgba(0, 0, 0, 0.15), rgba(255, 255, 255, 0.08));
}
.panel-header:active {
cursor: grabbing;
}
.header-content {
display: flex;
align-items: center;
gap: 10px;
}
.header-icon {
font-size: 18px;
opacity: 0.9;
}
.header-title {
font-weight: 600;
font-size: 18px;
}
.header-subtitle {
font-size: 14px;
opacity: 0.7;
font-style: italic;
}
.header-controls {
display: flex;
gap: 6px;
}
.minimize-btn {
background: rgba(255, 255, 255, 0.1);
border: none;
border-radius: 6px;
color: inherit;
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s;
font-weight: bold;
font-size: 16px;
}
.minimize-btn:hover {
background: rgba(255, 255, 255, 0.2);
transform: scale(1.05);
}
.minimize-btn:active {
transform: scale(0.95);
}
.panel-content {
padding: 0;
max-height: calc(100% - 60px);
overflow-y: auto;
scrollbar-width: thin;
}
.panel-content::-webkit-scrollbar {
width: 8px;
}
.panel-content::-webkit-scrollbar-track {
background: rgba(0, 0, 0, 0.1);
}
.panel-content::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 3px;
}
.info-section {
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
margin-bottom: 8px;
border-radius: 10px;
overflow: visible;
background: rgba(255, 255, 255, 0.02);
transition: all 0.3s ease;
}
.info-section:hover {
background: rgba(255, 255, 255, 0.04);
transform: translateY(-1px);
}
.section-header {
display: flex;
align-items: center;
gap: 12px;
padding: 16px 20px;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
font-weight: 500;
border-radius: 8px;
margin: 3px;
position: relative;
overflow: hidden;
}
.section-header::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.05) 50%, transparent 100%);
transform: translateX(-100%);
transition: transform 0.6s ease;
}
.section-header:hover::before {
transform: translateX(100%);
}
.section-header:hover {
background: rgba(255, 255, 255, 0.08);
transform: translateX(2px);
box-shadow: inset 2px 0 0 rgba(116, 185, 255, 0.5);
}
.section-header:active {
background: rgba(255, 255, 255, 0.12);
transform: translateX(1px);
}
.section-header.expanded {
background: rgba(116, 185, 255, 0.1);
border-left: 2px solid var(--info-panel-accent-color, #74b9ff);
}
.info-section[data-section="node"] {
background: linear-gradient(135deg, rgba(116, 185, 255, 0.05), rgba(160, 212, 104, 0.05));
border: 1px solid rgba(116, 185, 255, 0.2);
border-radius: 8px;
margin: 6px;
}
.info-section[data-section="node"] .section-header {
background: linear-gradient(135deg, rgba(116, 185, 255, 0.15), rgba(160, 212, 104, 0.15));
border-radius: 8px 8px 0 0;
cursor: default;
}
.info-section[data-section="node"] .section-header:hover {
transform: none;
box-shadow: none;
}
.info-section[data-section="node"] .section-title {
color: var(--info-panel-accent-color, #74b9ff);
font-weight: 700;
}
.info-section[data-section="inspector"] {
background: linear-gradient(135deg, rgba(100, 150, 255, 0.05), rgba(74, 144, 226, 0.05));
border: 1px solid rgba(100, 150, 255, 0.2);
border-radius: 8px;
margin: 6px;
}
.info-section[data-section="inspector"] .section-header {
background: linear-gradient(135deg, rgba(100, 150, 255, 0.15), rgba(74, 144, 226, 0.15));
border-radius: 8px 8px 0 0;
}
.info-section[data-section="inspector"] .section-title {
color: #6496ff;
font-weight: 700;
}
.info-section[data-section="media"] {
background: linear-gradient(135deg, rgba(253, 203, 110, 0.05), rgba(255, 215, 0, 0.05));
border: 1px solid rgba(253, 203, 110, 0.2);
border-radius: 8px;
margin: 6px;
}
.info-section[data-section="media"] .section-header {
background: linear-gradient(135deg, rgba(253, 203, 110, 0.15), rgba(255, 215, 0, 0.15));
border-radius: 8px 8px 0 0;
}
.info-section[data-section="media"] .section-title {
color: var(--info-panel-accent-color, #fdcb6e);
font-weight: 700;
}
.section-icon {
font-size: 18px;
width: 22px;
text-align: center;
}
.section-title {
flex: 1;
font-size: 16px;
font-weight: 600;
letter-spacing: 0.3px;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.section-badge {
background: rgba(100, 150, 255, 0.2);
color: #8bb3ff;
padding: 3px 10px;
border-radius: 10px;
font-size: 13px;
font-weight: 500;
}
.expand-icon {
font-size: 14px;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
color: rgba(255, 255, 255, 0.6);
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
background: rgba(255, 255, 255, 0.05);
margin-left: auto;
}
.section-header:hover .expand-icon {
color: var(--info-panel-accent-color, #74b9ff);
background: rgba(116, 185, 255, 0.15);
transform: scale(1.1);
}
.section-header.expanded .expand-icon {
transform: rotate(90deg) scale(1.1);
color: var(--info-panel-accent-color, #74b9ff);
background: rgba(116, 185, 255, 0.2);
}
.section-content {
max-height: 0;
overflow: visible;
transition: max-height 0.4s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s ease;
opacity: 0;
}
.section-content.expanded {
max-height: 2000px;
opacity: 1;
overflow: visible;
}
.section-body {
padding: 0 18px 16px 24px;
}
.info-row {
display: flex;
justify-content: space-between;
align-items: flex-start;
padding: 10px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
transition: all 0.2s ease;
border-radius: 4px;
margin: 0 -8px;
padding-left: 8px;
padding-right: 8px;
}
.info-row:last-child {
border-bottom: none;
}
.info-row:hover {
background: rgba(255, 255, 255, 0.03);
border-bottom-color: rgba(255, 255, 255, 0.08);
}
.info-label {
font-weight: 500;
opacity: 0.85;
font-size: 15px;
min-width: 80px;
padding-right: 12px;
line-height: 1.5;
}
.info-value {
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
font-size: 14px;
color: var(--info-panel-accent-color, #a0d468);
background: rgba(160, 212, 104, 0.12);
padding: 4px 10px;
border-radius: 6px;
max-width: 100%;
word-wrap: break-word;
word-break: break-word;
hyphens: auto;
line-height: 1.4;
text-align: left;
white-space: pre-wrap;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
transition: all 0.2s ease;
}
.info-value:hover {
background: rgba(160, 212, 104, 0.18);
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
.info-value.long-text {
white-space: pre-wrap;
word-wrap: break-word;
max-width: 100%;
line-height: 1.4;
}
.empty-state {
text-align: center;
padding: 50px 25px;
opacity: 0.6;
}
.empty-state-icon {
font-size: 36px;
margin-bottom: 15px;
opacity: 0.5;
}
.empty-state-text {
font-size: 16px;
font-style: italic;
}
/* Copy to clipboard functionality */
.info-value[title]:hover::after {
content: '📋';
position: absolute;
right: -20px;
top: 50%;
transform: translateY(-50%);
font-size: 12px;
opacity: 0.7;
}
/* Smooth loading states */
.section-body.loading {
opacity: 0.5;
pointer-events: none;
}
.section-body.loading::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 20px;
height: 20px;
border: 2px solid transparent;
border-top: 2px solid var(--info-panel-accent-color, #74b9ff);
border-radius: 50%;
animation: spin 1s linear infinite;
transform: translate(-50%, -50%);
}
@keyframes spin {
to {
transform: translate(-50%, -50%) rotate(360deg);
}
}
/* Enhanced scrollbar for better UX */
.section-body::-webkit-scrollbar {
width: 4px;
}
.section-body::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.05);
border-radius: 2px;
}
.section-body::-webkit-scrollbar-thumb {
background: var(--info-panel-accent-color, #74b9ff);
border-radius: 2px;
opacity: 0.6;
}
.section-body::-webkit-scrollbar-thumb:hover {
opacity: 1;
}
@keyframes pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.7;
}
}
.pulse {
animation: pulse 2s infinite;
}
+352
View File
@@ -0,0 +1,352 @@
/**
* ComfyUI MagnifyGlass - Sidebar CSS
*
* Styles for the sidebar settings and inspector panels.
*/
.magnify-sidebar {
display: flex;
flex-direction: column;
height: 100%;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 13px;
color: var(--fg-color, #ddd);
background: transparent;
padding: 0;
}
.magnify-sidebar-header {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 16px;
border-bottom: 1px solid var(--border-color, #333);
background: rgba(0, 0, 0, 0.2);
}
.magnify-sidebar-header svg {
width: 20px;
height: 20px;
fill: currentColor;
}
.magnify-sidebar-header h2 {
margin: 0;
font-size: 14px;
font-weight: 600;
}
.magnify-sidebar-content {
flex: 1;
overflow-y: auto;
padding: 8px 0;
}
/* Section styling */
.magnify-sidebar-section {
margin-bottom: 4px;
}
.magnify-sidebar-section-header {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 16px;
cursor: pointer;
background: rgba(255, 255, 255, 0.03);
border-bottom: 1px solid var(--border-color, #333);
transition: background 0.15s;
}
.magnify-sidebar-section-header:hover {
background: rgba(255, 255, 255, 0.06);
}
.magnify-sidebar-section-header svg {
width: 12px;
height: 12px;
transition: transform 0.2s;
}
.magnify-sidebar-section-header.collapsed svg {
transform: rotate(-90deg);
}
.magnify-sidebar-section-header span {
font-weight: 500;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.magnify-sidebar-section-body {
padding: 12px 16px;
display: flex;
flex-direction: column;
gap: 12px;
}
.magnify-sidebar-section-body.collapsed {
display: none;
}
/* Control row */
.magnify-control-row {
display: flex;
flex-direction: column;
gap: 4px;
}
.magnify-control-row label {
font-size: 11px;
color: var(--descrip-text, #999);
font-weight: 500;
}
.magnify-control-row .control-value {
font-size: 11px;
color: var(--fg-color, #ddd);
margin-left: auto;
}
.magnify-control-label-row {
display: flex;
justify-content: space-between;
align-items: center;
}
/* Slider styling */
.magnify-slider {
width: 100%;
height: 6px;
border-radius: 3px;
background: rgba(255, 255, 255, 0.1);
appearance: none;
cursor: pointer;
}
.magnify-slider::-webkit-slider-thumb {
appearance: none;
width: 14px;
height: 14px;
border-radius: 50%;
background: var(--p-primary-color, #3b82f6);
cursor: pointer;
transition: transform 0.1s;
}
.magnify-slider::-webkit-slider-thumb:hover {
transform: scale(1.15);
}
.magnify-slider::-moz-range-thumb {
width: 14px;
height: 14px;
border-radius: 50%;
background: var(--p-primary-color, #3b82f6);
border: none;
cursor: pointer;
}
/* Toggle styling */
.magnify-toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 0;
}
.magnify-toggle-row label {
font-size: 12px;
color: var(--fg-color, #ddd);
}
.magnify-toggle {
position: relative;
width: 36px;
height: 20px;
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
cursor: pointer;
transition: background 0.2s;
}
.magnify-toggle.active {
background: var(--p-primary-color, #3b82f6);
}
.magnify-toggle::after {
content: '';
position: absolute;
top: 2px;
left: 2px;
width: 16px;
height: 16px;
background: white;
border-radius: 50%;
transition: transform 0.2s;
}
.magnify-toggle.active::after {
transform: translateX(16px);
}
/* Select styling */
.magnify-select {
width: 100%;
padding: 6px 10px;
border: 1px solid var(--border-color, #444);
border-radius: 4px;
background: rgba(0, 0, 0, 0.3);
color: var(--fg-color, #ddd);
font-size: 12px;
cursor: pointer;
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23999' d='M6 8L2 4h8z'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 8px center;
}
.magnify-select:focus {
outline: none;
border-color: var(--p-primary-color, #3b82f6);
}
/* Inspector styles */
.magnify-inspector-section {
padding: 12px 16px;
}
.magnify-inspector-group {
margin-bottom: 16px;
}
.magnify-inspector-group:last-child {
margin-bottom: 0;
}
.magnify-inspector-group-title {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--descrip-text, #888);
margin-bottom: 8px;
font-weight: 600;
}
.magnify-inspector-row {
display: flex;
justify-content: space-between;
padding: 4px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}
.magnify-inspector-row:last-child {
border-bottom: none;
}
.magnify-inspector-label {
color: var(--descrip-text, #999);
font-size: 12px;
}
.magnify-inspector-value {
color: var(--fg-color, #ddd);
font-size: 12px;
font-family: monospace;
text-align: right;
max-width: 60%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.magnify-inspector-empty {
color: var(--descrip-text, #666);
font-style: italic;
font-size: 12px;
text-align: center;
padding: 20px 0;
}
/* Node badge */
.magnify-node-badge {
display: inline-block;
padding: 2px 8px;
background: var(--p-primary-color, #3b82f6);
border-radius: 4px;
font-size: 11px;
font-weight: 500;
margin-bottom: 8px;
}
/* Button styling */
.magnify-btn {
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
padding: 8px 12px;
border: none;
border-radius: 4px;
background: var(--p-primary-color, #3b82f6);
color: white;
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: background 0.15s, transform 0.1s;
}
.magnify-btn:hover {
background: var(--p-primary-hover-color, #2563eb);
}
.magnify-btn:active {
transform: scale(0.98);
}
.magnify-btn-secondary {
background: rgba(255, 255, 255, 0.1);
}
.magnify-btn-secondary:hover {
background: rgba(255, 255, 255, 0.15);
}
/* Color picker styling */
.magnify-color-row {
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.magnify-color-wrapper {
display: flex;
align-items: center;
gap: 8px;
}
.magnify-color-input {
width: 28px;
height: 28px;
padding: 0;
border: 1px solid var(--border-color, #444);
border-radius: 4px;
cursor: pointer;
background: transparent;
}
.magnify-color-input::-webkit-color-swatch-wrapper {
padding: 2px;
}
.magnify-color-input::-webkit-color-swatch {
border-radius: 2px;
border: none;
}
.magnify-color-preview {
font-size: 11px;
font-family: monospace;
color: var(--descrip-text, #999);
}
+4
View File
@@ -0,0 +1,4 @@
{
"count": 21,
"uniques": 20
}
+20
View File
@@ -0,0 +1,20 @@
{
"name": "comfyui-magnifyglass",
"version": "1.5.0",
"type": "module",
"description": "A professional magnifying glass and info panel for ComfyUI",
"scripts": {
"dev": "vite build --watch",
"build": "vite build",
"typecheck": "tsc --noEmit",
"test:e2e": "playwright test",
"test:unit": "vitest"
},
"devDependencies": {
"@playwright/test": "^1.57.0",
"happy-dom": "^20.0.11",
"typescript": "^5.3.0",
"vite": "^5.0.0",
"vitest": "^4.0.16"
}
}
+49
View File
@@ -0,0 +1,49 @@
import { defineConfig, devices } from '@playwright/test';
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
testDir: './tests/e2e',
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
// baseURL: 'http://127.0.0.1:8188',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
},
/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
// {
// name: 'firefox',
// use: { ...devices['Desktop Firefox'] },
// },
// {
// name: 'webkit',
// use: { ...devices['Desktop Safari'] },
// },
],
/* Run your local dev server before starting the tests */
// webServer: {
// command: 'npm run start',
// url: 'http://127.0.0.1:3000',
// reuseExistingServer: !process.env.CI,
// },
});
+14
View File
@@ -0,0 +1,14 @@
[project]
name = "comfyui-magnifyglass"
description = "ComfyUI-MagnifyGlass: A powerful & customizable magnifying glass for ComfyUI. Zoom into canvas details with smooth controls, configurable activation, custom styles (shape, size, border) & WebGL performance."
version = "1.4.5"
license = {file = "LICENSE"}
[project.urls]
Repository = "https://github.com/AEmotionStudio/ComfyUI-MagnifyGlass"
# Used by Comfy Registry https://comfyregistry.org
[tool.comfy]
PublisherId = "aemotionstudio"
DisplayName = "ComfyUI-MagnifyGlass"
Icon = ""
+227
View File
@@ -0,0 +1,227 @@
/**
* ComfyUI MagnifyGlass - Info Panel Event Manager (TypeScript)
*
* Complete Event Manager extracted from magnify_info_panel.js
* Handles all event binding and delegation for the info panel.
*/
import { StateManager } from './StateManager';
import { UIManager } from './UIManager';
import { PositionManager } from './PositionManager';
import { isUserTyping } from '../shared/utils';
import { Logger } from '../shared/logger';
export interface EventCallbacks {
toggleVisibility: () => void;
togglePin: () => void;
updatePosition: () => void;
}
/**
* Event Manager class.
* Handles all event listeners for the info panel.
*/
export class EventManager {
stateManager: StateManager;
panelElement: HTMLElement | null;
positionManager: PositionManager;
callbacks: EventCallbacks | null;
dragCleanup: (() => void) | null;
boundHandleMouseMove: (e: MouseEvent) => void;
boundHandleKeyDown: (e: KeyboardEvent) => void;
boundHandleKeyUp: (e: KeyboardEvent) => void;
constructor(stateManager: StateManager, panelElement: HTMLElement | null, positionManager: PositionManager, callbacks?: EventCallbacks) {
this.stateManager = stateManager;
this.panelElement = panelElement;
this.positionManager = positionManager;
this.callbacks = callbacks || null;
this.dragCleanup = null;
this.boundHandleMouseMove = this.handleMouseMove.bind(this);
this.boundHandleKeyDown = this.handleKeyDown.bind(this);
this.boundHandleKeyUp = this.handleKeyUp.bind(this);
this.setupEventListeners();
}
setupEventListeners(): void {
this.setupPanelEvents();
this.setupHotkeyEvents();
this.setupDragEvents();
this.setupHoverEvents();
}
setupPanelEvents(): void {
if (!this.panelElement) return;
// Vue handles most internal events now.
// We can keep specific global-ish listeners if needed here.
}
setupHotkeyEvents(): void {
document.addEventListener('keydown', this.boundHandleKeyDown);
}
setupDragEvents(): void {
if (!this.panelElement) return;
let isDragging = false;
let rafId: number | null = null;
let targetX = 0;
let targetY = 0;
const startDrag = (e: MouseEvent) => {
if (!this.panelElement) return;
const target = e.target as HTMLElement;
// Only allow dragging from header (expand clickable area)
const header = target.closest('.panel-header');
if (!header) return;
if (target.closest('button')) return;
// Button 2 (pin icon, data-action="lock") prevents dragging
if (this.stateManager.state.isPanelLocked) return;
// Also prevent dragging if we are "Following Glass" (not pinned to screen)
// This prevents fighting with the auto-positioner and accidental drags
if (!this.stateManager.state.isPanelPinned) return;
e.preventDefault();
e.stopPropagation();
isDragging = true;
const startX = e.clientX;
const startY = e.clientY;
const rect = this.panelElement.getBoundingClientRect();
const startLeft = rect.left;
const startTop = rect.top;
// Visual feedback - dragging state
this.panelElement.style.cursor = 'grabbing';
this.panelElement.style.opacity = '0.9';
this.panelElement.style.transition = 'none'; // Disable transitions during drag
document.body.style.cursor = 'grabbing';
document.body.style.userSelect = 'none';
const onMouseMove = (moveEvent: MouseEvent) => {
if (!isDragging) return;
const dx = moveEvent.clientX - startX;
const dy = moveEvent.clientY - startY;
targetX = startLeft + dx;
targetY = startTop + dy;
// Keep within viewport bounds
const panelWidth = this.panelElement?.offsetWidth || 0;
const panelHeight = this.panelElement?.offsetHeight || 0;
targetX = Math.max(0, Math.min(targetX, window.innerWidth - panelWidth));
targetY = Math.max(0, Math.min(targetY, window.innerHeight - panelHeight));
// Use RAF for smooth updates
if (rafId === null) {
rafId = requestAnimationFrame(() => {
if (this.panelElement && isDragging) {
this.panelElement.style.left = `${targetX}px`;
this.panelElement.style.top = `${targetY}px`;
}
rafId = null;
});
}
};
const onMouseUp = () => {
isDragging = false;
// Cancel any pending RAF
if (rafId !== null) {
cancelAnimationFrame(rafId);
rafId = null;
}
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
// Restore visual state
if (this.panelElement) {
this.panelElement.style.cursor = '';
this.panelElement.style.opacity = '';
this.panelElement.style.transition = '';
// Final position update
this.panelElement.style.left = `${targetX}px`;
this.panelElement.style.top = `${targetY}px`;
// Save pinned position
this.stateManager.state.pinnedPosition = { x: targetX, y: targetY };
}
document.body.style.cursor = '';
document.body.style.userSelect = '';
};
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
};
this.panelElement.addEventListener('mousedown', startDrag);
this.dragCleanup = () => {
if (this.panelElement) this.panelElement.removeEventListener('mousedown', startDrag);
};
}
setupHoverEvents(): void {
if (!this.panelElement) return;
this.panelElement.addEventListener('mouseenter', () => {
this.stateManager.state.isPanelHovered = true;
this.stateManager.clearAutoExpandTimer();
});
this.panelElement.addEventListener('mouseleave', () => {
this.stateManager.state.isPanelHovered = false;
if (!this.stateManager.state.isHoveringNode) {
this.stateManager.scheduleAutoCollapse();
}
});
}
handleKeyDown(e: KeyboardEvent): void {
if (isUserTyping()) return;
const settings = this.stateManager.state.settings;
const key = e.key.toLowerCase();
// console.log(`[InfoPanel] KeyDown: ${key}`);
// Toggle visibility
if (key === (settings["🔍MagnifyGlass.ToggleHotkey"] as string).toLowerCase()) {
Logger.debug('Toggle visibility hotkey matched!');
e.preventDefault();
this.callbacks?.toggleVisibility();
}
// Toggle Pin
if (key === (settings["🔍MagnifyGlass.PinPanelHotkey"] as string).toLowerCase()) {
e.preventDefault();
this.callbacks?.togglePin();
}
}
handleMouseMove(e: MouseEvent): void {
// Placeholder
}
handleKeyUp(e: KeyboardEvent): void {
// Placeholder
}
cleanup(): void {
document.removeEventListener('keydown', this.boundHandleKeyDown);
if (this.dragCleanup) this.dragCleanup();
}
}
+185
View File
@@ -0,0 +1,185 @@
/**
* ComfyUI MagnifyGlass - Info Panel Orchestrator (TypeScript)
*
* Complete Info Panel Manager extracted from magnify_info_panel.js
* Main class that orchestrates all info panel components.
*/
import type { MagnifyGlassInstance } from '../types/comfyui';
import { registerPanelSettings } from '../shared/settings';
import { Logger } from '../shared/logger';
import { StateManager } from './StateManager';
import { UIManager } from './UIManager';
import { PositionManager } from './PositionManager';
import { EventManager } from './EventManager';
import { InformationGatherer } from './InformationGatherer';
/**
* Professional Info Panel Manager.
* Orchestrates all the other components for the info panel.
*/
export class InfoPanel {
magnifyGlass: MagnifyGlassInstance;
stateManager: StateManager;
uiManager: UIManager;
positionManager: PositionManager;
eventManager: EventManager;
informationGatherer: InformationGatherer;
constructor(magnifyGlass: MagnifyGlassInstance) {
this.magnifyGlass = magnifyGlass;
// Initialize Managers
this.stateManager = new StateManager();
this.uiManager = new UIManager(this.stateManager);
this.informationGatherer = new InformationGatherer();
// Position Manager needs the UI elements
this.positionManager = new PositionManager(this.stateManager, this.uiManager.elements.panel!);
// Event Manager needs state and UI manager
this.eventManager = new EventManager(this.stateManager, this.uiManager.elements.panel!, this.positionManager, {
toggleVisibility: () => {
if (this.stateManager.state.isPanelVisible) {
this.uiManager.hide();
} else {
this.uiManager.show();
}
},
togglePin: () => {
this.stateManager.togglePinning();
this.uiManager.updatePinnedState();
},
updatePosition: () => this.positionManager.positionPanel()
});
this.hookIntoMagnifyGlass();
// Register settings with ComfyUI
registerPanelSettings(this.stateManager, this.uiManager, this.positionManager);
Logger.info('Info Panel initialized successfully');
}
hookIntoMagnifyGlass(): void {
// Hook into magnify glass update cycle
const originalUpdateMagnifiedView = this.magnifyGlass.updateMagnifiedView.bind(this.magnifyGlass);
this.magnifyGlass.updateMagnifiedView = (() => {
originalUpdateMagnifiedView();
if (this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelEnabled"] && this.magnifyGlass.state.active) {
this.scheduleInfoUpdate();
}
}).bind(this);
// Hook into show/hide
const originalShow = this.magnifyGlass.ui.show.bind(this.magnifyGlass.ui);
const originalHide = this.magnifyGlass.ui.hide.bind(this.magnifyGlass.ui);
this.magnifyGlass.ui.show = (() => {
originalShow();
if (this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelEnabled"]) {
// Restore state: If it was visible before hide, make it visible now.
// Otherwise only show controls.
if (this.stateManager.state.wasPanelVisibleBeforeHide) {
this.uiManager.show();
// Position properly
setTimeout(() => {
this.positionManager.positionPanel();
this.positionManager.positionFloatingControls(this.uiManager.elements.controls);
}, 10);
} else {
// Do NOT force panel visible. Only show controls.
const showControls = this.stateManager.state.settings["🔍MagnifyGlass.ShowHoveringControls"] !== false;
if (showControls && this.uiManager.elements.controls) {
this.uiManager.elements.controls.style.display = 'flex';
}
// Ensure states are updated
this.uiManager.updateControlStates();
// Position controls after showing (relative to glass since panel is hidden)
setTimeout(() => {
this.positionManager.positionFloatingControls(this.uiManager.elements.controls);
}, 10);
}
}
}).bind(this);
this.magnifyGlass.ui.hide = (() => {
// Save state before hiding
this.stateManager.state.wasPanelVisibleBeforeHide = this.stateManager.state.isPanelVisible;
originalHide();
this.uiManager.hide();
// Explicitly hide floating controls when glass is disabled
if (this.uiManager.elements.controls) {
this.uiManager.elements.controls.style.display = 'none';
}
}).bind(this);
}
scheduleInfoUpdate(): void {
if (this.stateManager.state.updateScheduled) return;
this.stateManager.state.updateScheduled = true;
requestAnimationFrame(() => {
this.updateInfo();
this.stateManager.state.updateScheduled = false;
});
}
updateInfo(): void {
const settings = this.stateManager.state.settings;
const isActive = this.magnifyGlass.state.active;
// Safety: If disabled or inactive, ensure hidden and return
if (!settings["🔍MagnifyGlass.InfoPanelEnabled"] || !isActive) {
if (this.uiManager.elements.controls && this.uiManager.elements.controls.style.display !== 'none') {
this.uiManager.elements.controls.style.display = 'none';
}
return;
}
const info = this.informationGatherer.gatherInformation();
this.stateManager.setCurrentInfo(info);
// Update the UI
this.uiManager.displayInfo(info);
this.positionManager.positionPanel();
this.positionManager.positionFloatingControls(this.uiManager.elements.controls);
// Handle node hover state logic if needed for internal state
if (info.hoveredNode) {
this.stateManager.state.isHoveringNode = true;
this.stateManager.expandNodeSections();
if (this.stateManager.state.lastNodeId !== info.hoveredNode.id) {
this.stateManager.state.lastNodeId = info.hoveredNode.id;
}
} else {
this.stateManager.state.isHoveringNode = false;
if (this.stateManager.state.lastNodeId !== null) {
this.stateManager.state.lastNodeId = null;
if (!this.stateManager.state.isPanelHovered) {
this.stateManager.scheduleAutoCollapse();
}
}
}
}
updateSettings(): void {
const changes = this.stateManager.updateSettings();
this.uiManager.applyStyles();
if (this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelEnabled"] && this.magnifyGlass.state.active) {
this.uiManager.show();
// Ensure position is updated after potential dimension changes
this.positionManager.positionPanel();
} else {
this.uiManager.hide();
}
}
}
+326
View File
@@ -0,0 +1,326 @@
/**
* ComfyUI MagnifyGlass - Info Panel Information Gatherer (TypeScript)
*
* Complete Information Gatherer extracted from magnify_info_panel.js
* Responsible for collecting information about nodes, widgets, and canvas state.
*/
import type { ComfyApp, ComfyNode, ComfyWidget, GatheredInfo, NodeInfo, WidgetInfo, MediaInfo } from '../types/comfyui';
declare const app: ComfyApp;
/**
* Information Gatherer class.
* Collects information about the current state under the cursor.
*/
export class InformationGatherer {
constructor() { }
gatherInformation(): GatheredInfo {
const magnifyGlass = window.comfyUIMagnifyGlass;
if (!magnifyGlass) {
return {
timestamp: Date.now(),
cursor: { screenX: 0, screenY: 0, canvasX: 0, canvasY: 0 },
zoom: 1,
nodeCount: 0,
hoveredNode: null,
hoveredWidget: null,
mediaElement: null
};
}
const info: GatheredInfo = {
timestamp: Date.now(),
cursor: {
screenX: magnifyGlass.lastKnownMousePosition.x,
screenY: magnifyGlass.lastKnownMousePosition.y,
canvasX: magnifyGlass.state.x,
canvasY: magnifyGlass.state.y
},
zoom: magnifyGlass.state.canvasScale,
nodeCount: app.graph?._nodes?.length ?? 0,
hoveredNode: null,
hoveredWidget: null,
mediaElement: null
};
if (magnifyGlass.isOverMedia && magnifyGlass.currentMediaElement) {
info.mediaElement = this.getMediaInfo(magnifyGlass.currentMediaElement);
}
const nodeUnderCursor = this.getNodeUnderCursor();
if (nodeUnderCursor) {
info.hoveredNode = this.getDetailedNodeInfo(nodeUnderCursor.node, nodeUnderCursor.localPos);
const widget = this.getWidgetUnderCursor(nodeUnderCursor.node, nodeUnderCursor.localPos);
if (widget) {
info.hoveredWidget = this.getWidgetInfo(widget);
}
}
return info;
}
getNodeUnderCursor(): { node: ComfyNode, localPos: { x: number, y: number } } | null {
const magnifyGlass = window.comfyUIMagnifyGlass;
if (!app.graph || !app.canvas || !magnifyGlass) {
return null;
}
try {
// Try to get the node from ComfyUI's state
if (app.canvas.node_over) {
const node = app.canvas.node_over;
if (node && node.pos && node.size) {
const canvasRect = app.canvas.canvas.getBoundingClientRect();
const mouseX = magnifyGlass.lastKnownMousePosition.x - canvasRect.left;
const mouseY = magnifyGlass.lastKnownMousePosition.y - canvasRect.top;
let graphPos: [number, number];
if (app.canvas.convertOffsetToCanvasPos) {
graphPos = app.canvas.convertOffsetToCanvasPos([mouseX, mouseY]);
} else {
const ds = app.canvas.ds || { scale: 1, offset: [0, 0] };
graphPos = [
(mouseX / ds.scale) - (ds.offset[0] / ds.scale),
(mouseY / ds.scale) - (ds.offset[1] / ds.scale)
];
}
return {
node: node,
localPos: {
x: graphPos[0] - node.pos[0],
y: graphPos[1] - node.pos[1]
}
};
}
}
// Fallback to manual detection
const canvasRect = app.canvas.canvas.getBoundingClientRect();
const mouseX = magnifyGlass.lastKnownMousePosition.x - canvasRect.left;
const mouseY = magnifyGlass.lastKnownMousePosition.y - canvasRect.top;
let graphPos: [number, number];
if (app.canvas.convertOffsetToCanvasPos) {
graphPos = app.canvas.convertOffsetToCanvasPos([mouseX, mouseY]);
} else {
const ds = app.canvas.ds || { scale: 1, offset: [0, 0] };
graphPos = [
(mouseX / ds.scale) - (ds.offset[0] / ds.scale),
(mouseY / ds.scale) - (ds.offset[1] / ds.scale)
];
}
for (let i = app.graph._nodes.length - 1; i >= 0; i--) {
const node = app.graph._nodes[i];
if (!node.pos || !node.size || (node.flags && node.flags.collapsed)) continue;
if (graphPos[0] >= node.pos[0] &&
graphPos[0] <= node.pos[0] + node.size[0] &&
graphPos[1] >= node.pos[1] &&
graphPos[1] <= node.pos[1] + node.size[1]) {
return {
node: node,
localPos: {
x: graphPos[0] - node.pos[0],
y: graphPos[1] - node.pos[1]
}
};
}
}
} catch (err) {
console.warn("Error in node detection:", err);
}
return null;
}
getDetailedNodeInfo(node: ComfyNode, localPos: { x: number, y: number }): NodeInfo {
return {
id: node.id,
title: node.title || "Untitled Node",
type: node.type,
mode: this.getNodeModeText(node.mode),
position: {
x: Math.round(node.pos[0]),
y: Math.round(node.pos[1]),
formatted: `(${Math.round(node.pos[0])}, ${Math.round(node.pos[1])})`
},
size: {
width: Math.round(node.size[0]),
height: Math.round(node.size[1]),
formatted: `${Math.round(node.size[0])}×${Math.round(node.size[1])}`
},
localPosition: {
x: Math.round(localPos.x),
y: Math.round(localPos.y),
formatted: `(${Math.round(localPos.x)}, ${Math.round(localPos.y)})`,
percentage: {
x: ((localPos.x / node.size[0]) * 100).toFixed(1),
y: ((localPos.y / node.size[1]) * 100).toFixed(1)
}
},
counts: {
widgets: node.widgets ? node.widgets.length : 0,
inputs: node.inputs ? node.inputs.length : 0,
outputs: node.outputs ? node.outputs.length : 0,
properties: node.properties ? Object.keys(node.properties).length : 0
},
widgets: node.widgets || [],
inputs: node.inputs || [],
outputs: node.outputs || [],
properties: node.properties || {},
hoverRegion: this.detectNodeRegion(localPos, node)
};
}
getNodeInfo(node: ComfyNode): NodeInfo {
return {
id: node.id,
title: node.title || "Untitled",
type: node.type,
mode: node.mode,
size: node.size ? `${Math.round(node.size[0])}×${Math.round(node.size[1])}` : "Unknown",
position: node.pos ? `(${Math.round(node.pos[0])}, ${Math.round(node.pos[1])})` : "Unknown",
widgets: node.widgets || [],
inputs: node.inputs || [],
outputs: node.outputs || [],
properties: node.properties || {}
};
}
getWidgetUnderCursor(node: ComfyNode, localPos: { x: number, y: number }): ComfyWidget | null {
if (!node.widgets || !node.widgets.length) return null;
const titleHeight = 30;
let currentY = titleHeight;
for (const widget of node.widgets) {
const widgetHeight = 25;
if (localPos.y >= currentY && localPos.y <= currentY + widgetHeight) {
return widget;
}
currentY += widgetHeight + 5;
}
return null;
}
getWidgetInfo(widget: ComfyWidget): WidgetInfo {
return {
name: widget.name,
type: widget.type,
value: this.formatValue(widget.value),
options: widget.options || null,
min: widget.min,
max: widget.max,
step: widget.step
};
}
getMediaInfo(mediaElement: HTMLImageElement | HTMLVideoElement): MediaInfo {
const info: MediaInfo = {
type: mediaElement instanceof HTMLImageElement ? 'image' : 'video',
tagName: mediaElement.tagName,
src: mediaElement.src ? mediaElement.src.substring(mediaElement.src.lastIndexOf('/') + 1) : 'No source',
naturalWidth: 0,
naturalHeight: 0,
displayWidth: 0,
displayHeight: 0,
aspectRatio: ''
};
if (mediaElement instanceof HTMLImageElement) {
info.naturalWidth = mediaElement.naturalWidth;
info.naturalHeight = mediaElement.naturalHeight;
info.displayWidth = Math.round(mediaElement.width);
info.displayHeight = Math.round(mediaElement.height);
if (mediaElement.naturalWidth && mediaElement.naturalHeight) {
info.aspectRatio = (mediaElement.naturalWidth / mediaElement.naturalHeight).toFixed(2);
}
} else if (mediaElement instanceof HTMLVideoElement) {
info.naturalWidth = mediaElement.videoWidth;
info.naturalHeight = mediaElement.videoHeight;
info.displayWidth = Math.round(mediaElement.width);
info.displayHeight = Math.round(mediaElement.height);
info.duration = mediaElement.duration;
info.currentTime = mediaElement.currentTime;
if (mediaElement.videoWidth && mediaElement.videoHeight) {
info.aspectRatio = (mediaElement.videoWidth / mediaElement.videoHeight).toFixed(2);
}
}
return info;
}
getNodeModeText(mode: number): string {
const modes: { [key: number]: string } = {
0: 'Always',
1: 'On Event',
2: 'Never',
3: 'On Trigger',
4: 'On Request'
};
return modes[mode] || `Mode ${mode}`;
}
detectNodeRegion(localPos: { x: number, y: number }, node: ComfyNode): string {
const titleHeight = 30;
const regions: string[] = [];
if (localPos.y <= titleHeight) {
regions.push("Title Bar");
}
if (localPos.x <= 10) {
regions.push("Left Edge");
} else if (localPos.x >= node.size[0] - 10) {
regions.push("Right Edge");
}
if (localPos.y <= 10) {
regions.push("Top Edge");
} else if (localPos.y >= node.size[1] - 10) {
regions.push("Bottom Edge");
}
if (regions.length === 0) {
if (localPos.y > titleHeight) {
regions.push("Content Area");
}
}
if (localPos.x <= 20 && localPos.y > titleHeight) {
regions.push("Input Area");
} else if (localPos.x >= node.size[0] - 20 && localPos.y > titleHeight) {
regions.push("Output Area");
}
return regions.length > 0 ? regions.join(", ") : "Unknown";
}
formatValue(value: unknown): string {
if (value === null) return "null";
if (value === undefined) return "undefined";
if (typeof value === "string") {
return value; // Show full text without truncation
}
if (typeof value === "number") {
return Number.isInteger(value) ? value.toString() : value.toFixed(3);
}
if (typeof value === "boolean") return value.toString();
if (Array.isArray(value)) {
return `Array(${value.length})`;
}
if (typeof value === "object") {
return "Object";
}
return String(value);
}
}
+259
View File
@@ -0,0 +1,259 @@
/**
* ComfyUI MagnifyGlass - Node Data Extractor
*
* Utility functions for extracting specific information from nodes.
* Extracted from UIManager.ts for better modularity.
*/
import { formatWidgetValue } from './ValueFormatter';
import type { NodeInfo } from '../types/comfyui';
/**
* Interface for extracted parameter items.
*/
export interface ParameterItem {
label: string;
value: string;
}
/**
* Get checkpoint/model info from a node.
* @param nodeInfo - Node information object
* @returns Model filename or null
*/
export function getCheckpointInfo(nodeInfo: NodeInfo): string | null {
if (nodeInfo.type && (
nodeInfo.type.includes('CheckpointLoader') ||
nodeInfo.type.includes('LoadCheckpoint') ||
nodeInfo.type.includes('ModelLoader') ||
nodeInfo.type.includes('UNETLoader') ||
nodeInfo.type.includes('VAELoader') ||
nodeInfo.type.includes('LoraLoader')
)) {
if (nodeInfo.widgets && nodeInfo.widgets.length > 0) {
for (const widget of nodeInfo.widgets) {
if (widget.name && (
widget.name.toLowerCase().includes('model') ||
widget.name.toLowerCase().includes('checkpoint') ||
widget.name.toLowerCase().includes('ckpt') ||
widget.name.toLowerCase().includes('lora') ||
widget.name.toLowerCase().includes('vae') ||
widget.name.toLowerCase().includes('file')
)) {
const value = String(widget.value);
const filename = value.split(/[\/\\]/).pop();
return filename || value;
}
}
}
}
return null;
}
/**
* Image info result type.
*/
export interface ImageInfoResult {
width: string | number;
height: string | number;
src: string;
}
/**
* Get image info from a node.
* @param nodeInfo - Node information object
* @returns Image info string, object, or null
*/
export function getImageInfo(nodeInfo: NodeInfo): string | ImageInfoResult | null {
if (nodeInfo.type && (
nodeInfo.type.includes('SaveImage') ||
nodeInfo.type.includes('PreviewImage') ||
nodeInfo.type.includes('VisionOutput') ||
nodeInfo.type.includes('ImageOutput') ||
nodeInfo.type.includes('LoadImage') ||
nodeInfo.type.includes('Display')
)) {
if (nodeInfo.widgets) {
for (const widget of nodeInfo.widgets) {
if (widget.name && (
widget.name.toLowerCase().includes('image') ||
widget.name.toLowerCase().includes('filename') ||
widget.name.toLowerCase().includes('file')
)) {
return String(widget.value);
}
}
}
if (nodeInfo.properties && (nodeInfo.properties as Record<string, unknown>).img) {
const img = (nodeInfo.properties as Record<string, unknown>).img as Record<string, unknown>;
return {
width: (img.width as string | number) || 'unknown',
height: (img.height as string | number) || 'unknown',
src: img.src ? String(img.src).split(/[\/\\]/).pop() || 'Preview available' : 'Preview available'
};
}
if (nodeInfo.outputs) {
for (const output of nodeInfo.outputs) {
if (output.links && output.links.length > 0) {
return 'Image connected to ' + output.links.length + ' node(s)';
}
}
}
return 'Image node';
}
return null;
}
/**
* Get text box content from a node.
* @param nodeInfo - Node information object
* @returns Text content or null
*/
export function getTextBoxContent(nodeInfo: NodeInfo): string | null {
if (nodeInfo.widgets && nodeInfo.widgets.length > 0) {
if (nodeInfo.type && nodeInfo.type.includes('CLIPTextEncode')) {
for (const widget of nodeInfo.widgets) {
if (widget.name === 'text' && typeof widget.value === 'string') {
return widget.value;
}
}
}
for (const widget of nodeInfo.widgets) {
if ((widget.name.toLowerCase().includes('prompt') ||
widget.name.toLowerCase().includes('conditioning')) &&
typeof widget.value === 'string' && widget.value.length > 0) {
return widget.value;
}
}
for (const widget of nodeInfo.widgets) {
if ((widget.type === 'text' || widget.type === 'textarea' ||
widget.type === 'string' || widget.name.toLowerCase().includes('text')) &&
typeof widget.value === 'string' && widget.value.length > 0) {
return widget.value;
}
}
}
return null;
}
/**
* List of important parameter names for complex nodes.
*/
const COMPLEX_NODE_PARAMS = [
'seed', 'steps', 'cfg', 'scale', 'sampler', 'scheduler',
'positive', 'negative', 'width', 'height', 'denoise', 'strength',
'noise', 'count', 'batch', 'size', 'phase', 'color', 'intensity',
'control_after_generate', 'control', 'after', 'generate',
'start_at_step', 'end_at_step', 'start', 'end',
'return_with_leftover_noise', 'leftover', 'noise_return',
'model', 'vae', 'clip', 'lora', 'checkpoint',
'latent', 'image', 'mask', 'filename', 'directory',
'prompt', 'conditioning', 'filename_prefix',
'resolution', 'num_chunks', 'seconds', 'aspect_ratio',
'style_type', 'background', 'n', 'human', 'raw', 'guidance',
'skip_preprocessing', 'movement_amplitude', 'animation',
'material_type', 'b1', 'b2', 's1', 's2', 'type', 'channel',
'sigma', 'rho', 'alpha', 'base_shift', 'shift', 'stretch', 'terminal',
'spacing', 'style', 'eta', 'norm_threshold', 'momentum',
'hypernetwork_name', 'reuse_threshold', 'verbose', 'layers',
'set_cond_area', 'audioui', 'camera_pose', 'fx', 'cx', 'fy', 'cy'
];
/**
* Parameters for save nodes.
*/
const SAVE_NODE_PARAMS = [
'filename_prefix', 'filename', 'directory', 'path',
'format', 'quality', 'extension'
];
/**
* Generic widget names to skip.
*/
const SKIP_WIDGET_NAMES = ['title', 'node', 'id', 'type', 'mode'];
/**
* Check if a node type should show all widgets.
* @param nodeType - The node type string
* @returns True if all widgets should be shown
*/
function shouldShowAllWidgets(nodeType: string): boolean {
const type = nodeType.toLowerCase();
const isSaveNode = type.includes('save') &&
!type.includes('checkpoint') &&
!type.includes('model') &&
!type.includes('preview');
return (
type.includes('ksampler') ||
type.includes('sampler') ||
type.includes('k_samplers') ||
type.includes('checkpoint') ||
type.includes('model') ||
type.includes('lora') ||
type.includes('controlnet') ||
type.includes('advanced') ||
type.includes('detailer') ||
type.includes('inpaint') ||
type.includes('upscale') ||
type.includes('clip') ||
type.includes('text') ||
type.includes('encode')
) && !isSaveNode;
}
/**
* Get important node parameters based on node type.
* @param nodeInfo - Node information object
* @returns Array of parameter items
*/
export function getImportantNodeParameters(nodeInfo: NodeInfo): ParameterItem[] {
const parameters: ParameterItem[] = [];
if (!nodeInfo.widgets || nodeInfo.widgets.length === 0) {
return parameters;
}
const nodeType = nodeInfo.type || '';
const typeLower = nodeType.toLowerCase();
const isSaveNode = typeLower.includes('save') &&
!typeLower.includes('checkpoint') &&
!typeLower.includes('model') &&
!typeLower.includes('preview');
// For complex nodes, show ALL widgets
if (nodeType && shouldShowAllWidgets(nodeType)) {
for (const widget of nodeInfo.widgets) {
if (widget.name && widget.name !== '') {
const widgetName = widget.name.toLowerCase();
if (!SKIP_WIDGET_NAMES.some(skip => widgetName.includes(skip))) {
parameters.push({
label: widget.name,
value: formatWidgetValue(widget.value)
});
}
}
}
return parameters;
}
// For other nodes, use filtered parameter lists
const importantParams = isSaveNode ? SAVE_NODE_PARAMS : COMPLEX_NODE_PARAMS;
for (const widget of nodeInfo.widgets) {
const paramName = widget.name.toLowerCase();
if (importantParams.some(param => paramName.includes(param))) {
parameters.push({
label: widget.name,
value: formatWidgetValue(widget.value)
});
}
}
return parameters;
}
+205
View File
@@ -0,0 +1,205 @@
/**
* Position Manager class.
* Handles all positioning logic for the info panel.
*/
import { StateManager } from './StateManager';
export class PositionManager {
stateManager: StateManager;
panelElement: HTMLElement;
constructor(stateManager: StateManager, panelElement: HTMLElement) {
this.stateManager = stateManager;
this.panelElement = panelElement;
}
positionPanel(): void {
if (!this.panelElement) return;
// If panel is pinned, keep it at its pinned position
if (this.stateManager.state.isPanelPinned) {
this.applyPinnedPosition();
return;
}
// Normal positioning logic
this.calculateNormalPosition();
}
applyPinnedPosition(): void {
if (!this.panelElement) return;
let { x, y } = this.stateManager.state.pinnedPosition;
// If pinnedPosition is uninitialized (0,0), use calculateNormalPosition to get a valid position
if (x === 0 && y === 0) {
this.calculateNormalPosition();
// Save the calculated position as the new pinned position
if (this.panelElement) {
const rect = this.panelElement.getBoundingClientRect();
this.stateManager.state.pinnedPosition = { x: rect.left, y: rect.top };
}
return;
}
const panelWidth = this.panelElement.offsetWidth || 300;
const panelHeight = this.panelElement.offsetHeight || 400;
const margin = 4;
const boundedX = Math.max(margin, Math.min(x, window.innerWidth - panelWidth - margin));
const boundedY = Math.max(margin, Math.min(y, window.innerHeight - panelHeight - margin));
this.panelElement.style.left = `${boundedX}px`;
this.panelElement.style.top = `${boundedY}px`;
}
calculateNormalPosition(): void {
const magnifyGlass = window.comfyUIMagnifyGlass;
if (!magnifyGlass || !this.panelElement) return;
const settings = this.stateManager.state.settings;
const panelWidth = Number(settings["🔍MagnifyGlass.InfoPanelWidth"]) || 300;
const panelHeight = this.panelElement.offsetHeight || 400;
let left: number;
let top: number;
const margin = 4;
// Check for valid glass rect first
const glassRect = magnifyGlass.ui.glassDiv?.getBoundingClientRect();
const hasValidGlassRect = glassRect && (glassRect.right > 0 || glassRect.top > 0);
// Check for valid mouse position
const mouseX = magnifyGlass.lastKnownMousePosition?.x || 0;
const mouseY = magnifyGlass.lastKnownMousePosition?.y || 0;
const hasValidMousePosition = mouseX > 0 || mouseY > 0;
if (!this.stateManager.state.isGlassPreviewVisible) {
// Glass is hidden, use mouse position
if (hasValidMousePosition) {
left = mouseX - (panelWidth / 2);
top = mouseY - 20;
} else {
// Fallback: right side of screen
left = window.innerWidth - panelWidth - 50;
top = 100;
}
} else if (hasValidGlassRect) {
// Position relative to glass
const position = settings["🔍MagnifyGlass.InfoPanelPosition"];
switch (position) {
case "Right":
left = glassRect!.right + margin;
top = glassRect!.top;
break;
case "Left":
left = glassRect!.left - panelWidth - margin;
top = glassRect!.top;
break;
case "Top":
left = glassRect!.left;
top = glassRect!.top - panelHeight - margin;
break;
case "Bottom":
left = glassRect!.left;
top = glassRect!.bottom + margin;
break;
default:
left = glassRect!.right + margin;
top = glassRect!.top;
break;
}
} else if (hasValidMousePosition) {
// Fall back to mouse position
left = mouseX - (panelWidth / 2);
top = mouseY - 20;
} else {
// Final fallback: right side of screen
left = window.innerWidth - panelWidth - 50;
top = 100;
}
left = Math.max(4, Math.min(left, window.innerWidth - panelWidth - 4));
top = Math.max(4, Math.min(top, window.innerHeight - panelHeight - 4));
this.panelElement.style.left = `${left}px`;
this.panelElement.style.top = `${top}px`;
}
/**
* Position the floating controls relative to the panel.
*/
positionFloatingControls(controlsElement: HTMLElement | null): void {
if (!controlsElement) return;
// Check if controls should be visible based on settings
const settings = this.stateManager.state.settings;
if (settings["🔍MagnifyGlass.ShowHoveringControls"] === false) {
controlsElement.style.display = 'none';
return;
}
const isPanelVisible = this.stateManager.state.isPanelVisible;
const magnifyGlass = window.comfyUIMagnifyGlass;
let referenceRect: DOMRect | null = null;
if (isPanelVisible && this.panelElement) {
// Position relative to panel
referenceRect = this.panelElement.getBoundingClientRect();
} else if (magnifyGlass && magnifyGlass.ui && magnifyGlass.ui.glassDiv) {
// Position relative to magnify glass
referenceRect = magnifyGlass.ui.glassDiv.getBoundingClientRect();
// Don't show controls if glass is hidden/invalid
if (referenceRect.width === 0 || referenceRect.height === 0) {
controlsElement.style.display = 'none';
return;
}
}
if (!referenceRect) return;
const controlsPosition = this.stateManager.state.settings["🔍MagnifyGlass.ControlsPosition"] || "right";
const margin = 4;
let left: number;
let top: number;
switch (controlsPosition) {
case "left":
left = referenceRect.left - controlsElement.offsetWidth - margin;
top = referenceRect.top;
break;
case "right":
left = referenceRect.right + margin;
top = referenceRect.top;
break;
case "top":
left = referenceRect.left;
top = referenceRect.top - controlsElement.offsetHeight - margin;
break;
case "bottom":
left = referenceRect.left;
top = referenceRect.bottom + margin;
break;
case "top-right":
left = referenceRect.right - controlsElement.offsetWidth;
top = referenceRect.top - controlsElement.offsetHeight - margin;
break;
default:
left = referenceRect.right + margin;
top = referenceRect.top;
}
// Keep controls within viewport
left = Math.max(10, Math.min(left, window.innerWidth - controlsElement.offsetWidth - 10));
top = Math.max(10, Math.min(top, window.innerHeight - controlsElement.offsetHeight - 10));
controlsElement.style.left = `${left}px`;
controlsElement.style.top = `${top}px`;
// Show controls now that they're positioned (initially hidden off-screen)
controlsElement.style.display = 'flex';
controlsElement.style.visibility = 'visible';
}
}
+420
View File
@@ -0,0 +1,420 @@
/**
* ComfyUI MagnifyGlass - Info Panel State Manager (TypeScript)
*
* Centralized state management for the information panel.
*/
import type { GatheredInfo, SettingsChange } from '../types/comfyui';
import { getSettingValue } from '../shared/utils';
import { DEFAULT_PANEL_SETTINGS } from '../shared/settings';
export interface InfoPanelStateData {
// Panel visibility and positioning
isPanelVisible: boolean;
wasPanelVisibleBeforeHide: boolean; // Persist state across glass toggles
isPanelMinimized: boolean;
isPanelPinned: boolean;
isPanelLocked: boolean; // New lock state
isAutoPinned: boolean; // Track if panel was auto-pinned by glass hide
pinnedPosition: { x: number; y: number };
lastPinnedPosition: { x: number; y: number } | null; // Remember last pinned location
// Glass visibility
isGlassPreviewVisible: boolean;
// Section expansion
expandedSections: Set<string>;
// Interaction states
isPanelHovered: boolean;
isHoveringNode: boolean;
// Auto-collapse
autoExpandTimer: ReturnType<typeof setTimeout> | null;
lastNodeId: string | number | null;
// Update scheduling
updateScheduled: boolean;
isInitialLoading: boolean;
// Current data
currentInfo: GatheredInfo | null;
// Settings cache - using index signature for dynamic ComfyUI settings
settings: { [key: string]: string | number | boolean };
// Auto-detected theme
currentTheme: string;
}
/**
* State Manager class.
* Handles all state-related operations and provides clean state transitions.
*/
export class StateManager {
state: InfoPanelStateData;
constructor() {
this.state = {
// Panel visibility and positioning
isPanelVisible: false,
wasPanelVisibleBeforeHide: false,
isPanelMinimized: true,
isPanelPinned: false,
isPanelLocked: false, // New lock state
isAutoPinned: false, // Track if panel was auto-pinned by glass hide
pinnedPosition: { x: 0, y: 0 },
lastPinnedPosition: null, // Remember last pinned location
// Glass visibility
isGlassPreviewVisible: true,
// Section expansion
expandedSections: new Set(['node']),
// Interaction states
isPanelHovered: false,
isHoveringNode: false,
// Auto-collapse
autoExpandTimer: null,
lastNodeId: null,
// Update scheduling
updateScheduled: false,
isInitialLoading: false,
// Current data
currentInfo: null,
// Settings cache
settings: {},
// Auto-detected theme
currentTheme: 'dark' // Will be auto-detected
};
this.initThemeDetection();
this.loadSettings();
}
initThemeDetection(): void {
// Detect ComfyUI's current theme
this.detectCurrentTheme();
// Force an immediate check in case we missed the initial state
setTimeout(() => {
if (this.detectCurrentTheme()) {
this.notifyThemeChange();
}
}, 1000);
// Set up mutation observer to watch for theme changes
this.setupThemeObserver();
// Listen for system theme changes as fallback
if (window.matchMedia) {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
if (prefersDark.addListener) {
prefersDark.addListener(() => this.detectCurrentTheme());
} else if (prefersDark.addEventListener) {
prefersDark.addEventListener('change', () => this.detectCurrentTheme());
}
}
// Add click listener to theme toggle buttons for immediate detection
this.setupThemeButtonListeners();
}
detectCurrentTheme(): boolean {
let detectedTheme = 'dark'; // Default fallback
// Method 1: Try to read from ComfyUI's color palette setting
try {
// ComfyUI stores theme in 'Comfy.ColorPalette' setting
const colorPalette = getSettingValue('Comfy.ColorPalette', '');
if (colorPalette) {
// Extract theme name from various possible formats
const paletteStr = String(colorPalette).toLowerCase();
if (paletteStr.includes('solarized')) {
detectedTheme = 'solarized';
} else if (paletteStr.includes('arc')) {
detectedTheme = 'arc';
} else if (paletteStr.includes('nord')) {
detectedTheme = 'nord';
} else if (paletteStr.includes('github')) {
detectedTheme = 'github';
} else if (paletteStr.includes('light')) {
detectedTheme = 'light';
} else if (paletteStr.includes('dark')) {
detectedTheme = 'dark';
}
}
} catch (e) {
// Fallback to brightness-based detection
console.warn('ComfyUI Info Panel: Could not read theme from settings, using fallback detection');
}
// Method 2: Fallback - check body/html for theme classes or data attributes
if (detectedTheme === 'dark') {
const body = document.body;
const html = document.documentElement;
// Check for data-theme attribute
const dataTheme = body.getAttribute('data-theme') || html.getAttribute('data-theme');
if (dataTheme) {
detectedTheme = dataTheme.toLowerCase();
}
// Check for theme classes
const classes = (body.className + ' ' + html.className).toLowerCase();
if (classes.includes('theme-solarized') || classes.includes('solarized')) {
detectedTheme = 'solarized';
} else if (classes.includes('theme-arc') || classes.includes('arc-theme')) {
detectedTheme = 'arc';
} else if (classes.includes('theme-nord') || classes.includes('nord-theme')) {
detectedTheme = 'nord';
} else if (classes.includes('theme-github') || classes.includes('github-theme')) {
detectedTheme = 'github';
} else if (classes.includes('theme-light') || classes.includes('light-theme')) {
detectedTheme = 'light';
}
}
// Method 3: Last resort - brightness detection for light vs dark
if (detectedTheme === 'dark') {
const bodyStyles = window.getComputedStyle(document.body);
const bgColor = bodyStyles.backgroundColor;
if (bgColor && bgColor !== 'rgba(0, 0, 0, 0)' && bgColor !== 'transparent') {
const rgbMatch = bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
if (rgbMatch) {
const [, r, g, b] = rgbMatch.map(Number);
const brightness = (r * 299 + g * 587 + b * 114) / 1000;
if (brightness > 180) {
detectedTheme = 'light';
}
}
}
}
// Update theme if it changed
if (this.state.currentTheme !== detectedTheme) {
this.state.currentTheme = detectedTheme;
return true; // Theme changed
}
return false; // No change
}
setupThemeObserver(): void {
// Watch for changes to body/html classes and attributes
const observer = new MutationObserver((mutations) => {
let shouldCheck = false;
mutations.forEach((mutation) => {
if (mutation.type === 'attributes' &&
(mutation.attributeName === 'class' ||
mutation.attributeName === 'data-theme' ||
mutation.attributeName === 'style')) {
shouldCheck = true;
}
});
if (shouldCheck && this.detectCurrentTheme()) {
// Theme changed, update UI immediately
this.notifyThemeChange();
}
});
// Observe changes to body, html, and vue app
observer.observe(document.body, { attributes: true, attributeOldValue: true });
observer.observe(document.documentElement, { attributes: true, attributeOldValue: true });
const vueApp = document.querySelector('#vue-app');
if (vueApp) {
observer.observe(vueApp, { attributes: true, attributeOldValue: true });
}
// Also watch for changes to any element with theme-related classes
const themeElements = document.querySelectorAll('[class*="theme"], [class*="dark"], [class*="light"], [data-theme]');
themeElements.forEach(el => {
observer.observe(el, { attributes: true, attributeOldValue: true });
});
// Periodic fallback check every 2 seconds
setInterval(() => {
if (this.detectCurrentTheme()) {
this.notifyThemeChange();
}
}, 2000);
}
setupThemeButtonListeners(): void {
// Listen for clicks on theme toggle buttons
document.addEventListener('click', (e) => {
// Check if clicked element might be a theme toggle
const target = e.target as HTMLElement;
const isThemeButton = target.textContent?.toLowerCase().includes('theme') ||
target.textContent?.toLowerCase().includes('light') ||
target.textContent?.toLowerCase().includes('dark') ||
target.title?.toLowerCase().includes('theme') ||
(typeof target.className === 'string' && target.className.toLowerCase().includes('theme'));
if (isThemeButton) {
setTimeout(() => {
if (this.detectCurrentTheme()) {
this.notifyThemeChange();
}
}, 100);
}
});
}
notifyThemeChange(): void {
// Update settings to reflect new theme
this.state.settings["🔍MagnifyGlass.InfoPanelTheme"] = this.state.currentTheme;
// Notify UI components of theme change immediately
if (window.infoPanelManager && window.infoPanelManager.uiManager) {
window.infoPanelManager.uiManager.updateTheme(this.state.currentTheme);
}
}
loadSettings(): void {
Object.keys(DEFAULT_PANEL_SETTINGS).forEach(key => {
// Skip the theme setting since we auto-detect it
if (key !== "🔍MagnifyGlass.InfoPanelTheme") {
this.state.settings[key] = getSettingValue(key, (DEFAULT_PANEL_SETTINGS as any)[key]);
}
});
// Set theme to auto-detected value
this.state.settings["🔍MagnifyGlass.InfoPanelTheme"] = this.state.currentTheme;
}
updateSettings(): Record<string, SettingsChange> {
const oldSettings = { ...this.state.settings };
this.loadSettings();
// Return what changed for reactive updates
const changes: Record<string, SettingsChange> = {};
Object.keys(this.state.settings).forEach(key => {
if (oldSettings[key] !== this.state.settings[key]) {
changes[key] = {
old: oldSettings[key],
new: this.state.settings[key]
};
}
});
return changes;
}
togglePanelVisibility(): boolean {
this.state.isPanelVisible = !this.state.isPanelVisible;
return this.state.isPanelVisible;
}
toggleGlassPreview(): boolean {
this.state.isGlassPreviewVisible = !this.state.isGlassPreviewVisible;
return this.state.isGlassPreviewVisible;
}
togglePinning(): boolean {
const wasPinned = this.state.isPanelPinned;
this.state.isPanelPinned = !this.state.isPanelPinned;
// When unpinning, also unlock and clear auto-pin flag
if (!this.state.isPanelPinned) {
this.state.isPanelLocked = false;
this.state.isAutoPinned = false; // Clear auto-pin flag when manually unpinning
} else {
// When manually pinning, also clear auto-pin flag (this is a user-initiated pin)
this.state.isAutoPinned = false;
}
if (this.state.isPanelPinned && this.state.lastPinnedPosition) {
// Restore to last pinned position
this.state.pinnedPosition = { ...this.state.lastPinnedPosition };
} else if (!this.state.isPanelPinned && wasPinned) {
// Save current position when unpinning
this.state.lastPinnedPosition = { ...this.state.pinnedPosition };
}
return this.state.isPanelPinned;
}
toggleLocking(): boolean {
// Only allow locking when pinned
if (!this.state.isPanelPinned) {
return false;
}
this.state.isPanelLocked = !this.state.isPanelLocked;
return this.state.isPanelLocked;
}
toggleMinimized(): boolean {
this.state.isPanelMinimized = !this.state.isPanelMinimized;
return this.state.isPanelMinimized;
}
toggleSection(sectionId: string): boolean {
if (sectionId === 'node') return false; // Node section always expanded
if (this.state.expandedSections.has(sectionId)) {
this.state.expandedSections.delete(sectionId);
} else {
this.state.expandedSections.add(sectionId);
}
return true;
}
setPinnedPosition(x: number, y: number): void {
this.state.pinnedPosition = { x, y };
// Also save as last pinned position for memory
this.state.lastPinnedPosition = { x, y };
}
setCurrentInfo(info: GatheredInfo): void {
this.state.currentInfo = info;
}
scheduleAutoCollapse(): void {
this.clearAutoExpandTimer();
if (this.state.settings["🔍MagnifyGlass.InfoPanelAnimations"]) {
this.state.autoExpandTimer = setTimeout(() => {
if (!this.state.isPanelHovered) {
this.collapseNodeSections();
}
}, 1500);
}
}
clearAutoExpandTimer(): void {
if (this.state.autoExpandTimer) {
clearTimeout(this.state.autoExpandTimer);
this.state.autoExpandTimer = null;
}
}
expandNodeSections(): void {
this.state.expandedSections.add('hoveredNode');
this.state.expandedSections.add('node');
this.state.expandedSections.add('cursor');
this.state.expandedSections.add('canvas');
this.state.expandedSections.add('magnifier');
this.clearAutoExpandTimer();
}
collapseNodeSections(): void {
this.state.expandedSections.delete('hoveredNode');
this.state.expandedSections.delete('node');
this.state.expandedSections.delete('widget');
}
cleanup(): void {
this.clearAutoExpandTimer();
}
}
+707
View File
@@ -0,0 +1,707 @@
/**
* ComfyUI MagnifyGlass - Info Panel UI Manager (TypeScript)
*
* Complete UI Manager extracted from magnify_info_panel.js
* Handles all DOM manipulation and UI creation for the info panel.
*/
import { StateManager } from './StateManager';
import { Icons } from '../shared/icons';
import { Logger } from '../shared/logger';
import { formatValue, getValueClass, getValueAttributes, formatWidgetValue } from './ValueFormatter';
import {
getCheckpointInfo,
getImageInfo,
getTextBoxContent,
getImportantNodeParameters,
type ImageInfoResult
} from './NodeDataExtractor';
interface InfoPanelElements {
panel: HTMLDivElement | null;
header: HTMLDivElement | null;
content: HTMLDivElement | null;
controls: HTMLDivElement | null;
}
/**
* UI Manager class.
* Handles all DOM manipulation and UI creation.
*/
export class UIManager {
stateManager: StateManager;
elements: InfoPanelElements;
constructor(stateManager: StateManager) {
this.stateManager = stateManager;
this.elements = {
panel: null,
header: null,
content: null,
controls: null
};
this.createPanel();
this.injectStyles();
}
/**
* Create the main panel and its components.
*/
createPanel(): void {
// Main panel container
this.elements.panel = document.createElement("div");
this.elements.panel.id = "comfyui-magnify-info-panel-pro-v2";
this.elements.panel.className = `magnify-info-panel theme-${this.stateManager.state.currentTheme}`;
// Header
this.elements.header = document.createElement("div");
this.elements.header.className = "panel-header";
this.elements.header.innerHTML = `
<div class="header-content">
<div class="header-icon">${Icons.magnifyGlass}</div>
<div class="header-title">Inspector</div>
<div class="header-subtitle">Real-time analysis</div>
</div>
<div class="header-controls">
<button class="control-btn minimize-btn" title="Minimize Panel" data-action="minimize">${Icons.minus}</button>
</div>
`;
// Content container
this.elements.content = document.createElement("div");
this.elements.content.className = "panel-content";
this.elements.panel.appendChild(this.elements.header);
this.elements.panel.appendChild(this.elements.content);
this.applyStyles();
// Apply initial minimized state if set
if (this.stateManager.state.isPanelMinimized) {
this.elements.panel.classList.add('panel-minimized');
}
document.body.appendChild(this.elements.panel);
// Add click event delegation for panel elements
this.elements.panel.addEventListener('click', (e: MouseEvent) => {
const target = e.target as HTMLElement;
// Handle minimize button
const minimizeBtn = target.closest('[data-action="minimize"]');
if (minimizeBtn) {
this.stateManager.state.isPanelMinimized = !this.stateManager.state.isPanelMinimized;
this.updateMinimizedState();
return;
}
// Handle section header clicks for expand/collapse
const sectionHeader = target.closest('.section-header') as HTMLElement;
if (sectionHeader) {
const sectionId = sectionHeader.getAttribute('data-section');
// Skip node section (always expanded)
if (sectionId && sectionId !== 'node') {
const isExpanded = this.stateManager.state.expandedSections.has(sectionId);
if (isExpanded) {
this.stateManager.state.expandedSections.delete(sectionId);
} else {
this.stateManager.state.expandedSections.add(sectionId);
}
// Update visual state
sectionHeader.classList.toggle('expanded', !isExpanded);
const sectionContent = sectionHeader.nextElementSibling as HTMLElement;
if (sectionContent && sectionContent.classList.contains('section-content')) {
sectionContent.classList.toggle('expanded', !isExpanded);
}
}
}
});
// Create floating controls after panel is in DOM
if (!this.elements.controls) {
this.createFloatingControls();
// Update control states immediately after creation
this.updateControlStates();
}
}
/**
* Create floating control buttons.
*/
createFloatingControls(): void {
this.elements.controls = document.createElement("div");
this.elements.controls.className = "floating-controls vertical-layout"; // Default to vertical
/**
* BUTTON MAPPING DOCUMENTATION:
* =============================
* Button 1 (Unlock Icon): data-action="pin" → controls isPanelPinned
* - Unpinned (default): Panel follows magnify glass
* - Pinned: Panel stays at fixed position (unlocked from following glass)
*
* Button 2 (Pin Icon): data-action="lock" → controls isPanelLocked
* - Unlocked (default): Panel can be dragged
* - Locked: Panel cannot be dragged (pinned in place)
*
* NOTE: The data-action names are counterintuitive but kept for backwards compatibility.
* The ICONS correctly represent the functionality:
* - Unlock icon = unlock from following glass
* - Pin icon = pin position (prevent drag)
*/
this.elements.controls.innerHTML = `
<button class="control-btn unlock-btn" title="Unlock/Lock Panel from Glass" data-action="pin">${Icons.unlock}</button>
<button class="control-btn pin-btn" title="Pin/Unpin Panel Position (Prevent Drag)" data-action="lock">${Icons.pin}</button>
<button class="control-btn visibility-btn" title="Toggle Panel Visibility (I)" data-action="toggle-panel">${Icons.eye}</button>
<button class="control-btn glass-btn" title="Toggle Glass Preview (G)" data-action="toggle-glass">${Icons.magnifyGlass}</button>
`;
// Insert before the panel in the document body, not as a child
document.body.appendChild(this.elements.controls);
// Hide and position off-screen initially - will be shown when magnify glass activates and positions them
this.elements.controls.style.display = 'none';
this.elements.controls.style.visibility = 'hidden';
this.elements.controls.style.left = '-9999px';
this.elements.controls.style.top = '-9999px';
// Add click event delegation for control buttons
this.elements.controls.addEventListener('click', (e: MouseEvent) => {
const target = e.target as HTMLElement;
const button = target.closest('button[data-action]') as HTMLButtonElement;
if (!button) return;
const action = button.getAttribute('data-action');
Logger.debug(`Control button clicked: ${action}`);
switch (action) {
case 'pin':
this.stateManager.togglePinning();
this.updatePinnedState();
this.updateControlStates();
break;
case 'lock':
this.stateManager.state.isPanelLocked = !this.stateManager.state.isPanelLocked;
this.updateControlStates();
if (this.elements.panel) {
this.elements.panel.classList.toggle('panel-locked', this.stateManager.state.isPanelLocked);
}
break;
case 'toggle-panel':
if (this.stateManager.state.isPanelVisible) {
this.hide();
} else {
this.show();
}
this.updateControlStates();
break;
case 'toggle-glass':
this.stateManager.state.isGlassPreviewVisible = !this.stateManager.state.isGlassPreviewVisible;
// Link Glass Visibility to Panel Pinning
if (!this.stateManager.state.isGlassPreviewVisible) {
// Glass Hidden
console.log(`[MagnifyGlass Debug] Glass Hidden. pinned=${this.stateManager.state.isPanelPinned}, autoPinned=${this.stateManager.state.isAutoPinned}`);
// Only auto-pin if not already pinned by the user
if (!this.stateManager.state.isPanelPinned) {
if (this.elements.panel) {
const rect = this.elements.panel.getBoundingClientRect();
this.stateManager.state.pinnedPosition = { x: rect.left, y: rect.top };
}
this.stateManager.state.isPanelPinned = true;
this.stateManager.state.isAutoPinned = true; // Track that this was auto-pinned
console.log(`[MagnifyGlass Debug] Auto-Pinned panel.`);
}
this.stateManager.state.isPanelLocked = false; // Ensure dragging is allowed
} else {
// Glass Shown
console.log(`[MagnifyGlass Debug] Glass Shown. pinned=${this.stateManager.state.isPanelPinned}, autoPinned=${this.stateManager.state.isAutoPinned}`);
// Only unpin if it was auto-pinned (not user-pinned)
if (this.stateManager.state.isAutoPinned) {
this.stateManager.state.isPanelPinned = false;
this.stateManager.state.isAutoPinned = false;
console.log(`[MagnifyGlass Debug] Auto-Unpinned panel.`);
}
// If user manually pinned, keep the panel pinned
}
this.updateControlStates();
this.updatePinnedState(); // Update visual class
// Toggle ONLY the visual visibility (opacity) of the glass preview
// The tool remains active so the inspector can track position
const magnifyGlass = (window as any).comfyUIMagnifyGlass;
if (magnifyGlass && magnifyGlass.ui?.setPreviewVisibility) {
magnifyGlass.ui.setPreviewVisibility(this.stateManager.state.isGlassPreviewVisible);
}
break;
}
});
// Set initial layout based on settings
const controlsPosition = String(this.stateManager.state.settings["🔍MagnifyGlass.ControlsPosition"] || "top-right");
this.updateControlsLayout(controlsPosition);
// Initial state update
this.updateControlStates();
}
/**
* Update control button states.
*/
updateControlStates(): void {
if (!this.elements.controls) return;
const pinBtn = this.elements.controls.querySelector('[data-action="pin"]') as HTMLButtonElement;
const lockBtn = this.elements.controls.querySelector('[data-action="lock"]') as HTMLButtonElement;
const visibilityBtn = this.elements.controls.querySelector('[data-action="toggle-panel"]') as HTMLButtonElement;
const glassBtn = this.elements.controls.querySelector('[data-action="toggle-glass"]') as HTMLButtonElement;
const isPanelVisible = this.stateManager.state.isPanelVisible;
const isGlassVisible = this.stateManager.state.isGlassPreviewVisible;
if (pinBtn) {
pinBtn.classList.toggle('active', this.stateManager.state.isPanelPinned);
pinBtn.title = this.stateManager.state.isPanelPinned ? "Lock Panel" : "Unlock Panel";
pinBtn.innerHTML = this.stateManager.state.isPanelPinned ? Icons.lock : Icons.unlock;
// Hide unlock button when panel is hidden
pinBtn.style.display = isPanelVisible ? 'flex' : 'none';
// Disable unlock (unpin) button if glass is hidden
// This prevents entering "Follow Mouse" mode when glass is invisible
if (!isGlassVisible) {
pinBtn.disabled = true;
pinBtn.style.opacity = '0.5';
pinBtn.title = "Cannot unlock panel from screen when glass preview is hidden";
} else {
pinBtn.disabled = false;
pinBtn.style.opacity = '';
}
}
if (lockBtn) {
// Only show pin button when panel is visible AND unlocked from glass
const showLockBtn = isPanelVisible && this.stateManager.state.isPanelPinned;
lockBtn.style.display = showLockBtn ? 'flex' : 'none';
lockBtn.classList.toggle('active', this.stateManager.state.isPanelLocked);
lockBtn.title = this.stateManager.state.isPanelLocked ? "Unpin Panel Position" : "Pin Panel Position";
lockBtn.disabled = !this.stateManager.state.isPanelPinned;
}
if (visibilityBtn) {
// Active means "Panel is Visible"
visibilityBtn.classList.toggle('active', isPanelVisible);
visibilityBtn.title = isPanelVisible ? "Hide Panel" : "Show Panel";
// Disable hide button if glass is hidden (prevent hiding everything)
if (!isGlassVisible) {
visibilityBtn.disabled = true;
visibilityBtn.style.opacity = '0.5';
visibilityBtn.title = "Cannot hide panel when glass preview is hidden";
} else {
visibilityBtn.disabled = false;
visibilityBtn.style.opacity = '';
}
}
if (glassBtn) {
glassBtn.classList.toggle('active', isGlassVisible);
glassBtn.title = isGlassVisible ? "Hide Glass Preview" : "Show Glass Preview";
// Only show glass toggle button if the inspector panel is visible
glassBtn.style.display = isPanelVisible ? 'flex' : 'none';
}
}
/**
* Update controls layout based on position setting.
* @param position
*/
updateControlsLayout(position: string): void {
if (!this.elements.controls) return;
// Remove existing layout classes
this.elements.controls.classList.remove('horizontal-layout', 'vertical-layout');
// Add appropriate layout class
if (['top', 'bottom'].includes(position)) {
this.elements.controls.classList.add('horizontal-layout');
} else {
this.elements.controls.classList.add('vertical-layout');
}
}
/**
* Apply current styles to elements.
*/
applyStyles(): void {
if (!this.elements.panel) return;
const settings = this.stateManager.state.settings;
// Debug Log
console.log(`[UIManager] applyStyles - MaxHeight: ${settings["🔍MagnifyGlass.InfoPanelMaxHeight"]}`);
// 1. Apply dimensions
this.elements.panel.style.width = `${settings["🔍MagnifyGlass.InfoPanelWidth"]}px`;
// Set both height and max-height so the panel always shows at this size
const maxHeight = settings["🔍MagnifyGlass.InfoPanelMaxHeight"];
this.elements.panel.style.height = `${maxHeight}px`;
this.elements.panel.style.maxHeight = `${maxHeight}px`;
// 2. Apply static styles (only needed once or if overwritten, but safe to set)
this.elements.panel.style.position = 'absolute';
this.elements.panel.style.zIndex = '99999';
this.elements.panel.style.transform = 'translateY(-10px)';
this.elements.panel.style.pointerEvents = 'auto';
this.elements.panel.style.userSelect = 'none';
this.elements.panel.style.fontFamily = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif";
// 3. Apply transition
this.elements.panel.style.transition = settings["🔍MagnifyGlass.InfoPanelAnimations"]
? 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)'
: 'none';
// 4. Apply Custom Colors (CSS Variables)
const textColor = settings["🔍MagnifyGlass.InfoPanelTextColor"] as string | undefined;
if (textColor && typeof textColor === 'string') {
const normalizedTextColor = textColor.startsWith('#') ? textColor : `#${textColor}`;
this.elements.panel.style.setProperty('--info-panel-text-color', normalizedTextColor);
}
const accentColor = settings["🔍MagnifyGlass.InfoPanelAccentColor"] as string | undefined;
if (accentColor && typeof accentColor === 'string') {
const normalizedAccentColor = accentColor.startsWith('#') ? accentColor : `#${accentColor}`;
this.elements.panel.style.setProperty('--info-panel-accent-color', normalizedAccentColor);
}
// 5. Apply Opacity
// Logic: If visible, use setting. If hidden, use 0.
// We do NOT touch 'display' here to avoid hiding it if it's currently shown.
// 'display' is managed by show() / hide() methods exclusively.
if (this.stateManager.state.isPanelVisible) {
const opacityPercent = Number(settings["🔍MagnifyGlass.InfoPanelOpacity"]) || 100;
this.elements.panel.style.opacity = (opacityPercent / 100).toString();
} else {
this.elements.panel.style.opacity = '0';
}
}
/**
* Show the panel.
*/
show(): void {
if (!this.elements.panel) return;
if (this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelEnabled"]) {
this.elements.panel.style.display = "block";
// Controls are shown by positionFloatingControls() after proper positioning
// Apply user's opacity setting when showing (convert percentage to decimal)
const opacityPercent = Number(this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelOpacity"]) || 100;
this.elements.panel.style.opacity = (opacityPercent / 100).toString();
// Trigger reflow
this.elements.panel.offsetHeight;
this.elements.panel.classList.add('visible');
this.stateManager.state.isPanelVisible = true;
this.updateControlStates();
}
}
/**
* Hide the panel.
*/
hide(): void {
if (!this.elements.panel) return;
this.elements.panel.classList.remove('visible');
setTimeout(() => {
if (!this.stateManager.state.isPanelVisible && this.elements.panel) {
this.elements.panel.style.display = "none";
// Do NOT hide controls when panel is hidden - they should remain visible on glass
// if (this.elements.controls) {
// this.elements.controls.style.display = "none";
// }
}
}, this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelAnimations"] ? 300 : 0);
this.stateManager.state.isPanelVisible = false;
this.updateControlStates();
}
/**
* Update minimized state.
*/
updateMinimizedState(): void {
if (!this.elements.panel || !this.elements.header) return;
this.elements.panel.classList.toggle('panel-minimized', this.stateManager.state.isPanelMinimized);
const minimizeBtn = this.elements.header.querySelector('.minimize-btn');
if (minimizeBtn) {
minimizeBtn.textContent = this.stateManager.state.isPanelMinimized ? '+' : '−';
(minimizeBtn as HTMLElement).title = this.stateManager.state.isPanelMinimized ? 'Expand Panel' : 'Minimize Panel';
}
}
/**
* Update pinned state.
*/
updatePinnedState(): void {
if (!this.elements.panel) return;
this.elements.panel.classList.toggle('panel-pinned', this.stateManager.state.isPanelPinned);
this.elements.panel.classList.toggle('panel-locked', this.stateManager.state.isPanelLocked);
this.updateControlStates();
}
/**
* Update theme class.
* @param newTheme
*/
updateTheme(newTheme: string): void {
if (this.elements.panel) {
this.elements.panel.className = this.elements.panel.className.replace(/theme-\w+/, `theme-${newTheme.toLowerCase()}`);
}
}
/**
* Display information in the panel.
* @param info
*/
displayInfo(info: any): void {
const sections = this.buildSections(info);
this.renderSections(sections);
this.updateSectionStates();
this.updateHeaderSubtitle(info);
}
/**
* Build section data from info object.
* @param info
* @returns
*/
buildSections(info: any): any[] {
const sections: any[] = [];
const settings = this.stateManager.state.settings;
// Inspector section
if (settings["🔍MagnifyGlass.ShowInspectorTab"] && info.cursor && info.cursor.canvas) {
const inspectorContent = [
{ label: 'Cursor Canvas', value: `(${Math.round(info.cursor.canvas.x)}, ${Math.round(info.cursor.canvas.y)})` },
{ label: 'Canvas Scale', value: `${(info.canvas.scale * 100).toFixed(1)}%` },
{ label: 'Magnifier Zoom', value: `${info.magnifier.zoomFactor}×` }
];
sections.push({
id: 'inspector',
icon: Icons.info,
title: 'Inspector',
content: inspectorContent
});
}
// Media section
if (info.media) {
const mediaContent = [
{ label: 'Type', value: info.media.tagName },
{ label: 'Source', value: info.media.src }
];
if (info.media.naturalSize) {
mediaContent.push({ label: 'Natural', value: info.media.naturalSize });
}
sections.push({
id: 'media',
icon: Icons.camera,
title: 'Media',
badge: info.media.tagName,
content: mediaContent
});
}
// Node Details section
if (info.hoveredNode) {
const nodeContent = [
{ label: 'Title', value: info.hoveredNode.title }
];
// Check if this is a complex node that shows all widgets
const nodeType = info.hoveredNode.type ? info.hoveredNode.type.toLowerCase() : '';
const isSaveNode = nodeType.includes('save') &&
!nodeType.includes('checkpoint') &&
!nodeType.includes('model') &&
!nodeType.includes('preview');
const showAllWidgets = info.hoveredNode.type && (
nodeType.includes('ksampler') ||
nodeType.includes('sampler') ||
nodeType.includes('k_samplers') ||
nodeType.includes('checkpoint') ||
nodeType.includes('model') ||
nodeType.includes('lora') ||
nodeType.includes('controlnet') ||
nodeType.includes('advanced') ||
nodeType.includes('detailer') ||
nodeType.includes('inpaint') ||
nodeType.includes('upscale') ||
nodeType.includes('clip') ||
nodeType.includes('text') ||
nodeType.includes('encode')
) && !isSaveNode;
if (!showAllWidgets) {
// Add specific extractions for simple nodes
const checkpoint = getCheckpointInfo(info.hoveredNode);
if (checkpoint) {
nodeContent.push({ label: 'Model', value: checkpoint });
}
const imgInfo = getImageInfo(info.hoveredNode);
if (imgInfo) {
if (typeof imgInfo === 'string') {
nodeContent.push({ label: 'Image', value: imgInfo });
} else if (typeof imgInfo === 'object' && imgInfo !== null) {
const imgResult = imgInfo as ImageInfoResult;
nodeContent.push({ label: 'Image Size', value: `${imgResult.width}×${imgResult.height}` });
if (imgResult.src) {
nodeContent.push({ label: 'Image Source', value: imgResult.src });
}
}
}
const textContent = getTextBoxContent(info.hoveredNode);
if (textContent) {
nodeContent.push({ label: 'Text', value: textContent });
}
}
const importantParameters = getImportantNodeParameters(info.hoveredNode);
nodeContent.push(...importantParameters);
sections.push({
id: 'node',
icon: Icons.box,
title: 'Node',
badge: info.hoveredNode.type,
content: nodeContent
});
}
return sections;
}
/**
* Render sections to the panel.
* @param sections
*/
renderSections(sections: any[]): void {
if (!this.elements.content) return;
if (sections.length === 0) {
this.elements.content.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">${Icons.mapPin}</div>
<div class="empty-state-text">Empty canvas area</div>
</div>
`;
return;
}
this.elements.content.innerHTML = sections.map(section => `
<div class="info-section" data-section="${section.id}">
<div class="section-header" data-section="${section.id}">
<span class="section-icon">${section.icon}</span>
<span class="section-title">${section.title}</span>
${section.badge ? `<span class="section-badge">${section.badge}</span>` : ''}
${section.id !== 'node' ? `<span class="expand-icon">${Icons.chevronRight}</span>` : ''}
</div>
<div class="section-content">
<div class="section-body">
${section.content.map((item: any) => {
const value = formatValue(item.value, item.label);
const valueClass = getValueClass(item.value);
const valueAttributes = getValueAttributes(item.value);
return `
<div class="info-row">
<span class="info-label">${item.label}</span>
<span class="info-value ${valueClass}" ${valueAttributes}>${value}</span>
</div>`;
}).join('')}
</div>
</div>
</div>
`).join('');
}
/**
* Update section expansion states.
*/
updateSectionStates(): void {
if (!this.elements.content) return;
const sections = this.elements.content.querySelectorAll('.info-section');
sections.forEach(section => {
const sectionId = (section as HTMLElement).dataset.section;
if (!sectionId) return;
const header = section.querySelector('.section-header');
const content = section.querySelector('.section-content');
if (header && content) {
if (this.stateManager.state.expandedSections.has(sectionId)) {
header.classList.add('expanded');
content.classList.add('expanded');
} else {
header.classList.remove('expanded');
content.classList.remove('expanded');
}
}
});
}
/**
* Update header subtitle.
* @param info
*/
updateHeaderSubtitle(info: any): void {
if (!this.elements.header) return;
const subtitleElement = this.elements.header.querySelector('.header-subtitle') as HTMLElement;
if (subtitleElement) {
const accentColor = String(this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelAccentColor"] || '');
if (info.hoveredNode) {
subtitleElement.textContent = `Analyzing: ${info.hoveredNode.title}`;
subtitleElement.style.color = accentColor;
} else if (info.media) {
subtitleElement.textContent = `Media: ${info.media.tagName}`;
subtitleElement.style.color = accentColor;
} else if (info.connection) {
subtitleElement.textContent = `Connection: ${info.connection.type}`;
subtitleElement.style.color = accentColor;
} else {
subtitleElement.textContent = 'Real-time analysis';
subtitleElement.style.color = '';
}
}
}
/**
* Inject CSS styles by loading external stylesheet.
*/
injectStyles(): void {
if (!document.getElementById('magnify-info-panel-styles-v2')) {
const link = document.createElement('link');
link.id = 'magnify-info-panel-styles-v2';
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'extensions/comfyui-magnifyglass/info-panel.css';
document.head.appendChild(link);
}
}
cleanup(): void {
if (this.elements.panel && this.elements.panel.parentNode) {
this.elements.panel.parentNode.removeChild(this.elements.panel);
}
if (this.elements.controls && this.elements.controls.parentNode) {
this.elements.controls.parentNode.removeChild(this.elements.controls);
}
}
}
+95
View File
@@ -0,0 +1,95 @@
/**
* ComfyUI MagnifyGlass - Value Formatter Utilities
*
* Pure utility functions for formatting values in the info panel display.
* Extracted from UIManager.ts for better modularity.
*/
/**
* Format a value for display in the info panel.
* @param value - The value to format
* @param label - Optional label to determine formatting rules
* @returns Formatted string representation
*/
export function formatValue(value: unknown, label?: string): string {
if (value === null || value === undefined) return '';
const str = String(value);
// Show full text for prompts, text content, model names, and file paths
if (label && (
label.toLowerCase().includes('text') ||
label.toLowerCase().includes('prompt') ||
label.toLowerCase().includes('model') ||
label.toLowerCase().includes('file') ||
label.toLowerCase().includes('conditioning') ||
label.toLowerCase().includes('positive') ||
label.toLowerCase().includes('negative')
)) {
return str;
}
// Show full text for very long values (no truncation)
return str;
}
/**
* Get CSS class names for styling a value.
* @param value - The value to get classes for
* @returns CSS class string
*/
export function getValueClass(value: unknown): string {
if (!value) return '';
const str = String(value);
const classes: string[] = [];
// Mark text that might benefit from special styling for readability
if (str.length > 100) {
classes.push('long-text');
}
return classes.join(' ');
}
/**
* Get HTML attributes for a value element.
* @param value - The value to get attributes for
* @returns HTML attribute string
*/
export function getValueAttributes(value: unknown): string {
// Since we show full text now, we don't need title attributes for long text
// Only add title for very long text that might benefit from tooltips
if (!value) return '';
const str = String(value);
if (str.length > 500) { // Only for extremely long text
return `title="${str.replace(/"/g, '&quot;')}"`;
}
return '';
}
/**
* Format widget value for display.
* @param value - Widget value to format
* @returns Formatted string representation
*/
export function formatWidgetValue(value: unknown): string {
if (value === null) return 'null';
if (value === undefined) return 'undefined';
if (typeof value === 'string') {
return value; // Show full text without truncation
}
if (typeof value === 'number') {
return Number.isInteger(value) ? value.toString() : value.toFixed(3);
}
if (typeof value === 'boolean') return value.toString();
if (Array.isArray(value)) {
return `Array(${value.length})`;
}
if (typeof value === 'object') {
return 'Object';
}
return String(value);
}
+6
View File
@@ -0,0 +1,6 @@
export * from './StateManager';
export * from './UIManager';
export * from './PositionManager';
export * from './InformationGatherer';
export * from './EventManager';
export * from './InfoPanel';
+182
View File
@@ -0,0 +1,182 @@
/**
* ComfyUI MagnifyGlass - ConfigManager (TypeScript)
*
* Manages configuration and settings for the magnifying glass.
*/
import { getSettingValue } from '../shared/utils';
import { STORAGE_KEYS } from '../shared/constants';
import type { GlassPosition, GlassShape, TextureFilter } from '../shared/constants';
// Default settings (we'll import these properly later)
const DEFAULT_GLASS_SETTINGS = {
"🔍MagnifyGlass.ZoomFactor": 300,
"🔍MagnifyGlass.GlassSize": 300,
"🔍MagnifyGlass.BorderColor": "#6b7280",
"🔍MagnifyGlass.BorderWidth": 1,
"🔍MagnifyGlass.ActivationKey": "x",
"🔍MagnifyGlass.AltRequired": false,
"🔍MagnifyGlass.FollowCursor": false,
"🔍MagnifyGlass.DebugMode": false,
"🔍MagnifyGlass.OffsetStep": 5,
"🔍MagnifyGlass.GlassPosition": "Top-Right" as GlassPosition,
"🔍MagnifyGlass.ResetKey": "o",
"🔍MagnifyGlass.GlassShape": "Rounded Square" as GlassShape,
"🔍MagnifyGlass.BorderEnabled": true,
"🔍MagnifyGlass.TextureFiltering": "Linear" as TextureFilter,
"🔍MagnifyGlass.AlwaysActiveMode": true,
"🔍MagnifyGlass.ToggleFollowCursorKey": "h",
};
/**
* Configuration manager class.
* Reads settings from ComfyUI and manages persistent offsets.
*/
export class ConfigManager {
/** Zoom factor (1.0 = 100%, 3.0 = 300%) */
zoomFactor: number;
/** Glass size in pixels */
glassSize: number;
/** Border color (CSS color string) */
borderColor: string;
/** Border width in pixels */
borderWidth: number;
/** Activation key (lowercase) */
activationKey: string;
/** Whether Alt key is required for activation */
altRequired: boolean;
/** Whether glass follows cursor */
followCursor: boolean;
/** Debug mode enabled */
debugMode: boolean;
/** Offset step for arrow key adjustments */
offsetStep: number;
/** Glass position relative to cursor */
glassPosition: string;
/** Reset key (lowercase) */
resetKey: string;
/** Glass shape */
glassShape: string;
/** Whether border is enabled */
borderEnabled: boolean;
/** Texture filtering mode */
textureFiltering: string;
/** Always active mode */
alwaysActiveMode: boolean;
/** Toggle follow cursor key */
toggleFollowCursorKey: string;
/** Manual offset X in graph units */
offsetX: number;
/** Manual offset Y in graph units */
offsetY: number;
constructor() {
// Initialize properties with defaults
this.zoomFactor = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.ZoomFactor"] / 100;
this.glassSize = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.GlassSize"];
this.borderColor = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.BorderColor"];
this.borderWidth = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.BorderWidth"];
this.activationKey = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.ActivationKey"];
this.altRequired = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.AltRequired"];
this.followCursor = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.FollowCursor"];
this.debugMode = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.DebugMode"];
this.offsetStep = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.OffsetStep"];
this.glassPosition = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.GlassPosition"];
this.resetKey = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.ResetKey"];
this.glassShape = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.GlassShape"];
this.borderEnabled = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.BorderEnabled"];
this.textureFiltering = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.TextureFiltering"];
this.alwaysActiveMode = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.AlwaysActiveMode"];
this.toggleFollowCursorKey = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.ToggleFollowCursorKey"];
// Alignment adjustment parameters - managed separately
this.offsetX = 0;
this.offsetY = 0;
}
/**
* Load settings from ComfyUI settings system.
*/
loadSettings(): void {
this.zoomFactor = getSettingValue<number>("🔍MagnifyGlass.ZoomFactor", this.zoomFactor * 100) / 100;
this.glassSize = getSettingValue<number>("🔍MagnifyGlass.GlassSize", this.glassSize);
this.borderColor = getSettingValue<string>("🔍MagnifyGlass.BorderColor", this.borderColor);
this.borderWidth = getSettingValue<number>("🔍MagnifyGlass.BorderWidth", this.borderWidth);
this.activationKey = getSettingValue<string>("🔍MagnifyGlass.ActivationKey", this.activationKey);
this.altRequired = getSettingValue<boolean>("🔍MagnifyGlass.AltRequired", this.altRequired);
this.followCursor = getSettingValue<boolean>("🔍MagnifyGlass.FollowCursor", this.followCursor);
this.debugMode = getSettingValue<boolean>("🔍MagnifyGlass.DebugMode", this.debugMode);
this.offsetStep = getSettingValue<number>("🔍MagnifyGlass.OffsetStep", this.offsetStep);
this.glassPosition = getSettingValue<string>("🔍MagnifyGlass.GlassPosition", this.glassPosition);
this.resetKey = getSettingValue<string>("🔍MagnifyGlass.ResetKey", this.resetKey);
this.glassShape = getSettingValue<string>("🔍MagnifyGlass.GlassShape", this.glassShape);
this.borderEnabled = getSettingValue<boolean>("🔍MagnifyGlass.BorderEnabled", this.borderEnabled);
this.textureFiltering = getSettingValue<string>("🔍MagnifyGlass.TextureFiltering", this.textureFiltering);
this.alwaysActiveMode = getSettingValue<boolean>("🔍MagnifyGlass.AlwaysActiveMode", this.alwaysActiveMode);
this.toggleFollowCursorKey = getSettingValue<string>("🔍MagnifyGlass.ToggleFollowCursorKey", this.toggleFollowCursorKey);
}
/**
* Load saved offsets from localStorage.
*/
loadSavedOffsets(): void {
try {
const savedOffsetX = localStorage.getItem(STORAGE_KEYS.OFFSET_X);
const savedOffsetY = localStorage.getItem(STORAGE_KEYS.OFFSET_Y);
if (savedOffsetX !== null) {
this.offsetX = parseInt(savedOffsetX, 10);
} else {
this.offsetX = 0;
}
if (savedOffsetY !== null) {
this.offsetY = parseInt(savedOffsetY, 10);
} else {
this.offsetY = 0;
}
} catch (e) {
console.error("ComfyUI Magnifying Glass ERROR: Error loading saved offsets:", e);
this.offsetX = 0;
this.offsetY = 0;
}
}
/**
* Save current offsets to localStorage.
*/
saveOffsets(): void {
try {
localStorage.setItem(STORAGE_KEYS.OFFSET_X, this.offsetX.toString());
localStorage.setItem(STORAGE_KEYS.OFFSET_Y, this.offsetY.toString());
} catch (e) {
console.error("ComfyUI Magnifying Glass ERROR: Error saving offsets:", e);
}
}
/**
* Reset offsets to default (zero).
*/
resetOffsets(): void {
this.offsetX = 0;
this.offsetY = 0;
this.saveOffsets();
}
}
+181
View File
@@ -0,0 +1,181 @@
/**
* ComfyUI MagnifyGlass - DebugManager (TypeScript)
*
* Handles debug visualization and logging.
*/
import type { ComfyApp } from '../types/comfyui';
import type { ConfigManager } from './ConfigManager';
import type { MagnifierState } from './MagnifierState';
import type { UiManager } from './UiManager';
declare const app: ComfyApp;
/**
* Debug Manager class.
* Provides debug logging and canvas visualization.
*/
export class DebugManager {
config: ConfigManager;
state: MagnifierState;
ui: UiManager;
constructor(config: ConfigManager, state: MagnifierState, ui: UiManager) {
this.config = config;
this.state = state;
this.ui = ui;
}
/**
* Log a message if debug mode is enabled.
*/
log(...args: unknown[]): void {
if (this.config.debugMode) {
console.log("ComfyUI Magnifying Glass:", ...args);
}
}
/**
* Log an error message.
*/
error(...args: unknown[]): void {
console.error("ComfyUI Magnifying Glass ERROR:", ...args);
}
/**
* Print detailed canvas information for debugging.
*/
printCanvasInfo(): void {
if (!this.config.debugMode) return;
try {
// Using any for deep property access on ComfyUI objects that might vary
const canvasManager = (app as any).canvas;
const canvas = canvasManager?.graph_canvas as HTMLCanvasElement;
if (!canvas) {
this.log("Could not find graph canvas for detailed info");
return;
}
this.log("---- Canvas Information ----");
this.log(`Canvas dimensions: ${canvas.width}x${canvas.height}`);
this.log(`Canvas display size: ${canvas.clientWidth}x${canvas.clientHeight}`);
this.log(`Canvas CSS transform: ${canvas.style.transform || 'none'}`);
const ds = canvasManager.ds;
if (ds) {
this.log(`Canvas DS scale: ${ds.scale}`);
if (ds.offset) {
this.log(`Canvas DS offset: [${ds.offset[0]}, ${ds.offset[1]}]`);
} else {
this.log("Canvas DS offset not found");
}
} else {
this.log("Canvas DS object not found");
}
const screenWidth = window.innerWidth;
const screenHeight = window.innerHeight;
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
this.log(`Window dimensions: ${screenWidth}x${screenHeight}`);
this.log(`Resolution scale factor: X=${canvasWidth / screenWidth}, Y=${canvasHeight / screenHeight}`);
this.log("---- End Canvas Information ----");
} catch (e) {
this.log("Error in printCanvasInfo:", e);
}
}
/**
* Update the debug visualization canvas.
*/
updateDebugView(): void {
if (!this.config.debugMode || !this.ui || !this.ui.debugCanvas || !this.ui.debugCtx) return;
const debugCtx = this.ui.debugCtx;
const debugCanvas = this.ui.debugCanvas;
debugCtx.clearRect(0, 0, debugCanvas.width, debugCanvas.height);
// Draw background
debugCtx.fillStyle = 'rgba(0,0,0,0.8)';
debugCtx.fillRect(0, 0, debugCanvas.width, debugCanvas.height);
// Header
debugCtx.fillStyle = '#FFFFFF';
debugCtx.font = '14px monospace';
debugCtx.fillText('Magnify Glass Debug', 10, 20);
// Position info
debugCtx.font = '12px monospace';
debugCtx.fillText(`Cursor: (${this.state.x.toFixed(1)}, ${this.state.y.toFixed(1)})`, 10, 50);
debugCtx.fillText(`Source Rect: (${this.state.sourceX.toFixed(1)}, ${this.state.sourceY.toFixed(1)}, w:${this.state.sourceWidth.toFixed(1)}, h:${this.state.sourceHeight.toFixed(1)})`, 10, 70);
// Canvas transform
debugCtx.fillText(`Canvas Scale: ${this.state.canvasScale.toFixed(2)}`, 10, 90);
debugCtx.fillText(`Canvas Offset: (${this.state.canvasOffsetX.toFixed(1)}, ${this.state.canvasOffsetY.toFixed(1)})`, 10, 110);
// Offset information
debugCtx.fillStyle = '#FFFF00';
debugCtx.fillText(`MANUAL OFFSETS: X=${this.config.offsetX}, Y=${this.config.offsetY} (Use arrow keys to adjust)`, 10, 130);
debugCtx.fillStyle = '#FFFFFF';
// Visualization
this.drawCanvasVisualization(debugCtx, debugCanvas);
}
/**
* Draw a scaled visualization of the canvas and source region.
*/
drawCanvasVisualization(debugCtx: CanvasRenderingContext2D, debugCanvas: HTMLCanvasElement): void {
const canvasScale = 0.1;
const canvasVisX = 10;
const canvasVisY = 170;
const canvasVisWidth = 380;
const canvasVisHeight = 150;
// Draw canvas representation
debugCtx.strokeStyle = '#AAAAAA';
debugCtx.strokeRect(canvasVisX, canvasVisY, canvasVisWidth, canvasVisHeight);
debugCtx.fillStyle = '#444444';
debugCtx.fillRect(canvasVisX, canvasVisY, canvasVisWidth, canvasVisHeight);
// Calculate cursor position in visualization
const cursorVisX = canvasVisX + (this.state.x * canvasScale);
const cursorVisY = canvasVisY + (this.state.y * canvasScale);
// Calculate source rect in visualization
const sourceRectVisX = canvasVisX + (this.state.sourceX * canvasScale);
const sourceRectVisY = canvasVisY + (this.state.sourceY * canvasScale);
const sourceRectVisWidth = this.state.sourceWidth * canvasScale;
const sourceRectVisHeight = this.state.sourceHeight * canvasScale;
// Draw source rect
debugCtx.strokeStyle = '#FF0000';
debugCtx.strokeRect(sourceRectVisX, sourceRectVisY, sourceRectVisWidth, sourceRectVisHeight);
// Draw cursor position
debugCtx.fillStyle = '#FFFF00';
debugCtx.beginPath();
debugCtx.arc(cursorVisX, cursorVisY, 3, 0, Math.PI * 2);
debugCtx.fill();
// Draw line from cursor to source rect center
debugCtx.strokeStyle = '#00FF00';
debugCtx.beginPath();
debugCtx.moveTo(cursorVisX, cursorVisY);
debugCtx.lineTo(sourceRectVisX + sourceRectVisWidth / 2, sourceRectVisY + sourceRectVisHeight / 2);
debugCtx.stroke();
// Label for visualization
debugCtx.fillStyle = '#FFFFFF';
debugCtx.fillText('Canvas Visualization (scaled)', canvasVisX, canvasVisY - 5);
// Offset values
const offsetX = this.state.sourceX - this.state.x + (this.state.sourceWidth / 2);
const offsetY = this.state.sourceY - this.state.y + (this.state.sourceHeight / 2);
debugCtx.fillText(`Alignment Offset: (${offsetX.toFixed(1)}, ${offsetY.toFixed(1)})`, 10, canvasVisY + canvasVisHeight + 20);
}
}
+226
View File
@@ -0,0 +1,226 @@
/**
* ComfyUI MagnifyGlass - EventHandler (TypeScript)
*
* Handles keyboard and mouse events for the magnifying glass.
*/
import { isUserTyping } from '../shared/utils';
import { Logger } from '../shared/logger';
import { DEFAULT_PADDING, DEFAULT_GLASS_Y_OFFSET } from '../shared/constants';
import type { MagnifyGlass } from './MagnifyGlass';
/**
* Event Handler class.
* Manages all keyboard and mouse event handling for the magnifier.
*/
export class EventHandler {
magnifyGlass: MagnifyGlass;
constructor(magnifyGlass: MagnifyGlass) {
this.magnifyGlass = magnifyGlass;
// Bind methods to maintain context
this.handleKeyDown = this.handleKeyDown.bind(this);
this.handleKeyUp = this.handleKeyUp.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
}
/**
* Attach all event listeners.
*/
attachListeners(): void {
document.addEventListener("keydown", this.handleKeyDown);
document.addEventListener("keyup", this.handleKeyUp);
document.addEventListener("mousemove", this.handleMouseMove);
}
/**
* Detach all event listeners.
*/
detachListeners(): void {
document.removeEventListener("keydown", this.handleKeyDown);
document.removeEventListener("keyup", this.handleKeyUp);
document.removeEventListener("mousemove", this.handleMouseMove);
}
/**
* Handle keydown events.
*/
handleKeyDown(e: KeyboardEvent): void {
const config = this.magnifyGlass.config;
const state = this.magnifyGlass.state;
// Don't handle hotkeys if user is typing in an input field
if (isUserTyping()) {
return;
}
// Magnifier activation
Logger.debug(`KeyDown: ${e.key} (config: ${config.activationKey}, active: ${state.active})`);
if (e.key.toLowerCase() === config.activationKey &&
(!config.altRequired || e.altKey)) {
Logger.debug('Activation key matched!');
if (config.alwaysActiveMode) {
this.magnifyGlass.toggle();
} else {
if (!state.active) {
this.magnifyGlass.toggle();
}
}
}
// Manual offset adjustment keys (only when magnifier is active)
if (state.active) {
let offsetChanged = false;
const stepSize = e.shiftKey ? config.offsetStep * 5 : config.offsetStep;
if (e.key === "ArrowUp") {
config.offsetY -= stepSize;
offsetChanged = true;
e.preventDefault();
} else if (e.key === "ArrowDown") {
config.offsetY += stepSize;
offsetChanged = true;
e.preventDefault();
} else if (e.key === "ArrowLeft") {
config.offsetX -= stepSize;
offsetChanged = true;
e.preventDefault();
} else if (e.key === "ArrowRight") {
config.offsetX += stepSize;
offsetChanged = true;
e.preventDefault();
} else if (e.key.toLowerCase() === config.resetKey.toLowerCase() &&
(!config.altRequired || e.altKey)) {
this.magnifyGlass.resetOffsets();
offsetChanged = true;
e.preventDefault();
}
// Toggle Follow Cursor Key
if (e.key.toLowerCase() === config.toggleFollowCursorKey &&
(!config.altRequired || e.altKey)) {
config.followCursor = !config.followCursor;
this.magnifyGlass.debugger.log(`Follow Cursor Toggled: ${config.followCursor ? 'ON' : 'OFF'}`);
if (state.active && config.followCursor) {
this.magnifyGlass.ui.positionGlass(
this.magnifyGlass.lastKnownMousePosition.x,
this.magnifyGlass.lastKnownMousePosition.y
);
}
e.preventDefault();
}
if (offsetChanged) {
config.saveOffsets();
this.magnifyGlass.updateMagnifiedView();
}
}
}
/**
* Handle keyup events.
*/
handleKeyUp(e: KeyboardEvent): void {
const config = this.magnifyGlass.config;
const state = this.magnifyGlass.state;
if (!config.alwaysActiveMode &&
(e.key.toLowerCase() === config.activationKey ||
(config.altRequired && e.key === "Alt"))) {
let shouldDeactivate = false;
if (config.altRequired) {
if (e.key === "Alt" || e.key.toLowerCase() === config.activationKey) {
shouldDeactivate = true;
}
} else {
if (e.key.toLowerCase() === config.activationKey) {
shouldDeactivate = true;
}
}
if (state.active && shouldDeactivate) {
state.active = false;
this.magnifyGlass.ui.hide();
}
}
}
/**
* Handle mousemove events.
*/
handleMouseMove(e: MouseEvent): void {
// Always track mouse position
this.magnifyGlass.lastKnownMousePosition.x = e.clientX;
this.magnifyGlass.lastKnownMousePosition.y = e.clientY;
if (!this.magnifyGlass.state.active || !this.magnifyGlass.litegraphCanvas) return;
const rect = this.magnifyGlass.litegraphCanvas.getBoundingClientRect();
const cssMouseXOnCanvas = e.clientX - rect.left;
const cssMouseYOnCanvas = e.clientY - rect.top;
// Check if the cursor is over the canvas element
if (cssMouseXOnCanvas >= 0 && cssMouseXOnCanvas <= rect.width &&
cssMouseYOnCanvas >= 0 && cssMouseYOnCanvas <= rect.height) {
const canvasElement = this.magnifyGlass.litegraphCanvas;
const scaleX = rect.width > 0 ? canvasElement.width / rect.width : 1;
const scaleY = rect.height > 0 ? canvasElement.height / rect.height : 1;
const pixelX = cssMouseXOnCanvas * scaleX;
const pixelY = cssMouseYOnCanvas * scaleY;
this.magnifyGlass.state.x = pixelX;
this.magnifyGlass.state.y = pixelY;
this.magnifyGlass.ui.positionGlass(e.clientX, e.clientY);
this.magnifyGlass.updateMagnifiedView();
}
}
/**
* Update the initial position when magnifier is activated.
*/
updateInitialPosition(): void {
if (!this.magnifyGlass.litegraphCanvas) return;
const rect = this.magnifyGlass.litegraphCanvas.getBoundingClientRect();
const clientX = this.magnifyGlass.lastKnownMousePosition.x;
const clientY = this.magnifyGlass.lastKnownMousePosition.y;
const isOverCanvas = clientX >= rect.left && clientX <= rect.right &&
clientY >= rect.top && clientY <= rect.bottom;
if (this.magnifyGlass.config.alwaysActiveMode || isOverCanvas) {
const cssMouseXOnCanvas = clientX - rect.left;
const cssMouseYOnCanvas = clientY - rect.top;
const canvasElement = this.magnifyGlass.litegraphCanvas;
const scaleX = rect.width > 0 ? canvasElement.width / rect.width : 1;
const scaleY = rect.height > 0 ? canvasElement.height / rect.height : 1;
const pixelX = cssMouseXOnCanvas * scaleX;
const pixelY = cssMouseYOnCanvas * scaleY;
this.magnifyGlass.state.x = pixelX;
this.magnifyGlass.state.y = pixelY;
const glassSize = this.magnifyGlass.config.glassSize;
if (!this.magnifyGlass.state.wasActivatedBefore && this.magnifyGlass.ui.glassDiv) {
// First activation - position at top right of the window
const leftPos = window.innerWidth - glassSize - DEFAULT_PADDING;
console.log(`[MagnifyGlass] Initial position - innerWidth: ${window.innerWidth}, glassSize: ${glassSize}, padding: ${DEFAULT_PADDING}, left: ${leftPos}, yOffset: ${DEFAULT_GLASS_Y_OFFSET}`);
this.magnifyGlass.ui.glassDiv.style.left = `${leftPos}px`;
this.magnifyGlass.ui.glassDiv.style.top = `${DEFAULT_GLASS_Y_OFFSET}px`;
this.magnifyGlass.state.wasActivatedBefore = true;
} else {
this.magnifyGlass.ui.positionGlass(clientX, clientY);
}
this.magnifyGlass.updateMagnifiedView();
}
}
}
+80
View File
@@ -0,0 +1,80 @@
/**
* ComfyUI MagnifyGlass - MagnifierState (TypeScript)
*
* Manages the state of the magnifying glass.
*/
/**
* Magnifier state class.
* Tracks activation state, cursor position, and canvas transforms.
*/
export class MagnifierState {
/** Whether the magnifier is currently active */
active: boolean;
/** Track if the glass has been activated before */
wasActivatedBefore: boolean;
/** Cursor X relative to litegraphCanvas */
x: number;
/** Cursor Y relative to litegraphCanvas */
y: number;
/** Calculated source area X */
sourceX: number;
/** Calculated source area Y */
sourceY: number;
/** Calculated source area width */
sourceWidth: number;
/** Calculated source area height */
sourceHeight: number;
/** Current canvas scale/zoom */
canvasScale: number;
/** Canvas translation X */
canvasOffsetX: number;
/** Canvas translation Y */
canvasOffsetY: number;
/** Flag to manage requestAnimationFrame */
isRenderScheduled: boolean;
constructor() {
this.active = false;
this.wasActivatedBefore = false;
this.x = 0;
this.y = 0;
this.sourceX = 0;
this.sourceY = 0;
this.sourceWidth = 0;
this.sourceHeight = 0;
this.canvasScale = 1.0;
this.canvasOffsetX = 0;
this.canvasOffsetY = 0;
this.isRenderScheduled = false;
}
/**
* Reset state to initial values.
*/
reset(): void {
this.active = false;
this.wasActivatedBefore = false;
this.x = 0;
this.y = 0;
this.sourceX = 0;
this.sourceY = 0;
this.sourceWidth = 0;
this.sourceHeight = 0;
this.canvasScale = 1.0;
this.canvasOffsetX = 0;
this.canvasOffsetY = 0;
this.isRenderScheduled = false;
}
}
+427
View File
@@ -0,0 +1,427 @@
/**
* ComfyUI MagnifyGlass - Main Class (TypeScript)
*
* Orchestrates all components of the magnifying glass.
*/
import type { ComfyApp, ComfyNode } from '../types/comfyui';
import { findLiteGraphCanvas, rectsOverlap, Rectangle } from '../shared/utils';
import { DEFAULT_PADDING, DEFAULT_GLASS_Y_OFFSET } from '../shared/constants';
import { registerGlassSettings } from '../shared/settings';
import { ConfigManager } from './ConfigManager';
import { MagnifierState } from './MagnifierState';
import { UiManager } from './UiManager';
import { WebGLRenderer } from './WebGLRenderer';
import { DebugManager } from './DebugManager';
import { EventHandler } from './EventHandler';
// External ComfyUI globals
declare const app: ComfyApp;
declare const LiteGraph: unknown;
/**
* Main MagnifyGlass class.
* Orchestrates all components and provides the main API.
*/
export class MagnifyGlass {
config: ConfigManager;
state: MagnifierState;
ui: UiManager;
renderer: WebGLRenderer | null;
debugger: DebugManager;
eventHandler: EventHandler;
/** The LiteGraph canvas */
litegraphCanvas: HTMLCanvasElement | null;
/** Last known mouse position for better initial positioning */
lastKnownMousePosition: { x: number; y: number };
/** Whether we're currently over media (for info panel) */
isOverMedia: boolean;
/** Current media element under cursor */
currentMediaElement: HTMLImageElement | HTMLVideoElement | null;
constructor() {
this.config = new ConfigManager();
this.state = new MagnifierState();
this.ui = new UiManager(this.config, this.state, () => this.toggle());
this.renderer = null;
this.debugger = new DebugManager(this.config, this.state, this.ui);
this.eventHandler = new EventHandler(this);
// The LiteGraph canvas
this.litegraphCanvas = null;
// Last known mouse position for better initial positioning
this.lastKnownMousePosition = { x: 0, y: 0 };
// Media tracking
this.isOverMedia = false;
this.currentMediaElement = null;
}
/**
* Initialize the magnifying glass.
*/
init(): void {
if (typeof LiteGraph === 'undefined' || typeof app === 'undefined' || !app.canvas) {
this.debugger.log("LiteGraph or app not ready, retrying in 100ms.");
setTimeout(() => this.init(), 100);
return;
}
this.debugger.log("LiteGraph and app ready.");
// Load saved offsets first
this.config.loadSavedOffsets();
// Print detailed canvas information
this.debugger.printCanvasInfo();
// Create UI elements
this.ui.createElements();
// Setup WebGL renderer
this.renderer = new WebGLRenderer(this.config, this.state, this.ui);
if (!this.renderer.isValid()) {
this.ui.cleanup();
return;
}
// Find the LiteGraph canvas
this.litegraphCanvas = findLiteGraphCanvas();
this.debugger.log("LiteGraph canvas found:", this.litegraphCanvas);
if (!this.litegraphCanvas) {
this.debugger.error("Could not find LiteGraph canvas. Magnifier will not work.");
this.ui.cleanup();
return;
}
// Attach event handlers
this.eventHandler.attachListeners();
// Register settings with ComfyUI
registerGlassSettings(this);
this.debugger.log(`Initialized (WebGL) with Smart Input Detection. Press ${this.config.altRequired ? 'Alt+' : ''}${this.config.activationKey.toUpperCase()} to activate.`);
}
/**
* Toggle the magnifying glass active state.
*/
toggle(): void {
const state = this.state;
const config = this.config;
if (state.active) {
state.active = false;
this.ui.hide();
} else {
state.active = true;
this.ui.show();
// Update initial position if needed
if (this.eventHandler) {
this.eventHandler.updateInitialPosition();
}
}
}
/**
* Update the magnified view.
*/
updateMagnifiedView(): void {
if (!this.state.active || !this.renderer || !this.litegraphCanvas) {
return;
}
// Get canvas transformation info
this.updateCanvasTransformation();
// Calculate the source region
this.calculateSourceRegion();
// Schedule the rendering operation
if (!this.state.isRenderScheduled) {
this.state.isRenderScheduled = true;
requestAnimationFrame(() => {
if (!this.state.active || !this.renderer || !this.litegraphCanvas) {
this.state.isRenderScheduled = false;
return;
}
// Render the magnified view
this.renderer.render(this.litegraphCanvas);
// Update debug visualization
this.debugger.updateDebugView();
// Render HTML overlays
this.renderHtmlOverlays();
this.state.isRenderScheduled = false;
});
}
}
/**
* Update canvas transformation state.
*/
updateCanvasTransformation(): void {
this.state.canvasScale = 1.0;
this.state.canvasOffsetX = 0;
this.state.canvasOffsetY = 0;
if (app?.canvas) {
const ds = (app.canvas as any).ds;
if (ds) {
if (typeof ds.scale === 'number') {
this.state.canvasScale = ds.scale;
}
if (ds.offset) {
this.state.canvasOffsetX = ds.offset[0] || 0;
this.state.canvasOffsetY = ds.offset[1] || 0;
}
}
}
}
/**
* Calculate the source region for magnification.
*/
calculateSourceRegion(): void {
const cursorPixelX = this.state.x;
const cursorPixelY = this.state.y;
const canvasScale = this.state.canvasScale;
const canvasOffsetX = this.state.canvasOffsetX;
const canvasOffsetY = this.state.canvasOffsetY;
if (canvasScale === 0) return;
// Convert cursor canvas pixels to LiteGraph graph coordinates
const cursorGraphX = (cursorPixelX - canvasOffsetX) / canvasScale;
const cursorGraphY = (cursorPixelY - canvasOffsetY) / canvasScale;
// Apply manual offset
const targetGraphCenterX = cursorGraphX + this.config.offsetX;
const targetGraphCenterY = cursorGraphY + this.config.offsetY;
// Calculate source dimensions in graph units
const sourceGraphWidth = (this.config.glassSize / this.config.zoomFactor) / canvasScale;
const sourceGraphHeight = (this.config.glassSize / this.config.zoomFactor) / canvasScale;
// Calculate source top-left corner in graph coordinates
const sourceGraphX = targetGraphCenterX - (sourceGraphWidth / 2);
const sourceGraphY = targetGraphCenterY - (sourceGraphHeight / 2);
// Convert back to canvas pixel coordinates
this.state.sourceX = (sourceGraphX * canvasScale) + canvasOffsetX;
this.state.sourceY = (sourceGraphY * canvasScale) + canvasOffsetY;
this.state.sourceWidth = sourceGraphWidth * canvasScale;
this.state.sourceHeight = sourceGraphHeight * canvasScale;
}
/**
* Render HTML overlays for text and media in the magnified view.
*/
renderHtmlOverlays(): void {
const graph = (app as any).graph;
if (!this.state.active || !this.ui.htmlOverlayContainer || !graph || !this.litegraphCanvas) {
if (this.ui.htmlOverlayContainer) this.ui.htmlOverlayContainer.innerHTML = '';
return;
}
this.ui.htmlOverlayContainer.innerHTML = '';
const magnifyRect: Rectangle = {
x: this.state.sourceX,
y: this.state.sourceY,
width: this.state.sourceWidth,
height: this.state.sourceHeight
};
const nodes: ComfyNode[] = graph._nodes;
if (!nodes) return;
for (const node of nodes) {
const widgets = (node as any).widgets;
if (!widgets) continue;
for (const widget of widgets) {
let isTextElement = false;
let isVideoElement = false;
let isImageElement = false;
let elementToProcess: HTMLElement | null = null;
if (widget.element) {
const element = widget.element as HTMLElement;
if (widget.type === "text" || widget.type === "string" || element.tagName === 'TEXTAREA') {
isTextElement = true;
elementToProcess = element;
} else if (element.tagName === 'VIDEO') {
isVideoElement = true;
elementToProcess = element;
} else if (element.tagName === 'IMG') {
isImageElement = true;
elementToProcess = element;
} else {
const potentialVideo = element.querySelector('video');
if (potentialVideo) {
isVideoElement = true;
elementToProcess = potentialVideo;
} else {
const potentialImage = element.querySelector('img');
if (potentialImage) {
isImageElement = true;
elementToProcess = potentialImage;
}
}
}
}
if (elementToProcess && (isTextElement || isVideoElement || isImageElement)) {
const widgetRect = elementToProcess.getBoundingClientRect();
const canvasRect = this.litegraphCanvas!.getBoundingClientRect();
const canvasToViewportScaleX = canvasRect.width > 0 ? (this.litegraphCanvas!.width / canvasRect.width) : 1;
const canvasToViewportScaleY = canvasRect.height > 0 ? (this.litegraphCanvas!.height / canvasRect.height) : 1;
const widgetCanvasX = (widgetRect.left - canvasRect.left) * canvasToViewportScaleX;
const widgetCanvasY = (widgetRect.top - canvasRect.top) * canvasToViewportScaleY;
const widgetCanvasWidth = widgetRect.width * canvasToViewportScaleX;
const widgetCanvasHeight = widgetRect.height * canvasToViewportScaleY;
const widgetSourceRect: Rectangle = {
x: widgetCanvasX,
y: widgetCanvasY,
width: widgetCanvasWidth,
height: widgetCanvasHeight
};
if (rectsOverlap(magnifyRect, widgetSourceRect)) {
const clonedElement = elementToProcess.cloneNode(true) as HTMLElement;
clonedElement.style.position = 'absolute';
clonedElement.style.pointerEvents = 'none';
if (isTextElement) {
clonedElement.style.backgroundColor = elementToProcess.style.backgroundColor || '#222';
clonedElement.style.color = elementToProcess.style.color || '#DDD';
clonedElement.style.border = elementToProcess.style.border || '1px solid #555';
(clonedElement as HTMLInputElement).disabled = true;
} else if (isVideoElement) {
const video = clonedElement as HTMLVideoElement;
const originalVideo = elementToProcess as HTMLVideoElement;
video.src = originalVideo.src;
video.autoplay = originalVideo.autoplay;
video.loop = originalVideo.loop;
video.preload = originalVideo.preload;
video.crossOrigin = originalVideo.crossOrigin;
video.muted = true;
if (!originalVideo.paused) {
video.play().catch(e => console.warn("Magnify Glass: Cloned video play failed", e));
}
video.currentTime = originalVideo.currentTime;
} else if (isImageElement) {
const img = clonedElement as HTMLImageElement;
const originalImg = elementToProcess as HTMLImageElement;
img.src = originalImg.src;
img.alt = originalImg.alt;
}
const relativeX = widgetSourceRect.x - magnifyRect.x;
const relativeY = widgetSourceRect.y - magnifyRect.y;
const magnifiedX = relativeX * this.config.zoomFactor;
const magnifiedY = relativeY * this.config.zoomFactor;
clonedElement.style.left = `${magnifiedX}px`;
clonedElement.style.top = `${magnifiedY}px`;
clonedElement.style.width = `${widgetSourceRect.width}px`;
clonedElement.style.height = `${widgetSourceRect.height}px`;
clonedElement.style.transformOrigin = 'top left';
clonedElement.style.transform = `scale(${this.config.zoomFactor})`;
if (isTextElement && clonedElement.style.fontSize) {
const originalFontSize = parseFloat(window.getComputedStyle(elementToProcess).fontSize);
clonedElement.style.fontSize = `${originalFontSize}px`;
}
this.ui.htmlOverlayContainer!.appendChild(clonedElement);
}
}
}
}
}
/**
* Update config from current settings values.
*/
updateConfigFromSettings(): void {
this.config.loadSettings();
}
/**
* Apply UI changes based on current config.
*/
applyUiChanges(): void {
this.ui.applyStyles();
if (this.renderer?.gl) {
this.renderer.updateViewport();
}
}
/**
* Reset offsets and panel positions to defaults.
*/
resetOffsets(): void {
this.config.resetOffsets();
// Also disable follow cursor
this.config.followCursor = false;
if (this.state.active) {
this.updateMagnifiedView();
}
// Reset magnify glass position to top-right corner
if (this.ui.glassDiv) {
const glassSize = this.config.glassSize;
this.ui.glassDiv.style.left = `${window.innerWidth - glassSize - DEFAULT_PADDING}px`;
this.ui.glassDiv.style.top = `${DEFAULT_GLASS_Y_OFFSET}px`;
this.state.wasActivatedBefore = false;
}
// Reset inspector panel position if exists
const extensions = window.comfyUIMagnifyGlassExtensions;
if (extensions && extensions.length > 0) {
extensions.forEach((extension: any) => {
if (extension?.stateManager) {
extension.stateManager.state.isPanelPinned = false;
extension.stateManager.state.isPanelLocked = false;
extension.stateManager.state.isAutoPinned = false;
extension.stateManager.state.pinnedPosition = { x: 0, y: 0 };
extension.stateManager.state.lastPinnedPosition = null;
if (extension.positionManager) {
extension.positionManager.positionPanel();
}
if (extension.uiManager?.updateControlStates) {
extension.uiManager.updateControlStates();
}
}
});
}
this.debugger.log("Reset: Magnify glass and inspector panel positions restored to defaults");
}
/**
* Cleanup all resources.
*/
cleanup(): void {
this.eventHandler.detachListeners();
this.ui.cleanup();
}
}
+420
View File
@@ -0,0 +1,420 @@
/**
* ComfyUI MagnifyGlass - UiManager (TypeScript)
*
* Handles creation and management of DOM elements for the magnifying glass.
*/
import { Z_INDEX, DEFAULT_PADDING } from '../shared/constants';
import { Icons } from '../shared/icons';
import { Logger } from '../shared/logger';
import type { ConfigManager } from './ConfigManager';
import type { MagnifierState } from './MagnifierState';
/**
* UI Manager class.
* Manages all DOM elements for the magnifying glass.
*/
export class UiManager {
config: ConfigManager;
state: MagnifierState;
glassDiv: HTMLDivElement | null;
glassCanvas: HTMLCanvasElement | null;
debugCanvas: HTMLCanvasElement | null;
debugCtx: CanvasRenderingContext2D | null;
htmlOverlayContainer: HTMLDivElement | null;
onToggle: (() => void) | undefined;
constructor(config: ConfigManager, state: MagnifierState, onToggle?: () => void) {
this.config = config;
this.state = state;
this.glassDiv = null;
this.glassCanvas = null;
this.debugCanvas = null;
this.debugCtx = null;
this.htmlOverlayContainer = null;
this.onToggle = onToggle;
}
/**
* Create all DOM elements for the magnifying glass.
*/
createElements(): void {
// Create magnifying glass container
this.glassDiv = document.createElement("div");
this.glassDiv.id = "comfyui-magnify-glass";
this.glassDiv.style.cssText = `
position: absolute;
box-sizing: border-box;
width: ${this.config.glassSize}px;
height: ${this.config.glassSize}px;
border-radius: ${this.config.glassShape === "Circle" ? "50%" : "0px"};
border: ${this.config.borderEnabled ? `${this.config.borderWidth}px solid ${this.config.borderColor}` : 'none'};
overflow: hidden;
pointer-events: none;
z-index: ${Z_INDEX.GLASS};
display: none;
box-shadow: 0 5px 15px rgba(0,0,0,0.3);
background-color: rgba(255,255,255,0.1);
`;
// Create WebGL canvas for the magnifying glass
this.glassCanvas = document.createElement("canvas");
this.glassCanvas.width = this.config.glassSize;
this.glassCanvas.height = this.config.glassSize;
this.glassCanvas.id = "comfyui-magnify-canvas";
this.glassDiv.appendChild(this.glassCanvas);
// Create HTML overlay container
this.htmlOverlayContainer = document.createElement("div");
this.htmlOverlayContainer.id = "comfyui-magnify-html-overlay";
this.htmlOverlayContainer.style.cssText = `
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
overflow: hidden;
`;
this.glassDiv.appendChild(this.htmlOverlayContainer);
document.body.appendChild(this.glassDiv);
// Create debug canvas if debug mode is enabled
if (this.config.debugMode) {
this.createDebugCanvas();
}
// Inject menu button
this.injectMenuButton();
}
/**
* Create the debug canvas overlay.
*/
createDebugCanvas(): void {
this.debugCanvas = document.createElement("canvas");
this.debugCanvas.id = "comfyui-magnify-debug";
this.debugCanvas.width = 400;
this.debugCanvas.height = 350;
this.debugCanvas.style.cssText = `
position: fixed;
top: 10px;
right: 10px;
background: rgba(0,0,0,0.7);
border: 1px solid #fff;
z-index: ${Z_INDEX.DEBUG};
pointer-events: none;
color: white;
font-family: monospace;
display: none;
`;
document.body.appendChild(this.debugCanvas);
this.debugCtx = this.debugCanvas.getContext('2d');
}
/**
* Show the magnifying glass.
*/
show(): void {
if (this.glassDiv) {
this.glassDiv.style.display = 'block';
// We do NOT modify opacity here, allowing it to be controlled independently
}
if (this.config.debugMode && this.debugCanvas) {
this.debugCanvas.style.display = "block";
}
}
/**
* Set the visual visibility of the glass preview (opacity).
* This allows the tool to remain "Active" (tracking mouse) but invisible,
* so that the Inspector Panel can be used in "Inspector Only" mode.
*/
setPreviewVisibility(visible: boolean): void {
if (this.glassDiv) {
this.glassDiv.style.opacity = visible ? '1' : '0';
// Disable pointer events when hidden to be safe, though usually they are none anyway
// this.glassDiv.style.pointerEvents = visible ? 'none' : 'none';
}
}
/**
* Hide the magnifying glass.
*/
hide(): void {
if (this.glassDiv) {
this.glassDiv.style.display = 'none';
}
if (this.config.debugMode && this.debugCanvas) {
this.debugCanvas.style.display = "none";
}
// Clear HTML overlays when hiding
if (this.htmlOverlayContainer) {
this.htmlOverlayContainer.innerHTML = '';
}
}
/**
* Position the glass relative to cursor.
* @param clientX - Client X coordinate
* @param clientY - Client Y coordinate
*/
positionGlass(clientX: number, clientY: number): void {
if (!this.config.followCursor || !this.glassDiv) return;
const glassSize = this.config.glassSize;
const offsetAmount = DEFAULT_PADDING;
let newLeft: number;
let newTop: number;
switch (this.config.glassPosition) {
case "Top":
newLeft = clientX - (glassSize / 2);
newTop = clientY - glassSize - offsetAmount;
break;
case "Bottom":
newLeft = clientX - (glassSize / 2);
newTop = clientY + offsetAmount;
break;
case "Left":
newLeft = clientX - glassSize - offsetAmount;
newTop = clientY - (glassSize / 2);
break;
case "Right":
newLeft = clientX + offsetAmount;
newTop = clientY - (glassSize / 2);
break;
case "Top-Left":
newLeft = clientX - glassSize - offsetAmount;
newTop = clientY - glassSize - offsetAmount;
break;
case "Top-Right":
newLeft = clientX + offsetAmount;
newTop = clientY - glassSize - offsetAmount;
break;
case "Bottom-Left":
newLeft = clientX - glassSize - offsetAmount;
newTop = clientY + offsetAmount;
break;
case "Bottom-Right":
newLeft = clientX + offsetAmount;
newTop = clientY + offsetAmount;
break;
default:
newLeft = clientX - (glassSize / 2);
newTop = clientY + offsetAmount;
break;
}
this.glassDiv.style.left = `${newLeft}px`;
this.glassDiv.style.top = `${newTop}px`;
this.adjustForBoundaries(clientX, clientY);
}
/**
* Adjust glass position to stay within viewport boundaries.
* @param clientX - Client X coordinate
* @param clientY - Client Y coordinate
*/
adjustForBoundaries(clientX: number, clientY: number): void {
if (!this.glassDiv) return;
const glassRect = this.glassDiv.getBoundingClientRect();
// Check right boundary
if (glassRect.right > window.innerWidth) {
this.glassDiv.style.left = `${clientX - glassRect.width - DEFAULT_PADDING}px`;
}
// Check left boundary
const currentRectLeft = this.glassDiv.getBoundingClientRect();
if (currentRectLeft.left < 0) {
this.glassDiv.style.left = "10px";
}
// Check bottom boundary
if (glassRect.bottom > window.innerHeight) {
this.glassDiv.style.top = `${clientY - glassRect.height - DEFAULT_PADDING}px`;
}
// Check top boundary
const currentRectTop = this.glassDiv.getBoundingClientRect();
if (currentRectTop.top < 0) {
this.glassDiv.style.top = "10px";
}
}
/**
* Apply current config to UI elements.
*/
applyStyles(): void {
if (this.glassDiv) {
this.glassDiv.style.width = `${this.config.glassSize}px`;
this.glassDiv.style.height = `${this.config.glassSize}px`;
this.glassDiv.style.border = this.config.borderEnabled
? `${this.config.borderWidth}px solid ${this.config.borderColor}`
: 'none';
// Reset clip-path and set default border-radius
this.glassDiv.style.clipPath = 'none';
this.glassDiv.style.borderRadius = '0px';
switch (this.config.glassShape) {
case "Circle":
this.glassDiv.style.borderRadius = "50%";
break;
case "Square":
// borderRadius is already '0px'
break;
case "Rounded Square":
this.glassDiv.style.borderRadius = "20%";
break;
default:
this.glassDiv.style.borderRadius = "50%";
break;
}
}
if (this.glassCanvas) {
this.glassCanvas.width = this.config.glassSize;
this.glassCanvas.height = this.config.glassSize;
}
// Handle debug canvas show/hide
if (this.config.debugMode) {
if (!this.debugCanvas) this.createDebugCanvas();
if (this.state.active && this.debugCanvas) this.debugCanvas.style.display = "block";
} else {
if (this.debugCanvas) this.debugCanvas.style.display = "none";
}
}
/**
* Cleanup DOM elements.
*/
cleanup(): void {
if (this.glassDiv) this.glassDiv.remove();
if (this.debugCanvas) this.debugCanvas.remove();
// Remove menu button if needed (though hard to track references here without saving it)
const btn = document.querySelector('.magnify-toggle-btn');
if (btn) btn.remove();
}
/**
* Inject a quick toggle button into the ComfyUI menu.
*/
/**
* Inject a quick toggle button into the ComfyUI menu.
*/
injectMenuButton(): void {
// Stop after 30 seconds
const stopTime = Date.now() + 30000;
// Define check function
const attemptInjection = () => {
const buttons = Array.from(document.querySelectorAll('button'));
// Try to find an anchor button (Minimap or Links)
// Priority 1: Minimap
let anchorBtn = buttons.find(b => {
const title = (b.title || '').toLowerCase();
const aria = (b.getAttribute('aria-label') || '').toLowerCase();
const text = (b.textContent || '').toLowerCase();
return (title.includes('map') && !title.includes('open')) ||
(aria.includes('map') && !aria.includes('open')) ||
(text.includes('map'));
});
// Priority 2: Link Visibility
if (!anchorBtn) {
anchorBtn = buttons.find(b => {
const title = (b.title || '').toLowerCase();
const aria = (b.getAttribute('aria-label') || '').toLowerCase();
return title.includes('link') || aria.includes('link');
});
}
if (anchorBtn && anchorBtn.parentElement) {
// Determine success BEFORE creating elements to allow early return if duplicate
if (anchorBtn.parentElement.querySelector('.magnify-toggle-btn')) return true;
Logger.debug('Found menu anchor:', anchorBtn.title || anchorBtn.getAttribute('aria-label') || 'Unknown Button');
const btn = document.createElement('button');
// Copy all classes to match theme/library (e.g. p-button, comfy-btn, etc)
btn.className = anchorBtn.className + ' magnify-toggle-btn';
// Copy key styles that might define shape/size
const computed = window.getComputedStyle(anchorBtn);
btn.style.height = computed.height;
btn.style.minHeight = computed.minHeight;
// btn.style.width = computed.width; // Don't copy width, let it adapt
btn.title = "Toggle Magnify Glass";
btn.innerHTML = Icons.magnifyGlass;
// Ensure specific display props
btn.style.display = "inline-flex";
btn.style.alignItems = "center";
btn.style.justifyContent = "center";
btn.style.padding = "0 8px";
btn.style.cursor = "pointer";
btn.style.border = anchorBtn.style.border || computed.border;
btn.style.borderRadius = anchorBtn.style.borderRadius || computed.borderRadius;
// Use cssText if available for background/color specific overrides
if (!btn.style.background) btn.style.background = computed.background;
if (!btn.style.color) btn.style.color = computed.color;
// Add active state tracking
btn.addEventListener('click', () => {
if (this.onToggle) {
this.onToggle();
// Try to apply common active classes found in modern UI frameworks
btn.classList.toggle('active');
btn.classList.toggle('p-highlight'); // PrimeVue
btn.classList.toggle('selected');
}
});
// Insert logic:
const isMinimap = (anchorBtn.title || '').toLowerCase().includes('map') ||
(anchorBtn.getAttribute('aria-label') || '').toLowerCase().includes('map');
if (isMinimap) {
// Insert AFTER Minimap
if (anchorBtn.nextSibling) {
anchorBtn.parentElement.insertBefore(btn, anchorBtn.nextSibling);
} else {
anchorBtn.parentElement.appendChild(btn);
}
} else {
// It's likely links, Insert BEFORE
anchorBtn.parentElement.insertBefore(btn, anchorBtn);
}
Logger.debug('Menu toggle button injected successfully');
return true;
}
return false;
};
// Run immediately first
if (attemptInjection()) return;
// Then poll rapidly
const checkForMenu = setInterval(() => {
if (Date.now() > stopTime) {
console.warn("[MagnifyGlass] Menu injection timed out. Found buttons:",
Array.from(document.querySelectorAll('button')).map(b => b.title || b.getAttribute('aria-label') || b.textContent || b.className).slice(0, 5));
clearInterval(checkForMenu);
return;
}
if (attemptInjection()) {
clearInterval(checkForMenu);
}
}, 100);
}
}
+437
View File
@@ -0,0 +1,437 @@
/**
* ComfyUI MagnifyGlass - WebGLRenderer (TypeScript)
*
* Handles WebGL-based rendering of the magnified view.
*/
import type { ConfigManager } from './ConfigManager';
import type { MagnifierState } from './MagnifierState';
import type { UiManager } from './UiManager';
import { Logger } from '../shared/logger';
interface UniformLocations {
sourceTexture: WebGLUniformLocation | null;
textureOffset: WebGLUniformLocation | null;
textureRepeat: WebGLUniformLocation | null;
glassSize: WebGLUniformLocation | null;
}
interface AttributeLocations {
position: number;
texCoord: number;
}
/**
* WebGL Renderer class.
* Provides efficient WebGL-based magnification rendering.
*/
export class WebGLRenderer {
config: ConfigManager;
state: MagnifierState;
ui: UiManager;
gl: WebGLRenderingContext | null;
program: WebGLProgram | null;
texture: WebGLTexture | null;
positionBuffer: WebGLBuffer | null;
texCoordBuffer: WebGLBuffer | null;
uniformLocations: UniformLocations | null;
attributeLocations: AttributeLocations | null;
currentFilteringMode: number | null;
// Dirty flag optimization
lastCanvasVersion: number;
lastSourceX: number;
lastSourceY: number;
lastSourceWidth: number;
lastSourceHeight: number;
textureUploadSkipCount: number;
vertexShaderSource: string;
fragmentShaderSource: string;
constructor(config: ConfigManager, state: MagnifierState, ui: UiManager) {
this.config = config;
this.state = state;
this.ui = ui;
this.gl = null;
this.program = null;
this.texture = null;
this.positionBuffer = null;
this.texCoordBuffer = null;
this.uniformLocations = null;
this.attributeLocations = null;
this.currentFilteringMode = null;
// Initialize dirty flag tracking
this.lastCanvasVersion = -1;
this.lastSourceX = -1;
this.lastSourceY = -1;
this.lastSourceWidth = -1;
this.lastSourceHeight = -1;
this.textureUploadSkipCount = 0;
this.vertexShaderSource = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;
void main() {
gl_Position = vec4(a_position, 0.0, 1.0);
v_texCoord = a_texCoord;
}
`;
this.fragmentShaderSource = `
precision mediump float;
varying vec2 v_texCoord;
uniform sampler2D u_sourceTexture;
uniform vec2 u_textureOffset;
uniform vec2 u_textureRepeat;
uniform float u_glassSize;
void main() {
vec2 sampleCoord = u_textureOffset + v_texCoord * u_textureRepeat;
vec4 color = texture2D(u_sourceTexture, sampleCoord);
gl_FragColor = color;
}
`;
this.initialize();
}
/**
* Initialize WebGL context and resources.
*/
initialize(): void {
// Get WebGL context
if (!this.ui.glassCanvas) return;
this.gl = this.ui.glassCanvas.getContext("webgl", { preserveDrawingBuffer: true });
if (!this.gl) {
// Try webgl2 as fallback
this.gl = this.ui.glassCanvas.getContext("webgl2", { preserveDrawingBuffer: true }) as WebGLRenderingContext | null;
}
if (!this.gl) {
const isFirefox = navigator.userAgent.toLowerCase().includes('firefox');
const browserInstructions = isFirefox
? "Firefox: Go to about:config, search for 'webgl.disabled' and set it to 'false', then restart Firefox."
: "Check your browser settings to ensure WebGL is enabled.";
console.error("ComfyUI Magnifying Glass ERROR: WebGL not supported or context creation failed.");
console.error(`To fix: ${browserInstructions}`);
// Show user notification
this.showWebGLError(browserInstructions);
return;
}
// Create shader program
this.program = this.createShaderProgram(this.gl, this.vertexShaderSource, this.fragmentShaderSource);
if (!this.program) return;
// Create position buffer
this.positionBuffer = this.gl.createBuffer();
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.positionBuffer);
const positions = [-1, -1, 1, -1, -1, 1, 1, 1];
this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(positions), this.gl.STATIC_DRAW);
// Create texture coordinate buffer
this.texCoordBuffer = this.gl.createBuffer();
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.texCoordBuffer);
const texCoords = [0, 1, 1, 1, 0, 0, 1, 0]; // Flipped Y for texCoords
this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(texCoords), this.gl.STATIC_DRAW);
// Create texture
this.texture = this.gl.createTexture();
this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);
this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR);
this.updateTextureFiltering(this.config.textureFiltering);
// Get uniform and attribute locations
this.uniformLocations = {
sourceTexture: this.gl.getUniformLocation(this.program, "u_sourceTexture"),
textureOffset: this.gl.getUniformLocation(this.program, "u_textureOffset"),
textureRepeat: this.gl.getUniformLocation(this.program, "u_textureRepeat"),
glassSize: this.gl.getUniformLocation(this.program, "u_glassSize"),
};
this.attributeLocations = {
position: this.gl.getAttribLocation(this.program, "a_position"),
texCoord: this.gl.getAttribLocation(this.program, "a_texCoord"),
};
}
/**
* Update texture filtering mode.
* @param filteringModeString - "Linear" or "Nearest"
*/
updateTextureFiltering(filteringModeString: string): void {
if (!this.gl || !this.texture) return;
let glFilterMode: number;
if (filteringModeString === "Nearest") {
glFilterMode = this.gl.NEAREST;
} else {
glFilterMode = this.gl.LINEAR;
}
if (this.currentFilteringMode === glFilterMode) return;
this.currentFilteringMode = glFilterMode;
this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, glFilterMode);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, glFilterMode);
this.gl.bindTexture(this.gl.TEXTURE_2D, null);
}
/**
* Check if renderer is valid and ready.
* @returns Boolean indicating if WebGL context and program are ready
*/
isValid(): boolean {
return this.gl !== null && this.program !== null;
}
/**
* Create a WebGL shader program.
* @param gl - WebGL context
* @param vsSource - Vertex shader source
* @param fsSource - Fragment shader source
* @returns WebGL program or null on failure
*/
createShaderProgram(gl: WebGLRenderingContext, vsSource: string, fsSource: string): WebGLProgram | null {
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
if (!vertexShader) return null;
gl.shaderSource(vertexShader, vsSource);
gl.compileShader(vertexShader);
if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
console.error('ComfyUI Magnifying Glass ERROR: Vertex shader compilation error:', gl.getShaderInfoLog(vertexShader));
gl.deleteShader(vertexShader);
return null;
}
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
if (!fragmentShader) {
gl.deleteShader(vertexShader);
return null;
}
gl.shaderSource(fragmentShader, fsSource);
gl.compileShader(fragmentShader);
if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
console.error('ComfyUI Magnifying Glass ERROR: Fragment shader compilation error:', gl.getShaderInfoLog(fragmentShader));
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
return null;
}
const program = gl.createProgram();
if (!program) {
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
return null;
}
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
console.error('ComfyUI Magnifying Glass ERROR: Shader program linking error:', gl.getProgramInfoLog(program));
gl.deleteProgram(program);
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
return null;
}
return program;
}
/**
* Render the magnified view.
* @param sourceCanvas - The source canvas to sample from
*/
render(sourceCanvas: HTMLCanvasElement): void {
if (!this.gl || !this.program || !this.texture || !this.uniformLocations || !this.attributeLocations) return;
// Check if we need to update the texture
// We track: canvas version (via LiteGraph's change counter), source coordinates, and source dimensions
const app = (window as any).app;
const currentCanvasVersion = app?.graph?.change_counter ?? -1;
const sourceChanged =
this.lastSourceX !== this.state.sourceX ||
this.lastSourceY !== this.state.sourceY ||
this.lastSourceWidth !== this.state.sourceWidth ||
this.lastSourceHeight !== this.state.sourceHeight;
const canvasChanged = currentCanvasVersion !== this.lastCanvasVersion;
// Only upload texture if something changed
const needsTextureUpdate = canvasChanged || sourceChanged || this.lastCanvasVersion === -1;
// Bind texture
this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);
if (needsTextureUpdate) {
try {
this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, sourceCanvas);
// Update tracking variables
this.lastCanvasVersion = currentCanvasVersion;
this.lastSourceX = this.state.sourceX;
this.lastSourceY = this.state.sourceY;
this.lastSourceWidth = this.state.sourceWidth;
this.lastSourceHeight = this.state.sourceHeight;
// Reset skip counter and log if debug mode
if (this.config.debugMode && this.textureUploadSkipCount > 0) {
Logger.debug(`Texture uploaded after skipping ${this.textureUploadSkipCount} frames`);
}
this.textureUploadSkipCount = 0;
} catch (e) {
console.error("ComfyUI Magnifying Glass ERROR: Error in texImage2D:", e);
return;
}
} else {
// Skip texture upload - just increment counter
this.textureUploadSkipCount++;
// Periodic debug logging
if (this.config.debugMode && this.textureUploadSkipCount % 60 === 0) {
Logger.debug(`Texture upload skipped (${this.textureUploadSkipCount} frames cached)`);
}
}
// Calculate normalized texture coordinates (UV space: 0-1)
const uvX = this.state.sourceX / sourceCanvas.width;
const uvY = this.state.sourceY / sourceCanvas.height;
const uvWidth = this.state.sourceWidth / sourceCanvas.width;
const uvHeight = this.state.sourceHeight / sourceCanvas.height;
// Set up rendering
this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);
this.gl.clearColor(0.0, 0.0, 0.0, 0.0);
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
this.gl.useProgram(this.program);
// Set uniforms
this.gl.activeTexture(this.gl.TEXTURE0);
this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);
this.gl.uniform1i(this.uniformLocations.sourceTexture, 0);
this.gl.uniform2f(this.uniformLocations.textureOffset, uvX, uvY);
this.gl.uniform2f(this.uniformLocations.textureRepeat, uvWidth, uvHeight);
this.gl.uniform1f(this.uniformLocations.glassSize, this.config.glassSize);
// Set attributes
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.positionBuffer);
this.gl.vertexAttribPointer(this.attributeLocations.position, 2, this.gl.FLOAT, false, 0, 0);
this.gl.enableVertexAttribArray(this.attributeLocations.position);
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.texCoordBuffer);
this.gl.vertexAttribPointer(this.attributeLocations.texCoord, 2, this.gl.FLOAT, false, 0, 0);
this.gl.enableVertexAttribArray(this.attributeLocations.texCoord);
// Draw
this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4);
}
/**
* Check for WebGL errors.
* @param label - Debug label
* @returns True if error occurred
*/
checkWebGLError(label: string): boolean {
if (!this.gl) return false;
const err = this.gl.getError();
if (err !== this.gl.NO_ERROR) {
console.error(`ComfyUI Magnifying Glass ERROR: WebGL Error (${label}):`, err);
return true;
}
return false;
}
/**
* Update viewport when glass size changes.
*/
updateViewport(): void {
if (this.gl) {
this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);
}
}
/**
* Show WebGL error notification to user.
* @param instructions - Browser-specific instructions to fix
*/
showWebGLError(instructions: string): void {
// Create a toast notification
const toast = document.createElement('div');
toast.id = 'magnifyglass-webgl-error';
toast.style.cssText = `
position: fixed;
bottom: 20px;
right: 20px;
max-width: 400px;
padding: 16px 20px;
background: linear-gradient(135deg, #ff4444 0%, #cc3333 100%);
color: white;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
font-family: system-ui, -apple-system, sans-serif;
font-size: 14px;
line-height: 1.5;
z-index: 100000;
animation: slideIn 0.3s ease-out;
`;
toast.innerHTML = `
<div style="display: flex; align-items: flex-start; gap: 12px;">
<span style="font-size: 24px;">⚠️</span>
<div>
<strong style="display: block; margin-bottom: 6px;">MagnifyGlass: WebGL Disabled</strong>
<span style="opacity: 0.9;">${instructions}</span>
<button onclick="this.parentElement.parentElement.parentElement.remove()"
style="display: block; margin-top: 10px; padding: 6px 12px; background: rgba(255,255,255,0.2);
border: 1px solid rgba(255,255,255,0.3); border-radius: 4px; color: white;
cursor: pointer; font-size: 12px;">
Dismiss
</button>
</div>
</div>
`;
// Add animation keyframes
if (!document.getElementById('magnifyglass-toast-style')) {
const style = document.createElement('style');
style.id = 'magnifyglass-toast-style';
style.textContent = `
@keyframes slideIn {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
`;
document.head.appendChild(style);
}
document.body.appendChild(toast);
// Auto-dismiss after 15 seconds
setTimeout(() => {
if (toast.parentElement) {
toast.style.animation = 'slideIn 0.3s ease-out reverse';
setTimeout(() => toast.remove(), 300);
}
}, 15000);
}
}
+13
View File
@@ -0,0 +1,13 @@
/**
* ComfyUI MagnifyGlass - Module Index (TypeScript)
*
* Re-exports all magnify-glass components.
*/
export { MagnifyGlass } from './MagnifyGlass';
export { MagnifierState } from './MagnifierState';
export { ConfigManager } from './ConfigManager';
export { UiManager } from './UiManager';
export { WebGLRenderer } from './WebGLRenderer';
export { DebugManager } from './DebugManager';
export { EventHandler } from './EventHandler';
+32
View File
@@ -0,0 +1,32 @@
/**
* ComfyUI Magnify Glass - Main Entry Point
*
* Initializes the Magnify Glass extension.
*/
import { MagnifyGlass } from './magnify-glass';
import { Logger } from './shared/logger';
import { initSidebar } from './sidebar';
// @ts-ignore
import { app } from "/scripts/app.js";
// Global declaration handled in comfyui.d.ts
// We rely on the global 'app' object provided by ComfyUI
// Register extension
app.registerExtension({
name: "comfyui.magnify.glass",
init() {
// Initialize the magnify glass
const magnifyGlass = new MagnifyGlass();
magnifyGlass.init();
// Expose to window for other extensions (like info panel) to access
window.comfyUIMagnifyGlass = magnifyGlass;
// Initialize sidebar
initSidebar();
Logger.info('Magnify Glass extension initialized');
}
});
+53
View File
@@ -0,0 +1,53 @@
/**
* ComfyUI Magnify Info Panel - Main Entry Point
*
* Initializes the Info Panel extension.
*/
import { InfoPanel } from './info-panel';
import { Logger } from './shared/logger';
// @ts-ignore
import { app } from "/scripts/app.js";
// We rely on the global 'app' object provided by ComfyUI
// No need to import it as it's global, but TypeScript needs to know about it.
// We handled this in types/comfyui.d.ts
app.registerExtension({
name: "comfyui.magnify.info.panel",
init() {
// Wait for magnify glass to be available
const checkDependencies = () => {
if (window.comfyUIMagnifyGlass) {
initializeInfoPanel();
} else {
setTimeout(checkDependencies, 100);
}
};
checkDependencies();
}
});
function initializeInfoPanel() {
const magnifyGlass = window.comfyUIMagnifyGlass;
if (!magnifyGlass) {
Logger.error('Failed to find MagnifyGlass instance.');
return;
}
try {
// Initialize the info panel
const infoPanel = new InfoPanel(magnifyGlass);
// Expose orchestrator globally if needed
window.infoPanelManager = infoPanel as any;
// CSS is loaded by UIManager.injectStyles() - no need to load separately
Logger.info('Info Panel extension initialized');
} catch (e) {
Logger.error('Error during initialization:', e);
}
}
+86
View File
@@ -0,0 +1,86 @@
/**
* ComfyUI MagnifyGlass - Shared Constants
*
* Configuration constants shared between magnify glass and info panel modules.
*/
// Glass positioning options
export const GLASS_POSITIONS = [
"Top",
"Bottom",
"Left",
"Right",
"Top-Left",
"Top-Right",
"Bottom-Left",
"Bottom-Right"
] as const;
export type GlassPosition = typeof GLASS_POSITIONS[number];
// Glass shape options
export const GLASS_SHAPES = [
"Circle",
"Square",
"Rounded Square"
] as const;
export type GlassShape = typeof GLASS_SHAPES[number];
// Texture filtering modes
export const TEXTURE_FILTERS = [
"Linear",
"Nearest"
] as const;
export type TextureFilter = typeof TEXTURE_FILTERS[number];
// Info panel positions relative to glass
export const PANEL_POSITIONS = [
"Top",
"Bottom",
"Left",
"Right"
] as const;
export type PanelPosition = typeof PANEL_POSITIONS[number];
// Available keys for settings
export const ACTIVATION_KEYS = ["x", "z", "m", "q", "v", "c"] as const;
export const RESET_KEYS = ["r", "o", "p", "k", "l"] as const;
export const TOGGLE_FOLLOW_KEYS = ["f", "g", "h", "j", "k"] as const;
// UI Constants
export const DEFAULT_PADDING = 4;
export const DEFAULT_GLASS_Y_OFFSET = 110; // Starting Y position offset (below top bar with 3px gap)
export const DEFAULT_GLASS_SIZE = 300;
export const DEFAULT_ZOOM_FACTOR = 300; // 3x as percentage
export const DEFAULT_BORDER_WIDTH = 1;
export const DEFAULT_BORDER_COLOR = "#6b7280";
export const DEFAULT_OFFSET_STEP = 5;
// Panel Constants
export const DEFAULT_PANEL_WIDTH = 300;
export const DEFAULT_PANEL_MAX_HEIGHT = 300;
export const DEFAULT_PANEL_OPACITY = 100;
// Z-Index hierarchy
export const Z_INDEX = {
GLASS: 98999,
DEBUG: 99000,
PANEL: 99999,
CONTROLS: 99998
} as const;
// Animation durations (ms)
export const ANIMATION = {
PANEL_TRANSITION: 300,
AUTO_COLLAPSE_DELAY: 1500,
THEME_DETECTION_INTERVAL: 2000
} as const;
// LocalStorage keys
export const STORAGE_KEYS = {
OFFSET_X: 'comfyui_magnify_offset_x',
OFFSET_Y: 'comfyui_magnify_offset_y'
} as const;
+89
View File
@@ -0,0 +1,89 @@
/**
* ComfyUI MagnifyGlass - SVG Icons
*
* Inline SVG icons to replace emoji icons for a more professional look.
* All icons are designed to be 16x16 or scalable.
*/
export const Icons = {
// Magnify glass icon - used for header and glass toggle
magnifyGlass: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8"/>
<line x1="21" y1="21" x2="16.65" y2="16.65"/>
</svg>`,
// Unlock icon - panel is floating/following cursor
unlock: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
<path d="M7 11V7a5 5 0 0 1 9.9-1"/>
</svg>`,
// Lock icon - panel is pinned
lock: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
<path d="M7 11V7a5 5 0 0 1 10 0v4"/>
</svg>`,
// Pin icon - lock panel position
pin: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="17" x2="12" y2="22"/>
<path d="M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z"/>
</svg>`,
// Eye icon - toggle visibility
eye: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
<circle cx="12" cy="12" r="3"/>
</svg>`,
// Camera/image icon - media section
camera: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
<circle cx="12" cy="13" r="4"/>
</svg>`,
// Target/crosshair icon - node section
target: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"/>
<circle cx="12" cy="12" r="6"/>
<circle cx="12" cy="12" r="2"/>
</svg>`,
// Location/map pin icon - empty state
mapPin: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
<circle cx="12" cy="10" r="3"/>
</svg>`,
// Chevron right - expand icon
chevronRight: `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="9 18 15 12 9 6"/>
</svg>`,
// Minus icon - minimize button
minus: `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="5" y1="12" x2="19" y2="12"/>
</svg>`,
// Inspector/info icon
info: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"/>
<line x1="12" y1="16" x2="12" y2="12"/>
<line x1="12" y1="8" x2="12.01" y2="8"/>
</svg>`,
// Box/node icon
box: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
<polyline points="3.27 6.96 12 12.01 20.73 6.96"/>
<line x1="12" y1="22.08" x2="12" y2="12"/>
</svg>`
};
/**
* Get an icon wrapped in a span for proper sizing
*/
export function getIcon(name: keyof typeof Icons, className: string = ''): string {
const icon = Icons[name] || '';
return `<span class="icon ${className}">${icon}</span>`;
}
+3
View File
@@ -0,0 +1,3 @@
export * from './constants';
export * from './utils';
export * from './settings';
+87
View File
@@ -0,0 +1,87 @@
/**
* ComfyUI MagnifyGlass - Logger Utility
*
* Conditional debug logging with environment awareness.
* Debug logs are only shown when:
* - localStorage.getItem('magnifyGlass.debug') === 'true'
* - OR window.magnifyGlassDebug === true
*/
const PREFIX = '[MagnifyGlass]';
/**
* Check if debug mode is enabled.
*/
function isDebugEnabled(): boolean {
try {
return (
localStorage.getItem('magnifyGlass.debug') === 'true' ||
(window as unknown as { magnifyGlassDebug?: boolean }).magnifyGlassDebug === true
);
} catch {
return false;
}
}
/**
* Logger utility with conditional debug output.
*/
export const Logger = {
/**
* Debug log - only shown when debug mode is enabled.
* Use for verbose development logging.
*/
debug: (...args: unknown[]): void => {
if (isDebugEnabled()) {
console.log(PREFIX, ...args);
}
},
/**
* Info log - always shown.
* Use for important initialization messages.
*/
info: (...args: unknown[]): void => {
console.log(PREFIX, ...args);
},
/**
* Warning log - always shown.
* Use for non-critical issues.
*/
warn: (...args: unknown[]): void => {
console.warn(PREFIX, ...args);
},
/**
* Error log - always shown.
* Use for critical errors.
*/
error: (...args: unknown[]): void => {
console.error(PREFIX, ...args);
}
};
/**
* Enable debug mode programmatically.
*/
export function enableDebug(): void {
try {
localStorage.setItem('magnifyGlass.debug', 'true');
console.log(PREFIX, 'Debug mode enabled');
} catch {
(window as unknown as { magnifyGlassDebug?: boolean }).magnifyGlassDebug = true;
}
}
/**
* Disable debug mode.
*/
export function disableDebug(): void {
try {
localStorage.removeItem('magnifyGlass.debug');
console.log(PREFIX, 'Debug mode disabled');
} catch {
(window as unknown as { magnifyGlassDebug?: boolean }).magnifyGlassDebug = false;
}
}
+162
View File
@@ -0,0 +1,162 @@
/**
* ComfyUI MagnifyGlass - Settings Configuration
*
* Centralized settings definitions and registration functions.
*
* This file re-exports from the modular settings directory for backwards compatibility.
*/
// Re-export everything from the settings module
export type { GlassSettings, PanelSettings, AllSettings } from './settings/types';
export { DEFAULT_GLASS_SETTINGS, DEFAULT_PANEL_SETTINGS } from './settings/defaults';
export { registerGlassSettings } from './settings/glassSettings';
export { registerPanelSettings } from './settings/panelSettings';
// Legacy getSettingConfig function for backwards compatibility
// @ts-ignore
import { app } from "/scripts/app.js";
import { PANEL_POSITIONS } from './constants';
import { DEFAULT_PANEL_SETTINGS } from './settings/defaults';
/**
* Get a setting configuration object for ComfyUI settings registration.
* This function generates the setting config based on the key and default value.
*
* @param key - The setting key
* @param defaultValue - The default value for the setting
* @returns The setting configuration or null if not found
*/
export function getSettingConfig(key: string, defaultValue: any): any {
const configs: Record<string, any> = {
"🔍MagnifyGlass.InfoPanelEnabled": {
id: key,
name: "📋 Magnify Glass: Info Panel",
type: "combo",
options: [
{ value: true, text: "Enabled" },
{ value: false, text: "Disabled" }
],
defaultValue,
tooltip: "Enable or disable the professional information panel."
},
"🔍MagnifyGlass.InfoPanelPosition": {
id: key,
name: "📋 Info Panel: Position",
type: "combo",
options: PANEL_POSITIONS.map(pos => ({ value: pos, text: pos })),
defaultValue,
tooltip: "Position of the info panel relative to the magnify glass."
},
"🔍MagnifyGlass.InfoPanelWidth": {
id: key,
name: "📋 Info Panel: Width (px)",
type: "slider",
defaultValue,
min: 200,
max: 600,
step: 20,
tooltip: "Width of the info panel in pixels."
},
"🔍MagnifyGlass.InfoPanelMaxHeight": {
id: key,
name: "📋 Info Panel: Max Height (px)",
type: "slider",
defaultValue,
min: 200,
max: 1500,
step: 50,
tooltip: "Maximum height of the info panel."
},
"🔍MagnifyGlass.InfoPanelOpacity": {
id: key,
name: "📋 Info Panel: Opacity (%)",
type: "slider",
defaultValue,
min: 10,
max: 100,
step: 5,
tooltip: "Opacity of the info panel background."
},
"🔍MagnifyGlass.InfoPanelAnimations": {
id: key,
name: "📋 Info Panel: Animations",
type: "combo",
options: [
{ value: true, text: "Enabled" },
{ value: false, text: "Disabled" }
],
defaultValue,
tooltip: "Enable smooth animations for the info panel."
},
"🔍MagnifyGlass.ShowInspectorTab": {
id: key,
name: "📋 Info Panel: Show Inspector",
type: "combo",
options: [
{ value: true, text: "Yes" },
{ value: false, text: "No" }
],
defaultValue,
tooltip: "Show the inspector tab with cursor and canvas information."
},
"🔍MagnifyGlass.ToggleHotkey": {
id: key,
name: "📋 Info Panel: Toggle Hotkey",
type: "combo",
options: ["i", "j", "k", "l", "n", "m"].map(k => ({ value: k, text: k.toUpperCase() })),
defaultValue,
tooltip: "Key to toggle the info panel visibility."
},
"🔍MagnifyGlass.GlassPreviewToggleHotkey": {
id: key,
name: "📋 Info Panel: Glass Toggle Hotkey",
type: "combo",
options: ["g", "f", "v", "b"].map(k => ({ value: k, text: k.toUpperCase() })),
defaultValue,
tooltip: "Key to toggle the magnify glass preview visibility."
},
"🔍MagnifyGlass.PinPanelHotkey": {
id: key,
name: "📋 Info Panel: Pin Hotkey",
type: "combo",
options: ["u", "p", "y", "t"].map(k => ({ value: k, text: k.toUpperCase() })),
defaultValue,
tooltip: "Key to pin/unlock the info panel at the current mouse location."
},
"🔍MagnifyGlass.ShowHoveringControls": {
id: key,
name: "📋 Info Panel: Floating Controls",
type: "combo",
options: [
{ value: true, text: "Show" },
{ value: false, text: "Hide" }
],
defaultValue,
tooltip: "Show floating control buttons near the info panel."
},
"🔍MagnifyGlass.ControlsPosition": {
id: key,
name: "📋 Info Panel: Controls Position",
type: "combo",
options: ["top-left", "top-right", "bottom-left", "bottom-right", "top", "bottom", "left", "right"].map(p => ({ value: p, text: p })),
defaultValue,
tooltip: "Position of the floating control buttons."
},
"🔍MagnifyGlass.InfoPanelTextColor": {
id: key,
name: "🎨 Info Panel: Text Color",
type: "color",
defaultValue,
tooltip: "Color for text in the info panel."
},
"🔍MagnifyGlass.InfoPanelAccentColor": {
id: key,
name: "🎨 Info Panel: Accent Color",
type: "color",
defaultValue,
tooltip: "Accent color for highlights in the info panel."
}
};
return configs[key] || null;
}
+59
View File
@@ -0,0 +1,59 @@
/**
* ComfyUI MagnifyGlass - Default Settings Values
*
* Default values for all magnify glass and info panel settings.
*/
import {
DEFAULT_GLASS_SIZE,
DEFAULT_ZOOM_FACTOR,
DEFAULT_BORDER_WIDTH,
DEFAULT_BORDER_COLOR,
DEFAULT_OFFSET_STEP,
DEFAULT_PANEL_WIDTH,
DEFAULT_PANEL_MAX_HEIGHT,
DEFAULT_PANEL_OPACITY
} from '../constants';
import type { GlassSettings, PanelSettings } from './types';
/**
* Default settings for the magnify glass component.
*/
export const DEFAULT_GLASS_SETTINGS: GlassSettings = {
"🔍MagnifyGlass.ZoomFactor": DEFAULT_ZOOM_FACTOR,
"🔍MagnifyGlass.GlassSize": DEFAULT_GLASS_SIZE,
"🔍MagnifyGlass.BorderColor": DEFAULT_BORDER_COLOR,
"🔍MagnifyGlass.BorderWidth": DEFAULT_BORDER_WIDTH,
"🔍MagnifyGlass.ActivationKey": "x",
"🔍MagnifyGlass.AltRequired": false,
"🔍MagnifyGlass.FollowCursor": false,
"🔍MagnifyGlass.DebugMode": false,
"🔍MagnifyGlass.OffsetStep": DEFAULT_OFFSET_STEP,
"🔍MagnifyGlass.GlassPosition": "Top-Right",
"🔍MagnifyGlass.ResetKey": "o",
"🔍MagnifyGlass.GlassShape": "Rounded Square",
"🔍MagnifyGlass.BorderEnabled": true,
"🔍MagnifyGlass.TextureFiltering": "Linear",
"🔍MagnifyGlass.AlwaysActiveMode": true,
"🔍MagnifyGlass.ToggleFollowCursorKey": "h",
};
/**
* Default settings for the info panel component.
*/
export const DEFAULT_PANEL_SETTINGS: PanelSettings = {
"🔍MagnifyGlass.InfoPanelEnabled": true,
"🔍MagnifyGlass.InfoPanelPosition": "Bottom",
"🔍MagnifyGlass.InfoPanelWidth": DEFAULT_PANEL_WIDTH,
"🔍MagnifyGlass.InfoPanelOpacity": DEFAULT_PANEL_OPACITY,
"🔍MagnifyGlass.InfoPanelMaxHeight": DEFAULT_PANEL_MAX_HEIGHT,
"🔍MagnifyGlass.InfoPanelAnimations": false,
"🔍MagnifyGlass.ShowInspectorTab": false,
"🔍MagnifyGlass.ToggleHotkey": "i",
"🔍MagnifyGlass.GlassPreviewToggleHotkey": "g",
"🔍MagnifyGlass.PinPanelHotkey": "u",
"🔍MagnifyGlass.ShowHoveringControls": true,
"🔍MagnifyGlass.ControlsPosition": "left",
"🔍MagnifyGlass.InfoPanelTextColor": "#6b7280",
"🔍MagnifyGlass.InfoPanelAccentColor": "#3b82f6",
};
+365
View File
@@ -0,0 +1,365 @@
/**
* ComfyUI MagnifyGlass - Glass Settings Registration
*
* Registers all magnify glass settings with ComfyUI.
*/
// @ts-ignore
import { app } from "/scripts/app.js";
import {
GLASS_POSITIONS,
GLASS_SHAPES,
ACTIVATION_KEYS,
RESET_KEYS,
TOGGLE_FOLLOW_KEYS
} from '../constants';
import { DEFAULT_GLASS_SETTINGS } from './defaults';
/**
* Register all magnify glass settings with ComfyUI.
* @param magnifyGlass - The MagnifyGlass instance
*/
export function registerGlassSettings(magnifyGlass: any): void {
const settings = DEFAULT_GLASS_SETTINGS;
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.ZoomFactor",
name: "🔍 Magnify Glass: Zoom Factor (%)",
type: "slider",
defaultValue: settings["🔍MagnifyGlass.ZoomFactor"],
min: 100,
max: 1000,
step: 25,
tooltip: "Magnification level as a percentage (e.g., 300 = 3x zoom, 150 = 1.5x zoom).",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.zoomFactor = typeof value === 'number' ? value / 100 : parseFloat(value) / 100;
if (magnifyGlass.state.active) {
magnifyGlass.updateMagnifiedView();
}
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.GlassSize",
name: "🔍 Magnify Glass: Size (px)",
type: "slider",
defaultValue: settings["🔍MagnifyGlass.GlassSize"],
min: 50,
max: 100,
step: 10,
tooltip: "Diameter of the magnifying glass circle in pixels.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.glassSize = parseInt(String(value), 10);
magnifyGlass.applyUiChanges();
if (magnifyGlass.state.active) {
magnifyGlass.updateMagnifiedView();
}
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.BorderWidth",
name: "🔍 Magnify Glass: Border Width (px)",
type: "slider",
defaultValue: settings["🔍MagnifyGlass.BorderWidth"],
min: 0,
max: 10,
step: 0.1,
tooltip: "Width of the border around the magnifying glass.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.borderWidth = parseFloat(String(value));
magnifyGlass.applyUiChanges();
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.BorderColor",
name: "🎨 Magnify Glass: Border Color",
type: "color",
defaultValue: settings["🔍MagnifyGlass.BorderColor"],
tooltip: "Color of the border around the magnifying glass.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
const strValue = String(value);
const normalizedColor = strValue && !strValue.startsWith('#') ? `#${strValue}` : strValue;
magnifyGlass.config.borderColor = normalizedColor;
if (strValue !== normalizedColor) {
try {
app.ui.settings.setSettingValue("🔍MagnifyGlass.BorderColor", normalizedColor);
} catch (e) {
console.warn('Failed to save normalized border color:', e);
}
}
magnifyGlass.applyUiChanges();
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.ActivationKey",
name: "⌨️ Magnify Glass: Activation Key",
type: "combo",
options: ACTIVATION_KEYS.map(k => ({ value: k, text: k })),
defaultValue: settings["🔍MagnifyGlass.ActivationKey"],
tooltip: "The key to activate the magnifier.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.activationKey = String(value).toLowerCase();
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.AltRequired",
name: "⌨️ Magnify Glass: Require Alt/Option Key",
type: "combo",
options: [{ value: true, text: "Yes" }, { value: false, text: "No" }],
defaultValue: settings["🔍MagnifyGlass.AltRequired"],
tooltip: "If Yes, Alt (Windows/Linux) or Option (Mac) must be held for activation.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.altRequired = !!value;
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.FollowCursor",
name: "🖱️ Magnify Glass: Follow Cursor Position",
type: "combo",
options: [{ value: true, text: "Yes" }, { value: false, text: "No" }],
defaultValue: settings["🔍MagnifyGlass.FollowCursor"],
tooltip: "If Yes, the magnifier window moves with the cursor.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.followCursor = !!value;
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.OffsetStep",
name: "⌨️ Magnify Glass: Offset Adjust Step",
type: "slider",
defaultValue: settings["🔍MagnifyGlass.OffsetStep"],
min: 1,
max: 50,
step: 1,
tooltip: "How many graph units the view shifts when pressing arrow keys.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.offsetStep = parseInt(String(value), 10);
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.ResetKey",
name: "⌨️ Magnify Glass: Reset Offset Key",
type: "combo",
options: RESET_KEYS.map(k => ({ value: k, text: k })),
defaultValue: settings["🔍MagnifyGlass.ResetKey"],
tooltip: "The key to reset the magnify glass offset to default.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.resetKey = String(value).toLowerCase();
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.DebugMode",
name: "🐞 Magnify Glass: Debug Mode",
type: "combo",
options: [{ value: true, text: "Enabled" }, { value: false, text: "Disabled" }],
defaultValue: settings["🔍MagnifyGlass.DebugMode"],
tooltip: "Show detailed logging and the debug visualization overlay.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.debugMode = !!value;
magnifyGlass.applyUiChanges();
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.GlassPosition",
name: "🖱️ Magnify Glass: Glass Position",
type: "combo",
options: GLASS_POSITIONS.map(p => ({ value: p, text: p === "Bottom" ? "Bottom (Default)" : p })),
defaultValue: settings["🔍MagnifyGlass.GlassPosition"],
tooltip: "Position of the magnifying glass relative to the cursor.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.glassPosition = String(value);
if (magnifyGlass.state.active && !magnifyGlass.config.followCursor) {
const { x, y } = magnifyGlass.lastKnownMousePosition;
magnifyGlass.ui.positionGlass(x, y);
}
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.GlassShape",
name: "🖼️ Magnify Glass: Shape",
type: "combo",
options: GLASS_SHAPES.map(s => ({ value: s, text: s })),
defaultValue: settings["🔍MagnifyGlass.GlassShape"],
tooltip: "Shape of the magnifying glass.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.glassShape = String(value);
magnifyGlass.applyUiChanges();
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.BorderEnabled",
name: "🖼️ Magnify Glass: Show Border",
type: "combo",
options: [{ value: true, text: "Yes" }, { value: false, text: "No" }],
defaultValue: settings["🔍MagnifyGlass.BorderEnabled"],
tooltip: "Enable or disable the border around the magnifying glass.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.borderEnabled = !!value;
magnifyGlass.applyUiChanges();
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.TextureFiltering",
name: "🖼️ Magnify Glass: Texture Filtering",
type: "combo",
options: [
{ value: "Linear", text: "Linear (Smooth)" },
{ value: "Nearest", text: "Nearest (Pixelated)" }
],
defaultValue: settings["🔍MagnifyGlass.TextureFiltering"],
tooltip: "Controls how the magnified image is scaled.",
onChange: (value: any) => {
if (magnifyGlass?.config && magnifyGlass.renderer) {
magnifyGlass.config.textureFiltering = String(value);
magnifyGlass.renderer.updateTextureFiltering(value);
if (magnifyGlass.state.active) {
magnifyGlass.updateMagnifiedView();
}
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.AlwaysActiveMode",
name: "🔒 Magnify Glass: Always Active Mode",
type: "combo",
options: [{ value: true, text: "Yes" }, { value: false, text: "No" }],
defaultValue: settings["🔍MagnifyGlass.AlwaysActiveMode"],
tooltip: "If Yes, activating the magnifier keeps it on until activated again.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.alwaysActiveMode = !!value;
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.ToggleFollowCursorKey",
name: "🔑 Magnify Glass: Toggle Follow Key",
type: "combo",
options: TOGGLE_FOLLOW_KEYS.map(k => ({ value: k, text: k })),
defaultValue: settings["🔍MagnifyGlass.ToggleFollowCursorKey"],
tooltip: "The key to toggle the 'Follow Cursor' behavior.",
onChange: (value: any) => {
if (magnifyGlass?.config) {
magnifyGlass.config.toggleFollowCursorKey = String(value).toLowerCase();
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.Action.ResetPosition",
name: "🔄 Magnify Glass: Reset Position",
type: "boolean",
defaultValue: false,
tooltip: "Toggle to reset the glass position and disable follow cursor.",
onChange: (value: any) => {
if (value) {
if (magnifyGlass?.resetOffsets) {
magnifyGlass.resetOffsets();
}
// Reset the toggle back to false
setTimeout(() => {
try {
app.ui.settings.setSettingValue("🔍MagnifyGlass.Action.ResetPosition", false);
} catch (e) { /* ignore */ }
}, 500);
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.Action.ResetAll",
name: "⚠️ Magnify Glass: Reset ALL Settings",
type: "boolean",
defaultValue: false,
tooltip: "Toggle to reset ALL settings to defaults.",
onChange: (value: any) => {
if (value) {
if (confirm("Reset ALL Magnify Glass settings?")) {
// Glass Defaults
app.ui.settings.setSettingValue('🔍MagnifyGlass.ZoomFactor', 300);
app.ui.settings.setSettingValue('🔍MagnifyGlass.GlassSize', 300);
app.ui.settings.setSettingValue('🔍MagnifyGlass.GlassShape', 'Rounded Square');
app.ui.settings.setSettingValue('🔍MagnifyGlass.GlassPosition', 'Top-Right');
app.ui.settings.setSettingValue('🔍MagnifyGlass.TextureFiltering', 'Linear');
app.ui.settings.setSettingValue('🔍MagnifyGlass.BorderWidth', 1);
app.ui.settings.setSettingValue('🔍MagnifyGlass.BorderColor', '#6b7280');
app.ui.settings.setSettingValue('🔍MagnifyGlass.BorderEnabled', true);
app.ui.settings.setSettingValue('🔍MagnifyGlass.FollowCursor', false);
app.ui.settings.setSettingValue('🔍MagnifyGlass.AlwaysActiveMode', true);
app.ui.settings.setSettingValue('🔍MagnifyGlass.ActivationKey', 'x');
app.ui.settings.setSettingValue('🔍MagnifyGlass.ResetKey', 'o');
app.ui.settings.setSettingValue('🔍MagnifyGlass.ToggleFollowCursorKey', 'h');
app.ui.settings.setSettingValue('🔍MagnifyGlass.AltRequired', false);
app.ui.settings.setSettingValue('🔍MagnifyGlass.OffsetStep', 5);
app.ui.settings.setSettingValue('🔍MagnifyGlass.DebugMode', false);
// Panel Defaults
app.ui.settings.setSettingValue('🔍MagnifyGlass.InfoPanelEnabled', true);
app.ui.settings.setSettingValue('🔍MagnifyGlass.InfoPanelPosition', 'Bottom');
app.ui.settings.setSettingValue('🔍MagnifyGlass.InfoPanelWidth', 300);
app.ui.settings.setSettingValue('🔍MagnifyGlass.InfoPanelMaxHeight', 300);
app.ui.settings.setSettingValue('🔍MagnifyGlass.InfoPanelOpacity', 100);
app.ui.settings.setSettingValue('🔍MagnifyGlass.InfoPanelTextColor', '#6b7280');
app.ui.settings.setSettingValue('🔍MagnifyGlass.InfoPanelAccentColor', '#3b82f6');
app.ui.settings.setSettingValue('🔍MagnifyGlass.InfoPanelAnimations', false);
app.ui.settings.setSettingValue('🔍MagnifyGlass.ShowHoveringControls', true);
app.ui.settings.setSettingValue('🔍MagnifyGlass.ControlsPosition', 'left');
app.ui.settings.setSettingValue('🔍MagnifyGlass.ToggleHotkey', 'i');
app.ui.settings.setSettingValue('🔍MagnifyGlass.GlassPreviewToggleHotkey', 'g');
app.ui.settings.setSettingValue('🔍MagnifyGlass.PinPanelHotkey', 'u');
// Also force position reset
if (magnifyGlass?.resetOffsets) {
magnifyGlass.resetOffsets();
}
}
// Reset the toggle back to false
setTimeout(() => {
try {
app.ui.settings.setSettingValue("🔍MagnifyGlass.Action.ResetAll", false);
} catch (e) { /* ignore */ }
}, 500);
}
}
});
}
+15
View File
@@ -0,0 +1,15 @@
/**
* ComfyUI MagnifyGlass - Settings Module
*
* Re-exports all settings-related types, defaults, and registration functions.
*/
// Type definitions
export type { GlassSettings, PanelSettings, AllSettings } from './types';
// Default values
export { DEFAULT_GLASS_SETTINGS, DEFAULT_PANEL_SETTINGS } from './defaults';
// Registration functions
export { registerGlassSettings } from './glassSettings';
export { registerPanelSettings } from './panelSettings';
+192
View File
@@ -0,0 +1,192 @@
/**
* ComfyUI MagnifyGlass - Panel Settings Registration
*
* Registers all info panel settings with ComfyUI.
*/
// @ts-ignore
import { app } from "/scripts/app.js";
import { PANEL_POSITIONS } from '../constants';
import { DEFAULT_PANEL_SETTINGS } from './defaults';
/**
* Register all info panel settings with ComfyUI.
* @param stateManager - The StateManager instance for the info panel
* @param uiManager - The UIManager instance for the info panel
* @param positionManager - The PositionManager instance for the info panel
*/
export function registerPanelSettings(stateManager: any, uiManager: any, positionManager: any): void {
const settings = DEFAULT_PANEL_SETTINGS;
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.InfoPanelEnabled",
name: "📊 Info Panel: Enable",
type: "combo",
options: [{ value: true, text: "Yes" }, { value: false, text: "No" }],
defaultValue: settings["🔍MagnifyGlass.InfoPanelEnabled"],
tooltip: "Enable or disable the information panel.",
onChange: (value: any) => {
if (stateManager) {
stateManager.state.settings["🔍MagnifyGlass.InfoPanelEnabled"] = !!value;
if (!value && uiManager) {
uiManager.hide();
}
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.InfoPanelPosition",
name: "📊 Info Panel: Position",
type: "combo",
options: PANEL_POSITIONS.map(p => ({ value: p, text: p })),
defaultValue: settings["🔍MagnifyGlass.InfoPanelPosition"],
tooltip: "Position of the info panel relative to the magnifying glass.",
onChange: (value: any) => {
if (stateManager) {
stateManager.state.settings["🔍MagnifyGlass.InfoPanelPosition"] = String(value);
if (positionManager) {
positionManager.positionPanel();
}
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.InfoPanelWidth",
name: "📊 Info Panel: Width (px)",
type: "slider",
defaultValue: settings["🔍MagnifyGlass.InfoPanelWidth"],
min: 200,
max: 600,
step: 20,
tooltip: "Width of the information panel in pixels.",
onChange: (value: any) => {
if (stateManager) {
stateManager.state.settings["🔍MagnifyGlass.InfoPanelWidth"] = parseInt(String(value), 10);
if (uiManager) {
uiManager.applyStyles();
}
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.InfoPanelOpacity",
name: "📊 Info Panel: Opacity (%)",
type: "slider",
defaultValue: settings["🔍MagnifyGlass.InfoPanelOpacity"],
min: 10,
max: 100,
step: 5,
tooltip: "Opacity of the information panel background.",
onChange: (value: any) => {
if (stateManager) {
stateManager.state.settings["🔍MagnifyGlass.InfoPanelOpacity"] = parseInt(String(value), 10);
if (uiManager) {
uiManager.applyStyles();
}
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.InfoPanelMaxHeight",
name: "📊 Info Panel: Max Height (px)",
type: "slider",
defaultValue: settings["🔍MagnifyGlass.InfoPanelMaxHeight"],
min: 200,
max: 1500,
step: 50,
tooltip: "Maximum height of the information panel in pixels.",
onChange: (value: any) => {
if (stateManager) {
stateManager.state.settings["🔍MagnifyGlass.InfoPanelMaxHeight"] = parseInt(String(value), 10);
if (uiManager) {
uiManager.applyStyles();
}
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.InfoPanelAnimations",
name: "📊 Info Panel: Animations",
type: "combo",
options: [{ value: true, text: "Enabled" }, { value: false, text: "Disabled" }],
defaultValue: settings["🔍MagnifyGlass.InfoPanelAnimations"],
tooltip: "Enable or disable animations for the info panel.",
onChange: (value: any) => {
if (stateManager) {
stateManager.state.settings["🔍MagnifyGlass.InfoPanelAnimations"] = !!value;
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.ShowInspectorTab",
name: "📊 Info Panel: Show Inspector Tab",
type: "combo",
options: [{ value: true, text: "Yes" }, { value: false, text: "No" }],
defaultValue: settings["🔍MagnifyGlass.ShowInspectorTab"],
tooltip: "Show or hide the Inspector tab with cursor and canvas information.",
onChange: (value: any) => {
if (stateManager) {
stateManager.state.settings["🔍MagnifyGlass.ShowInspectorTab"] = !!value;
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.ShowHoveringControls",
name: "📊 Info Panel: Show Hover Controls",
type: "combo",
options: [{ value: true, text: "Yes" }, { value: false, text: "No" }],
defaultValue: settings["🔍MagnifyGlass.ShowHoveringControls"],
tooltip: "Show or hide hovering UI controls above the info panel.",
onChange: (value: any) => {
if (stateManager) {
stateManager.state.settings["🔍MagnifyGlass.ShowHoveringControls"] = !!value;
if (uiManager && uiManager.elements.controls) {
uiManager.elements.controls.style.display = value ? 'flex' : 'none';
}
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.InfoPanelTextColor",
name: "🎨 Info Panel: Text Color",
type: "color",
defaultValue: settings["🔍MagnifyGlass.InfoPanelTextColor"],
tooltip: "Custom text color for the info panel.",
onChange: (value: any) => {
if (stateManager) {
const strValue = String(value);
const normalizedColor = strValue && !strValue.startsWith('#') ? `#${strValue}` : strValue;
stateManager.state.settings["🔍MagnifyGlass.InfoPanelTextColor"] = normalizedColor;
if (uiManager) {
uiManager.applyStyles();
}
}
}
});
app.ui.settings.addSetting({
id: "🔍MagnifyGlass.InfoPanelAccentColor",
name: "🎨 Info Panel: Accent Color",
type: "color",
defaultValue: settings["🔍MagnifyGlass.InfoPanelAccentColor"],
tooltip: "Custom accent color for the info panel.",
onChange: (value: any) => {
if (stateManager) {
const strValue = String(value);
const normalizedColor = strValue && !strValue.startsWith('#') ? `#${strValue}` : strValue;
stateManager.state.settings["🔍MagnifyGlass.InfoPanelAccentColor"] = normalizedColor;
if (uiManager) {
uiManager.applyStyles();
}
}
}
});
}
+53
View File
@@ -0,0 +1,53 @@
/**
* ComfyUI MagnifyGlass - Settings Type Definitions
*
* Type definitions for magnify glass and info panel settings.
*/
/**
* Settings for the magnify glass component.
*/
export interface GlassSettings {
"🔍MagnifyGlass.ZoomFactor": number;
"🔍MagnifyGlass.GlassSize": number;
"🔍MagnifyGlass.BorderColor": string;
"🔍MagnifyGlass.BorderWidth": number;
"🔍MagnifyGlass.ActivationKey": string;
"🔍MagnifyGlass.AltRequired": boolean;
"🔍MagnifyGlass.FollowCursor": boolean;
"🔍MagnifyGlass.DebugMode": boolean;
"🔍MagnifyGlass.OffsetStep": number;
"🔍MagnifyGlass.GlassPosition": string;
"🔍MagnifyGlass.ResetKey": string;
"🔍MagnifyGlass.GlassShape": string;
"🔍MagnifyGlass.BorderEnabled": boolean;
"🔍MagnifyGlass.TextureFiltering": string;
"🔍MagnifyGlass.AlwaysActiveMode": boolean;
"🔍MagnifyGlass.ToggleFollowCursorKey": string;
}
/**
* Settings for the info panel component.
*/
export interface PanelSettings {
"🔍MagnifyGlass.InfoPanelEnabled": boolean;
"🔍MagnifyGlass.InfoPanelPosition": string;
"🔍MagnifyGlass.InfoPanelWidth": number;
"🔍MagnifyGlass.InfoPanelOpacity": number;
"🔍MagnifyGlass.InfoPanelMaxHeight": number;
"🔍MagnifyGlass.InfoPanelAnimations": boolean;
"🔍MagnifyGlass.ShowInspectorTab": boolean;
"🔍MagnifyGlass.ToggleHotkey": string;
"🔍MagnifyGlass.GlassPreviewToggleHotkey": string;
"🔍MagnifyGlass.PinPanelHotkey": string;
"🔍MagnifyGlass.ShowHoveringControls": boolean;
"🔍MagnifyGlass.ControlsPosition": string;
"🔍MagnifyGlass.InfoPanelTextColor": string;
"🔍MagnifyGlass.InfoPanelAccentColor": string;
[key: string]: string | number | boolean; // Allow indexing
}
/**
* Combined settings type.
*/
export type AllSettings = GlassSettings & PanelSettings;
+161
View File
@@ -0,0 +1,161 @@
/**
* ComfyUI MagnifyGlass - Shared Utilities
*
* Common utility functions shared between magnify glass and info panel modules.
*/
import type { ComfyApp } from '../types/comfyui';
// Reference to ComfyUI's app - will be set at runtime
// @ts-ignore
import { app } from "/scripts/app.js";
/**
* Rectangle interface for overlap calculations
*/
export interface Rectangle {
x: number;
y: number;
width: number;
height: number;
}
/**
* Debug logger interface
*/
export interface DebugLogger {
log(...args: unknown[]): void;
error(...args: unknown[]): void;
}
/**
* Safely get a setting value from ComfyUI settings with fallback to default.
* @param key - The setting key
* @param defaultValue - Default value if setting not found
* @returns The setting value or default
*/
export function getSettingValue<T>(key: string, defaultValue: T): T {
try {
const value = app.ui.settings.getSettingValue(key);
return value === undefined ? defaultValue : value as T;
} catch (e) {
console.warn(`ComfyUI Magnifying Glass: Could not get setting ${key}, using default ${defaultValue}. Error: ${e}`);
return defaultValue;
}
}
/**
* Check if the user is currently typing in an input field.
* Used for smart input detection to avoid triggering hotkeys while typing.
* @returns True if user is typing in an input field
*/
export function isUserTyping(): boolean {
const activeElement = document.activeElement as HTMLElement | null;
if (!activeElement) return false;
// Check if the active element is an input, textarea, or contenteditable
const tagName = activeElement.tagName.toLowerCase();
if (tagName === 'input' || tagName === 'textarea') {
return true;
}
// Check for contenteditable elements
if (activeElement.contentEditable === 'true') {
return true;
}
// Check if it's inside a form or has input-like classes
if (activeElement.closest('form') ||
activeElement.classList.contains('cm-editor') || // CodeMirror editor
activeElement.classList.contains('monaco-editor') || // Monaco editor
activeElement.closest('.cm-editor') ||
activeElement.closest('.monaco-editor')) {
return true;
}
return false;
}
/**
* Check if two rectangles overlap.
* @param rect1 - First rectangle
* @param rect2 - Second rectangle
* @returns True if rectangles overlap
*/
export function rectsOverlap(rect1: Rectangle, rect2: Rectangle): boolean {
return rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y;
}
/**
* Find the LiteGraph canvas element in the DOM.
* Tries multiple selectors for compatibility with different ComfyUI versions.
* @returns The canvas element or null if not found
*/
export function findLiteGraphCanvas(): HTMLCanvasElement | null {
// Try multiple selectors for compatibility
const canvas = document.getElementById("graph-canvas") as HTMLCanvasElement | null;
if (canvas) return canvas;
const graphCanvas = document.querySelector("canvas.graphcanvas") as HTMLCanvasElement | null;
if (graphCanvas) return graphCanvas;
// Try canvas manager (dynamic access for ComfyUI compatibility)
const appAny = app as any;
if (appAny?.canvas_manager?.container) {
const managerCanvas = appAny.canvas_manager.container.querySelector("canvas") as HTMLCanvasElement | null;
if (managerCanvas) return managerCanvas;
}
// Try direct canvas reference
if (appAny?.canvas?.graph_canvas) {
return appAny.canvas.graph_canvas;
}
return null;
}
/**
* Normalize a color value to include the # symbol for CSS.
* @param color - The color value (with or without #)
* @returns The normalized color with # prefix
*/
export function normalizeColor(color: string | null | undefined): string {
if (!color) return color ?? '';
return color.startsWith('#') ? color : `#${color}`;
}
/**
* Clamp a value between min and max bounds.
* @param value - The value to clamp
* @param min - Minimum bound
* @param max - Maximum bound
* @returns The clamped value
*/
export function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
/**
* Create a debug logger that only logs when debug mode is enabled.
* @param prefix - Prefix for log messages
* @param isDebugEnabled - Function that returns whether debug is enabled
* @returns Logger object
*/
export function createDebugLogger(
prefix: string,
isDebugEnabled: () => boolean
): DebugLogger {
return {
log(...args: unknown[]): void {
if (isDebugEnabled()) {
console.log(`${prefix}:`, ...args);
}
},
error(...args: unknown[]): void {
console.error(`${prefix} ERROR:`, ...args);
}
};
}
+261
View File
@@ -0,0 +1,261 @@
/**
* ComfyUI MagnifyGlass - Sidebar Inspector Panel
*
* Real-time inspector view for the sidebar.
*/
// @ts-ignore
import { app } from "/scripts/app.js";
/**
* Icons for the inspector panel
*/
const Icons = {
chevronDown: `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg>`,
};
/**
* Inspector state
*/
interface InspectorState {
cursor: { x: number; y: number };
canvasScale: number;
hoveredNode: any | null;
}
let inspectorState: InspectorState = {
cursor: { x: 0, y: 0 },
canvasScale: 1,
hoveredNode: null
};
let inspectorBody: HTMLElement | null = null;
let updateInterval: number | null = null;
/**
* Format a number for display
*/
function formatNumber(value: number, decimals: number = 0): string {
return value.toFixed(decimals);
}
/**
* Get the currently hovered node from the graph
*/
function getHoveredNode(): any | null {
try {
const graph = app.graph;
if (!graph || !graph.canvas) return null;
const canvas = graph.canvas;
const mousePos = canvas.graph_mouse;
if (!mousePos) return null;
// Find node at mouse position
const nodes = graph._nodes;
for (let i = nodes.length - 1; i >= 0; i--) {
const node = nodes[i];
if (node.pos && node.size) {
const [x, y] = node.pos;
const [w, h] = node.size;
if (mousePos[0] >= x && mousePos[0] <= x + w &&
mousePos[1] >= y && mousePos[1] <= y + h) {
return node;
}
}
}
return null;
} catch {
return null;
}
}
/**
* Get canvas information
*/
function getCanvasInfo(): { scale: number; cursor: { x: number; y: number } } {
try {
const graph = app.graph;
if (!graph || !graph.canvas) {
return { scale: 1, cursor: { x: 0, y: 0 } };
}
const canvas = graph.canvas;
const scale = canvas.ds?.scale || 1;
const mousePos = canvas.graph_mouse || [0, 0];
return {
scale: scale * 100,
cursor: { x: mousePos[0] || 0, y: mousePos[1] || 0 }
};
} catch {
return { scale: 1, cursor: { x: 0, y: 0 } };
}
}
/**
* Create an inspector row
*/
function createRow(label: string, value: string): HTMLElement {
const row = document.createElement('div');
row.className = 'magnify-inspector-row';
const labelEl = document.createElement('span');
labelEl.className = 'magnify-inspector-label';
labelEl.textContent = label;
const valueEl = document.createElement('span');
valueEl.className = 'magnify-inspector-value';
valueEl.textContent = value;
valueEl.title = value;
row.appendChild(labelEl);
row.appendChild(valueEl);
return row;
}
/**
* Create a group with title
*/
function createGroup(title: string): HTMLElement {
const group = document.createElement('div');
group.className = 'magnify-inspector-group';
const titleEl = document.createElement('div');
titleEl.className = 'magnify-inspector-group-title';
titleEl.textContent = title;
group.appendChild(titleEl);
return group;
}
/**
* Update the inspector display
*/
function updateInspector(): void {
if (!inspectorBody) return;
const canvasInfo = getCanvasInfo();
const hoveredNode = getHoveredNode();
// Clear body
inspectorBody.innerHTML = '';
// Canvas info group
const canvasGroup = createGroup('Canvas');
canvasGroup.appendChild(createRow('Cursor', `(${formatNumber(canvasInfo.cursor.x)}, ${formatNumber(canvasInfo.cursor.y)})`));
canvasGroup.appendChild(createRow('Scale', `${formatNumber(canvasInfo.scale, 1)}%`));
inspectorBody.appendChild(canvasGroup);
// MagnifyGlass info
const magnifyGlass = window.comfyUIMagnifyGlass;
if (magnifyGlass) {
const glassGroup = createGroup('Magnify Glass');
glassGroup.appendChild(createRow('Zoom', `${formatNumber((magnifyGlass.config?.zoomFactor || 1) * 100)}%`));
glassGroup.appendChild(createRow('Active', magnifyGlass.state?.active ? 'Yes' : 'No'));
inspectorBody.appendChild(glassGroup);
}
// Node info group
if (hoveredNode) {
const nodeGroup = createGroup('Hovered Node');
// Node badge
const badge = document.createElement('div');
badge.className = 'magnify-node-badge';
badge.textContent = hoveredNode.type || 'Unknown';
nodeGroup.appendChild(badge);
nodeGroup.appendChild(createRow('Title', hoveredNode.title || 'Untitled'));
nodeGroup.appendChild(createRow('ID', String(hoveredNode.id)));
// Position
if (hoveredNode.pos) {
nodeGroup.appendChild(createRow('Position', `(${formatNumber(hoveredNode.pos[0])}, ${formatNumber(hoveredNode.pos[1])})`));
}
// Size
if (hoveredNode.size) {
nodeGroup.appendChild(createRow('Size', `${formatNumber(hoveredNode.size[0])} × ${formatNumber(hoveredNode.size[1])}`));
}
// Widgets (first few)
if (hoveredNode.widgets && hoveredNode.widgets.length > 0) {
const widgetGroup = createGroup('Parameters');
const widgetsToShow = hoveredNode.widgets.slice(0, 6);
for (const widget of widgetsToShow) {
if (widget.name && widget.value !== undefined) {
let value = String(widget.value);
if (value.length > 30) value = value.substring(0, 27) + '...';
widgetGroup.appendChild(createRow(widget.name, value));
}
}
if (hoveredNode.widgets.length > 6) {
const moreEl = document.createElement('div');
moreEl.style.cssText = 'font-size: 11px; color: #666; padding: 4px 0;';
moreEl.textContent = `+${hoveredNode.widgets.length - 6} more...`;
widgetGroup.appendChild(moreEl);
}
inspectorBody.appendChild(widgetGroup);
}
inspectorBody.appendChild(nodeGroup);
} else {
// Empty state
const empty = document.createElement('div');
empty.className = 'magnify-inspector-empty';
empty.textContent = 'Hover over a node to inspect';
inspectorBody.appendChild(empty);
}
}
/**
* Render the inspector panel into the container
*/
export function renderInspectorPanel(container: HTMLElement): void {
const section = document.createElement('div');
section.className = 'magnify-sidebar-section';
// Section header
const header = document.createElement('div');
header.className = 'magnify-sidebar-section-header';
header.innerHTML = `${Icons.chevronDown}<span>Inspector</span>`;
// Section body
const body = document.createElement('div');
body.className = 'magnify-sidebar-section-body magnify-inspector-section';
inspectorBody = body;
// Toggle collapse
header.addEventListener('click', () => {
header.classList.toggle('collapsed');
body.classList.toggle('collapsed');
});
section.appendChild(header);
section.appendChild(body);
container.appendChild(section);
// Initial update
updateInspector();
// Start update interval
if (updateInterval) {
clearInterval(updateInterval);
}
updateInterval = window.setInterval(updateInspector, 100);
}
/**
* Cleanup the inspector (call when sidebar is destroyed)
*/
export function cleanupInspector(): void {
if (updateInterval) {
clearInterval(updateInterval);
updateInterval = null;
}
inspectorBody = null;
}
+697
View File
@@ -0,0 +1,697 @@
/**
* ComfyUI MagnifyGlass - Sidebar Settings Panel
*
* All settings controls for the sidebar.
*/
// @ts-ignore
import { app } from "/scripts/app.js";
import {
GLASS_POSITIONS,
GLASS_SHAPES,
ACTIVATION_KEYS,
RESET_KEYS,
TOGGLE_FOLLOW_KEYS,
PANEL_POSITIONS
} from '../shared/constants';
/**
* Icons for the settings panel
*/
const Icons = {
chevronDown: `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg>`,
reset: `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"></polyline><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path></svg>`,
};
/**
* Create a slider control with tooltip
*/
/**
* Create a slider control with tooltip
*/
function createSlider(
label: string,
value: number,
min: number,
max: number,
step: number,
unit: string,
onChange: (value: number) => void,
tooltip?: string,
onInput?: (value: number) => void
): HTMLElement {
const row = document.createElement('div');
row.className = 'magnify-control-row';
if (tooltip) row.title = tooltip;
const labelRow = document.createElement('div');
labelRow.className = 'magnify-control-label-row';
const labelEl = document.createElement('label');
labelEl.textContent = label;
const valueEl = document.createElement('span');
valueEl.className = 'control-value';
valueEl.textContent = `${value}${unit}`;
labelRow.appendChild(labelEl);
labelRow.appendChild(valueEl);
const slider = document.createElement('input');
slider.type = 'range';
slider.className = 'magnify-slider';
slider.min = String(min);
slider.max = String(max);
slider.step = String(step);
slider.value = String(value);
// Prevent ComfyUI from capturing mouse events during drag
slider.addEventListener('mousedown', (e) => e.stopPropagation());
slider.addEventListener('touchstart', (e) => e.stopPropagation());
slider.addEventListener('pointerdown', (e) => e.stopPropagation());
slider.addEventListener('input', (e) => {
e.stopPropagation();
const newValue = parseFloat(slider.value);
valueEl.textContent = `${newValue}${unit}`;
if (onInput) onInput(newValue);
});
slider.addEventListener('change', (e) => {
e.stopPropagation();
const newValue = parseFloat(slider.value);
onChange(newValue);
});
row.appendChild(labelRow);
row.appendChild(slider);
return row;
}
/**
* Create a toggle control with tooltip
*/
function createToggle(
label: string,
checked: boolean,
onChange: (checked: boolean) => void,
tooltip?: string
): HTMLElement {
const row = document.createElement('div');
row.className = 'magnify-toggle-row';
if (tooltip) row.title = tooltip;
const labelEl = document.createElement('label');
labelEl.textContent = label;
const toggle = document.createElement('div');
toggle.className = `magnify-toggle${checked ? ' active' : ''}`;
toggle.addEventListener('click', () => {
const isActive = toggle.classList.toggle('active');
onChange(isActive);
});
row.appendChild(labelEl);
row.appendChild(toggle);
return row;
}
/**
* Create a select dropdown control with tooltip
*/
function createSelect(
label: string,
value: string,
options: readonly string[] | string[],
onChange: (value: string) => void,
tooltip?: string,
onInput?: (value: string) => void
): HTMLElement {
const row = document.createElement('div');
row.className = 'magnify-control-row';
if (tooltip) row.title = tooltip;
const labelEl = document.createElement('label');
labelEl.textContent = label;
const select = document.createElement('select');
select.className = 'magnify-select';
options.forEach(opt => {
const option = document.createElement('option');
option.value = opt;
option.textContent = opt;
if (opt === value) option.selected = true;
select.appendChild(option);
});
select.addEventListener('change', () => {
// Call onInput first for live preview
if (onInput) {
onInput(select.value);
}
// Then persist the setting
onChange(select.value);
});
row.appendChild(labelEl);
row.appendChild(select);
return row;
}
/**
* Create a color picker control with tooltip
*/
/**
* Create a color picker control with tooltip
*/
function createColorPicker(
label: string,
value: string,
onChange: (value: string) => void,
tooltip?: string,
onInput?: (value: string) => void
): HTMLElement {
const row = document.createElement('div');
row.className = 'magnify-control-row magnify-color-row';
if (tooltip) row.title = tooltip;
const labelEl = document.createElement('label');
labelEl.textContent = label;
const colorWrapper = document.createElement('div');
colorWrapper.className = 'magnify-color-wrapper';
const colorInput = document.createElement('input');
colorInput.type = 'color';
colorInput.className = 'magnify-color-input';
colorInput.value = value;
const colorPreview = document.createElement('span');
colorPreview.className = 'magnify-color-preview';
colorPreview.textContent = value;
colorInput.addEventListener('input', () => {
colorPreview.textContent = colorInput.value;
if (onInput) onInput(colorInput.value);
});
colorInput.addEventListener('change', () => {
onChange(colorInput.value);
});
colorWrapper.appendChild(colorInput);
colorWrapper.appendChild(colorPreview);
row.appendChild(labelEl);
row.appendChild(colorWrapper);
return row;
}
/**
* Get current MagnifyGlass settings from app.ui.settings
*/
function getSettingValue(id: string, defaultValue: any): any {
try {
const value = app.ui.settings.getSettingValue(id);
return value !== undefined ? value : defaultValue;
} catch {
return defaultValue;
}
}
/**
* Set a MagnifyGlass setting via app.ui.settings
*/
function setSettingValue(id: string, value: any): void {
try {
app.ui.settings.setSettingValue(id, value);
} catch (e) {
console.warn(`Failed to set setting ${id}:`, e);
}
}
/** Storage key for section states */
const SECTION_STATE_KEY = 'magnifyglass-sidebar-sections';
/**
* Get saved section states from localStorage
*/
function getSectionStates(): Record<string, boolean> {
try {
const saved = localStorage.getItem(SECTION_STATE_KEY);
return saved ? JSON.parse(saved) : {};
} catch {
return {};
}
}
/**
* Save section state to localStorage
*/
function saveSectionState(title: string, collapsed: boolean): void {
try {
const states = getSectionStates();
states[title] = collapsed;
localStorage.setItem(SECTION_STATE_KEY, JSON.stringify(states));
} catch {
// Ignore storage errors
}
}
/**
* Create a collapsible section with persistent state
*/
function createSection(title: string, defaultCollapsed: boolean = false): { section: HTMLElement; body: HTMLElement } {
const section = document.createElement('div');
section.className = 'magnify-sidebar-section';
// Check if we have a saved state for this section
const savedStates = getSectionStates();
const collapsed = savedStates[title] !== undefined ? savedStates[title] : defaultCollapsed;
const header = document.createElement('div');
header.className = `magnify-sidebar-section-header${collapsed ? ' collapsed' : ''}`;
header.innerHTML = `${Icons.chevronDown}<span>${title}</span>`;
const body = document.createElement('div');
body.className = `magnify-sidebar-section-body${collapsed ? ' collapsed' : ''}`;
header.addEventListener('click', () => {
const isCollapsed = header.classList.toggle('collapsed');
body.classList.toggle('collapsed');
// Save the new state
saveSectionState(title, isCollapsed);
});
section.appendChild(header);
section.appendChild(body);
return { section, body };
}
/**
* Render the settings panel into the container
*/
export function renderSettingsPanel(container: HTMLElement): void {
// Get current hotkey values for tooltips
const activationKey = getSettingValue('🔍MagnifyGlass.ActivationKey', 'x').toUpperCase();
const resetKey = getSettingValue('🔍MagnifyGlass.ResetKey', 'o').toUpperCase();
const toggleFollowKey = getSettingValue('🔍MagnifyGlass.ToggleFollowCursorKey', 'h').toUpperCase();
// ===== Glass Settings Section =====
const glassSection = createSection('Glass Settings');
glassSection.body.appendChild(createSlider('Zoom Factor',
getSettingValue('🔍MagnifyGlass.ZoomFactor', 300), 100, 1000, 25, '%',
(value) => setSettingValue('🔍MagnifyGlass.ZoomFactor', value),
'Magnification level of the glass (100-1000%)',
(value) => {
const mg = (window as any).comfyUIMagnifyGlass;
if (mg?.config) {
mg.config.zoomFactor = value / 100;
if (mg.state.active) mg.updateMagnifiedView();
}
}
));
glassSection.body.appendChild(createSlider('Glass Size',
getSettingValue('🔍MagnifyGlass.GlassSize', 250), 50, 500, 10, 'px',
(value) => setSettingValue('🔍MagnifyGlass.GlassSize', value),
'Size of the magnifying glass in pixels',
(value) => {
const mg = (window as any).comfyUIMagnifyGlass;
if (mg?.config) {
mg.config.glassSize = value;
mg.applyUiChanges();
if (mg.state.active) mg.updateMagnifiedView();
}
}
));
glassSection.body.appendChild(createSelect('Shape',
getSettingValue('🔍MagnifyGlass.GlassShape', 'Rounded Square'), GLASS_SHAPES,
(value) => setSettingValue('🔍MagnifyGlass.GlassShape', value),
'Shape of the magnifying glass'
));
glassSection.body.appendChild(createSelect('Position',
getSettingValue('🔍MagnifyGlass.GlassPosition', 'Top-Right'), GLASS_POSITIONS,
(value) => setSettingValue('🔍MagnifyGlass.GlassPosition', value),
`Default position of the glass. Press ${resetKey} to reset.`
));
glassSection.body.appendChild(createSelect('Filtering',
getSettingValue('🔍MagnifyGlass.TextureFiltering', 'Linear'), ['Linear', 'Nearest'],
(value) => setSettingValue('🔍MagnifyGlass.TextureFiltering', value),
'Texture filtering: Linear (smooth) or Nearest (pixelated)'
));
glassSection.body.appendChild(createSlider('Border Width',
getSettingValue('🔍MagnifyGlass.BorderWidth', 2), 0, 10, 0.5, 'px',
(value) => setSettingValue('🔍MagnifyGlass.BorderWidth', value),
'Width of the glass border in pixels',
(value) => {
const mg = (window as any).comfyUIMagnifyGlass;
if (mg?.config) {
mg.config.borderWidth = value;
mg.applyUiChanges();
}
}
));
glassSection.body.appendChild(createColorPicker('Border Color',
getSettingValue('🔍MagnifyGlass.BorderColor', '#ffffff'),
(value) => setSettingValue('🔍MagnifyGlass.BorderColor', value),
'Color of the glass border',
(value) => {
const mg = (window as any).comfyUIMagnifyGlass;
if (mg?.config) {
mg.config.borderColor = value;
mg.applyUiChanges();
}
}
));
glassSection.body.appendChild(createToggle('Show Border',
getSettingValue('🔍MagnifyGlass.BorderEnabled', true),
(checked) => setSettingValue('🔍MagnifyGlass.BorderEnabled', checked),
'Show or hide the glass border'
));
glassSection.body.appendChild(createToggle('Follow Cursor',
getSettingValue('🔍MagnifyGlass.FollowCursor', false),
(checked) => setSettingValue('🔍MagnifyGlass.FollowCursor', checked),
`Glass follows the cursor. Hotkey: ${toggleFollowKey}`
));
glassSection.body.appendChild(createToggle('Always Active Mode',
getSettingValue('🔍MagnifyGlass.AlwaysActiveMode', true),
(checked) => setSettingValue('🔍MagnifyGlass.AlwaysActiveMode', checked),
`When enabled, glass stays visible. Toggle with ${activationKey}`
));
container.appendChild(glassSection.section);
// ===== Hotkeys Section =====
const hotkeySection = createSection('Hotkeys', true);
hotkeySection.body.appendChild(createSelect('Activation Key',
getSettingValue('🔍MagnifyGlass.ActivationKey', 'x'), ACTIVATION_KEYS,
(value) => setSettingValue('🔍MagnifyGlass.ActivationKey', value),
'Key to toggle or hold to activate the magnifying glass'
));
hotkeySection.body.appendChild(createSelect('Reset Key',
getSettingValue('🔍MagnifyGlass.ResetKey', 'o'), RESET_KEYS,
(value) => setSettingValue('🔍MagnifyGlass.ResetKey', value),
'Key to reset glass position and disable follow cursor'
));
hotkeySection.body.appendChild(createSelect('Toggle Follow Key',
getSettingValue('🔍MagnifyGlass.ToggleFollowCursorKey', 'h'), TOGGLE_FOLLOW_KEYS,
(value) => setSettingValue('🔍MagnifyGlass.ToggleFollowCursorKey', value),
'Key to toggle follow cursor mode'
));
hotkeySection.body.appendChild(createToggle('Require Alt Key',
getSettingValue('🔍MagnifyGlass.AltRequired', false),
(checked) => setSettingValue('🔍MagnifyGlass.AltRequired', checked),
'Require Alt key to be held with activation key'
));
hotkeySection.body.appendChild(createSlider('Offset Step',
getSettingValue('🔍MagnifyGlass.OffsetStep', 10), 1, 50, 1, 'px',
(value) => setSettingValue('🔍MagnifyGlass.OffsetStep', value),
'Amount to move glass per arrow key press (pixels)'
));
container.appendChild(hotkeySection.section);
// ===== Info Panel Section =====
const panelSection = createSection('Info Panel', true);
const toggleHotkey = getSettingValue('🔍MagnifyGlass.ToggleHotkey', 'i').toUpperCase();
const glassToggleKey = getSettingValue('🔍MagnifyGlass.GlassPreviewToggleHotkey', 'g').toUpperCase();
const pinHotkeyVal = getSettingValue('🔍MagnifyGlass.PinPanelHotkey', 'u').toUpperCase();
panelSection.body.appendChild(createToggle('Enable Panel',
getSettingValue('🔍MagnifyGlass.InfoPanelEnabled', true),
(checked) => setSettingValue('🔍MagnifyGlass.InfoPanelEnabled', checked),
`Show info panel with node details. Toggle: ${toggleHotkey}`
));
panelSection.body.appendChild(createSelect('Position',
getSettingValue('🔍MagnifyGlass.InfoPanelPosition', 'Bottom'), PANEL_POSITIONS,
(value) => setSettingValue('🔍MagnifyGlass.InfoPanelPosition', value),
'Position of the info panel relative to the glass'
));
panelSection.body.appendChild(createSlider('Width',
getSettingValue('🔍MagnifyGlass.InfoPanelWidth', 300), 200, 600, 20, 'px',
(value) => setSettingValue('🔍MagnifyGlass.InfoPanelWidth', value),
'Width of the info panel',
(value) => {
const infoPanel = (window as any).infoPanelManager;
if (infoPanel?.stateManager?.state?.settings) {
infoPanel.stateManager.state.settings['🔍MagnifyGlass.InfoPanelWidth'] = value;
infoPanel.uiManager.applyStyles();
// Ensure visible and reflow if active
if (infoPanel.magnifyGlass.state.active) {
infoPanel.uiManager.show();
infoPanel.positionManager.positionPanel();
}
}
}
));
panelSection.body.appendChild(createSlider('Max Height',
getSettingValue('🔍MagnifyGlass.InfoPanelMaxHeight', 300), 200, 1500, 50, 'px',
(value) => setSettingValue('🔍MagnifyGlass.InfoPanelMaxHeight', value),
'Maximum height of the info panel',
(value) => {
console.log('[MaxHeight] Handler called with value:', value);
const infoPanel = (window as any).infoPanelManager;
console.log('[MaxHeight] infoPanelManager:', infoPanel ? 'found' : 'NOT FOUND');
if (infoPanel?.stateManager?.state?.settings) {
console.log('[MaxHeight] Updating setting and calling applyStyles');
infoPanel.stateManager.state.settings['🔍MagnifyGlass.InfoPanelMaxHeight'] = value;
infoPanel.uiManager.applyStyles();
// Ensure visible and reflow if active
if (infoPanel.magnifyGlass.state.active) {
console.log('[MaxHeight] Glass is active, calling show() and positionPanel()');
infoPanel.uiManager.show();
infoPanel.positionManager.positionPanel();
} else {
console.log('[MaxHeight] Glass is NOT active, skipping show()');
}
} else {
console.warn('[MaxHeight] Check failed - stateManager/state/settings missing');
}
}
));
panelSection.body.appendChild(createSlider('Opacity',
getSettingValue('🔍MagnifyGlass.InfoPanelOpacity', 95), 10, 100, 5, '%',
(value) => setSettingValue('🔍MagnifyGlass.InfoPanelOpacity', value),
'Background opacity of the info panel',
(value) => {
const infoPanel = (window as any).infoPanelManager;
if (infoPanel?.stateManager?.state?.settings) {
infoPanel.stateManager.state.settings['🔍MagnifyGlass.InfoPanelOpacity'] = value;
infoPanel.uiManager.applyStyles();
}
}
));
panelSection.body.appendChild(createColorPicker('Text Color',
getSettingValue('🔍MagnifyGlass.InfoPanelTextColor', '#6b7280'),
(value) => setSettingValue('🔍MagnifyGlass.InfoPanelTextColor', value),
'Text color in the info panel',
(value) => {
const infoPanel = (window as any).infoPanelManager;
if (infoPanel?.stateManager?.state?.settings) {
infoPanel.stateManager.state.settings['🔍MagnifyGlass.InfoPanelTextColor'] = value;
infoPanel.uiManager.applyStyles();
}
}
));
panelSection.body.appendChild(createColorPicker('Accent Color',
getSettingValue('🔍MagnifyGlass.InfoPanelAccentColor', '#3b82f6'),
(value) => setSettingValue('🔍MagnifyGlass.InfoPanelAccentColor', value),
'Accent color for highlights',
(value) => {
const infoPanel = (window as any).infoPanelManager;
if (infoPanel?.stateManager?.state?.settings) {
infoPanel.stateManager.state.settings['🔍MagnifyGlass.InfoPanelAccentColor'] = value;
infoPanel.uiManager.applyStyles();
}
}
));
panelSection.body.appendChild(createToggle('Animations',
getSettingValue('🔍MagnifyGlass.InfoPanelAnimations', false),
(checked) => setSettingValue('🔍MagnifyGlass.InfoPanelAnimations', checked),
'Enable smooth animations for panel updates'
));
panelSection.body.appendChild(createToggle('Hover Controls',
getSettingValue('🔍MagnifyGlass.ShowHoveringControls', true),
(checked) => setSettingValue('🔍MagnifyGlass.ShowHoveringControls', checked),
'Show floating control buttons near the panel'
));
panelSection.body.appendChild(createSelect('Controls Position',
getSettingValue('🔍MagnifyGlass.ControlsPosition', 'left'),
['top', 'bottom', 'left', 'right', 'top-left', 'top-right', 'bottom-left', 'bottom-right'],
(value) => setSettingValue('🔍MagnifyGlass.ControlsPosition', value),
'Position of floating control buttons',
(value) => {
// Live update controls position
const infoPanel = (window as any).infoPanelManager;
if (infoPanel?.stateManager?.state?.settings) {
infoPanel.stateManager.state.settings['🔍MagnifyGlass.ControlsPosition'] = value;
infoPanel.uiManager.updateControlsLayout(value);
if (infoPanel.magnifyGlass.state.active) {
infoPanel.positionManager.positionFloatingControls();
}
}
}
));
container.appendChild(panelSection.section);
// ===== Panel Hotkeys Section =====
const panelHotkeySection = createSection('Panel Hotkeys', true);
panelHotkeySection.body.appendChild(createSelect('Toggle Key',
getSettingValue('🔍MagnifyGlass.ToggleHotkey', 'i'), ['i', 'j', 'k', 'l', 'n', 'm'],
(value) => setSettingValue('🔍MagnifyGlass.ToggleHotkey', value),
'Key to toggle info panel visibility'
));
panelHotkeySection.body.appendChild(createSelect('Glass Toggle Key',
getSettingValue('🔍MagnifyGlass.GlassPreviewToggleHotkey', 'g'), ['g', 'f', 'v', 'b'],
(value) => setSettingValue('🔍MagnifyGlass.GlassPreviewToggleHotkey', value),
'Key to toggle glass preview in panel'
));
panelHotkeySection.body.appendChild(createSelect('Pin Key',
getSettingValue('🔍MagnifyGlass.PinPanelHotkey', 'u'), ['u', 'p', 'y', 't'],
(value) => setSettingValue('🔍MagnifyGlass.PinPanelHotkey', value),
'Key to pin/unpin the info panel position'
));
container.appendChild(panelHotkeySection.section);
// ===== Debug Section =====
const debugSection = createSection('Debug', true);
debugSection.body.appendChild(createToggle('Debug Mode',
getSettingValue('🔍MagnifyGlass.DebugMode', false),
(checked) => setSettingValue('🔍MagnifyGlass.DebugMode', checked),
'Enable debug logging and visual indicators'
));
container.appendChild(debugSection.section);
// ===== Button Row =====
const buttonRow = document.createElement('div');
buttonRow.style.padding = '16px';
buttonRow.style.borderTop = '1px solid var(--border-color, #333)';
buttonRow.style.display = 'flex';
buttonRow.style.flexDirection = 'column';
buttonRow.style.gap = '8px';
// Reset Position Button
const resetBtn = document.createElement('button');
resetBtn.className = 'magnify-btn';
resetBtn.style.width = '100%';
resetBtn.innerHTML = `${Icons.reset} Reset Position`;
resetBtn.title = `Reset glass position and disable follow cursor. Hotkey: ${resetKey}`;
resetBtn.addEventListener('click', (e) => {
e.stopPropagation();
const magnifyGlass = window.comfyUIMagnifyGlass;
if (magnifyGlass && magnifyGlass.resetOffsets) {
magnifyGlass.resetOffsets();
// Update follow cursor toggle in UI
const followToggles = container.querySelectorAll('.magnify-toggle-row');
followToggles.forEach(row => {
const label = row.querySelector('label');
if (label && label.textContent === 'Follow Cursor') {
const toggle = row.querySelector('.magnify-toggle');
if (toggle) toggle.classList.remove('active');
}
});
}
});
buttonRow.appendChild(resetBtn);
// Reset All Settings Button
const resetAllBtn = document.createElement('button');
resetAllBtn.className = 'magnify-btn magnify-btn-secondary';
resetAllBtn.style.width = '100%';
resetAllBtn.innerHTML = `${Icons.reset} Reset All Settings`;
resetAllBtn.title = 'Reset all settings to their default values';
resetAllBtn.addEventListener('click', (e) => {
e.stopPropagation();
// Confirm with user
if (!confirm('Reset all MagnifyGlass settings to defaults?')) {
return;
}
// Default glass settings
setSettingValue('🔍MagnifyGlass.ZoomFactor', 300);
setSettingValue('🔍MagnifyGlass.GlassSize', 300);
setSettingValue('🔍MagnifyGlass.GlassShape', 'Rounded Square');
setSettingValue('🔍MagnifyGlass.GlassPosition', 'Top-Right');
setSettingValue('🔍MagnifyGlass.TextureFiltering', 'Linear');
setSettingValue('🔍MagnifyGlass.BorderWidth', 1);
setSettingValue('🔍MagnifyGlass.BorderColor', '#6b7280');
setSettingValue('🔍MagnifyGlass.BorderEnabled', true);
setSettingValue('🔍MagnifyGlass.FollowCursor', false);
setSettingValue('🔍MagnifyGlass.AlwaysActiveMode', true);
setSettingValue('🔍MagnifyGlass.ActivationKey', 'x');
setSettingValue('🔍MagnifyGlass.ResetKey', 'o');
setSettingValue('🔍MagnifyGlass.ToggleFollowCursorKey', 'h');
setSettingValue('🔍MagnifyGlass.AltRequired', false);
setSettingValue('🔍MagnifyGlass.OffsetStep', 5);
setSettingValue('🔍MagnifyGlass.DebugMode', false);
// Default panel settings
setSettingValue('🔍MagnifyGlass.InfoPanelEnabled', true);
setSettingValue('🔍MagnifyGlass.InfoPanelPosition', 'Bottom');
setSettingValue('🔍MagnifyGlass.InfoPanelWidth', 300);
setSettingValue('🔍MagnifyGlass.InfoPanelMaxHeight', 300);
setSettingValue('🔍MagnifyGlass.InfoPanelOpacity', 100);
setSettingValue('🔍MagnifyGlass.InfoPanelTextColor', '#6b7280');
setSettingValue('🔍MagnifyGlass.InfoPanelAccentColor', '#3b82f6');
setSettingValue('🔍MagnifyGlass.InfoPanelAnimations', false);
setSettingValue('🔍MagnifyGlass.ShowHoveringControls', true);
setSettingValue('🔍MagnifyGlass.ControlsPosition', 'left');
setSettingValue('🔍MagnifyGlass.ToggleHotkey', 'i');
setSettingValue('🔍MagnifyGlass.GlassPreviewToggleHotkey', 'g');
setSettingValue('🔍MagnifyGlass.PinPanelHotkey', 'u');
// Also reset position
const magnifyGlass = window.comfyUIMagnifyGlass;
if (magnifyGlass && magnifyGlass.resetOffsets) {
magnifyGlass.resetOffsets();
}
});
buttonRow.appendChild(resetAllBtn);
container.appendChild(buttonRow);
}
+8
View File
@@ -0,0 +1,8 @@
/**
* ComfyUI MagnifyGlass - Sidebar Index
*
* Re-exports all sidebar modules.
*/
export { registerSidebar, initSidebar } from './sidebar';
export { renderSettingsPanel } from './SidebarSettings';
+106
View File
@@ -0,0 +1,106 @@
/**
* ComfyUI MagnifyGlass - Sidebar Entry Point
*
* Registers the MagnifyGlass sidebar tab with ComfyUI.
*/
// @ts-ignore
import { app } from "/scripts/app.js";
import { renderSettingsPanel } from './SidebarSettings';
/**
* Magnify glass icon SVG
*/
const MAGNIFY_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>`;
/** Track if sidebar has been registered */
let sidebarRegistered = false;
/**
* Load sidebar CSS
*/
function loadSidebarStyles(): void {
if (!document.getElementById('magnify-sidebar-styles')) {
const link = document.createElement('link');
link.id = 'magnify-sidebar-styles';
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'extensions/comfyui-magnifyglass/sidebar.css';
document.head.appendChild(link);
}
}
/**
* Render the sidebar content
*/
function renderSidebar(container: HTMLElement): void {
// Load styles
loadSidebarStyles();
// Clear existing content to prevent duplicates
container.innerHTML = '';
// Create main container
const sidebar = document.createElement('div');
sidebar.className = 'magnify-sidebar';
// Header
const header = document.createElement('div');
header.className = 'magnify-sidebar-header';
header.innerHTML = `${MAGNIFY_ICON}<h2>Magnify G.</h2>`;
sidebar.appendChild(header);
// Content area
const content = document.createElement('div');
content.className = 'magnify-sidebar-content';
// Render settings panel (contains all settings)
renderSettingsPanel(content);
sidebar.appendChild(content);
container.appendChild(sidebar);
}
/**
* Register the sidebar tab with ComfyUI
*/
export function registerSidebar(): void {
// Prevent duplicate registration
if (sidebarRegistered) {
return;
}
// Wait for app to be ready
if (!app.extensionManager) {
console.warn('MagnifyGlass: extensionManager not available, sidebar registration skipped');
return;
}
try {
app.extensionManager.registerSidebarTab({
id: 'magnifyglass',
icon: 'pi pi-search',
title: 'Magnify G.',
tooltip: 'MagnifyGlass Settings',
type: 'custom',
render: (el: HTMLElement) => {
renderSidebar(el);
}
});
sidebarRegistered = true;
console.log('MagnifyGlass: Sidebar registered successfully');
} catch (e) {
console.warn('MagnifyGlass: Failed to register sidebar:', e);
}
}
/**
* Initialize sidebar (called after app setup)
*/
export function initSidebar(): void {
// Register on next tick to ensure app is ready
setTimeout(() => {
registerSidebar();
}, 100);
}
+11
View File
@@ -0,0 +1,11 @@
declare module "../../scripts/app.js" {
export const app: any;
}
declare module "../../scripts/ui.js" {
export const ui: any;
}
declare module "../../scripts/api.js" {
export const api: any;
}
+387
View File
@@ -0,0 +1,387 @@
/**
* ComfyUI Type Definitions
*
* Type definitions for ComfyUI's app, canvas, and graph APIs.
* These types are based on the runtime behavior of ComfyUI.
*/
// ============================================================================
// ComfyUI App
// ============================================================================
export interface ComfyApp {
graph: ComfyGraph;
canvas: ComfyCanvas;
ui: ComfyUI;
extensionManager: ComfyExtensionManager;
registerExtension(extension: ComfyExtension): void;
}
export interface ComfyExtension {
name: string;
setup?: () => Promise<void> | void;
init?: () => Promise<void> | void;
commands?: ComfyCommand[];
keybindings?: ComfyKeybinding[];
menuCommands?: ComfyMenuCommand[];
settings?: ComfySetting[];
bottomPanelTabs?: ComfyBottomPanelTab[];
aboutPageBadges?: ComfyBadge[];
getSelectionToolboxCommands?: (selectedItem: unknown) => string[];
}
export interface ComfyCommand {
id: string;
label?: string;
icon?: string;
function: () => void;
}
export interface ComfyKeybinding {
combo: {
key: string;
alt?: boolean;
ctrl?: boolean;
shift?: boolean;
meta?: boolean;
};
commandId: string;
}
export interface ComfyMenuCommand {
path: string[];
commands: string[];
}
export interface ComfySetting {
id: string;
name: string;
type: 'text' | 'number' | 'slider' | 'combo' | 'color' | 'boolean';
defaultValue: unknown;
min?: number;
max?: number;
step?: number;
options?: Array<{ value: unknown; text: string }>;
tooltip?: string;
onChange?: (value: unknown) => void;
}
export interface ComfyBottomPanelTab {
id: string;
title: string;
type: 'custom';
render: (el: HTMLElement) => void;
}
export interface ComfyBadge {
label: string;
url: string;
icon: string;
}
// ============================================================================
// ComfyUI UI
// ============================================================================
export interface ComfyUI {
settings: ComfySettings;
}
export interface ComfySettings {
addSetting(setting: ComfySetting): void;
getSettingValue(id: string): unknown;
setSettingValue(id: string, value: unknown): void;
}
// ============================================================================
// ComfyUI Extension Manager
// ============================================================================
export interface ComfyExtensionManager {
setting: {
get(id: string): unknown;
set(id: string, value: unknown): void;
};
toast: ComfyToast;
dialog: ComfyDialog;
registerSidebarTab(tab: ComfySidebarTab): void;
}
export interface ComfySidebarTab {
id: string;
icon: string;
title: string;
tooltip: string;
type: 'custom';
render: (el: HTMLElement) => void;
}
export interface ComfyToast {
add(options: ComfyToastOptions): void;
addAlert(message: string): void;
}
export interface ComfyToastOptions {
severity: 'success' | 'info' | 'warn' | 'error';
summary: string;
detail: string;
life?: number;
}
export interface ComfyDialog {
prompt(options: { title: string; message: string }): Promise<string>;
confirm(options: { title: string; message: string }): Promise<boolean>;
}
// ============================================================================
// ComfyUI Graph
// ============================================================================
export interface ComfyGraph {
_nodes: ComfyNode[];
getNodeById(id: number): ComfyNode | null;
}
export interface ComfyNode {
id: number;
title: string;
type: string;
mode: number;
pos: [number, number];
size: [number, number];
flags?: {
collapsed?: boolean;
};
widgets?: ComfyWidget[];
inputs?: ComfySlot[];
outputs?: ComfySlot[];
properties?: Record<string, unknown>;
}
export interface ComfyWidget {
name: string;
type: string;
value: unknown;
options?: Record<string, unknown>;
min?: number;
max?: number;
step?: number;
}
export interface ComfySlot {
name: string;
type: string;
link?: number | null;
links?: number[];
}
// ============================================================================
// ComfyUI Canvas
// ============================================================================
export interface ComfyCanvas {
canvas: HTMLCanvasElement;
ds: {
scale: number;
offset: [number, number];
};
node_over: ComfyNode | null;
convertOffsetToCanvasPos?(pos: [number, number]): [number, number];
}
// ============================================================================
// Global Window Extensions
// ============================================================================
declare global {
interface Window {
comfyUIMagnifyGlass?: MagnifyGlassInstance;
magnifyGlass?: MagnifyGlassInstance; // Alias used by info panel controls
comfyUIMagnifyGlassExtensions?: unknown[];
infoPanelManager?: { uiManager?: { updateTheme: (theme: string) => void } };
}
var app: ComfyApp;
}
export interface MagnifyGlassInstance {
state: MagnifyGlassState;
config: MagnifyGlassConfig;
ui: MagnifyGlassUI;
renderer: MagnifyGlassRenderer | null;
lastKnownMousePosition: { x: number; y: number };
isOverMedia: boolean;
currentMediaElement: HTMLImageElement | HTMLVideoElement | null;
updateMagnifiedView(): void;
applyUiChanges(): void;
toggle(): void;
resetOffsets(): void;
}
export interface MagnifyGlassState {
active: boolean;
x: number;
y: number;
sourceX: number;
sourceY: number;
sourceWidth: number;
sourceHeight: number;
canvasScale: number;
canvasOffsetX: number;
canvasOffsetY: number;
}
export interface MagnifyGlassConfig {
zoomFactor: number;
glassSize: number;
borderColor: string;
borderWidth: number;
borderEnabled: boolean;
activationKey: string;
altRequired: boolean;
followCursor: boolean;
debugMode: boolean;
offsetStep: number;
offsetX: number;
offsetY: number;
glassPosition: string;
glassShape: string;
resetKey: string;
textureFiltering: string;
alwaysActiveMode: boolean;
toggleFollowCursorKey: string;
}
export interface MagnifyGlassUI {
glassDiv: HTMLDivElement | null;
show(): void;
hide(): void;
positionGlass(x: number, y: number): void;
}
export interface MagnifyGlassRenderer {
updateTextureFiltering(filtering: string): void;
}
// ============================================================================
// Info Panel Types
// ============================================================================
/**
* Information gathered about the current cursor position.
* Returned by InformationGatherer.gatherInformation()
*/
export interface GatheredInfo {
timestamp: number;
cursor: {
screenX: number;
screenY: number;
canvasX: number;
canvasY: number;
};
zoom: number;
nodeCount: number;
hoveredNode: NodeInfo | null;
hoveredWidget: WidgetInfo | null;
mediaElement: MediaInfo | null;
}
/**
* Detailed information about a node.
* Structure matches InformationGatherer.getDetailedNodeInfo() output.
*/
export interface NodeInfo {
id: number;
title: string;
type: string;
mode: string | number;
position: {
x: number;
y: number;
formatted?: string;
} | string;
size: {
width: number;
height: number;
formatted?: string;
} | string;
localPosition?: {
x: number;
y: number;
formatted?: string;
percentage?: { x: string; y: string };
};
counts?: {
widgets: number;
inputs: number;
outputs: number;
properties: number;
};
widgets: ComfyWidget[];
inputs: ComfyInput[];
outputs: ComfyOutput[];
properties: Record<string, unknown>;
hoverRegion?: string;
}
/**
* Information about a widget.
*/
export interface WidgetInfo {
name: string;
type: string;
value: string;
options?: unknown;
min?: number;
max?: number;
step?: number;
}
/**
* Information about a media element (image or video).
*/
export interface MediaInfo {
type: 'image' | 'video';
tagName: string;
src: string;
naturalWidth: number;
naturalHeight: number;
displayWidth: number;
displayHeight: number;
aspectRatio: string;
duration?: number;
currentTime?: number;
}
/**
* A section in the info panel display.
*/
export interface SectionData {
id: string;
title: string;
icon: string;
visible: boolean;
expanded: boolean;
content: ParameterItem[];
}
/**
* A parameter item displayed in a section.
*/
export interface ParameterItem {
label: string;
value: unknown;
formattedValue?: string;
highlight?: boolean;
}
/**
* Settings change tracking.
*/
export interface SettingsChange {
old: unknown;
new: unknown;
}
export { };
+5
View File
@@ -0,0 +1,5 @@
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
+12
View File
@@ -0,0 +1,12 @@
import { test, expect } from '@playwright/test';
test('magnify glass extension loads', async ({ page }) => {
// This is a placeholder test.
// To test ComfyUI, you would typically need to start the ComfyUI server and navigate to it.
// console.log('This test needs a running ComfyUI instance to verify the extension.');
// Example of what we might check if ComfyUI was running locally:
// await page.goto('http://127.0.0.1:8188');
// await expect(page).toHaveTitle(/ComfyUI/);
// await expect(page.locator('.magnify-glass-icon')).toBeVisible(); // Hypothetical check
});
+15
View File
@@ -0,0 +1,15 @@
/**
* Mock for ComfyUI app object
* Used in tests to avoid importing actual ComfyUI modules
*/
export const app = {
ui: {
settings: {
getSettingValue: (key: string) => undefined,
addSetting: () => { }
}
},
canvas: null,
graph: null
};
+117
View File
@@ -0,0 +1,117 @@
/**
* ConfigManager Unit Tests
*
* Tests for the ConfigManager class which handles settings and offset management.
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
// Mock localStorage
const localStorageMock = (() => {
let store: Record<string, string> = {};
return {
getItem: (key: string) => store[key] || null,
setItem: (key: string, value: string) => { store[key] = value; },
removeItem: (key: string) => { delete store[key]; },
clear: () => { store = {}; }
};
})();
// Mock global app object for getSettingValue
vi.mock('/scripts/app.js', () => ({
app: {
ui: {
settings: {
getSettingValue: (key: string) => undefined
}
}
}
}));
// Apply localStorage mock
Object.defineProperty(globalThis, 'localStorage', {
value: localStorageMock
});
// Import after mocks are set up
import { ConfigManager } from '../../src/magnify-glass/ConfigManager';
describe('ConfigManager', () => {
let configManager: ConfigManager;
beforeEach(() => {
localStorageMock.clear();
configManager = new ConfigManager();
});
describe('constructor', () => {
it('should initialize with default values', () => {
expect(configManager.zoomFactor).toBe(3); // 300 / 100
expect(configManager.glassSize).toBe(300);
expect(configManager.borderColor).toBe('#6b7280');
expect(configManager.borderWidth).toBe(1);
expect(configManager.activationKey).toBe('x');
expect(configManager.altRequired).toBe(false);
expect(configManager.followCursor).toBe(false);
expect(configManager.debugMode).toBe(false);
});
it('should initialize offsets to zero', () => {
expect(configManager.offsetX).toBe(0);
expect(configManager.offsetY).toBe(0);
});
});
describe('loadSavedOffsets', () => {
it('should load offsets from localStorage', () => {
localStorageMock.setItem('comfyui_magnify_offset_x', '50');
localStorageMock.setItem('comfyui_magnify_offset_y', '-25');
configManager.loadSavedOffsets();
expect(configManager.offsetX).toBe(50);
expect(configManager.offsetY).toBe(-25);
});
it('should default to zero if localStorage is empty', () => {
configManager.loadSavedOffsets();
expect(configManager.offsetX).toBe(0);
expect(configManager.offsetY).toBe(0);
});
});
describe('saveOffsets', () => {
it('should save offsets to localStorage', () => {
configManager.offsetX = 100;
configManager.offsetY = -50;
configManager.saveOffsets();
expect(localStorageMock.getItem('comfyui_magnify_offset_x')).toBe('100');
expect(localStorageMock.getItem('comfyui_magnify_offset_y')).toBe('-50');
});
});
describe('resetOffsets', () => {
it('should reset offsets to zero', () => {
configManager.offsetX = 100;
configManager.offsetY = -50;
configManager.resetOffsets();
expect(configManager.offsetX).toBe(0);
expect(configManager.offsetY).toBe(0);
});
it('should save reset offsets to localStorage', () => {
configManager.offsetX = 100;
configManager.offsetY = -50;
configManager.resetOffsets();
expect(localStorageMock.getItem('comfyui_magnify_offset_x')).toBe('0');
expect(localStorageMock.getItem('comfyui_magnify_offset_y')).toBe('0');
});
});
});
+158
View File
@@ -0,0 +1,158 @@
/**
* InformationGatherer Unit Tests
*
* Tests for the InformationGatherer class which collects node and canvas information.
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
// Mock ComfyUI app
vi.mock('/scripts/app.js', () => ({
app: {
graph: {
_nodes: []
},
canvas: {
canvas: {
getBoundingClientRect: () => ({ left: 0, top: 0, width: 800, height: 600, right: 800, bottom: 600 })
},
node_over: null,
ds: { scale: 1, offset: [0, 0] }
}
}
}));
// Mock window.comfyUIMagnifyGlass
const mockMagnifyGlass = {
state: {
x: 100,
y: 100,
canvasScale: 1,
canvasOffsetX: 0,
canvasOffsetY: 0,
sourceX: 50,
sourceY: 50,
sourceWidth: 100,
sourceHeight: 100
},
config: {
zoomFactor: 3,
offsetX: 0,
offsetY: 0
},
lastKnownMousePosition: { x: 200, y: 200 },
isOverMedia: false,
currentMediaElement: null
};
Object.defineProperty(globalThis, 'window', {
value: {
comfyUIMagnifyGlass: mockMagnifyGlass
},
writable: true
});
import { InformationGatherer } from '../../src/info-panel/InformationGatherer';
describe('InformationGatherer', () => {
let gatherer: InformationGatherer;
beforeEach(() => {
gatherer = new InformationGatherer();
// Reset mock state
mockMagnifyGlass.isOverMedia = false;
mockMagnifyGlass.currentMediaElement = null;
});
describe('constructor', () => {
it('should create an instance', () => {
expect(gatherer).toBeDefined();
});
});
describe('gatherInformation', () => {
it('should return a GatheredInfo object with required fields', () => {
const info = gatherer.gatherInformation();
expect(info).toHaveProperty('timestamp');
expect(info).toHaveProperty('cursor');
expect(info).toHaveProperty('zoom');
expect(info).toHaveProperty('nodeCount');
expect(info).toHaveProperty('hoveredNode');
expect(info).toHaveProperty('hoveredWidget');
expect(info).toHaveProperty('mediaElement');
});
it('should return cursor position from magnifyGlass state', () => {
const info = gatherer.gatherInformation();
expect(info.cursor.screenX).toBe(200);
expect(info.cursor.screenY).toBe(200);
expect(info.cursor.canvasX).toBe(100);
expect(info.cursor.canvasY).toBe(100);
});
it('should return zoom from canvas scale', () => {
const info = gatherer.gatherInformation();
expect(info.zoom).toBe(1);
});
it('should return null for hoveredNode when no node is hovered', () => {
const info = gatherer.gatherInformation();
expect(info.hoveredNode).toBeNull();
});
});
describe('formatValue', () => {
it('should format null values', () => {
expect(gatherer.formatValue(null)).toBe('null');
});
it('should format undefined values', () => {
expect(gatherer.formatValue(undefined)).toBe('undefined');
});
it('should format string values as-is', () => {
expect(gatherer.formatValue('hello world')).toBe('hello world');
});
it('should format integer values without decimals', () => {
expect(gatherer.formatValue(42)).toBe('42');
});
it('should format float values with 3 decimals', () => {
expect(gatherer.formatValue(3.14159)).toBe('3.142');
});
it('should format boolean values', () => {
expect(gatherer.formatValue(true)).toBe('true');
expect(gatherer.formatValue(false)).toBe('false');
});
it('should format arrays with length', () => {
expect(gatherer.formatValue([1, 2, 3])).toBe('Array(3)');
});
it('should format objects as "Object"', () => {
expect(gatherer.formatValue({ key: 'value' })).toBe('Object');
});
});
describe('getNodeModeText', () => {
it('should return "Always" for mode 0', () => {
expect(gatherer.getNodeModeText(0)).toBe('Always');
});
it('should return "On Event" for mode 1', () => {
expect(gatherer.getNodeModeText(1)).toBe('On Event');
});
it('should return "Never" for mode 2', () => {
expect(gatherer.getNodeModeText(2)).toBe('Never');
});
it('should return fallback for unknown modes', () => {
expect(gatherer.getNodeModeText(99)).toBe('Mode 99');
});
});
});
+103
View File
@@ -0,0 +1,103 @@
/**
* MagnifierState Unit Tests
*
* Tests for the MagnifierState class which manages magnifier state.
*/
import { describe, it, expect, beforeEach } from 'vitest';
import { MagnifierState } from '../../src/magnify-glass/MagnifierState';
describe('MagnifierState', () => {
let state: MagnifierState;
beforeEach(() => {
state = new MagnifierState();
});
describe('constructor', () => {
it('should initialize as inactive', () => {
expect(state.active).toBe(false);
});
it('should initialize cursor at origin', () => {
expect(state.x).toBe(0);
expect(state.y).toBe(0);
});
it('should initialize source dimensions to zero', () => {
expect(state.sourceX).toBe(0);
expect(state.sourceY).toBe(0);
expect(state.sourceWidth).toBe(0);
expect(state.sourceHeight).toBe(0);
});
it('should initialize canvas scale to 1', () => {
expect(state.canvasScale).toBe(1.0);
});
it('should initialize canvas offsets to zero', () => {
expect(state.canvasOffsetX).toBe(0);
expect(state.canvasOffsetY).toBe(0);
});
it('should not be scheduled for render initially', () => {
expect(state.isRenderScheduled).toBe(false);
});
});
describe('reset', () => {
it('should reset all state values to defaults', () => {
// Modify state
state.active = true;
state.x = 100;
state.y = 200;
state.sourceX = 50;
state.sourceY = 75;
state.canvasScale = 2.5;
// Reset
state.reset();
// Verify defaults
expect(state.active).toBe(false);
expect(state.x).toBe(0);
expect(state.y).toBe(0);
expect(state.sourceX).toBe(0);
expect(state.sourceY).toBe(0);
expect(state.canvasScale).toBe(1.0);
});
it('should reset wasActivatedBefore flag', () => {
state.wasActivatedBefore = true;
state.reset();
expect(state.wasActivatedBefore).toBe(false);
});
});
describe('state mutations', () => {
it('should allow setting active state', () => {
state.active = true;
expect(state.active).toBe(true);
});
it('should allow setting cursor position', () => {
state.x = 150;
state.y = 250;
expect(state.x).toBe(150);
expect(state.y).toBe(250);
});
it('should allow setting canvas transform values', () => {
state.canvasScale = 3.0;
state.canvasOffsetX = -100;
state.canvasOffsetY = -200;
expect(state.canvasScale).toBe(3.0);
expect(state.canvasOffsetX).toBe(-100);
expect(state.canvasOffsetY).toBe(-200);
});
});
});
+268
View File
@@ -0,0 +1,268 @@
/**
* StateManager Unit Tests
*
* Tests for the StateManager class which manages info panel state.
*/
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
// Mock localStorage
const localStorageMock = (() => {
let store: Record<string, string> = {};
return {
getItem: (key: string) => store[key] || null,
setItem: (key: string, value: string) => { store[key] = value; },
removeItem: (key: string) => { delete store[key]; },
clear: () => { store = {}; }
};
})();
Object.defineProperty(globalThis, 'localStorage', {
value: localStorageMock
});
// Mock window
Object.defineProperty(globalThis, 'window', {
value: {
matchMedia: () => ({
addListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
}),
infoPanelManager: null
},
writable: true
});
// Mock document
Object.defineProperty(globalThis, 'document', {
value: {
body: {
getAttribute: () => null,
className: ''
},
documentElement: {
getAttribute: () => null,
className: ''
},
querySelector: () => null,
querySelectorAll: () => [],
addEventListener: vi.fn()
},
writable: true
});
// Mock getComputedStyle
(globalThis as any).getComputedStyle = () => ({
backgroundColor: 'rgb(30, 30, 30)'
});
// Mock MutationObserver
(globalThis as any).MutationObserver = class {
observe = vi.fn();
disconnect = vi.fn();
takeRecords = vi.fn();
};
// Mock app object for settings
vi.mock('/scripts/app.js', () => ({
app: {
ui: {
settings: {
getSettingValue: (key: string) => undefined
}
}
}
}));
import { StateManager } from '../../src/info-panel/StateManager';
describe('StateManager', () => {
let stateManager: StateManager;
beforeEach(() => {
vi.useFakeTimers();
stateManager = new StateManager();
});
afterEach(() => {
vi.useRealTimers();
stateManager.cleanup();
});
describe('constructor', () => {
it('should initialize with default state values', () => {
expect(stateManager.state.isPanelVisible).toBe(false);
expect(stateManager.state.isPanelMinimized).toBe(false);
expect(stateManager.state.isPanelPinned).toBe(false);
expect(stateManager.state.isPanelLocked).toBe(false);
});
it('should initialize glass preview as visible', () => {
expect(stateManager.state.isGlassPreviewVisible).toBe(true);
});
it('should initialize with node section expanded', () => {
expect(stateManager.state.expandedSections.has('node')).toBe(true);
});
it('should initialize currentInfo as null', () => {
expect(stateManager.state.currentInfo).toBeNull();
});
it('should initialize with dark theme as default', () => {
expect(stateManager.state.currentTheme).toBe('dark');
});
});
describe('togglePanelVisibility', () => {
it('should toggle panel visibility', () => {
expect(stateManager.state.isPanelVisible).toBe(false);
stateManager.togglePanelVisibility();
expect(stateManager.state.isPanelVisible).toBe(true);
stateManager.togglePanelVisibility();
expect(stateManager.state.isPanelVisible).toBe(false);
});
it('should return new visibility state', () => {
expect(stateManager.togglePanelVisibility()).toBe(true);
expect(stateManager.togglePanelVisibility()).toBe(false);
});
});
describe('toggleGlassPreview', () => {
it('should toggle glass preview visibility', () => {
expect(stateManager.state.isGlassPreviewVisible).toBe(true);
stateManager.toggleGlassPreview();
expect(stateManager.state.isGlassPreviewVisible).toBe(false);
stateManager.toggleGlassPreview();
expect(stateManager.state.isGlassPreviewVisible).toBe(true);
});
});
describe('togglePinning', () => {
it('should toggle pinned state', () => {
expect(stateManager.state.isPanelPinned).toBe(false);
stateManager.togglePinning();
expect(stateManager.state.isPanelPinned).toBe(true);
stateManager.togglePinning();
expect(stateManager.state.isPanelPinned).toBe(false);
});
it('should clear locked state when unpinning', () => {
stateManager.state.isPanelPinned = true;
stateManager.state.isPanelLocked = true;
stateManager.togglePinning(); // Unpin
expect(stateManager.state.isPanelLocked).toBe(false);
});
});
describe('toggleLocking', () => {
it('should not allow locking when not pinned', () => {
stateManager.state.isPanelPinned = false;
const result = stateManager.toggleLocking();
expect(result).toBe(false);
expect(stateManager.state.isPanelLocked).toBe(false);
});
it('should toggle locking when pinned', () => {
stateManager.state.isPanelPinned = true;
stateManager.toggleLocking();
expect(stateManager.state.isPanelLocked).toBe(true);
stateManager.toggleLocking();
expect(stateManager.state.isPanelLocked).toBe(false);
});
});
describe('toggleMinimized', () => {
it('should toggle minimized state', () => {
expect(stateManager.state.isPanelMinimized).toBe(false);
stateManager.toggleMinimized();
expect(stateManager.state.isPanelMinimized).toBe(true);
stateManager.toggleMinimized();
expect(stateManager.state.isPanelMinimized).toBe(false);
});
});
describe('toggleSection', () => {
it('should not toggle node section (always expanded)', () => {
const result = stateManager.toggleSection('node');
expect(result).toBe(false);
});
it('should toggle other sections', () => {
expect(stateManager.state.expandedSections.has('media')).toBe(false);
stateManager.toggleSection('media');
expect(stateManager.state.expandedSections.has('media')).toBe(true);
stateManager.toggleSection('media');
expect(stateManager.state.expandedSections.has('media')).toBe(false);
});
});
describe('setPinnedPosition', () => {
it('should set pinned position', () => {
stateManager.setPinnedPosition(100, 200);
expect(stateManager.state.pinnedPosition).toEqual({ x: 100, y: 200 });
expect(stateManager.state.lastPinnedPosition).toEqual({ x: 100, y: 200 });
});
});
describe('setCurrentInfo', () => {
it('should set current info', () => {
const mockInfo = {
timestamp: Date.now(),
cursor: { screenX: 0, screenY: 0, canvasX: 0, canvasY: 0 },
zoom: 1,
nodeCount: 5,
hoveredNode: null,
hoveredWidget: null,
mediaElement: null
};
stateManager.setCurrentInfo(mockInfo);
expect(stateManager.state.currentInfo).toEqual(mockInfo);
});
});
describe('expandNodeSections', () => {
it('should expand all node-related sections', () => {
stateManager.expandNodeSections();
expect(stateManager.state.expandedSections.has('hoveredNode')).toBe(true);
expect(stateManager.state.expandedSections.has('node')).toBe(true);
expect(stateManager.state.expandedSections.has('cursor')).toBe(true);
expect(stateManager.state.expandedSections.has('canvas')).toBe(true);
expect(stateManager.state.expandedSections.has('magnifier')).toBe(true);
});
});
describe('collapseNodeSections', () => {
it('should collapse node-related sections', () => {
stateManager.state.expandedSections.add('hoveredNode');
stateManager.state.expandedSections.add('widget');
stateManager.collapseNodeSections();
expect(stateManager.state.expandedSections.has('hoveredNode')).toBe(false);
expect(stateManager.state.expandedSections.has('widget')).toBe(false);
});
});
});
+29
View File
@@ -0,0 +1,29 @@
import { describe, it, expect } from 'vitest';
import { clamp, normalizeColor } from '../../src/shared/utils';
describe('Shared Utilities', () => {
describe('clamp', () => {
it('should clamp value within range', () => {
expect(clamp(150, 0, 100)).toBe(100);
expect(clamp(-50, 0, 100)).toBe(0);
expect(clamp(50, 0, 100)).toBe(50);
});
});
describe('normalizeColor', () => {
it('should add # prefix if missing', () => {
expect(normalizeColor('ffffff')).toBe('#ffffff');
expect(normalizeColor('000')).toBe('#000');
});
it('should keep # prefix if present', () => {
expect(normalizeColor('#ff0000')).toBe('#ff0000');
});
it('should handle falsy values', () => {
expect(normalizeColor('')).toBe('');
expect(normalizeColor(null)).toBe('');
expect(normalizeColor(undefined)).toBe('');
});
});
});
+11
View File
@@ -0,0 +1,11 @@
{
"clones": {
"count": 21,
"uniques": 20
},
"views": {
"count": 21,
"uniques": 16
},
"timestamp": "2026-01-02T07:22:08.007Z"
}
+44
View File
@@ -0,0 +1,44 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": [
"ES2022",
"DOM",
"DOM.Iterable"
],
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"allowSyntheticDefaultImports": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"baseUrl": ".",
"paths": {
"@shared/*": [
"src/shared/*"
],
"@magnify-glass/*": [
"src/magnify-glass/*"
],
"@info-panel/*": [
"src/info-panel/*"
]
}
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts"
],
"exclude": [
"node_modules",
"dist",
"web"
]
}
+42
View File
@@ -0,0 +1,42 @@
/// <reference types="vitest" />
import { defineConfig } from 'vite';
import { resolve } from 'path';
export default defineConfig({
build: {
lib: {
entry: {
'magnify_glass': resolve(__dirname, 'src/magnify_glass.ts'),
'magnify_info_panel': resolve(__dirname, 'src/magnify_info_panel.ts')
},
formats: ['es'],
fileName: (format, entryName) => `${entryName}.js`
},
outDir: 'web',
emptyOutDir: false, // Keep existing files
rollupOptions: {
external: [
/^\/scripts\//, // Match /scripts/ (Absolute path)
/^\.\.\/\.\.\/scripts\//, // Match ../../scripts/ (Browser path - deprecated)
],
output: {
preserveModules: true,
preserveModulesRoot: 'src',
entryFileNames: '[name].js',
}
},
sourcemap: true,
minify: false // Keep readable for debugging
},
resolve: {
alias: {
'@shared': resolve(__dirname, 'src/shared'),
'@magnify-glass': resolve(__dirname, 'src/magnify-glass'),
'@info-panel': resolve(__dirname, 'src/info-panel')
}
},
test: {
environment: 'happy-dom',
globals: true
}
});
+22
View File
@@ -0,0 +1,22 @@
import { defineConfig } from 'vitest/config';
import path from 'path';
export default defineConfig({
test: {
globals: true,
environment: 'happy-dom',
include: ['tests/unit/**/*.test.ts'],
exclude: ['node_modules', 'web'],
coverage: {
reporter: ['text', 'html'],
include: ['src/**/*.ts'],
exclude: ['src/types/**']
}
},
resolve: {
alias: {
'/scripts/app.js': path.resolve(__dirname, 'tests/mocks/app.ts')
}
}
});
+664
View File
@@ -0,0 +1,664 @@
/**
* ComfyUI MagnifyGlass - Info Panel Styles
*
* Complete CSS styles for the info panel component.
*/
/* SVG Icon Styling */
.magnify-info-panel svg,
.floating-controls svg {
width: 1em;
height: 1em;
vertical-align: middle;
fill: none;
stroke: currentColor;
pointer-events: none;
/* Allow clicks to pass through to button */
}
.header-icon svg {
width: 18px;
height: 18px;
}
.section-icon svg {
width: 18px;
height: 18px;
}
.control-btn svg {
width: 14px;
height: 14px;
}
.expand-icon svg {
width: 12px;
height: 12px;
}
.empty-state-icon svg {
width: 36px;
height: 36px;
stroke-width: 1.5;
}
.magnify-info-panel {
border-radius: 12px;
backdrop-filter: blur(20px);
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3), 0 0 0 1px rgba(255, 255, 255, 0.1);
overflow: hidden;
font-size: 16px;
line-height: 1.6;
pointer-events: auto;
}
.magnify-info-panel * {
pointer-events: auto;
}
.magnify-info-panel.theme-dark {
background: linear-gradient(135deg, rgba(0, 0, 0, 0.96), rgba(10, 10, 15, 0.96));
color: var(--info-panel-text-color, #e0e0e0);
border: 1px solid rgba(100, 100, 120, 0.4);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 2px 16px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(12px);
}
.magnify-info-panel.theme-light {
background: linear-gradient(135deg, rgba(250, 250, 255, 0.96), rgba(240, 240, 250, 0.96));
color: var(--info-panel-text-color, #2a2a2a);
border: 1px solid rgba(200, 200, 220, 0.5);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1), 0 2px 16px rgba(0, 0, 0, 0.05);
backdrop-filter: blur(12px);
}
/* Solarized Theme - warm, muted tones */
.magnify-info-panel.theme-solarized {
background: linear-gradient(135deg, rgba(0, 43, 54, 0.96), rgba(7, 54, 66, 0.96));
color: var(--info-panel-text-color, #839496);
border: 1px solid rgba(88, 110, 117, 0.5);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 2px 16px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(12px);
--info-panel-accent-color: #268bd2;
}
/* Arc Theme - modern blue-gray */
.magnify-info-panel.theme-arc {
background: linear-gradient(135deg, rgba(56, 60, 74, 0.96), rgba(64, 69, 82, 0.96));
color: var(--info-panel-text-color, #d3dae3);
border: 1px solid rgba(90, 100, 120, 0.5);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25), 0 2px 16px rgba(0, 0, 0, 0.15);
backdrop-filter: blur(12px);
--info-panel-accent-color: #5294e2;
}
/* Nord Theme - cool arctic colors */
.magnify-info-panel.theme-nord {
background: linear-gradient(135deg, rgba(46, 52, 64, 0.96), rgba(59, 66, 82, 0.96));
color: var(--info-panel-text-color, #d8dee9);
border: 1px solid rgba(76, 86, 106, 0.5);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25), 0 2px 16px rgba(0, 0, 0, 0.15);
backdrop-filter: blur(12px);
--info-panel-accent-color: #88c0d0;
}
/* GitHub Theme - clean, professional */
.magnify-info-panel.theme-github {
background: linear-gradient(135deg, rgba(255, 255, 255, 0.96), rgba(246, 248, 250, 0.96));
color: var(--info-panel-text-color, #24292e);
border: 1px solid rgba(225, 228, 232, 0.8);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1), 0 2px 16px rgba(0, 0, 0, 0.05);
backdrop-filter: blur(12px);
--info-panel-accent-color: #0366d6;
}
.magnify-info-panel.visible {
transform: translateY(0) !important;
}
.magnify-info-panel.panel-pinned {
cursor: grab;
box-shadow: 0 0 0 2px rgba(255, 215, 0, 0.5), 0 20px 40px rgba(0, 0, 0, 0.3);
}
.magnify-info-panel.panel-locked {
cursor: default !important;
box-shadow: 0 0 0 2px rgba(255, 69, 0, 0.5), 0 20px 40px rgba(0, 0, 0, 0.3);
}
.magnify-info-panel.panel-locked::after {
content: '📌';
position: absolute;
top: 8px;
right: 8px;
font-size: 14px;
opacity: 0.7;
pointer-events: none;
z-index: 1;
}
.magnify-info-panel.panel-pinned.panel-dragging {
cursor: grabbing;
box-shadow: 0 25px 50px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(255, 215, 0, 0.7);
transform: scale(1.02) !important;
z-index: 100001 !important;
transition: none !important;
}
.magnify-info-panel.panel-pinned::before {
content: '';
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background: linear-gradient(45deg, rgba(255, 215, 0, 0.05) 0%, transparent 100%);
pointer-events: none;
border-radius: inherit;
}
.panel-dragging * {
pointer-events: none !important;
user-select: none !important;
transition: none !important;
}
.magnify-info-panel.panel-minimized .panel-content {
max-height: 0 !important;
overflow: hidden;
transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.floating-controls {
position: fixed;
display: none;
/* Hidden initially - JS will show when positioned */
padding: 4px;
background: rgba(40, 40, 50, 0.95);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 4px;
opacity: 1;
z-index: 100000;
backdrop-filter: blur(8px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
}
.floating-controls.vertical-layout {
flex-direction: column;
gap: 4px;
}
.floating-controls.horizontal-layout {
flex-direction: row;
gap: 4px;
}
.control-btn {
background: rgba(60, 60, 70, 0.8);
border: 1px solid rgba(255, 255, 255, 0.2);
width: 28px;
height: 28px;
font-size: 14px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
color: #ddd;
border-radius: 3px;
transition: background-color 0.15s ease;
}
.control-btn:hover {
background: rgba(80, 80, 90, 0.9);
color: white;
}
.control-btn:active {
background: rgba(100, 100, 110, 0.9);
}
.control-btn:disabled {
background: rgba(40, 40, 50, 0.5);
color: #666;
cursor: not-allowed;
opacity: 0.5;
}
.control-btn.active {
background: rgba(255, 200, 50, 0.3);
border-color: rgba(255, 200, 50, 0.6);
color: #ffcc33;
}
.control-btn.lock-btn.active {
background: rgba(255, 69, 0, 0.3);
border-color: rgba(255, 69, 0, 0.6);
color: #ff4500;
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 18px;
background: linear-gradient(135deg, rgba(0, 0, 0, 0.1), rgba(255, 255, 255, 0.05));
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
user-select: none;
cursor: grab;
transition: background 0.15s ease;
}
.panel-header:hover {
background: linear-gradient(135deg, rgba(0, 0, 0, 0.15), rgba(255, 255, 255, 0.08));
}
.panel-header:active {
cursor: grabbing;
}
.header-content {
display: flex;
align-items: center;
gap: 10px;
}
.header-icon {
font-size: 18px;
opacity: 0.9;
}
.header-title {
font-weight: 600;
font-size: 18px;
}
.header-subtitle {
font-size: 14px;
opacity: 0.7;
font-style: italic;
}
.header-controls {
display: flex;
gap: 6px;
}
.minimize-btn {
background: rgba(255, 255, 255, 0.1);
border: none;
border-radius: 6px;
color: inherit;
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s;
font-weight: bold;
font-size: 16px;
}
.minimize-btn:hover {
background: rgba(255, 255, 255, 0.2);
transform: scale(1.05);
}
.minimize-btn:active {
transform: scale(0.95);
}
.panel-content {
padding: 0;
max-height: calc(100% - 60px);
overflow-y: auto;
scrollbar-width: thin;
}
.panel-content::-webkit-scrollbar {
width: 8px;
}
.panel-content::-webkit-scrollbar-track {
background: rgba(0, 0, 0, 0.1);
}
.panel-content::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 3px;
}
.info-section {
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
margin-bottom: 8px;
border-radius: 10px;
overflow: visible;
background: rgba(255, 255, 255, 0.02);
transition: all 0.3s ease;
}
.info-section:hover {
background: rgba(255, 255, 255, 0.04);
transform: translateY(-1px);
}
.section-header {
display: flex;
align-items: center;
gap: 12px;
padding: 16px 20px;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
font-weight: 500;
border-radius: 8px;
margin: 3px;
position: relative;
overflow: hidden;
}
.section-header::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.05) 50%, transparent 100%);
transform: translateX(-100%);
transition: transform 0.6s ease;
}
.section-header:hover::before {
transform: translateX(100%);
}
.section-header:hover {
background: rgba(255, 255, 255, 0.08);
transform: translateX(2px);
box-shadow: inset 2px 0 0 rgba(116, 185, 255, 0.5);
}
.section-header:active {
background: rgba(255, 255, 255, 0.12);
transform: translateX(1px);
}
.section-header.expanded {
background: rgba(116, 185, 255, 0.1);
border-left: 2px solid var(--info-panel-accent-color, #74b9ff);
}
.info-section[data-section="node"] {
background: linear-gradient(135deg, rgba(116, 185, 255, 0.05), rgba(160, 212, 104, 0.05));
border: 1px solid rgba(116, 185, 255, 0.2);
border-radius: 8px;
margin: 6px;
}
.info-section[data-section="node"] .section-header {
background: linear-gradient(135deg, rgba(116, 185, 255, 0.15), rgba(160, 212, 104, 0.15));
border-radius: 8px 8px 0 0;
cursor: default;
}
.info-section[data-section="node"] .section-header:hover {
transform: none;
box-shadow: none;
}
.info-section[data-section="node"] .section-title {
color: var(--info-panel-accent-color, #74b9ff);
font-weight: 700;
}
.info-section[data-section="inspector"] {
background: linear-gradient(135deg, rgba(100, 150, 255, 0.05), rgba(74, 144, 226, 0.05));
border: 1px solid rgba(100, 150, 255, 0.2);
border-radius: 8px;
margin: 6px;
}
.info-section[data-section="inspector"] .section-header {
background: linear-gradient(135deg, rgba(100, 150, 255, 0.15), rgba(74, 144, 226, 0.15));
border-radius: 8px 8px 0 0;
}
.info-section[data-section="inspector"] .section-title {
color: #6496ff;
font-weight: 700;
}
.info-section[data-section="media"] {
background: linear-gradient(135deg, rgba(253, 203, 110, 0.05), rgba(255, 215, 0, 0.05));
border: 1px solid rgba(253, 203, 110, 0.2);
border-radius: 8px;
margin: 6px;
}
.info-section[data-section="media"] .section-header {
background: linear-gradient(135deg, rgba(253, 203, 110, 0.15), rgba(255, 215, 0, 0.15));
border-radius: 8px 8px 0 0;
}
.info-section[data-section="media"] .section-title {
color: var(--info-panel-accent-color, #fdcb6e);
font-weight: 700;
}
.section-icon {
font-size: 18px;
width: 22px;
text-align: center;
}
.section-title {
flex: 1;
font-size: 16px;
font-weight: 600;
letter-spacing: 0.3px;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.section-badge {
background: rgba(100, 150, 255, 0.2);
color: #8bb3ff;
padding: 3px 10px;
border-radius: 10px;
font-size: 13px;
font-weight: 500;
}
.expand-icon {
font-size: 14px;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
color: rgba(255, 255, 255, 0.6);
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
background: rgba(255, 255, 255, 0.05);
margin-left: auto;
}
.section-header:hover .expand-icon {
color: var(--info-panel-accent-color, #74b9ff);
background: rgba(116, 185, 255, 0.15);
transform: scale(1.1);
}
.section-header.expanded .expand-icon {
transform: rotate(90deg) scale(1.1);
color: var(--info-panel-accent-color, #74b9ff);
background: rgba(116, 185, 255, 0.2);
}
.section-content {
max-height: 0;
overflow: visible;
transition: max-height 0.4s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s ease;
opacity: 0;
}
.section-content.expanded {
max-height: 2000px;
opacity: 1;
overflow: visible;
}
.section-body {
padding: 0 18px 16px 24px;
}
.info-row {
display: flex;
justify-content: space-between;
align-items: flex-start;
padding: 10px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
transition: all 0.2s ease;
border-radius: 4px;
margin: 0 -8px;
padding-left: 8px;
padding-right: 8px;
}
.info-row:last-child {
border-bottom: none;
}
.info-row:hover {
background: rgba(255, 255, 255, 0.03);
border-bottom-color: rgba(255, 255, 255, 0.08);
}
.info-label {
font-weight: 500;
opacity: 0.85;
font-size: 15px;
min-width: 80px;
padding-right: 12px;
line-height: 1.5;
}
.info-value {
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
font-size: 14px;
color: var(--info-panel-accent-color, #a0d468);
background: rgba(160, 212, 104, 0.12);
padding: 4px 10px;
border-radius: 6px;
max-width: 100%;
word-wrap: break-word;
word-break: break-word;
hyphens: auto;
line-height: 1.4;
text-align: left;
white-space: pre-wrap;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
transition: all 0.2s ease;
}
.info-value:hover {
background: rgba(160, 212, 104, 0.18);
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
.info-value.long-text {
white-space: pre-wrap;
word-wrap: break-word;
max-width: 100%;
line-height: 1.4;
}
.empty-state {
text-align: center;
padding: 50px 25px;
opacity: 0.6;
}
.empty-state-icon {
font-size: 36px;
margin-bottom: 15px;
opacity: 0.5;
}
.empty-state-text {
font-size: 16px;
font-style: italic;
}
/* Copy to clipboard functionality */
.info-value[title]:hover::after {
content: '📋';
position: absolute;
right: -20px;
top: 50%;
transform: translateY(-50%);
font-size: 12px;
opacity: 0.7;
}
/* Smooth loading states */
.section-body.loading {
opacity: 0.5;
pointer-events: none;
}
.section-body.loading::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 20px;
height: 20px;
border: 2px solid transparent;
border-top: 2px solid var(--info-panel-accent-color, #74b9ff);
border-radius: 50%;
animation: spin 1s linear infinite;
transform: translate(-50%, -50%);
}
@keyframes spin {
to {
transform: translate(-50%, -50%) rotate(360deg);
}
}
/* Enhanced scrollbar for better UX */
.section-body::-webkit-scrollbar {
width: 4px;
}
.section-body::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.05);
border-radius: 2px;
}
.section-body::-webkit-scrollbar-thumb {
background: var(--info-panel-accent-color, #74b9ff);
border-radius: 2px;
opacity: 0.6;
}
.section-body::-webkit-scrollbar-thumb:hover {
opacity: 1;
}
@keyframes pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.7;
}
}
.pulse {
animation: pulse 2s infinite;
}
+674
View File
@@ -0,0 +1,674 @@
/**
* ComfyUI MagnifyGlass - Info Panel Styles
*
* Complete CSS styles for the info panel component.
*/
/* SVG Icon Styling */
.magnify-info-panel svg,
.floating-controls svg {
width: 1em;
height: 1em;
vertical-align: middle;
fill: none;
stroke: currentColor;
pointer-events: none;
/* Allow clicks to pass through to button */
}
.header-icon svg {
width: 18px;
height: 18px;
}
.section-icon svg {
width: 18px;
height: 18px;
}
.control-btn svg {
width: 14px;
height: 14px;
}
.expand-icon svg {
width: 12px;
height: 12px;
}
.empty-state-icon svg {
width: 36px;
height: 36px;
stroke-width: 1.5;
}
.magnify-info-panel {
border-radius: 12px;
backdrop-filter: blur(20px);
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3), 0 0 0 1px rgba(255, 255, 255, 0.1);
overflow: hidden;
font-size: 16px;
line-height: 1.6;
pointer-events: auto;
display: flex;
flex-direction: column;
}
.magnify-info-panel * {
pointer-events: auto;
}
.magnify-info-panel.theme-dark {
background: linear-gradient(135deg, rgba(0, 0, 0, 0.96), rgba(10, 10, 15, 0.96));
color: var(--info-panel-text-color, #e0e0e0);
border: 1px solid rgba(100, 100, 120, 0.4);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 2px 16px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(12px);
}
.magnify-info-panel.theme-light {
background: linear-gradient(135deg, rgba(250, 250, 255, 0.96), rgba(240, 240, 250, 0.96));
color: var(--info-panel-text-color, #2a2a2a);
border: 1px solid rgba(200, 200, 220, 0.5);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1), 0 2px 16px rgba(0, 0, 0, 0.05);
backdrop-filter: blur(12px);
}
/* Solarized Theme - warm, muted tones */
.magnify-info-panel.theme-solarized {
background: linear-gradient(135deg, rgba(0, 43, 54, 0.96), rgba(7, 54, 66, 0.96));
color: var(--info-panel-text-color, #839496);
border: 1px solid rgba(88, 110, 117, 0.5);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 2px 16px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(12px);
--info-panel-accent-color: #268bd2;
}
/* Arc Theme - modern blue-gray */
.magnify-info-panel.theme-arc {
background: linear-gradient(135deg, rgba(56, 60, 74, 0.96), rgba(64, 69, 82, 0.96));
color: var(--info-panel-text-color, #d3dae3);
border: 1px solid rgba(90, 100, 120, 0.5);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25), 0 2px 16px rgba(0, 0, 0, 0.15);
backdrop-filter: blur(12px);
--info-panel-accent-color: #5294e2;
}
/* Nord Theme - cool arctic colors */
.magnify-info-panel.theme-nord {
background: linear-gradient(135deg, rgba(46, 52, 64, 0.96), rgba(59, 66, 82, 0.96));
color: var(--info-panel-text-color, #d8dee9);
border: 1px solid rgba(76, 86, 106, 0.5);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25), 0 2px 16px rgba(0, 0, 0, 0.15);
backdrop-filter: blur(12px);
--info-panel-accent-color: #88c0d0;
}
/* GitHub Theme - clean, professional */
.magnify-info-panel.theme-github {
background: linear-gradient(135deg, rgba(255, 255, 255, 0.96), rgba(246, 248, 250, 0.96));
color: var(--info-panel-text-color, #24292e);
border: 1px solid rgba(225, 228, 232, 0.8);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1), 0 2px 16px rgba(0, 0, 0, 0.05);
backdrop-filter: blur(12px);
--info-panel-accent-color: #0366d6;
}
.magnify-info-panel.visible {
transform: translateY(0) !important;
}
.magnify-info-panel.panel-pinned {
cursor: grab;
box-shadow: 0 0 0 2px rgba(255, 215, 0, 0.5), 0 20px 40px rgba(0, 0, 0, 0.3);
}
.magnify-info-panel.panel-locked {
cursor: default !important;
box-shadow: 0 0 0 2px rgba(255, 69, 0, 0.5), 0 20px 40px rgba(0, 0, 0, 0.3);
}
.magnify-info-panel.panel-locked::after {
content: '📌';
position: absolute;
top: 8px;
right: 8px;
font-size: 14px;
opacity: 0.7;
pointer-events: none;
z-index: 1;
}
.magnify-info-panel.panel-pinned.panel-dragging {
cursor: grabbing;
box-shadow: 0 25px 50px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(255, 215, 0, 0.7);
transform: scale(1.02) !important;
z-index: 100001 !important;
transition: none !important;
}
.magnify-info-panel.panel-pinned::before {
content: '';
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background: linear-gradient(45deg, rgba(255, 215, 0, 0.05) 0%, transparent 100%);
pointer-events: none;
border-radius: inherit;
}
.panel-dragging * {
pointer-events: none !important;
user-select: none !important;
transition: none !important;
}
.magnify-info-panel.panel-minimized {
height: auto !important;
}
.magnify-info-panel.panel-minimized .panel-content {
max-height: 0 !important;
height: 0 !important;
overflow: hidden;
padding: 0 !important;
margin: 0 !important;
transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.floating-controls {
position: fixed;
display: none;
/* Hidden initially - JS will show when positioned */
padding: 4px;
background: rgba(40, 40, 50, 0.95);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 4px;
opacity: 1;
z-index: 100000;
backdrop-filter: blur(8px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
}
.floating-controls.vertical-layout {
flex-direction: column;
gap: 4px;
}
.floating-controls.horizontal-layout {
flex-direction: row;
gap: 4px;
}
.control-btn {
background: rgba(60, 60, 70, 0.8);
border: 1px solid rgba(255, 255, 255, 0.2);
width: 28px;
height: 28px;
font-size: 14px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
color: #ddd;
border-radius: 3px;
transition: background-color 0.15s ease;
}
.control-btn:hover {
background: rgba(80, 80, 90, 0.9);
color: white;
}
.control-btn:active {
background: rgba(100, 100, 110, 0.9);
}
.control-btn:disabled {
background: rgba(40, 40, 50, 0.5);
color: #666;
cursor: not-allowed;
opacity: 0.5;
}
.control-btn.active {
background: rgba(255, 200, 50, 0.3);
border-color: rgba(255, 200, 50, 0.6);
color: #ffcc33;
}
.control-btn.lock-btn.active {
background: rgba(255, 69, 0, 0.3);
border-color: rgba(255, 69, 0, 0.6);
color: #ff4500;
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 18px;
background: linear-gradient(135deg, rgba(0, 0, 0, 0.1), rgba(255, 255, 255, 0.05));
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
user-select: none;
cursor: grab;
transition: background 0.15s ease;
}
.panel-header:hover {
background: linear-gradient(135deg, rgba(0, 0, 0, 0.15), rgba(255, 255, 255, 0.08));
}
.panel-header:active {
cursor: grabbing;
}
.header-content {
display: flex;
align-items: center;
gap: 10px;
}
.header-icon {
font-size: 18px;
opacity: 0.9;
}
.header-title {
font-weight: 600;
font-size: 18px;
}
.header-subtitle {
font-size: 14px;
opacity: 0.7;
font-style: italic;
}
.header-controls {
display: flex;
gap: 6px;
}
.minimize-btn {
background: rgba(255, 255, 255, 0.1);
border: none;
border-radius: 6px;
color: inherit;
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s;
font-weight: bold;
font-size: 16px;
}
.minimize-btn:hover {
background: rgba(255, 255, 255, 0.2);
transform: scale(1.05);
}
.minimize-btn:active {
transform: scale(0.95);
}
.panel-content {
padding: 0;
flex: 1;
min-height: 0;
overflow-y: auto;
scrollbar-width: thin;
}
.panel-content::-webkit-scrollbar {
width: 8px;
}
.panel-content::-webkit-scrollbar-track {
background: rgba(0, 0, 0, 0.1);
}
.panel-content::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 3px;
}
.info-section {
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
margin-bottom: 8px;
border-radius: 10px;
overflow: visible;
background: rgba(255, 255, 255, 0.02);
transition: all 0.3s ease;
}
.info-section:hover {
background: rgba(255, 255, 255, 0.04);
transform: translateY(-1px);
}
.section-header {
display: flex;
align-items: center;
gap: 12px;
padding: 16px 20px;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
font-weight: 500;
border-radius: 8px;
margin: 3px;
position: relative;
overflow: hidden;
}
.section-header::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.05) 50%, transparent 100%);
transform: translateX(-100%);
transition: transform 0.6s ease;
}
.section-header:hover::before {
transform: translateX(100%);
}
.section-header:hover {
background: rgba(255, 255, 255, 0.08);
transform: translateX(2px);
box-shadow: inset 2px 0 0 rgba(116, 185, 255, 0.5);
}
.section-header:active {
background: rgba(255, 255, 255, 0.12);
transform: translateX(1px);
}
.section-header.expanded {
background: rgba(116, 185, 255, 0.1);
border-left: 2px solid var(--info-panel-accent-color, #74b9ff);
}
.info-section[data-section="node"] {
background: linear-gradient(135deg, rgba(116, 185, 255, 0.05), rgba(160, 212, 104, 0.05));
border: 1px solid rgba(116, 185, 255, 0.2);
border-radius: 8px;
margin: 6px;
}
.info-section[data-section="node"] .section-header {
background: linear-gradient(135deg, rgba(116, 185, 255, 0.15), rgba(160, 212, 104, 0.15));
border-radius: 8px 8px 0 0;
cursor: default;
}
.info-section[data-section="node"] .section-header:hover {
transform: none;
box-shadow: none;
}
.info-section[data-section="node"] .section-title {
color: var(--info-panel-accent-color, #74b9ff);
font-weight: 700;
}
.info-section[data-section="inspector"] {
background: linear-gradient(135deg, rgba(100, 150, 255, 0.05), rgba(74, 144, 226, 0.05));
border: 1px solid rgba(100, 150, 255, 0.2);
border-radius: 8px;
margin: 6px;
}
.info-section[data-section="inspector"] .section-header {
background: linear-gradient(135deg, rgba(100, 150, 255, 0.15), rgba(74, 144, 226, 0.15));
border-radius: 8px 8px 0 0;
}
.info-section[data-section="inspector"] .section-title {
color: #6496ff;
font-weight: 700;
}
.info-section[data-section="media"] {
background: linear-gradient(135deg, rgba(253, 203, 110, 0.05), rgba(255, 215, 0, 0.05));
border: 1px solid rgba(253, 203, 110, 0.2);
border-radius: 8px;
margin: 6px;
}
.info-section[data-section="media"] .section-header {
background: linear-gradient(135deg, rgba(253, 203, 110, 0.15), rgba(255, 215, 0, 0.15));
border-radius: 8px 8px 0 0;
}
.info-section[data-section="media"] .section-title {
color: var(--info-panel-accent-color, #fdcb6e);
font-weight: 700;
}
.section-icon {
font-size: 18px;
width: 22px;
text-align: center;
}
.section-title {
flex: 1;
font-size: 16px;
font-weight: 600;
letter-spacing: 0.3px;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.section-badge {
background: rgba(100, 150, 255, 0.2);
color: #8bb3ff;
padding: 3px 10px;
border-radius: 10px;
font-size: 13px;
font-weight: 500;
}
.expand-icon {
font-size: 14px;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
color: rgba(255, 255, 255, 0.6);
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
background: rgba(255, 255, 255, 0.05);
margin-left: auto;
}
.section-header:hover .expand-icon {
color: var(--info-panel-accent-color, #74b9ff);
background: rgba(116, 185, 255, 0.15);
transform: scale(1.1);
}
.section-header.expanded .expand-icon {
transform: rotate(90deg) scale(1.1);
color: var(--info-panel-accent-color, #74b9ff);
background: rgba(116, 185, 255, 0.2);
}
.section-content {
max-height: 0;
overflow: visible;
transition: max-height 0.4s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s ease;
opacity: 0;
}
.section-content.expanded {
max-height: 2000px;
opacity: 1;
overflow: visible;
}
.section-body {
padding: 0 18px 16px 24px;
}
.info-row {
display: flex;
justify-content: space-between;
align-items: flex-start;
padding: 10px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
transition: all 0.2s ease;
border-radius: 4px;
margin: 0 -8px;
padding-left: 8px;
padding-right: 8px;
}
.info-row:last-child {
border-bottom: none;
}
.info-row:hover {
background: rgba(255, 255, 255, 0.03);
border-bottom-color: rgba(255, 255, 255, 0.08);
}
.info-label {
font-weight: 500;
opacity: 0.85;
font-size: 15px;
min-width: 80px;
padding-right: 12px;
line-height: 1.5;
}
.info-value {
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
font-size: 14px;
color: var(--info-panel-accent-color, #a0d468);
background: rgba(160, 212, 104, 0.12);
padding: 4px 10px;
border-radius: 6px;
max-width: 100%;
word-wrap: break-word;
word-break: break-word;
hyphens: auto;
line-height: 1.4;
text-align: left;
white-space: pre-wrap;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
transition: all 0.2s ease;
}
.info-value:hover {
background: rgba(160, 212, 104, 0.18);
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
.info-value.long-text {
white-space: pre-wrap;
word-wrap: break-word;
max-width: 100%;
line-height: 1.4;
}
.empty-state {
text-align: center;
padding: 50px 25px;
opacity: 0.6;
}
.empty-state-icon {
font-size: 36px;
margin-bottom: 15px;
opacity: 0.5;
}
.empty-state-text {
font-size: 16px;
font-style: italic;
}
/* Copy to clipboard functionality */
.info-value[title]:hover::after {
content: '📋';
position: absolute;
right: -20px;
top: 50%;
transform: translateY(-50%);
font-size: 12px;
opacity: 0.7;
}
/* Smooth loading states */
.section-body.loading {
opacity: 0.5;
pointer-events: none;
}
.section-body.loading::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 20px;
height: 20px;
border: 2px solid transparent;
border-top: 2px solid var(--info-panel-accent-color, #74b9ff);
border-radius: 50%;
animation: spin 1s linear infinite;
transform: translate(-50%, -50%);
}
@keyframes spin {
to {
transform: translate(-50%, -50%) rotate(360deg);
}
}
/* Enhanced scrollbar for better UX */
.section-body::-webkit-scrollbar {
width: 4px;
}
.section-body::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.05);
border-radius: 2px;
}
.section-body::-webkit-scrollbar-thumb {
background: var(--info-panel-accent-color, #74b9ff);
border-radius: 2px;
opacity: 0.6;
}
.section-body::-webkit-scrollbar-thumb:hover {
opacity: 1;
}
@keyframes pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.7;
}
}
.pulse {
animation: pulse 2s infinite;
}
+153
View File
@@ -0,0 +1,153 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { isUserTyping } from "../shared/utils.js";
import { Logger } from "../shared/logger.js";
class EventManager {
constructor(stateManager, panelElement, positionManager, callbacks) {
__publicField(this, "stateManager");
__publicField(this, "panelElement");
__publicField(this, "positionManager");
__publicField(this, "callbacks");
__publicField(this, "dragCleanup");
__publicField(this, "boundHandleMouseMove");
__publicField(this, "boundHandleKeyDown");
__publicField(this, "boundHandleKeyUp");
this.stateManager = stateManager;
this.panelElement = panelElement;
this.positionManager = positionManager;
this.callbacks = callbacks || null;
this.dragCleanup = null;
this.boundHandleMouseMove = this.handleMouseMove.bind(this);
this.boundHandleKeyDown = this.handleKeyDown.bind(this);
this.boundHandleKeyUp = this.handleKeyUp.bind(this);
this.setupEventListeners();
}
setupEventListeners() {
this.setupPanelEvents();
this.setupHotkeyEvents();
this.setupDragEvents();
this.setupHoverEvents();
}
setupPanelEvents() {
if (!this.panelElement) return;
}
setupHotkeyEvents() {
document.addEventListener("keydown", this.boundHandleKeyDown);
}
setupDragEvents() {
if (!this.panelElement) return;
let isDragging = false;
let rafId = null;
let targetX = 0;
let targetY = 0;
const startDrag = (e) => {
if (!this.panelElement) return;
const target = e.target;
const header = target.closest(".panel-header");
if (!header) return;
if (target.closest("button")) return;
if (this.stateManager.state.isPanelLocked) return;
if (!this.stateManager.state.isPanelPinned) return;
e.preventDefault();
e.stopPropagation();
isDragging = true;
const startX = e.clientX;
const startY = e.clientY;
const rect = this.panelElement.getBoundingClientRect();
const startLeft = rect.left;
const startTop = rect.top;
this.panelElement.style.cursor = "grabbing";
this.panelElement.style.opacity = "0.9";
this.panelElement.style.transition = "none";
document.body.style.cursor = "grabbing";
document.body.style.userSelect = "none";
const onMouseMove = (moveEvent) => {
var _a, _b;
if (!isDragging) return;
const dx = moveEvent.clientX - startX;
const dy = moveEvent.clientY - startY;
targetX = startLeft + dx;
targetY = startTop + dy;
const panelWidth = ((_a = this.panelElement) == null ? void 0 : _a.offsetWidth) || 0;
const panelHeight = ((_b = this.panelElement) == null ? void 0 : _b.offsetHeight) || 0;
targetX = Math.max(0, Math.min(targetX, window.innerWidth - panelWidth));
targetY = Math.max(0, Math.min(targetY, window.innerHeight - panelHeight));
if (rafId === null) {
rafId = requestAnimationFrame(() => {
if (this.panelElement && isDragging) {
this.panelElement.style.left = `${targetX}px`;
this.panelElement.style.top = `${targetY}px`;
}
rafId = null;
});
}
};
const onMouseUp = () => {
isDragging = false;
if (rafId !== null) {
cancelAnimationFrame(rafId);
rafId = null;
}
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
if (this.panelElement) {
this.panelElement.style.cursor = "";
this.panelElement.style.opacity = "";
this.panelElement.style.transition = "";
this.panelElement.style.left = `${targetX}px`;
this.panelElement.style.top = `${targetY}px`;
this.stateManager.state.pinnedPosition = { x: targetX, y: targetY };
}
document.body.style.cursor = "";
document.body.style.userSelect = "";
};
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
};
this.panelElement.addEventListener("mousedown", startDrag);
this.dragCleanup = () => {
if (this.panelElement) this.panelElement.removeEventListener("mousedown", startDrag);
};
}
setupHoverEvents() {
if (!this.panelElement) return;
this.panelElement.addEventListener("mouseenter", () => {
this.stateManager.state.isPanelHovered = true;
this.stateManager.clearAutoExpandTimer();
});
this.panelElement.addEventListener("mouseleave", () => {
this.stateManager.state.isPanelHovered = false;
if (!this.stateManager.state.isHoveringNode) {
this.stateManager.scheduleAutoCollapse();
}
});
}
handleKeyDown(e) {
var _a, _b;
if (isUserTyping()) return;
const settings = this.stateManager.state.settings;
const key = e.key.toLowerCase();
if (key === settings["🔍MagnifyGlass.ToggleHotkey"].toLowerCase()) {
Logger.debug("Toggle visibility hotkey matched!");
e.preventDefault();
(_a = this.callbacks) == null ? void 0 : _a.toggleVisibility();
}
if (key === settings["🔍MagnifyGlass.PinPanelHotkey"].toLowerCase()) {
e.preventDefault();
(_b = this.callbacks) == null ? void 0 : _b.togglePin();
}
}
handleMouseMove(e) {
}
handleKeyUp(e) {
}
cleanup() {
document.removeEventListener("keydown", this.boundHandleKeyDown);
if (this.dragCleanup) this.dragCleanup();
}
}
export {
EventManager
};
//# sourceMappingURL=EventManager.js.map
File diff suppressed because one or more lines are too long
+135
View File
@@ -0,0 +1,135 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import "/scripts/app.js";
import { registerPanelSettings } from "../shared/settings/panelSettings.js";
import { Logger } from "../shared/logger.js";
import { StateManager } from "./StateManager.js";
import { UIManager } from "./UIManager.js";
import { PositionManager } from "./PositionManager.js";
import { EventManager } from "./EventManager.js";
import { InformationGatherer } from "./InformationGatherer.js";
class InfoPanel {
constructor(magnifyGlass) {
__publicField(this, "magnifyGlass");
__publicField(this, "stateManager");
__publicField(this, "uiManager");
__publicField(this, "positionManager");
__publicField(this, "eventManager");
__publicField(this, "informationGatherer");
this.magnifyGlass = magnifyGlass;
this.stateManager = new StateManager();
this.uiManager = new UIManager(this.stateManager);
this.informationGatherer = new InformationGatherer();
this.positionManager = new PositionManager(this.stateManager, this.uiManager.elements.panel);
this.eventManager = new EventManager(this.stateManager, this.uiManager.elements.panel, this.positionManager, {
toggleVisibility: () => {
if (this.stateManager.state.isPanelVisible) {
this.uiManager.hide();
} else {
this.uiManager.show();
}
},
togglePin: () => {
this.stateManager.togglePinning();
this.uiManager.updatePinnedState();
},
updatePosition: () => this.positionManager.positionPanel()
});
this.hookIntoMagnifyGlass();
registerPanelSettings(this.stateManager, this.uiManager, this.positionManager);
Logger.info("Info Panel initialized successfully");
}
hookIntoMagnifyGlass() {
const originalUpdateMagnifiedView = this.magnifyGlass.updateMagnifiedView.bind(this.magnifyGlass);
this.magnifyGlass.updateMagnifiedView = (() => {
originalUpdateMagnifiedView();
if (this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelEnabled"] && this.magnifyGlass.state.active) {
this.scheduleInfoUpdate();
}
}).bind(this);
const originalShow = this.magnifyGlass.ui.show.bind(this.magnifyGlass.ui);
const originalHide = this.magnifyGlass.ui.hide.bind(this.magnifyGlass.ui);
this.magnifyGlass.ui.show = (() => {
originalShow();
if (this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelEnabled"]) {
if (this.stateManager.state.wasPanelVisibleBeforeHide) {
this.uiManager.show();
setTimeout(() => {
this.positionManager.positionPanel();
this.positionManager.positionFloatingControls(this.uiManager.elements.controls);
}, 10);
} else {
const showControls = this.stateManager.state.settings["🔍MagnifyGlass.ShowHoveringControls"] !== false;
if (showControls && this.uiManager.elements.controls) {
this.uiManager.elements.controls.style.display = "flex";
}
this.uiManager.updateControlStates();
setTimeout(() => {
this.positionManager.positionFloatingControls(this.uiManager.elements.controls);
}, 10);
}
}
}).bind(this);
this.magnifyGlass.ui.hide = (() => {
this.stateManager.state.wasPanelVisibleBeforeHide = this.stateManager.state.isPanelVisible;
originalHide();
this.uiManager.hide();
if (this.uiManager.elements.controls) {
this.uiManager.elements.controls.style.display = "none";
}
}).bind(this);
}
scheduleInfoUpdate() {
if (this.stateManager.state.updateScheduled) return;
this.stateManager.state.updateScheduled = true;
requestAnimationFrame(() => {
this.updateInfo();
this.stateManager.state.updateScheduled = false;
});
}
updateInfo() {
const settings = this.stateManager.state.settings;
const isActive = this.magnifyGlass.state.active;
if (!settings["🔍MagnifyGlass.InfoPanelEnabled"] || !isActive) {
if (this.uiManager.elements.controls && this.uiManager.elements.controls.style.display !== "none") {
this.uiManager.elements.controls.style.display = "none";
}
return;
}
const info = this.informationGatherer.gatherInformation();
this.stateManager.setCurrentInfo(info);
this.uiManager.displayInfo(info);
this.positionManager.positionPanel();
this.positionManager.positionFloatingControls(this.uiManager.elements.controls);
if (info.hoveredNode) {
this.stateManager.state.isHoveringNode = true;
this.stateManager.expandNodeSections();
if (this.stateManager.state.lastNodeId !== info.hoveredNode.id) {
this.stateManager.state.lastNodeId = info.hoveredNode.id;
}
} else {
this.stateManager.state.isHoveringNode = false;
if (this.stateManager.state.lastNodeId !== null) {
this.stateManager.state.lastNodeId = null;
if (!this.stateManager.state.isPanelHovered) {
this.stateManager.scheduleAutoCollapse();
}
}
}
}
updateSettings() {
this.stateManager.updateSettings();
this.uiManager.applyStyles();
if (this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelEnabled"] && this.magnifyGlass.state.active) {
this.uiManager.show();
this.positionManager.positionPanel();
} else {
this.uiManager.hide();
}
}
}
export {
InfoPanel
};
//# sourceMappingURL=InfoPanel.js.map
File diff suppressed because one or more lines are too long
+275
View File
@@ -0,0 +1,275 @@
class InformationGatherer {
constructor() {
}
gatherInformation() {
var _a, _b;
const magnifyGlass = window.comfyUIMagnifyGlass;
if (!magnifyGlass) {
return {
timestamp: Date.now(),
cursor: { screenX: 0, screenY: 0, canvasX: 0, canvasY: 0 },
zoom: 1,
nodeCount: 0,
hoveredNode: null,
hoveredWidget: null,
mediaElement: null
};
}
const info = {
timestamp: Date.now(),
cursor: {
screenX: magnifyGlass.lastKnownMousePosition.x,
screenY: magnifyGlass.lastKnownMousePosition.y,
canvasX: magnifyGlass.state.x,
canvasY: magnifyGlass.state.y
},
zoom: magnifyGlass.state.canvasScale,
nodeCount: ((_b = (_a = app.graph) == null ? void 0 : _a._nodes) == null ? void 0 : _b.length) ?? 0,
hoveredNode: null,
hoveredWidget: null,
mediaElement: null
};
if (magnifyGlass.isOverMedia && magnifyGlass.currentMediaElement) {
info.mediaElement = this.getMediaInfo(magnifyGlass.currentMediaElement);
}
const nodeUnderCursor = this.getNodeUnderCursor();
if (nodeUnderCursor) {
info.hoveredNode = this.getDetailedNodeInfo(nodeUnderCursor.node, nodeUnderCursor.localPos);
const widget = this.getWidgetUnderCursor(nodeUnderCursor.node, nodeUnderCursor.localPos);
if (widget) {
info.hoveredWidget = this.getWidgetInfo(widget);
}
}
return info;
}
getNodeUnderCursor() {
const magnifyGlass = window.comfyUIMagnifyGlass;
if (!app.graph || !app.canvas || !magnifyGlass) {
return null;
}
try {
if (app.canvas.node_over) {
const node = app.canvas.node_over;
if (node && node.pos && node.size) {
const canvasRect2 = app.canvas.canvas.getBoundingClientRect();
const mouseX2 = magnifyGlass.lastKnownMousePosition.x - canvasRect2.left;
const mouseY2 = magnifyGlass.lastKnownMousePosition.y - canvasRect2.top;
let graphPos2;
if (app.canvas.convertOffsetToCanvasPos) {
graphPos2 = app.canvas.convertOffsetToCanvasPos([mouseX2, mouseY2]);
} else {
const ds = app.canvas.ds || { scale: 1, offset: [0, 0] };
graphPos2 = [
mouseX2 / ds.scale - ds.offset[0] / ds.scale,
mouseY2 / ds.scale - ds.offset[1] / ds.scale
];
}
return {
node,
localPos: {
x: graphPos2[0] - node.pos[0],
y: graphPos2[1] - node.pos[1]
}
};
}
}
const canvasRect = app.canvas.canvas.getBoundingClientRect();
const mouseX = magnifyGlass.lastKnownMousePosition.x - canvasRect.left;
const mouseY = magnifyGlass.lastKnownMousePosition.y - canvasRect.top;
let graphPos;
if (app.canvas.convertOffsetToCanvasPos) {
graphPos = app.canvas.convertOffsetToCanvasPos([mouseX, mouseY]);
} else {
const ds = app.canvas.ds || { scale: 1, offset: [0, 0] };
graphPos = [
mouseX / ds.scale - ds.offset[0] / ds.scale,
mouseY / ds.scale - ds.offset[1] / ds.scale
];
}
for (let i = app.graph._nodes.length - 1; i >= 0; i--) {
const node = app.graph._nodes[i];
if (!node.pos || !node.size || node.flags && node.flags.collapsed) continue;
if (graphPos[0] >= node.pos[0] && graphPos[0] <= node.pos[0] + node.size[0] && graphPos[1] >= node.pos[1] && graphPos[1] <= node.pos[1] + node.size[1]) {
return {
node,
localPos: {
x: graphPos[0] - node.pos[0],
y: graphPos[1] - node.pos[1]
}
};
}
}
} catch (err) {
console.warn("Error in node detection:", err);
}
return null;
}
getDetailedNodeInfo(node, localPos) {
return {
id: node.id,
title: node.title || "Untitled Node",
type: node.type,
mode: this.getNodeModeText(node.mode),
position: {
x: Math.round(node.pos[0]),
y: Math.round(node.pos[1]),
formatted: `(${Math.round(node.pos[0])}, ${Math.round(node.pos[1])})`
},
size: {
width: Math.round(node.size[0]),
height: Math.round(node.size[1]),
formatted: `${Math.round(node.size[0])}×${Math.round(node.size[1])}`
},
localPosition: {
x: Math.round(localPos.x),
y: Math.round(localPos.y),
formatted: `(${Math.round(localPos.x)}, ${Math.round(localPos.y)})`,
percentage: {
x: (localPos.x / node.size[0] * 100).toFixed(1),
y: (localPos.y / node.size[1] * 100).toFixed(1)
}
},
counts: {
widgets: node.widgets ? node.widgets.length : 0,
inputs: node.inputs ? node.inputs.length : 0,
outputs: node.outputs ? node.outputs.length : 0,
properties: node.properties ? Object.keys(node.properties).length : 0
},
widgets: node.widgets || [],
inputs: node.inputs || [],
outputs: node.outputs || [],
properties: node.properties || {},
hoverRegion: this.detectNodeRegion(localPos, node)
};
}
getNodeInfo(node) {
return {
id: node.id,
title: node.title || "Untitled",
type: node.type,
mode: node.mode,
size: node.size ? `${Math.round(node.size[0])}×${Math.round(node.size[1])}` : "Unknown",
position: node.pos ? `(${Math.round(node.pos[0])}, ${Math.round(node.pos[1])})` : "Unknown",
widgets: node.widgets || [],
inputs: node.inputs || [],
outputs: node.outputs || [],
properties: node.properties || {}
};
}
getWidgetUnderCursor(node, localPos) {
if (!node.widgets || !node.widgets.length) return null;
const titleHeight = 30;
let currentY = titleHeight;
for (const widget of node.widgets) {
const widgetHeight = 25;
if (localPos.y >= currentY && localPos.y <= currentY + widgetHeight) {
return widget;
}
currentY += widgetHeight + 5;
}
return null;
}
getWidgetInfo(widget) {
return {
name: widget.name,
type: widget.type,
value: this.formatValue(widget.value),
options: widget.options || null,
min: widget.min,
max: widget.max,
step: widget.step
};
}
getMediaInfo(mediaElement) {
const info = {
type: mediaElement instanceof HTMLImageElement ? "image" : "video",
tagName: mediaElement.tagName,
src: mediaElement.src ? mediaElement.src.substring(mediaElement.src.lastIndexOf("/") + 1) : "No source",
naturalWidth: 0,
naturalHeight: 0,
displayWidth: 0,
displayHeight: 0,
aspectRatio: ""
};
if (mediaElement instanceof HTMLImageElement) {
info.naturalWidth = mediaElement.naturalWidth;
info.naturalHeight = mediaElement.naturalHeight;
info.displayWidth = Math.round(mediaElement.width);
info.displayHeight = Math.round(mediaElement.height);
if (mediaElement.naturalWidth && mediaElement.naturalHeight) {
info.aspectRatio = (mediaElement.naturalWidth / mediaElement.naturalHeight).toFixed(2);
}
} else if (mediaElement instanceof HTMLVideoElement) {
info.naturalWidth = mediaElement.videoWidth;
info.naturalHeight = mediaElement.videoHeight;
info.displayWidth = Math.round(mediaElement.width);
info.displayHeight = Math.round(mediaElement.height);
info.duration = mediaElement.duration;
info.currentTime = mediaElement.currentTime;
if (mediaElement.videoWidth && mediaElement.videoHeight) {
info.aspectRatio = (mediaElement.videoWidth / mediaElement.videoHeight).toFixed(2);
}
}
return info;
}
getNodeModeText(mode) {
const modes = {
0: "Always",
1: "On Event",
2: "Never",
3: "On Trigger",
4: "On Request"
};
return modes[mode] || `Mode ${mode}`;
}
detectNodeRegion(localPos, node) {
const titleHeight = 30;
const regions = [];
if (localPos.y <= titleHeight) {
regions.push("Title Bar");
}
if (localPos.x <= 10) {
regions.push("Left Edge");
} else if (localPos.x >= node.size[0] - 10) {
regions.push("Right Edge");
}
if (localPos.y <= 10) {
regions.push("Top Edge");
} else if (localPos.y >= node.size[1] - 10) {
regions.push("Bottom Edge");
}
if (regions.length === 0) {
if (localPos.y > titleHeight) {
regions.push("Content Area");
}
}
if (localPos.x <= 20 && localPos.y > titleHeight) {
regions.push("Input Area");
} else if (localPos.x >= node.size[0] - 20 && localPos.y > titleHeight) {
regions.push("Output Area");
}
return regions.length > 0 ? regions.join(", ") : "Unknown";
}
formatValue(value) {
if (value === null) return "null";
if (value === void 0) return "undefined";
if (typeof value === "string") {
return value;
}
if (typeof value === "number") {
return Number.isInteger(value) ? value.toString() : value.toFixed(3);
}
if (typeof value === "boolean") return value.toString();
if (Array.isArray(value)) {
return `Array(${value.length})`;
}
if (typeof value === "object") {
return "Object";
}
return String(value);
}
}
export {
InformationGatherer
};
//# sourceMappingURL=InformationGatherer.js.map
File diff suppressed because one or more lines are too long
+209
View File
@@ -0,0 +1,209 @@
import { formatWidgetValue } from "./ValueFormatter.js";
function getCheckpointInfo(nodeInfo) {
if (nodeInfo.type && (nodeInfo.type.includes("CheckpointLoader") || nodeInfo.type.includes("LoadCheckpoint") || nodeInfo.type.includes("ModelLoader") || nodeInfo.type.includes("UNETLoader") || nodeInfo.type.includes("VAELoader") || nodeInfo.type.includes("LoraLoader"))) {
if (nodeInfo.widgets && nodeInfo.widgets.length > 0) {
for (const widget of nodeInfo.widgets) {
if (widget.name && (widget.name.toLowerCase().includes("model") || widget.name.toLowerCase().includes("checkpoint") || widget.name.toLowerCase().includes("ckpt") || widget.name.toLowerCase().includes("lora") || widget.name.toLowerCase().includes("vae") || widget.name.toLowerCase().includes("file"))) {
const value = String(widget.value);
const filename = value.split(/[\/\\]/).pop();
return filename || value;
}
}
}
}
return null;
}
function getImageInfo(nodeInfo) {
if (nodeInfo.type && (nodeInfo.type.includes("SaveImage") || nodeInfo.type.includes("PreviewImage") || nodeInfo.type.includes("VisionOutput") || nodeInfo.type.includes("ImageOutput") || nodeInfo.type.includes("LoadImage") || nodeInfo.type.includes("Display"))) {
if (nodeInfo.widgets) {
for (const widget of nodeInfo.widgets) {
if (widget.name && (widget.name.toLowerCase().includes("image") || widget.name.toLowerCase().includes("filename") || widget.name.toLowerCase().includes("file"))) {
return String(widget.value);
}
}
}
if (nodeInfo.properties && nodeInfo.properties.img) {
const img = nodeInfo.properties.img;
return {
width: img.width || "unknown",
height: img.height || "unknown",
src: img.src ? String(img.src).split(/[\/\\]/).pop() || "Preview available" : "Preview available"
};
}
if (nodeInfo.outputs) {
for (const output of nodeInfo.outputs) {
if (output.links && output.links.length > 0) {
return "Image connected to " + output.links.length + " node(s)";
}
}
}
return "Image node";
}
return null;
}
function getTextBoxContent(nodeInfo) {
if (nodeInfo.widgets && nodeInfo.widgets.length > 0) {
if (nodeInfo.type && nodeInfo.type.includes("CLIPTextEncode")) {
for (const widget of nodeInfo.widgets) {
if (widget.name === "text" && typeof widget.value === "string") {
return widget.value;
}
}
}
for (const widget of nodeInfo.widgets) {
if ((widget.name.toLowerCase().includes("prompt") || widget.name.toLowerCase().includes("conditioning")) && typeof widget.value === "string" && widget.value.length > 0) {
return widget.value;
}
}
for (const widget of nodeInfo.widgets) {
if ((widget.type === "text" || widget.type === "textarea" || widget.type === "string" || widget.name.toLowerCase().includes("text")) && typeof widget.value === "string" && widget.value.length > 0) {
return widget.value;
}
}
}
return null;
}
const COMPLEX_NODE_PARAMS = [
"seed",
"steps",
"cfg",
"scale",
"sampler",
"scheduler",
"positive",
"negative",
"width",
"height",
"denoise",
"strength",
"noise",
"count",
"batch",
"size",
"phase",
"color",
"intensity",
"control_after_generate",
"control",
"after",
"generate",
"start_at_step",
"end_at_step",
"start",
"end",
"return_with_leftover_noise",
"leftover",
"noise_return",
"model",
"vae",
"clip",
"lora",
"checkpoint",
"latent",
"image",
"mask",
"filename",
"directory",
"prompt",
"conditioning",
"filename_prefix",
"resolution",
"num_chunks",
"seconds",
"aspect_ratio",
"style_type",
"background",
"n",
"human",
"raw",
"guidance",
"skip_preprocessing",
"movement_amplitude",
"animation",
"material_type",
"b1",
"b2",
"s1",
"s2",
"type",
"channel",
"sigma",
"rho",
"alpha",
"base_shift",
"shift",
"stretch",
"terminal",
"spacing",
"style",
"eta",
"norm_threshold",
"momentum",
"hypernetwork_name",
"reuse_threshold",
"verbose",
"layers",
"set_cond_area",
"audioui",
"camera_pose",
"fx",
"cx",
"fy",
"cy"
];
const SAVE_NODE_PARAMS = [
"filename_prefix",
"filename",
"directory",
"path",
"format",
"quality",
"extension"
];
const SKIP_WIDGET_NAMES = ["title", "node", "id", "type", "mode"];
function shouldShowAllWidgets(nodeType) {
const type = nodeType.toLowerCase();
const isSaveNode = type.includes("save") && !type.includes("checkpoint") && !type.includes("model") && !type.includes("preview");
return (type.includes("ksampler") || type.includes("sampler") || type.includes("k_samplers") || type.includes("checkpoint") || type.includes("model") || type.includes("lora") || type.includes("controlnet") || type.includes("advanced") || type.includes("detailer") || type.includes("inpaint") || type.includes("upscale") || type.includes("clip") || type.includes("text") || type.includes("encode")) && !isSaveNode;
}
function getImportantNodeParameters(nodeInfo) {
const parameters = [];
if (!nodeInfo.widgets || nodeInfo.widgets.length === 0) {
return parameters;
}
const nodeType = nodeInfo.type || "";
const typeLower = nodeType.toLowerCase();
const isSaveNode = typeLower.includes("save") && !typeLower.includes("checkpoint") && !typeLower.includes("model") && !typeLower.includes("preview");
if (nodeType && shouldShowAllWidgets(nodeType)) {
for (const widget of nodeInfo.widgets) {
if (widget.name && widget.name !== "") {
const widgetName = widget.name.toLowerCase();
if (!SKIP_WIDGET_NAMES.some((skip) => widgetName.includes(skip))) {
parameters.push({
label: widget.name,
value: formatWidgetValue(widget.value)
});
}
}
}
return parameters;
}
const importantParams = isSaveNode ? SAVE_NODE_PARAMS : COMPLEX_NODE_PARAMS;
for (const widget of nodeInfo.widgets) {
const paramName = widget.name.toLowerCase();
if (importantParams.some((param) => paramName.includes(param))) {
parameters.push({
label: widget.name,
value: formatWidgetValue(widget.value)
});
}
}
return parameters;
}
export {
getCheckpointInfo,
getImageInfo,
getImportantNodeParameters,
getTextBoxContent
};
//# sourceMappingURL=NodeDataExtractor.js.map
File diff suppressed because one or more lines are too long
+160
View File
@@ -0,0 +1,160 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
class PositionManager {
constructor(stateManager, panelElement) {
__publicField(this, "stateManager");
__publicField(this, "panelElement");
this.stateManager = stateManager;
this.panelElement = panelElement;
}
positionPanel() {
if (!this.panelElement) return;
if (this.stateManager.state.isPanelPinned) {
this.applyPinnedPosition();
return;
}
this.calculateNormalPosition();
}
applyPinnedPosition() {
if (!this.panelElement) return;
let { x, y } = this.stateManager.state.pinnedPosition;
if (x === 0 && y === 0) {
this.calculateNormalPosition();
if (this.panelElement) {
const rect = this.panelElement.getBoundingClientRect();
this.stateManager.state.pinnedPosition = { x: rect.left, y: rect.top };
}
return;
}
const panelWidth = this.panelElement.offsetWidth || 300;
const panelHeight = this.panelElement.offsetHeight || 400;
const margin = 4;
const boundedX = Math.max(margin, Math.min(x, window.innerWidth - panelWidth - margin));
const boundedY = Math.max(margin, Math.min(y, window.innerHeight - panelHeight - margin));
this.panelElement.style.left = `${boundedX}px`;
this.panelElement.style.top = `${boundedY}px`;
}
calculateNormalPosition() {
var _a, _b, _c;
const magnifyGlass = window.comfyUIMagnifyGlass;
if (!magnifyGlass || !this.panelElement) return;
const settings = this.stateManager.state.settings;
const panelWidth = Number(settings["🔍MagnifyGlass.InfoPanelWidth"]) || 300;
const panelHeight = this.panelElement.offsetHeight || 400;
let left;
let top;
const margin = 4;
const glassRect = (_a = magnifyGlass.ui.glassDiv) == null ? void 0 : _a.getBoundingClientRect();
const hasValidGlassRect = glassRect && (glassRect.right > 0 || glassRect.top > 0);
const mouseX = ((_b = magnifyGlass.lastKnownMousePosition) == null ? void 0 : _b.x) || 0;
const mouseY = ((_c = magnifyGlass.lastKnownMousePosition) == null ? void 0 : _c.y) || 0;
const hasValidMousePosition = mouseX > 0 || mouseY > 0;
if (!this.stateManager.state.isGlassPreviewVisible) {
if (hasValidMousePosition) {
left = mouseX - panelWidth / 2;
top = mouseY - 20;
} else {
left = window.innerWidth - panelWidth - 50;
top = 100;
}
} else if (hasValidGlassRect) {
const position = settings["🔍MagnifyGlass.InfoPanelPosition"];
switch (position) {
case "Right":
left = glassRect.right + margin;
top = glassRect.top;
break;
case "Left":
left = glassRect.left - panelWidth - margin;
top = glassRect.top;
break;
case "Top":
left = glassRect.left;
top = glassRect.top - panelHeight - margin;
break;
case "Bottom":
left = glassRect.left;
top = glassRect.bottom + margin;
break;
default:
left = glassRect.right + margin;
top = glassRect.top;
break;
}
} else if (hasValidMousePosition) {
left = mouseX - panelWidth / 2;
top = mouseY - 20;
} else {
left = window.innerWidth - panelWidth - 50;
top = 100;
}
left = Math.max(4, Math.min(left, window.innerWidth - panelWidth - 4));
top = Math.max(4, Math.min(top, window.innerHeight - panelHeight - 4));
this.panelElement.style.left = `${left}px`;
this.panelElement.style.top = `${top}px`;
}
/**
* Position the floating controls relative to the panel.
*/
positionFloatingControls(controlsElement) {
if (!controlsElement) return;
const settings = this.stateManager.state.settings;
if (settings["🔍MagnifyGlass.ShowHoveringControls"] === false) {
controlsElement.style.display = "none";
return;
}
const isPanelVisible = this.stateManager.state.isPanelVisible;
const magnifyGlass = window.comfyUIMagnifyGlass;
let referenceRect = null;
if (isPanelVisible && this.panelElement) {
referenceRect = this.panelElement.getBoundingClientRect();
} else if (magnifyGlass && magnifyGlass.ui && magnifyGlass.ui.glassDiv) {
referenceRect = magnifyGlass.ui.glassDiv.getBoundingClientRect();
if (referenceRect.width === 0 || referenceRect.height === 0) {
controlsElement.style.display = "none";
return;
}
}
if (!referenceRect) return;
const controlsPosition = this.stateManager.state.settings["🔍MagnifyGlass.ControlsPosition"] || "right";
const margin = 4;
let left;
let top;
switch (controlsPosition) {
case "left":
left = referenceRect.left - controlsElement.offsetWidth - margin;
top = referenceRect.top;
break;
case "right":
left = referenceRect.right + margin;
top = referenceRect.top;
break;
case "top":
left = referenceRect.left;
top = referenceRect.top - controlsElement.offsetHeight - margin;
break;
case "bottom":
left = referenceRect.left;
top = referenceRect.bottom + margin;
break;
case "top-right":
left = referenceRect.right - controlsElement.offsetWidth;
top = referenceRect.top - controlsElement.offsetHeight - margin;
break;
default:
left = referenceRect.right + margin;
top = referenceRect.top;
}
left = Math.max(10, Math.min(left, window.innerWidth - controlsElement.offsetWidth - 10));
top = Math.max(10, Math.min(top, window.innerHeight - controlsElement.offsetHeight - 10));
controlsElement.style.left = `${left}px`;
controlsElement.style.top = `${top}px`;
controlsElement.style.display = "flex";
controlsElement.style.visibility = "visible";
}
}
export {
PositionManager
};
//# sourceMappingURL=PositionManager.js.map
File diff suppressed because one or more lines are too long
+285
View File
@@ -0,0 +1,285 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { getSettingValue } from "../shared/utils.js";
import { DEFAULT_PANEL_SETTINGS } from "../shared/settings/defaults.js";
import "/scripts/app.js";
class StateManager {
constructor() {
__publicField(this, "state");
this.state = {
// Panel visibility and positioning
isPanelVisible: false,
wasPanelVisibleBeforeHide: false,
isPanelMinimized: true,
isPanelPinned: false,
isPanelLocked: false,
// New lock state
isAutoPinned: false,
// Track if panel was auto-pinned by glass hide
pinnedPosition: { x: 0, y: 0 },
lastPinnedPosition: null,
// Remember last pinned location
// Glass visibility
isGlassPreviewVisible: true,
// Section expansion
expandedSections: /* @__PURE__ */ new Set(["node"]),
// Interaction states
isPanelHovered: false,
isHoveringNode: false,
// Auto-collapse
autoExpandTimer: null,
lastNodeId: null,
// Update scheduling
updateScheduled: false,
isInitialLoading: false,
// Current data
currentInfo: null,
// Settings cache
settings: {},
// Auto-detected theme
currentTheme: "dark"
// Will be auto-detected
};
this.initThemeDetection();
this.loadSettings();
}
initThemeDetection() {
this.detectCurrentTheme();
setTimeout(() => {
if (this.detectCurrentTheme()) {
this.notifyThemeChange();
}
}, 1e3);
this.setupThemeObserver();
if (window.matchMedia) {
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)");
if (prefersDark.addListener) {
prefersDark.addListener(() => this.detectCurrentTheme());
} else if (prefersDark.addEventListener) {
prefersDark.addEventListener("change", () => this.detectCurrentTheme());
}
}
this.setupThemeButtonListeners();
}
detectCurrentTheme() {
let detectedTheme = "dark";
try {
const colorPalette = getSettingValue("Comfy.ColorPalette", "");
if (colorPalette) {
const paletteStr = String(colorPalette).toLowerCase();
if (paletteStr.includes("solarized")) {
detectedTheme = "solarized";
} else if (paletteStr.includes("arc")) {
detectedTheme = "arc";
} else if (paletteStr.includes("nord")) {
detectedTheme = "nord";
} else if (paletteStr.includes("github")) {
detectedTheme = "github";
} else if (paletteStr.includes("light")) {
detectedTheme = "light";
} else if (paletteStr.includes("dark")) {
detectedTheme = "dark";
}
}
} catch (e) {
console.warn("ComfyUI Info Panel: Could not read theme from settings, using fallback detection");
}
if (detectedTheme === "dark") {
const body = document.body;
const html = document.documentElement;
const dataTheme = body.getAttribute("data-theme") || html.getAttribute("data-theme");
if (dataTheme) {
detectedTheme = dataTheme.toLowerCase();
}
const classes = (body.className + " " + html.className).toLowerCase();
if (classes.includes("theme-solarized") || classes.includes("solarized")) {
detectedTheme = "solarized";
} else if (classes.includes("theme-arc") || classes.includes("arc-theme")) {
detectedTheme = "arc";
} else if (classes.includes("theme-nord") || classes.includes("nord-theme")) {
detectedTheme = "nord";
} else if (classes.includes("theme-github") || classes.includes("github-theme")) {
detectedTheme = "github";
} else if (classes.includes("theme-light") || classes.includes("light-theme")) {
detectedTheme = "light";
}
}
if (detectedTheme === "dark") {
const bodyStyles = window.getComputedStyle(document.body);
const bgColor = bodyStyles.backgroundColor;
if (bgColor && bgColor !== "rgba(0, 0, 0, 0)" && bgColor !== "transparent") {
const rgbMatch = bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
if (rgbMatch) {
const [, r, g, b] = rgbMatch.map(Number);
const brightness = (r * 299 + g * 587 + b * 114) / 1e3;
if (brightness > 180) {
detectedTheme = "light";
}
}
}
}
if (this.state.currentTheme !== detectedTheme) {
this.state.currentTheme = detectedTheme;
return true;
}
return false;
}
setupThemeObserver() {
const observer = new MutationObserver((mutations) => {
let shouldCheck = false;
mutations.forEach((mutation) => {
if (mutation.type === "attributes" && (mutation.attributeName === "class" || mutation.attributeName === "data-theme" || mutation.attributeName === "style")) {
shouldCheck = true;
}
});
if (shouldCheck && this.detectCurrentTheme()) {
this.notifyThemeChange();
}
});
observer.observe(document.body, { attributes: true, attributeOldValue: true });
observer.observe(document.documentElement, { attributes: true, attributeOldValue: true });
const vueApp = document.querySelector("#vue-app");
if (vueApp) {
observer.observe(vueApp, { attributes: true, attributeOldValue: true });
}
const themeElements = document.querySelectorAll('[class*="theme"], [class*="dark"], [class*="light"], [data-theme]');
themeElements.forEach((el) => {
observer.observe(el, { attributes: true, attributeOldValue: true });
});
setInterval(() => {
if (this.detectCurrentTheme()) {
this.notifyThemeChange();
}
}, 2e3);
}
setupThemeButtonListeners() {
document.addEventListener("click", (e) => {
var _a, _b, _c, _d;
const target = e.target;
const isThemeButton = ((_a = target.textContent) == null ? void 0 : _a.toLowerCase().includes("theme")) || ((_b = target.textContent) == null ? void 0 : _b.toLowerCase().includes("light")) || ((_c = target.textContent) == null ? void 0 : _c.toLowerCase().includes("dark")) || ((_d = target.title) == null ? void 0 : _d.toLowerCase().includes("theme")) || typeof target.className === "string" && target.className.toLowerCase().includes("theme");
if (isThemeButton) {
setTimeout(() => {
if (this.detectCurrentTheme()) {
this.notifyThemeChange();
}
}, 100);
}
});
}
notifyThemeChange() {
this.state.settings["🔍MagnifyGlass.InfoPanelTheme"] = this.state.currentTheme;
if (window.infoPanelManager && window.infoPanelManager.uiManager) {
window.infoPanelManager.uiManager.updateTheme(this.state.currentTheme);
}
}
loadSettings() {
Object.keys(DEFAULT_PANEL_SETTINGS).forEach((key) => {
if (key !== "🔍MagnifyGlass.InfoPanelTheme") {
this.state.settings[key] = getSettingValue(key, DEFAULT_PANEL_SETTINGS[key]);
}
});
this.state.settings["🔍MagnifyGlass.InfoPanelTheme"] = this.state.currentTheme;
}
updateSettings() {
const oldSettings = { ...this.state.settings };
this.loadSettings();
const changes = {};
Object.keys(this.state.settings).forEach((key) => {
if (oldSettings[key] !== this.state.settings[key]) {
changes[key] = {
old: oldSettings[key],
new: this.state.settings[key]
};
}
});
return changes;
}
togglePanelVisibility() {
this.state.isPanelVisible = !this.state.isPanelVisible;
return this.state.isPanelVisible;
}
toggleGlassPreview() {
this.state.isGlassPreviewVisible = !this.state.isGlassPreviewVisible;
return this.state.isGlassPreviewVisible;
}
togglePinning() {
const wasPinned = this.state.isPanelPinned;
this.state.isPanelPinned = !this.state.isPanelPinned;
if (!this.state.isPanelPinned) {
this.state.isPanelLocked = false;
this.state.isAutoPinned = false;
} else {
this.state.isAutoPinned = false;
}
if (this.state.isPanelPinned && this.state.lastPinnedPosition) {
this.state.pinnedPosition = { ...this.state.lastPinnedPosition };
} else if (!this.state.isPanelPinned && wasPinned) {
this.state.lastPinnedPosition = { ...this.state.pinnedPosition };
}
return this.state.isPanelPinned;
}
toggleLocking() {
if (!this.state.isPanelPinned) {
return false;
}
this.state.isPanelLocked = !this.state.isPanelLocked;
return this.state.isPanelLocked;
}
toggleMinimized() {
this.state.isPanelMinimized = !this.state.isPanelMinimized;
return this.state.isPanelMinimized;
}
toggleSection(sectionId) {
if (sectionId === "node") return false;
if (this.state.expandedSections.has(sectionId)) {
this.state.expandedSections.delete(sectionId);
} else {
this.state.expandedSections.add(sectionId);
}
return true;
}
setPinnedPosition(x, y) {
this.state.pinnedPosition = { x, y };
this.state.lastPinnedPosition = { x, y };
}
setCurrentInfo(info) {
this.state.currentInfo = info;
}
scheduleAutoCollapse() {
this.clearAutoExpandTimer();
if (this.state.settings["🔍MagnifyGlass.InfoPanelAnimations"]) {
this.state.autoExpandTimer = setTimeout(() => {
if (!this.state.isPanelHovered) {
this.collapseNodeSections();
}
}, 1500);
}
}
clearAutoExpandTimer() {
if (this.state.autoExpandTimer) {
clearTimeout(this.state.autoExpandTimer);
this.state.autoExpandTimer = null;
}
}
expandNodeSections() {
this.state.expandedSections.add("hoveredNode");
this.state.expandedSections.add("node");
this.state.expandedSections.add("cursor");
this.state.expandedSections.add("canvas");
this.state.expandedSections.add("magnifier");
this.clearAutoExpandTimer();
}
collapseNodeSections() {
this.state.expandedSections.delete("hoveredNode");
this.state.expandedSections.delete("node");
this.state.expandedSections.delete("widget");
}
cleanup() {
this.clearAutoExpandTimer();
}
}
export {
StateManager
};
//# sourceMappingURL=StateManager.js.map
File diff suppressed because one or more lines are too long
+517
View File
@@ -0,0 +1,517 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { Icons } from "../shared/icons.js";
import { Logger } from "../shared/logger.js";
import { formatValue, getValueClass, getValueAttributes } from "./ValueFormatter.js";
import { getCheckpointInfo, getImageInfo, getTextBoxContent, getImportantNodeParameters } from "./NodeDataExtractor.js";
class UIManager {
constructor(stateManager) {
__publicField(this, "stateManager");
__publicField(this, "elements");
this.stateManager = stateManager;
this.elements = {
panel: null,
header: null,
content: null,
controls: null
};
this.createPanel();
this.injectStyles();
}
/**
* Create the main panel and its components.
*/
createPanel() {
this.elements.panel = document.createElement("div");
this.elements.panel.id = "comfyui-magnify-info-panel-pro-v2";
this.elements.panel.className = `magnify-info-panel theme-${this.stateManager.state.currentTheme}`;
this.elements.header = document.createElement("div");
this.elements.header.className = "panel-header";
this.elements.header.innerHTML = `
<div class="header-content">
<div class="header-icon">${Icons.magnifyGlass}</div>
<div class="header-title">Inspector</div>
<div class="header-subtitle">Real-time analysis</div>
</div>
<div class="header-controls">
<button class="control-btn minimize-btn" title="Minimize Panel" data-action="minimize">${Icons.minus}</button>
</div>
`;
this.elements.content = document.createElement("div");
this.elements.content.className = "panel-content";
this.elements.panel.appendChild(this.elements.header);
this.elements.panel.appendChild(this.elements.content);
this.applyStyles();
if (this.stateManager.state.isPanelMinimized) {
this.elements.panel.classList.add("panel-minimized");
}
document.body.appendChild(this.elements.panel);
this.elements.panel.addEventListener("click", (e) => {
const target = e.target;
const minimizeBtn = target.closest('[data-action="minimize"]');
if (minimizeBtn) {
this.stateManager.state.isPanelMinimized = !this.stateManager.state.isPanelMinimized;
this.updateMinimizedState();
return;
}
const sectionHeader = target.closest(".section-header");
if (sectionHeader) {
const sectionId = sectionHeader.getAttribute("data-section");
if (sectionId && sectionId !== "node") {
const isExpanded = this.stateManager.state.expandedSections.has(sectionId);
if (isExpanded) {
this.stateManager.state.expandedSections.delete(sectionId);
} else {
this.stateManager.state.expandedSections.add(sectionId);
}
sectionHeader.classList.toggle("expanded", !isExpanded);
const sectionContent = sectionHeader.nextElementSibling;
if (sectionContent && sectionContent.classList.contains("section-content")) {
sectionContent.classList.toggle("expanded", !isExpanded);
}
}
}
});
if (!this.elements.controls) {
this.createFloatingControls();
this.updateControlStates();
}
}
/**
* Create floating control buttons.
*/
createFloatingControls() {
this.elements.controls = document.createElement("div");
this.elements.controls.className = "floating-controls vertical-layout";
this.elements.controls.innerHTML = `
<button class="control-btn unlock-btn" title="Unlock/Lock Panel from Glass" data-action="pin">${Icons.unlock}</button>
<button class="control-btn pin-btn" title="Pin/Unpin Panel Position (Prevent Drag)" data-action="lock">${Icons.pin}</button>
<button class="control-btn visibility-btn" title="Toggle Panel Visibility (I)" data-action="toggle-panel">${Icons.eye}</button>
<button class="control-btn glass-btn" title="Toggle Glass Preview (G)" data-action="toggle-glass">${Icons.magnifyGlass}</button>
`;
document.body.appendChild(this.elements.controls);
this.elements.controls.style.display = "none";
this.elements.controls.style.visibility = "hidden";
this.elements.controls.style.left = "-9999px";
this.elements.controls.style.top = "-9999px";
this.elements.controls.addEventListener("click", (e) => {
var _a;
const target = e.target;
const button = target.closest("button[data-action]");
if (!button) return;
const action = button.getAttribute("data-action");
Logger.debug(`Control button clicked: ${action}`);
switch (action) {
case "pin":
this.stateManager.togglePinning();
this.updatePinnedState();
this.updateControlStates();
break;
case "lock":
this.stateManager.state.isPanelLocked = !this.stateManager.state.isPanelLocked;
this.updateControlStates();
if (this.elements.panel) {
this.elements.panel.classList.toggle("panel-locked", this.stateManager.state.isPanelLocked);
}
break;
case "toggle-panel":
if (this.stateManager.state.isPanelVisible) {
this.hide();
} else {
this.show();
}
this.updateControlStates();
break;
case "toggle-glass":
this.stateManager.state.isGlassPreviewVisible = !this.stateManager.state.isGlassPreviewVisible;
if (!this.stateManager.state.isGlassPreviewVisible) {
console.log(`[MagnifyGlass Debug] Glass Hidden. pinned=${this.stateManager.state.isPanelPinned}, autoPinned=${this.stateManager.state.isAutoPinned}`);
if (!this.stateManager.state.isPanelPinned) {
if (this.elements.panel) {
const rect = this.elements.panel.getBoundingClientRect();
this.stateManager.state.pinnedPosition = { x: rect.left, y: rect.top };
}
this.stateManager.state.isPanelPinned = true;
this.stateManager.state.isAutoPinned = true;
console.log(`[MagnifyGlass Debug] Auto-Pinned panel.`);
}
this.stateManager.state.isPanelLocked = false;
} else {
console.log(`[MagnifyGlass Debug] Glass Shown. pinned=${this.stateManager.state.isPanelPinned}, autoPinned=${this.stateManager.state.isAutoPinned}`);
if (this.stateManager.state.isAutoPinned) {
this.stateManager.state.isPanelPinned = false;
this.stateManager.state.isAutoPinned = false;
console.log(`[MagnifyGlass Debug] Auto-Unpinned panel.`);
}
}
this.updateControlStates();
this.updatePinnedState();
const magnifyGlass = window.comfyUIMagnifyGlass;
if (magnifyGlass && ((_a = magnifyGlass.ui) == null ? void 0 : _a.setPreviewVisibility)) {
magnifyGlass.ui.setPreviewVisibility(this.stateManager.state.isGlassPreviewVisible);
}
break;
}
});
const controlsPosition = String(this.stateManager.state.settings["🔍MagnifyGlass.ControlsPosition"] || "top-right");
this.updateControlsLayout(controlsPosition);
this.updateControlStates();
}
/**
* Update control button states.
*/
updateControlStates() {
if (!this.elements.controls) return;
const pinBtn = this.elements.controls.querySelector('[data-action="pin"]');
const lockBtn = this.elements.controls.querySelector('[data-action="lock"]');
const visibilityBtn = this.elements.controls.querySelector('[data-action="toggle-panel"]');
const glassBtn = this.elements.controls.querySelector('[data-action="toggle-glass"]');
const isPanelVisible = this.stateManager.state.isPanelVisible;
const isGlassVisible = this.stateManager.state.isGlassPreviewVisible;
if (pinBtn) {
pinBtn.classList.toggle("active", this.stateManager.state.isPanelPinned);
pinBtn.title = this.stateManager.state.isPanelPinned ? "Lock Panel" : "Unlock Panel";
pinBtn.innerHTML = this.stateManager.state.isPanelPinned ? Icons.lock : Icons.unlock;
pinBtn.style.display = isPanelVisible ? "flex" : "none";
if (!isGlassVisible) {
pinBtn.disabled = true;
pinBtn.style.opacity = "0.5";
pinBtn.title = "Cannot unlock panel from screen when glass preview is hidden";
} else {
pinBtn.disabled = false;
pinBtn.style.opacity = "";
}
}
if (lockBtn) {
const showLockBtn = isPanelVisible && this.stateManager.state.isPanelPinned;
lockBtn.style.display = showLockBtn ? "flex" : "none";
lockBtn.classList.toggle("active", this.stateManager.state.isPanelLocked);
lockBtn.title = this.stateManager.state.isPanelLocked ? "Unpin Panel Position" : "Pin Panel Position";
lockBtn.disabled = !this.stateManager.state.isPanelPinned;
}
if (visibilityBtn) {
visibilityBtn.classList.toggle("active", isPanelVisible);
visibilityBtn.title = isPanelVisible ? "Hide Panel" : "Show Panel";
if (!isGlassVisible) {
visibilityBtn.disabled = true;
visibilityBtn.style.opacity = "0.5";
visibilityBtn.title = "Cannot hide panel when glass preview is hidden";
} else {
visibilityBtn.disabled = false;
visibilityBtn.style.opacity = "";
}
}
if (glassBtn) {
glassBtn.classList.toggle("active", isGlassVisible);
glassBtn.title = isGlassVisible ? "Hide Glass Preview" : "Show Glass Preview";
glassBtn.style.display = isPanelVisible ? "flex" : "none";
}
}
/**
* Update controls layout based on position setting.
* @param position
*/
updateControlsLayout(position) {
if (!this.elements.controls) return;
this.elements.controls.classList.remove("horizontal-layout", "vertical-layout");
if (["top", "bottom"].includes(position)) {
this.elements.controls.classList.add("horizontal-layout");
} else {
this.elements.controls.classList.add("vertical-layout");
}
}
/**
* Apply current styles to elements.
*/
applyStyles() {
if (!this.elements.panel) return;
const settings = this.stateManager.state.settings;
console.log(`[UIManager] applyStyles - MaxHeight: ${settings["🔍MagnifyGlass.InfoPanelMaxHeight"]}`);
this.elements.panel.style.width = `${settings["🔍MagnifyGlass.InfoPanelWidth"]}px`;
const maxHeight = settings["🔍MagnifyGlass.InfoPanelMaxHeight"];
this.elements.panel.style.height = `${maxHeight}px`;
this.elements.panel.style.maxHeight = `${maxHeight}px`;
this.elements.panel.style.position = "absolute";
this.elements.panel.style.zIndex = "99999";
this.elements.panel.style.transform = "translateY(-10px)";
this.elements.panel.style.pointerEvents = "auto";
this.elements.panel.style.userSelect = "none";
this.elements.panel.style.fontFamily = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif";
this.elements.panel.style.transition = settings["🔍MagnifyGlass.InfoPanelAnimations"] ? "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)" : "none";
const textColor = settings["🔍MagnifyGlass.InfoPanelTextColor"];
if (textColor && typeof textColor === "string") {
const normalizedTextColor = textColor.startsWith("#") ? textColor : `#${textColor}`;
this.elements.panel.style.setProperty("--info-panel-text-color", normalizedTextColor);
}
const accentColor = settings["🔍MagnifyGlass.InfoPanelAccentColor"];
if (accentColor && typeof accentColor === "string") {
const normalizedAccentColor = accentColor.startsWith("#") ? accentColor : `#${accentColor}`;
this.elements.panel.style.setProperty("--info-panel-accent-color", normalizedAccentColor);
}
if (this.stateManager.state.isPanelVisible) {
const opacityPercent = Number(settings["🔍MagnifyGlass.InfoPanelOpacity"]) || 100;
this.elements.panel.style.opacity = (opacityPercent / 100).toString();
} else {
this.elements.panel.style.opacity = "0";
}
}
/**
* Show the panel.
*/
show() {
if (!this.elements.panel) return;
if (this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelEnabled"]) {
this.elements.panel.style.display = "block";
const opacityPercent = Number(this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelOpacity"]) || 100;
this.elements.panel.style.opacity = (opacityPercent / 100).toString();
this.elements.panel.offsetHeight;
this.elements.panel.classList.add("visible");
this.stateManager.state.isPanelVisible = true;
this.updateControlStates();
}
}
/**
* Hide the panel.
*/
hide() {
if (!this.elements.panel) return;
this.elements.panel.classList.remove("visible");
setTimeout(() => {
if (!this.stateManager.state.isPanelVisible && this.elements.panel) {
this.elements.panel.style.display = "none";
}
}, this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelAnimations"] ? 300 : 0);
this.stateManager.state.isPanelVisible = false;
this.updateControlStates();
}
/**
* Update minimized state.
*/
updateMinimizedState() {
if (!this.elements.panel || !this.elements.header) return;
this.elements.panel.classList.toggle("panel-minimized", this.stateManager.state.isPanelMinimized);
const minimizeBtn = this.elements.header.querySelector(".minimize-btn");
if (minimizeBtn) {
minimizeBtn.textContent = this.stateManager.state.isPanelMinimized ? "+" : "−";
minimizeBtn.title = this.stateManager.state.isPanelMinimized ? "Expand Panel" : "Minimize Panel";
}
}
/**
* Update pinned state.
*/
updatePinnedState() {
if (!this.elements.panel) return;
this.elements.panel.classList.toggle("panel-pinned", this.stateManager.state.isPanelPinned);
this.elements.panel.classList.toggle("panel-locked", this.stateManager.state.isPanelLocked);
this.updateControlStates();
}
/**
* Update theme class.
* @param newTheme
*/
updateTheme(newTheme) {
if (this.elements.panel) {
this.elements.panel.className = this.elements.panel.className.replace(/theme-\w+/, `theme-${newTheme.toLowerCase()}`);
}
}
/**
* Display information in the panel.
* @param info
*/
displayInfo(info) {
const sections = this.buildSections(info);
this.renderSections(sections);
this.updateSectionStates();
this.updateHeaderSubtitle(info);
}
/**
* Build section data from info object.
* @param info
* @returns
*/
buildSections(info) {
const sections = [];
const settings = this.stateManager.state.settings;
if (settings["🔍MagnifyGlass.ShowInspectorTab"] && info.cursor && info.cursor.canvas) {
const inspectorContent = [
{ label: "Cursor Canvas", value: `(${Math.round(info.cursor.canvas.x)}, ${Math.round(info.cursor.canvas.y)})` },
{ label: "Canvas Scale", value: `${(info.canvas.scale * 100).toFixed(1)}%` },
{ label: "Magnifier Zoom", value: `${info.magnifier.zoomFactor}×` }
];
sections.push({
id: "inspector",
icon: Icons.info,
title: "Inspector",
content: inspectorContent
});
}
if (info.media) {
const mediaContent = [
{ label: "Type", value: info.media.tagName },
{ label: "Source", value: info.media.src }
];
if (info.media.naturalSize) {
mediaContent.push({ label: "Natural", value: info.media.naturalSize });
}
sections.push({
id: "media",
icon: Icons.camera,
title: "Media",
badge: info.media.tagName,
content: mediaContent
});
}
if (info.hoveredNode) {
const nodeContent = [
{ label: "Title", value: info.hoveredNode.title }
];
const nodeType = info.hoveredNode.type ? info.hoveredNode.type.toLowerCase() : "";
const isSaveNode = nodeType.includes("save") && !nodeType.includes("checkpoint") && !nodeType.includes("model") && !nodeType.includes("preview");
const showAllWidgets = info.hoveredNode.type && (nodeType.includes("ksampler") || nodeType.includes("sampler") || nodeType.includes("k_samplers") || nodeType.includes("checkpoint") || nodeType.includes("model") || nodeType.includes("lora") || nodeType.includes("controlnet") || nodeType.includes("advanced") || nodeType.includes("detailer") || nodeType.includes("inpaint") || nodeType.includes("upscale") || nodeType.includes("clip") || nodeType.includes("text") || nodeType.includes("encode")) && !isSaveNode;
if (!showAllWidgets) {
const checkpoint = getCheckpointInfo(info.hoveredNode);
if (checkpoint) {
nodeContent.push({ label: "Model", value: checkpoint });
}
const imgInfo = getImageInfo(info.hoveredNode);
if (imgInfo) {
if (typeof imgInfo === "string") {
nodeContent.push({ label: "Image", value: imgInfo });
} else if (typeof imgInfo === "object" && imgInfo !== null) {
const imgResult = imgInfo;
nodeContent.push({ label: "Image Size", value: `${imgResult.width}×${imgResult.height}` });
if (imgResult.src) {
nodeContent.push({ label: "Image Source", value: imgResult.src });
}
}
}
const textContent = getTextBoxContent(info.hoveredNode);
if (textContent) {
nodeContent.push({ label: "Text", value: textContent });
}
}
const importantParameters = getImportantNodeParameters(info.hoveredNode);
nodeContent.push(...importantParameters);
sections.push({
id: "node",
icon: Icons.box,
title: "Node",
badge: info.hoveredNode.type,
content: nodeContent
});
}
return sections;
}
/**
* Render sections to the panel.
* @param sections
*/
renderSections(sections) {
if (!this.elements.content) return;
if (sections.length === 0) {
this.elements.content.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">${Icons.mapPin}</div>
<div class="empty-state-text">Empty canvas area</div>
</div>
`;
return;
}
this.elements.content.innerHTML = sections.map((section) => `
<div class="info-section" data-section="${section.id}">
<div class="section-header" data-section="${section.id}">
<span class="section-icon">${section.icon}</span>
<span class="section-title">${section.title}</span>
${section.badge ? `<span class="section-badge">${section.badge}</span>` : ""}
${section.id !== "node" ? `<span class="expand-icon">${Icons.chevronRight}</span>` : ""}
</div>
<div class="section-content">
<div class="section-body">
${section.content.map((item) => {
const value = formatValue(item.value, item.label);
const valueClass = getValueClass(item.value);
const valueAttributes = getValueAttributes(item.value);
return `
<div class="info-row">
<span class="info-label">${item.label}</span>
<span class="info-value ${valueClass}" ${valueAttributes}>${value}</span>
</div>`;
}).join("")}
</div>
</div>
</div>
`).join("");
}
/**
* Update section expansion states.
*/
updateSectionStates() {
if (!this.elements.content) return;
const sections = this.elements.content.querySelectorAll(".info-section");
sections.forEach((section) => {
const sectionId = section.dataset.section;
if (!sectionId) return;
const header = section.querySelector(".section-header");
const content = section.querySelector(".section-content");
if (header && content) {
if (this.stateManager.state.expandedSections.has(sectionId)) {
header.classList.add("expanded");
content.classList.add("expanded");
} else {
header.classList.remove("expanded");
content.classList.remove("expanded");
}
}
});
}
/**
* Update header subtitle.
* @param info
*/
updateHeaderSubtitle(info) {
if (!this.elements.header) return;
const subtitleElement = this.elements.header.querySelector(".header-subtitle");
if (subtitleElement) {
const accentColor = String(this.stateManager.state.settings["🔍MagnifyGlass.InfoPanelAccentColor"] || "");
if (info.hoveredNode) {
subtitleElement.textContent = `Analyzing: ${info.hoveredNode.title}`;
subtitleElement.style.color = accentColor;
} else if (info.media) {
subtitleElement.textContent = `Media: ${info.media.tagName}`;
subtitleElement.style.color = accentColor;
} else if (info.connection) {
subtitleElement.textContent = `Connection: ${info.connection.type}`;
subtitleElement.style.color = accentColor;
} else {
subtitleElement.textContent = "Real-time analysis";
subtitleElement.style.color = "";
}
}
}
/**
* Inject CSS styles by loading external stylesheet.
*/
injectStyles() {
if (!document.getElementById("magnify-info-panel-styles-v2")) {
const link = document.createElement("link");
link.id = "magnify-info-panel-styles-v2";
link.rel = "stylesheet";
link.type = "text/css";
link.href = "extensions/comfyui-magnifyglass/info-panel.css";
document.head.appendChild(link);
}
}
cleanup() {
if (this.elements.panel && this.elements.panel.parentNode) {
this.elements.panel.parentNode.removeChild(this.elements.panel);
}
if (this.elements.controls && this.elements.controls.parentNode) {
this.elements.controls.parentNode.removeChild(this.elements.controls);
}
}
}
export {
UIManager
};
//# sourceMappingURL=UIManager.js.map
File diff suppressed because one or more lines are too long
+50
View File
@@ -0,0 +1,50 @@
function formatValue(value, label) {
if (value === null || value === void 0) return "";
const str = String(value);
if (label && (label.toLowerCase().includes("text") || label.toLowerCase().includes("prompt") || label.toLowerCase().includes("model") || label.toLowerCase().includes("file") || label.toLowerCase().includes("conditioning") || label.toLowerCase().includes("positive") || label.toLowerCase().includes("negative"))) {
return str;
}
return str;
}
function getValueClass(value) {
if (!value) return "";
const str = String(value);
const classes = [];
if (str.length > 100) {
classes.push("long-text");
}
return classes.join(" ");
}
function getValueAttributes(value) {
if (!value) return "";
const str = String(value);
if (str.length > 500) {
return `title="${str.replace(/"/g, "&quot;")}"`;
}
return "";
}
function formatWidgetValue(value) {
if (value === null) return "null";
if (value === void 0) return "undefined";
if (typeof value === "string") {
return value;
}
if (typeof value === "number") {
return Number.isInteger(value) ? value.toString() : value.toFixed(3);
}
if (typeof value === "boolean") return value.toString();
if (Array.isArray(value)) {
return `Array(${value.length})`;
}
if (typeof value === "object") {
return "Object";
}
return String(value);
}
export {
formatValue,
formatWidgetValue,
getValueAttributes,
getValueClass
};
//# sourceMappingURL=ValueFormatter.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"ValueFormatter.js","sources":["../../src/info-panel/ValueFormatter.ts"],"sourcesContent":["/**\n * ComfyUI MagnifyGlass - Value Formatter Utilities\n * \n * Pure utility functions for formatting values in the info panel display.\n * Extracted from UIManager.ts for better modularity.\n */\n\n/**\n * Format a value for display in the info panel.\n * @param value - The value to format\n * @param label - Optional label to determine formatting rules\n * @returns Formatted string representation\n */\nexport function formatValue(value: unknown, label?: string): string {\n if (value === null || value === undefined) return '';\n\n const str = String(value);\n\n // Show full text for prompts, text content, model names, and file paths\n if (label && (\n label.toLowerCase().includes('text') ||\n label.toLowerCase().includes('prompt') ||\n label.toLowerCase().includes('model') ||\n label.toLowerCase().includes('file') ||\n label.toLowerCase().includes('conditioning') ||\n label.toLowerCase().includes('positive') ||\n label.toLowerCase().includes('negative')\n )) {\n return str;\n }\n\n // Show full text for very long values (no truncation)\n return str;\n}\n\n/**\n * Get CSS class names for styling a value.\n * @param value - The value to get classes for\n * @returns CSS class string\n */\nexport function getValueClass(value: unknown): string {\n if (!value) return '';\n\n const str = String(value);\n const classes: string[] = [];\n\n // Mark text that might benefit from special styling for readability\n if (str.length > 100) {\n classes.push('long-text');\n }\n\n return classes.join(' ');\n}\n\n/**\n * Get HTML attributes for a value element.\n * @param value - The value to get attributes for\n * @returns HTML attribute string\n */\nexport function getValueAttributes(value: unknown): string {\n // Since we show full text now, we don't need title attributes for long text\n // Only add title for very long text that might benefit from tooltips\n if (!value) return '';\n\n const str = String(value);\n if (str.length > 500) { // Only for extremely long text\n return `title=\"${str.replace(/\"/g, '&quot;')}\"`;\n }\n\n return '';\n}\n\n/**\n * Format widget value for display.\n * @param value - Widget value to format\n * @returns Formatted string representation\n */\nexport function formatWidgetValue(value: unknown): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (typeof value === 'string') {\n return value; // Show full text without truncation\n }\n if (typeof value === 'number') {\n return Number.isInteger(value) ? value.toString() : value.toFixed(3);\n }\n if (typeof value === 'boolean') return value.toString();\n if (Array.isArray(value)) {\n return `Array(${value.length})`;\n }\n if (typeof value === 'object') {\n return 'Object';\n }\n return String(value);\n}\n"],"names":[],"mappings":"AAaO,SAAS,YAAY,OAAgB,OAAwB;AAChE,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO;AAElD,QAAM,MAAM,OAAO,KAAK;AAGxB,MAAI,UACA,MAAM,YAAA,EAAc,SAAS,MAAM,KACnC,MAAM,YAAA,EAAc,SAAS,QAAQ,KACrC,MAAM,YAAA,EAAc,SAAS,OAAO,KACpC,MAAM,YAAA,EAAc,SAAS,MAAM,KACnC,MAAM,cAAc,SAAS,cAAc,KAC3C,MAAM,cAAc,SAAS,UAAU,KACvC,MAAM,cAAc,SAAS,UAAU,IACxC;AACC,WAAO;AAAA,EACX;AAGA,SAAO;AACX;AAOO,SAAS,cAAc,OAAwB;AAClD,MAAI,CAAC,MAAO,QAAO;AAEnB,QAAM,MAAM,OAAO,KAAK;AACxB,QAAM,UAAoB,CAAA;AAG1B,MAAI,IAAI,SAAS,KAAK;AAClB,YAAQ,KAAK,WAAW;AAAA,EAC5B;AAEA,SAAO,QAAQ,KAAK,GAAG;AAC3B;AAOO,SAAS,mBAAmB,OAAwB;AAGvD,MAAI,CAAC,MAAO,QAAO;AAEnB,QAAM,MAAM,OAAO,KAAK;AACxB,MAAI,IAAI,SAAS,KAAK;AAClB,WAAO,UAAU,IAAI,QAAQ,MAAM,QAAQ,CAAC;AAAA,EAChD;AAEA,SAAO;AACX;AAOO,SAAS,kBAAkB,OAAwB;AACtD,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO;AAAA,EACX;AACA,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO,OAAO,UAAU,KAAK,IAAI,MAAM,aAAa,MAAM,QAAQ,CAAC;AAAA,EACvE;AACA,MAAI,OAAO,UAAU,UAAW,QAAO,MAAM,SAAA;AAC7C,MAAI,MAAM,QAAQ,KAAK,GAAG;AACtB,WAAO,SAAS,MAAM,MAAM;AAAA,EAChC;AACA,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO;AAAA,EACX;AACA,SAAO,OAAO,KAAK;AACvB;"}
+148
View File
@@ -0,0 +1,148 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { getSettingValue } from "../shared/utils.js";
import { STORAGE_KEYS } from "../shared/constants.js";
const DEFAULT_GLASS_SETTINGS = {
"🔍MagnifyGlass.ZoomFactor": 300,
"🔍MagnifyGlass.GlassSize": 300,
"🔍MagnifyGlass.BorderColor": "#6b7280",
"🔍MagnifyGlass.BorderWidth": 1,
"🔍MagnifyGlass.ActivationKey": "x",
"🔍MagnifyGlass.AltRequired": false,
"🔍MagnifyGlass.FollowCursor": false,
"🔍MagnifyGlass.DebugMode": false,
"🔍MagnifyGlass.OffsetStep": 5,
"🔍MagnifyGlass.GlassPosition": "Top-Right",
"🔍MagnifyGlass.ResetKey": "o",
"🔍MagnifyGlass.GlassShape": "Rounded Square",
"🔍MagnifyGlass.BorderEnabled": true,
"🔍MagnifyGlass.TextureFiltering": "Linear",
"🔍MagnifyGlass.AlwaysActiveMode": true,
"🔍MagnifyGlass.ToggleFollowCursorKey": "h"
};
class ConfigManager {
constructor() {
/** Zoom factor (1.0 = 100%, 3.0 = 300%) */
__publicField(this, "zoomFactor");
/** Glass size in pixels */
__publicField(this, "glassSize");
/** Border color (CSS color string) */
__publicField(this, "borderColor");
/** Border width in pixels */
__publicField(this, "borderWidth");
/** Activation key (lowercase) */
__publicField(this, "activationKey");
/** Whether Alt key is required for activation */
__publicField(this, "altRequired");
/** Whether glass follows cursor */
__publicField(this, "followCursor");
/** Debug mode enabled */
__publicField(this, "debugMode");
/** Offset step for arrow key adjustments */
__publicField(this, "offsetStep");
/** Glass position relative to cursor */
__publicField(this, "glassPosition");
/** Reset key (lowercase) */
__publicField(this, "resetKey");
/** Glass shape */
__publicField(this, "glassShape");
/** Whether border is enabled */
__publicField(this, "borderEnabled");
/** Texture filtering mode */
__publicField(this, "textureFiltering");
/** Always active mode */
__publicField(this, "alwaysActiveMode");
/** Toggle follow cursor key */
__publicField(this, "toggleFollowCursorKey");
/** Manual offset X in graph units */
__publicField(this, "offsetX");
/** Manual offset Y in graph units */
__publicField(this, "offsetY");
this.zoomFactor = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.ZoomFactor"] / 100;
this.glassSize = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.GlassSize"];
this.borderColor = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.BorderColor"];
this.borderWidth = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.BorderWidth"];
this.activationKey = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.ActivationKey"];
this.altRequired = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.AltRequired"];
this.followCursor = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.FollowCursor"];
this.debugMode = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.DebugMode"];
this.offsetStep = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.OffsetStep"];
this.glassPosition = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.GlassPosition"];
this.resetKey = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.ResetKey"];
this.glassShape = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.GlassShape"];
this.borderEnabled = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.BorderEnabled"];
this.textureFiltering = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.TextureFiltering"];
this.alwaysActiveMode = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.AlwaysActiveMode"];
this.toggleFollowCursorKey = DEFAULT_GLASS_SETTINGS["🔍MagnifyGlass.ToggleFollowCursorKey"];
this.offsetX = 0;
this.offsetY = 0;
}
/**
* Load settings from ComfyUI settings system.
*/
loadSettings() {
this.zoomFactor = getSettingValue("🔍MagnifyGlass.ZoomFactor", this.zoomFactor * 100) / 100;
this.glassSize = getSettingValue("🔍MagnifyGlass.GlassSize", this.glassSize);
this.borderColor = getSettingValue("🔍MagnifyGlass.BorderColor", this.borderColor);
this.borderWidth = getSettingValue("🔍MagnifyGlass.BorderWidth", this.borderWidth);
this.activationKey = getSettingValue("🔍MagnifyGlass.ActivationKey", this.activationKey);
this.altRequired = getSettingValue("🔍MagnifyGlass.AltRequired", this.altRequired);
this.followCursor = getSettingValue("🔍MagnifyGlass.FollowCursor", this.followCursor);
this.debugMode = getSettingValue("🔍MagnifyGlass.DebugMode", this.debugMode);
this.offsetStep = getSettingValue("🔍MagnifyGlass.OffsetStep", this.offsetStep);
this.glassPosition = getSettingValue("🔍MagnifyGlass.GlassPosition", this.glassPosition);
this.resetKey = getSettingValue("🔍MagnifyGlass.ResetKey", this.resetKey);
this.glassShape = getSettingValue("🔍MagnifyGlass.GlassShape", this.glassShape);
this.borderEnabled = getSettingValue("🔍MagnifyGlass.BorderEnabled", this.borderEnabled);
this.textureFiltering = getSettingValue("🔍MagnifyGlass.TextureFiltering", this.textureFiltering);
this.alwaysActiveMode = getSettingValue("🔍MagnifyGlass.AlwaysActiveMode", this.alwaysActiveMode);
this.toggleFollowCursorKey = getSettingValue("🔍MagnifyGlass.ToggleFollowCursorKey", this.toggleFollowCursorKey);
}
/**
* Load saved offsets from localStorage.
*/
loadSavedOffsets() {
try {
const savedOffsetX = localStorage.getItem(STORAGE_KEYS.OFFSET_X);
const savedOffsetY = localStorage.getItem(STORAGE_KEYS.OFFSET_Y);
if (savedOffsetX !== null) {
this.offsetX = parseInt(savedOffsetX, 10);
} else {
this.offsetX = 0;
}
if (savedOffsetY !== null) {
this.offsetY = parseInt(savedOffsetY, 10);
} else {
this.offsetY = 0;
}
} catch (e) {
console.error("ComfyUI Magnifying Glass ERROR: Error loading saved offsets:", e);
this.offsetX = 0;
this.offsetY = 0;
}
}
/**
* Save current offsets to localStorage.
*/
saveOffsets() {
try {
localStorage.setItem(STORAGE_KEYS.OFFSET_X, this.offsetX.toString());
localStorage.setItem(STORAGE_KEYS.OFFSET_Y, this.offsetY.toString());
} catch (e) {
console.error("ComfyUI Magnifying Glass ERROR: Error saving offsets:", e);
}
}
/**
* Reset offsets to default (zero).
*/
resetOffsets() {
this.offsetX = 0;
this.offsetY = 0;
this.saveOffsets();
}
}
export {
ConfigManager
};
//# sourceMappingURL=ConfigManager.js.map
File diff suppressed because one or more lines are too long
+128
View File
@@ -0,0 +1,128 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
class DebugManager {
constructor(config, state, ui) {
__publicField(this, "config");
__publicField(this, "state");
__publicField(this, "ui");
this.config = config;
this.state = state;
this.ui = ui;
}
/**
* Log a message if debug mode is enabled.
*/
log(...args) {
if (this.config.debugMode) {
console.log("ComfyUI Magnifying Glass:", ...args);
}
}
/**
* Log an error message.
*/
error(...args) {
console.error("ComfyUI Magnifying Glass ERROR:", ...args);
}
/**
* Print detailed canvas information for debugging.
*/
printCanvasInfo() {
if (!this.config.debugMode) return;
try {
const canvasManager = app.canvas;
const canvas = canvasManager == null ? void 0 : canvasManager.graph_canvas;
if (!canvas) {
this.log("Could not find graph canvas for detailed info");
return;
}
this.log("---- Canvas Information ----");
this.log(`Canvas dimensions: ${canvas.width}x${canvas.height}`);
this.log(`Canvas display size: ${canvas.clientWidth}x${canvas.clientHeight}`);
this.log(`Canvas CSS transform: ${canvas.style.transform || "none"}`);
const ds = canvasManager.ds;
if (ds) {
this.log(`Canvas DS scale: ${ds.scale}`);
if (ds.offset) {
this.log(`Canvas DS offset: [${ds.offset[0]}, ${ds.offset[1]}]`);
} else {
this.log("Canvas DS offset not found");
}
} else {
this.log("Canvas DS object not found");
}
const screenWidth = window.innerWidth;
const screenHeight = window.innerHeight;
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
this.log(`Window dimensions: ${screenWidth}x${screenHeight}`);
this.log(`Resolution scale factor: X=${canvasWidth / screenWidth}, Y=${canvasHeight / screenHeight}`);
this.log("---- End Canvas Information ----");
} catch (e) {
this.log("Error in printCanvasInfo:", e);
}
}
/**
* Update the debug visualization canvas.
*/
updateDebugView() {
if (!this.config.debugMode || !this.ui || !this.ui.debugCanvas || !this.ui.debugCtx) return;
const debugCtx = this.ui.debugCtx;
const debugCanvas = this.ui.debugCanvas;
debugCtx.clearRect(0, 0, debugCanvas.width, debugCanvas.height);
debugCtx.fillStyle = "rgba(0,0,0,0.8)";
debugCtx.fillRect(0, 0, debugCanvas.width, debugCanvas.height);
debugCtx.fillStyle = "#FFFFFF";
debugCtx.font = "14px monospace";
debugCtx.fillText("Magnify Glass Debug", 10, 20);
debugCtx.font = "12px monospace";
debugCtx.fillText(`Cursor: (${this.state.x.toFixed(1)}, ${this.state.y.toFixed(1)})`, 10, 50);
debugCtx.fillText(`Source Rect: (${this.state.sourceX.toFixed(1)}, ${this.state.sourceY.toFixed(1)}, w:${this.state.sourceWidth.toFixed(1)}, h:${this.state.sourceHeight.toFixed(1)})`, 10, 70);
debugCtx.fillText(`Canvas Scale: ${this.state.canvasScale.toFixed(2)}`, 10, 90);
debugCtx.fillText(`Canvas Offset: (${this.state.canvasOffsetX.toFixed(1)}, ${this.state.canvasOffsetY.toFixed(1)})`, 10, 110);
debugCtx.fillStyle = "#FFFF00";
debugCtx.fillText(`MANUAL OFFSETS: X=${this.config.offsetX}, Y=${this.config.offsetY} (Use arrow keys to adjust)`, 10, 130);
debugCtx.fillStyle = "#FFFFFF";
this.drawCanvasVisualization(debugCtx, debugCanvas);
}
/**
* Draw a scaled visualization of the canvas and source region.
*/
drawCanvasVisualization(debugCtx, debugCanvas) {
const canvasScale = 0.1;
const canvasVisX = 10;
const canvasVisY = 170;
const canvasVisWidth = 380;
const canvasVisHeight = 150;
debugCtx.strokeStyle = "#AAAAAA";
debugCtx.strokeRect(canvasVisX, canvasVisY, canvasVisWidth, canvasVisHeight);
debugCtx.fillStyle = "#444444";
debugCtx.fillRect(canvasVisX, canvasVisY, canvasVisWidth, canvasVisHeight);
const cursorVisX = canvasVisX + this.state.x * canvasScale;
const cursorVisY = canvasVisY + this.state.y * canvasScale;
const sourceRectVisX = canvasVisX + this.state.sourceX * canvasScale;
const sourceRectVisY = canvasVisY + this.state.sourceY * canvasScale;
const sourceRectVisWidth = this.state.sourceWidth * canvasScale;
const sourceRectVisHeight = this.state.sourceHeight * canvasScale;
debugCtx.strokeStyle = "#FF0000";
debugCtx.strokeRect(sourceRectVisX, sourceRectVisY, sourceRectVisWidth, sourceRectVisHeight);
debugCtx.fillStyle = "#FFFF00";
debugCtx.beginPath();
debugCtx.arc(cursorVisX, cursorVisY, 3, 0, Math.PI * 2);
debugCtx.fill();
debugCtx.strokeStyle = "#00FF00";
debugCtx.beginPath();
debugCtx.moveTo(cursorVisX, cursorVisY);
debugCtx.lineTo(sourceRectVisX + sourceRectVisWidth / 2, sourceRectVisY + sourceRectVisHeight / 2);
debugCtx.stroke();
debugCtx.fillStyle = "#FFFFFF";
debugCtx.fillText("Canvas Visualization (scaled)", canvasVisX, canvasVisY - 5);
const offsetX = this.state.sourceX - this.state.x + this.state.sourceWidth / 2;
const offsetY = this.state.sourceY - this.state.y + this.state.sourceHeight / 2;
debugCtx.fillText(`Alignment Offset: (${offsetX.toFixed(1)}, ${offsetY.toFixed(1)})`, 10, canvasVisY + canvasVisHeight + 20);
}
}
export {
DebugManager
};
//# sourceMappingURL=DebugManager.js.map
File diff suppressed because one or more lines are too long
+173
View File
@@ -0,0 +1,173 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { isUserTyping } from "../shared/utils.js";
import { Logger } from "../shared/logger.js";
import { DEFAULT_PADDING, DEFAULT_GLASS_Y_OFFSET } from "../shared/constants.js";
class EventHandler {
constructor(magnifyGlass) {
__publicField(this, "magnifyGlass");
this.magnifyGlass = magnifyGlass;
this.handleKeyDown = this.handleKeyDown.bind(this);
this.handleKeyUp = this.handleKeyUp.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
}
/**
* Attach all event listeners.
*/
attachListeners() {
document.addEventListener("keydown", this.handleKeyDown);
document.addEventListener("keyup", this.handleKeyUp);
document.addEventListener("mousemove", this.handleMouseMove);
}
/**
* Detach all event listeners.
*/
detachListeners() {
document.removeEventListener("keydown", this.handleKeyDown);
document.removeEventListener("keyup", this.handleKeyUp);
document.removeEventListener("mousemove", this.handleMouseMove);
}
/**
* Handle keydown events.
*/
handleKeyDown(e) {
const config = this.magnifyGlass.config;
const state = this.magnifyGlass.state;
if (isUserTyping()) {
return;
}
Logger.debug(`KeyDown: ${e.key} (config: ${config.activationKey}, active: ${state.active})`);
if (e.key.toLowerCase() === config.activationKey && (!config.altRequired || e.altKey)) {
Logger.debug("Activation key matched!");
if (config.alwaysActiveMode) {
this.magnifyGlass.toggle();
} else {
if (!state.active) {
this.magnifyGlass.toggle();
}
}
}
if (state.active) {
let offsetChanged = false;
const stepSize = e.shiftKey ? config.offsetStep * 5 : config.offsetStep;
if (e.key === "ArrowUp") {
config.offsetY -= stepSize;
offsetChanged = true;
e.preventDefault();
} else if (e.key === "ArrowDown") {
config.offsetY += stepSize;
offsetChanged = true;
e.preventDefault();
} else if (e.key === "ArrowLeft") {
config.offsetX -= stepSize;
offsetChanged = true;
e.preventDefault();
} else if (e.key === "ArrowRight") {
config.offsetX += stepSize;
offsetChanged = true;
e.preventDefault();
} else if (e.key.toLowerCase() === config.resetKey.toLowerCase() && (!config.altRequired || e.altKey)) {
this.magnifyGlass.resetOffsets();
offsetChanged = true;
e.preventDefault();
}
if (e.key.toLowerCase() === config.toggleFollowCursorKey && (!config.altRequired || e.altKey)) {
config.followCursor = !config.followCursor;
this.magnifyGlass.debugger.log(`Follow Cursor Toggled: ${config.followCursor ? "ON" : "OFF"}`);
if (state.active && config.followCursor) {
this.magnifyGlass.ui.positionGlass(
this.magnifyGlass.lastKnownMousePosition.x,
this.magnifyGlass.lastKnownMousePosition.y
);
}
e.preventDefault();
}
if (offsetChanged) {
config.saveOffsets();
this.magnifyGlass.updateMagnifiedView();
}
}
}
/**
* Handle keyup events.
*/
handleKeyUp(e) {
const config = this.magnifyGlass.config;
const state = this.magnifyGlass.state;
if (!config.alwaysActiveMode && (e.key.toLowerCase() === config.activationKey || config.altRequired && e.key === "Alt")) {
let shouldDeactivate = false;
if (config.altRequired) {
if (e.key === "Alt" || e.key.toLowerCase() === config.activationKey) {
shouldDeactivate = true;
}
} else {
if (e.key.toLowerCase() === config.activationKey) {
shouldDeactivate = true;
}
}
if (state.active && shouldDeactivate) {
state.active = false;
this.magnifyGlass.ui.hide();
}
}
}
/**
* Handle mousemove events.
*/
handleMouseMove(e) {
this.magnifyGlass.lastKnownMousePosition.x = e.clientX;
this.magnifyGlass.lastKnownMousePosition.y = e.clientY;
if (!this.magnifyGlass.state.active || !this.magnifyGlass.litegraphCanvas) return;
const rect = this.magnifyGlass.litegraphCanvas.getBoundingClientRect();
const cssMouseXOnCanvas = e.clientX - rect.left;
const cssMouseYOnCanvas = e.clientY - rect.top;
if (cssMouseXOnCanvas >= 0 && cssMouseXOnCanvas <= rect.width && cssMouseYOnCanvas >= 0 && cssMouseYOnCanvas <= rect.height) {
const canvasElement = this.magnifyGlass.litegraphCanvas;
const scaleX = rect.width > 0 ? canvasElement.width / rect.width : 1;
const scaleY = rect.height > 0 ? canvasElement.height / rect.height : 1;
const pixelX = cssMouseXOnCanvas * scaleX;
const pixelY = cssMouseYOnCanvas * scaleY;
this.magnifyGlass.state.x = pixelX;
this.magnifyGlass.state.y = pixelY;
this.magnifyGlass.ui.positionGlass(e.clientX, e.clientY);
this.magnifyGlass.updateMagnifiedView();
}
}
/**
* Update the initial position when magnifier is activated.
*/
updateInitialPosition() {
if (!this.magnifyGlass.litegraphCanvas) return;
const rect = this.magnifyGlass.litegraphCanvas.getBoundingClientRect();
const clientX = this.magnifyGlass.lastKnownMousePosition.x;
const clientY = this.magnifyGlass.lastKnownMousePosition.y;
const isOverCanvas = clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
if (this.magnifyGlass.config.alwaysActiveMode || isOverCanvas) {
const cssMouseXOnCanvas = clientX - rect.left;
const cssMouseYOnCanvas = clientY - rect.top;
const canvasElement = this.magnifyGlass.litegraphCanvas;
const scaleX = rect.width > 0 ? canvasElement.width / rect.width : 1;
const scaleY = rect.height > 0 ? canvasElement.height / rect.height : 1;
const pixelX = cssMouseXOnCanvas * scaleX;
const pixelY = cssMouseYOnCanvas * scaleY;
this.magnifyGlass.state.x = pixelX;
this.magnifyGlass.state.y = pixelY;
const glassSize = this.magnifyGlass.config.glassSize;
if (!this.magnifyGlass.state.wasActivatedBefore && this.magnifyGlass.ui.glassDiv) {
const leftPos = window.innerWidth - glassSize - DEFAULT_PADDING;
console.log(`[MagnifyGlass] Initial position - innerWidth: ${window.innerWidth}, glassSize: ${glassSize}, padding: ${DEFAULT_PADDING}, left: ${leftPos}, yOffset: ${DEFAULT_GLASS_Y_OFFSET}`);
this.magnifyGlass.ui.glassDiv.style.left = `${leftPos}px`;
this.magnifyGlass.ui.glassDiv.style.top = `${DEFAULT_GLASS_Y_OFFSET}px`;
this.magnifyGlass.state.wasActivatedBefore = true;
} else {
this.magnifyGlass.ui.positionGlass(clientX, clientY);
}
this.magnifyGlass.updateMagnifiedView();
}
}
}
export {
EventHandler
};
//# sourceMappingURL=EventHandler.js.map
File diff suppressed because one or more lines are too long
+64
View File
@@ -0,0 +1,64 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
class MagnifierState {
constructor() {
/** Whether the magnifier is currently active */
__publicField(this, "active");
/** Track if the glass has been activated before */
__publicField(this, "wasActivatedBefore");
/** Cursor X relative to litegraphCanvas */
__publicField(this, "x");
/** Cursor Y relative to litegraphCanvas */
__publicField(this, "y");
/** Calculated source area X */
__publicField(this, "sourceX");
/** Calculated source area Y */
__publicField(this, "sourceY");
/** Calculated source area width */
__publicField(this, "sourceWidth");
/** Calculated source area height */
__publicField(this, "sourceHeight");
/** Current canvas scale/zoom */
__publicField(this, "canvasScale");
/** Canvas translation X */
__publicField(this, "canvasOffsetX");
/** Canvas translation Y */
__publicField(this, "canvasOffsetY");
/** Flag to manage requestAnimationFrame */
__publicField(this, "isRenderScheduled");
this.active = false;
this.wasActivatedBefore = false;
this.x = 0;
this.y = 0;
this.sourceX = 0;
this.sourceY = 0;
this.sourceWidth = 0;
this.sourceHeight = 0;
this.canvasScale = 1;
this.canvasOffsetX = 0;
this.canvasOffsetY = 0;
this.isRenderScheduled = false;
}
/**
* Reset state to initial values.
*/
reset() {
this.active = false;
this.wasActivatedBefore = false;
this.x = 0;
this.y = 0;
this.sourceX = 0;
this.sourceY = 0;
this.sourceWidth = 0;
this.sourceHeight = 0;
this.canvasScale = 1;
this.canvasOffsetX = 0;
this.canvasOffsetY = 0;
this.isRenderScheduled = false;
}
}
export {
MagnifierState
};
//# sourceMappingURL=MagnifierState.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"MagnifierState.js","sources":["../../src/magnify-glass/MagnifierState.ts"],"sourcesContent":["/**\n * ComfyUI MagnifyGlass - MagnifierState (TypeScript)\n * \n * Manages the state of the magnifying glass.\n */\n\n/**\n * Magnifier state class.\n * Tracks activation state, cursor position, and canvas transforms.\n */\nexport class MagnifierState {\n /** Whether the magnifier is currently active */\n active: boolean;\n\n /** Track if the glass has been activated before */\n wasActivatedBefore: boolean;\n\n /** Cursor X relative to litegraphCanvas */\n x: number;\n\n /** Cursor Y relative to litegraphCanvas */\n y: number;\n\n /** Calculated source area X */\n sourceX: number;\n\n /** Calculated source area Y */\n sourceY: number;\n\n /** Calculated source area width */\n sourceWidth: number;\n\n /** Calculated source area height */\n sourceHeight: number;\n\n /** Current canvas scale/zoom */\n canvasScale: number;\n\n /** Canvas translation X */\n canvasOffsetX: number;\n\n /** Canvas translation Y */\n canvasOffsetY: number;\n\n /** Flag to manage requestAnimationFrame */\n isRenderScheduled: boolean;\n\n constructor() {\n this.active = false;\n this.wasActivatedBefore = false;\n this.x = 0;\n this.y = 0;\n this.sourceX = 0;\n this.sourceY = 0;\n this.sourceWidth = 0;\n this.sourceHeight = 0;\n this.canvasScale = 1.0;\n this.canvasOffsetX = 0;\n this.canvasOffsetY = 0;\n this.isRenderScheduled = false;\n }\n\n /**\n * Reset state to initial values.\n */\n reset(): void {\n this.active = false;\n this.wasActivatedBefore = false;\n this.x = 0;\n this.y = 0;\n this.sourceX = 0;\n this.sourceY = 0;\n this.sourceWidth = 0;\n this.sourceHeight = 0;\n this.canvasScale = 1.0;\n this.canvasOffsetX = 0;\n this.canvasOffsetY = 0;\n this.isRenderScheduled = false;\n }\n}\n"],"names":[],"mappings":";;;AAUO,MAAM,eAAe;AAAA,EAqCxB,cAAc;AAnCd;AAAA;AAGA;AAAA;AAGA;AAAA;AAGA;AAAA;AAGA;AAAA;AAGA;AAAA;AAGA;AAAA;AAGA;AAAA;AAGA;AAAA;AAGA;AAAA;AAGA;AAAA;AAGA;AAAA;AAGI,SAAK,SAAS;AACd,SAAK,qBAAqB;AAC1B,SAAK,IAAI;AACT,SAAK,IAAI;AACT,SAAK,UAAU;AACf,SAAK,UAAU;AACf,SAAK,cAAc;AACnB,SAAK,eAAe;AACpB,SAAK,cAAc;AACnB,SAAK,gBAAgB;AACrB,SAAK,gBAAgB;AACrB,SAAK,oBAAoB;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA,EAKA,QAAc;AACV,SAAK,SAAS;AACd,SAAK,qBAAqB;AAC1B,SAAK,IAAI;AACT,SAAK,IAAI;AACT,SAAK,UAAU;AACf,SAAK,UAAU;AACf,SAAK,cAAc;AACnB,SAAK,eAAe;AACpB,SAAK,cAAc;AACnB,SAAK,gBAAgB;AACrB,SAAK,gBAAgB;AACrB,SAAK,oBAAoB;AAAA,EAC7B;AACJ;"}
+330
View File
@@ -0,0 +1,330 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { findLiteGraphCanvas, rectsOverlap } from "../shared/utils.js";
import { DEFAULT_PADDING, DEFAULT_GLASS_Y_OFFSET } from "../shared/constants.js";
import { registerGlassSettings } from "../shared/settings/glassSettings.js";
import "/scripts/app.js";
import { ConfigManager } from "./ConfigManager.js";
import { MagnifierState } from "./MagnifierState.js";
import { UiManager } from "./UiManager.js";
import { WebGLRenderer } from "./WebGLRenderer.js";
import { DebugManager } from "./DebugManager.js";
import { EventHandler } from "./EventHandler.js";
class MagnifyGlass {
constructor() {
__publicField(this, "config");
__publicField(this, "state");
__publicField(this, "ui");
__publicField(this, "renderer");
__publicField(this, "debugger");
__publicField(this, "eventHandler");
/** The LiteGraph canvas */
__publicField(this, "litegraphCanvas");
/** Last known mouse position for better initial positioning */
__publicField(this, "lastKnownMousePosition");
/** Whether we're currently over media (for info panel) */
__publicField(this, "isOverMedia");
/** Current media element under cursor */
__publicField(this, "currentMediaElement");
this.config = new ConfigManager();
this.state = new MagnifierState();
this.ui = new UiManager(this.config, this.state, () => this.toggle());
this.renderer = null;
this.debugger = new DebugManager(this.config, this.state, this.ui);
this.eventHandler = new EventHandler(this);
this.litegraphCanvas = null;
this.lastKnownMousePosition = { x: 0, y: 0 };
this.isOverMedia = false;
this.currentMediaElement = null;
}
/**
* Initialize the magnifying glass.
*/
init() {
if (typeof LiteGraph === "undefined" || typeof app === "undefined" || !app.canvas) {
this.debugger.log("LiteGraph or app not ready, retrying in 100ms.");
setTimeout(() => this.init(), 100);
return;
}
this.debugger.log("LiteGraph and app ready.");
this.config.loadSavedOffsets();
this.debugger.printCanvasInfo();
this.ui.createElements();
this.renderer = new WebGLRenderer(this.config, this.state, this.ui);
if (!this.renderer.isValid()) {
this.ui.cleanup();
return;
}
this.litegraphCanvas = findLiteGraphCanvas();
this.debugger.log("LiteGraph canvas found:", this.litegraphCanvas);
if (!this.litegraphCanvas) {
this.debugger.error("Could not find LiteGraph canvas. Magnifier will not work.");
this.ui.cleanup();
return;
}
this.eventHandler.attachListeners();
registerGlassSettings(this);
this.debugger.log(`Initialized (WebGL) with Smart Input Detection. Press ${this.config.altRequired ? "Alt+" : ""}${this.config.activationKey.toUpperCase()} to activate.`);
}
/**
* Toggle the magnifying glass active state.
*/
toggle() {
const state = this.state;
this.config;
if (state.active) {
state.active = false;
this.ui.hide();
} else {
state.active = true;
this.ui.show();
if (this.eventHandler) {
this.eventHandler.updateInitialPosition();
}
}
}
/**
* Update the magnified view.
*/
updateMagnifiedView() {
if (!this.state.active || !this.renderer || !this.litegraphCanvas) {
return;
}
this.updateCanvasTransformation();
this.calculateSourceRegion();
if (!this.state.isRenderScheduled) {
this.state.isRenderScheduled = true;
requestAnimationFrame(() => {
if (!this.state.active || !this.renderer || !this.litegraphCanvas) {
this.state.isRenderScheduled = false;
return;
}
this.renderer.render(this.litegraphCanvas);
this.debugger.updateDebugView();
this.renderHtmlOverlays();
this.state.isRenderScheduled = false;
});
}
}
/**
* Update canvas transformation state.
*/
updateCanvasTransformation() {
this.state.canvasScale = 1;
this.state.canvasOffsetX = 0;
this.state.canvasOffsetY = 0;
if (app == null ? void 0 : app.canvas) {
const ds = app.canvas.ds;
if (ds) {
if (typeof ds.scale === "number") {
this.state.canvasScale = ds.scale;
}
if (ds.offset) {
this.state.canvasOffsetX = ds.offset[0] || 0;
this.state.canvasOffsetY = ds.offset[1] || 0;
}
}
}
}
/**
* Calculate the source region for magnification.
*/
calculateSourceRegion() {
const cursorPixelX = this.state.x;
const cursorPixelY = this.state.y;
const canvasScale = this.state.canvasScale;
const canvasOffsetX = this.state.canvasOffsetX;
const canvasOffsetY = this.state.canvasOffsetY;
if (canvasScale === 0) return;
const cursorGraphX = (cursorPixelX - canvasOffsetX) / canvasScale;
const cursorGraphY = (cursorPixelY - canvasOffsetY) / canvasScale;
const targetGraphCenterX = cursorGraphX + this.config.offsetX;
const targetGraphCenterY = cursorGraphY + this.config.offsetY;
const sourceGraphWidth = this.config.glassSize / this.config.zoomFactor / canvasScale;
const sourceGraphHeight = this.config.glassSize / this.config.zoomFactor / canvasScale;
const sourceGraphX = targetGraphCenterX - sourceGraphWidth / 2;
const sourceGraphY = targetGraphCenterY - sourceGraphHeight / 2;
this.state.sourceX = sourceGraphX * canvasScale + canvasOffsetX;
this.state.sourceY = sourceGraphY * canvasScale + canvasOffsetY;
this.state.sourceWidth = sourceGraphWidth * canvasScale;
this.state.sourceHeight = sourceGraphHeight * canvasScale;
}
/**
* Render HTML overlays for text and media in the magnified view.
*/
renderHtmlOverlays() {
const graph = app.graph;
if (!this.state.active || !this.ui.htmlOverlayContainer || !graph || !this.litegraphCanvas) {
if (this.ui.htmlOverlayContainer) this.ui.htmlOverlayContainer.innerHTML = "";
return;
}
this.ui.htmlOverlayContainer.innerHTML = "";
const magnifyRect = {
x: this.state.sourceX,
y: this.state.sourceY,
width: this.state.sourceWidth,
height: this.state.sourceHeight
};
const nodes = graph._nodes;
if (!nodes) return;
for (const node of nodes) {
const widgets = node.widgets;
if (!widgets) continue;
for (const widget of widgets) {
let isTextElement = false;
let isVideoElement = false;
let isImageElement = false;
let elementToProcess = null;
if (widget.element) {
const element = widget.element;
if (widget.type === "text" || widget.type === "string" || element.tagName === "TEXTAREA") {
isTextElement = true;
elementToProcess = element;
} else if (element.tagName === "VIDEO") {
isVideoElement = true;
elementToProcess = element;
} else if (element.tagName === "IMG") {
isImageElement = true;
elementToProcess = element;
} else {
const potentialVideo = element.querySelector("video");
if (potentialVideo) {
isVideoElement = true;
elementToProcess = potentialVideo;
} else {
const potentialImage = element.querySelector("img");
if (potentialImage) {
isImageElement = true;
elementToProcess = potentialImage;
}
}
}
}
if (elementToProcess && (isTextElement || isVideoElement || isImageElement)) {
const widgetRect = elementToProcess.getBoundingClientRect();
const canvasRect = this.litegraphCanvas.getBoundingClientRect();
const canvasToViewportScaleX = canvasRect.width > 0 ? this.litegraphCanvas.width / canvasRect.width : 1;
const canvasToViewportScaleY = canvasRect.height > 0 ? this.litegraphCanvas.height / canvasRect.height : 1;
const widgetCanvasX = (widgetRect.left - canvasRect.left) * canvasToViewportScaleX;
const widgetCanvasY = (widgetRect.top - canvasRect.top) * canvasToViewportScaleY;
const widgetCanvasWidth = widgetRect.width * canvasToViewportScaleX;
const widgetCanvasHeight = widgetRect.height * canvasToViewportScaleY;
const widgetSourceRect = {
x: widgetCanvasX,
y: widgetCanvasY,
width: widgetCanvasWidth,
height: widgetCanvasHeight
};
if (rectsOverlap(magnifyRect, widgetSourceRect)) {
const clonedElement = elementToProcess.cloneNode(true);
clonedElement.style.position = "absolute";
clonedElement.style.pointerEvents = "none";
if (isTextElement) {
clonedElement.style.backgroundColor = elementToProcess.style.backgroundColor || "#222";
clonedElement.style.color = elementToProcess.style.color || "#DDD";
clonedElement.style.border = elementToProcess.style.border || "1px solid #555";
clonedElement.disabled = true;
} else if (isVideoElement) {
const video = clonedElement;
const originalVideo = elementToProcess;
video.src = originalVideo.src;
video.autoplay = originalVideo.autoplay;
video.loop = originalVideo.loop;
video.preload = originalVideo.preload;
video.crossOrigin = originalVideo.crossOrigin;
video.muted = true;
if (!originalVideo.paused) {
video.play().catch((e) => console.warn("Magnify Glass: Cloned video play failed", e));
}
video.currentTime = originalVideo.currentTime;
} else if (isImageElement) {
const img = clonedElement;
const originalImg = elementToProcess;
img.src = originalImg.src;
img.alt = originalImg.alt;
}
const relativeX = widgetSourceRect.x - magnifyRect.x;
const relativeY = widgetSourceRect.y - magnifyRect.y;
const magnifiedX = relativeX * this.config.zoomFactor;
const magnifiedY = relativeY * this.config.zoomFactor;
clonedElement.style.left = `${magnifiedX}px`;
clonedElement.style.top = `${magnifiedY}px`;
clonedElement.style.width = `${widgetSourceRect.width}px`;
clonedElement.style.height = `${widgetSourceRect.height}px`;
clonedElement.style.transformOrigin = "top left";
clonedElement.style.transform = `scale(${this.config.zoomFactor})`;
if (isTextElement && clonedElement.style.fontSize) {
const originalFontSize = parseFloat(window.getComputedStyle(elementToProcess).fontSize);
clonedElement.style.fontSize = `${originalFontSize}px`;
}
this.ui.htmlOverlayContainer.appendChild(clonedElement);
}
}
}
}
}
/**
* Update config from current settings values.
*/
updateConfigFromSettings() {
this.config.loadSettings();
}
/**
* Apply UI changes based on current config.
*/
applyUiChanges() {
var _a;
this.ui.applyStyles();
if ((_a = this.renderer) == null ? void 0 : _a.gl) {
this.renderer.updateViewport();
}
}
/**
* Reset offsets and panel positions to defaults.
*/
resetOffsets() {
this.config.resetOffsets();
this.config.followCursor = false;
if (this.state.active) {
this.updateMagnifiedView();
}
if (this.ui.glassDiv) {
const glassSize = this.config.glassSize;
this.ui.glassDiv.style.left = `${window.innerWidth - glassSize - DEFAULT_PADDING}px`;
this.ui.glassDiv.style.top = `${DEFAULT_GLASS_Y_OFFSET}px`;
this.state.wasActivatedBefore = false;
}
const extensions = window.comfyUIMagnifyGlassExtensions;
if (extensions && extensions.length > 0) {
extensions.forEach((extension) => {
var _a;
if (extension == null ? void 0 : extension.stateManager) {
extension.stateManager.state.isPanelPinned = false;
extension.stateManager.state.isPanelLocked = false;
extension.stateManager.state.isAutoPinned = false;
extension.stateManager.state.pinnedPosition = { x: 0, y: 0 };
extension.stateManager.state.lastPinnedPosition = null;
if (extension.positionManager) {
extension.positionManager.positionPanel();
}
if ((_a = extension.uiManager) == null ? void 0 : _a.updateControlStates) {
extension.uiManager.updateControlStates();
}
}
});
}
this.debugger.log("Reset: Magnify glass and inspector panel positions restored to defaults");
}
/**
* Cleanup all resources.
*/
cleanup() {
this.eventHandler.detachListeners();
this.ui.cleanup();
}
}
export {
MagnifyGlass
};
//# sourceMappingURL=MagnifyGlass.js.map
File diff suppressed because one or more lines are too long
+331
View File
@@ -0,0 +1,331 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { Z_INDEX, DEFAULT_PADDING } from "../shared/constants.js";
import { Icons } from "../shared/icons.js";
import { Logger } from "../shared/logger.js";
class UiManager {
constructor(config, state, onToggle) {
__publicField(this, "config");
__publicField(this, "state");
__publicField(this, "glassDiv");
__publicField(this, "glassCanvas");
__publicField(this, "debugCanvas");
__publicField(this, "debugCtx");
__publicField(this, "htmlOverlayContainer");
__publicField(this, "onToggle");
this.config = config;
this.state = state;
this.glassDiv = null;
this.glassCanvas = null;
this.debugCanvas = null;
this.debugCtx = null;
this.htmlOverlayContainer = null;
this.onToggle = onToggle;
}
/**
* Create all DOM elements for the magnifying glass.
*/
createElements() {
this.glassDiv = document.createElement("div");
this.glassDiv.id = "comfyui-magnify-glass";
this.glassDiv.style.cssText = `
position: absolute;
box-sizing: border-box;
width: ${this.config.glassSize}px;
height: ${this.config.glassSize}px;
border-radius: ${this.config.glassShape === "Circle" ? "50%" : "0px"};
border: ${this.config.borderEnabled ? `${this.config.borderWidth}px solid ${this.config.borderColor}` : "none"};
overflow: hidden;
pointer-events: none;
z-index: ${Z_INDEX.GLASS};
display: none;
box-shadow: 0 5px 15px rgba(0,0,0,0.3);
background-color: rgba(255,255,255,0.1);
`;
this.glassCanvas = document.createElement("canvas");
this.glassCanvas.width = this.config.glassSize;
this.glassCanvas.height = this.config.glassSize;
this.glassCanvas.id = "comfyui-magnify-canvas";
this.glassDiv.appendChild(this.glassCanvas);
this.htmlOverlayContainer = document.createElement("div");
this.htmlOverlayContainer.id = "comfyui-magnify-html-overlay";
this.htmlOverlayContainer.style.cssText = `
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
overflow: hidden;
`;
this.glassDiv.appendChild(this.htmlOverlayContainer);
document.body.appendChild(this.glassDiv);
if (this.config.debugMode) {
this.createDebugCanvas();
}
this.injectMenuButton();
}
/**
* Create the debug canvas overlay.
*/
createDebugCanvas() {
this.debugCanvas = document.createElement("canvas");
this.debugCanvas.id = "comfyui-magnify-debug";
this.debugCanvas.width = 400;
this.debugCanvas.height = 350;
this.debugCanvas.style.cssText = `
position: fixed;
top: 10px;
right: 10px;
background: rgba(0,0,0,0.7);
border: 1px solid #fff;
z-index: ${Z_INDEX.DEBUG};
pointer-events: none;
color: white;
font-family: monospace;
display: none;
`;
document.body.appendChild(this.debugCanvas);
this.debugCtx = this.debugCanvas.getContext("2d");
}
/**
* Show the magnifying glass.
*/
show() {
if (this.glassDiv) {
this.glassDiv.style.display = "block";
}
if (this.config.debugMode && this.debugCanvas) {
this.debugCanvas.style.display = "block";
}
}
/**
* Set the visual visibility of the glass preview (opacity).
* This allows the tool to remain "Active" (tracking mouse) but invisible,
* so that the Inspector Panel can be used in "Inspector Only" mode.
*/
setPreviewVisibility(visible) {
if (this.glassDiv) {
this.glassDiv.style.opacity = visible ? "1" : "0";
}
}
/**
* Hide the magnifying glass.
*/
hide() {
if (this.glassDiv) {
this.glassDiv.style.display = "none";
}
if (this.config.debugMode && this.debugCanvas) {
this.debugCanvas.style.display = "none";
}
if (this.htmlOverlayContainer) {
this.htmlOverlayContainer.innerHTML = "";
}
}
/**
* Position the glass relative to cursor.
* @param clientX - Client X coordinate
* @param clientY - Client Y coordinate
*/
positionGlass(clientX, clientY) {
if (!this.config.followCursor || !this.glassDiv) return;
const glassSize = this.config.glassSize;
const offsetAmount = DEFAULT_PADDING;
let newLeft;
let newTop;
switch (this.config.glassPosition) {
case "Top":
newLeft = clientX - glassSize / 2;
newTop = clientY - glassSize - offsetAmount;
break;
case "Bottom":
newLeft = clientX - glassSize / 2;
newTop = clientY + offsetAmount;
break;
case "Left":
newLeft = clientX - glassSize - offsetAmount;
newTop = clientY - glassSize / 2;
break;
case "Right":
newLeft = clientX + offsetAmount;
newTop = clientY - glassSize / 2;
break;
case "Top-Left":
newLeft = clientX - glassSize - offsetAmount;
newTop = clientY - glassSize - offsetAmount;
break;
case "Top-Right":
newLeft = clientX + offsetAmount;
newTop = clientY - glassSize - offsetAmount;
break;
case "Bottom-Left":
newLeft = clientX - glassSize - offsetAmount;
newTop = clientY + offsetAmount;
break;
case "Bottom-Right":
newLeft = clientX + offsetAmount;
newTop = clientY + offsetAmount;
break;
default:
newLeft = clientX - glassSize / 2;
newTop = clientY + offsetAmount;
break;
}
this.glassDiv.style.left = `${newLeft}px`;
this.glassDiv.style.top = `${newTop}px`;
this.adjustForBoundaries(clientX, clientY);
}
/**
* Adjust glass position to stay within viewport boundaries.
* @param clientX - Client X coordinate
* @param clientY - Client Y coordinate
*/
adjustForBoundaries(clientX, clientY) {
if (!this.glassDiv) return;
const glassRect = this.glassDiv.getBoundingClientRect();
if (glassRect.right > window.innerWidth) {
this.glassDiv.style.left = `${clientX - glassRect.width - DEFAULT_PADDING}px`;
}
const currentRectLeft = this.glassDiv.getBoundingClientRect();
if (currentRectLeft.left < 0) {
this.glassDiv.style.left = "10px";
}
if (glassRect.bottom > window.innerHeight) {
this.glassDiv.style.top = `${clientY - glassRect.height - DEFAULT_PADDING}px`;
}
const currentRectTop = this.glassDiv.getBoundingClientRect();
if (currentRectTop.top < 0) {
this.glassDiv.style.top = "10px";
}
}
/**
* Apply current config to UI elements.
*/
applyStyles() {
if (this.glassDiv) {
this.glassDiv.style.width = `${this.config.glassSize}px`;
this.glassDiv.style.height = `${this.config.glassSize}px`;
this.glassDiv.style.border = this.config.borderEnabled ? `${this.config.borderWidth}px solid ${this.config.borderColor}` : "none";
this.glassDiv.style.clipPath = "none";
this.glassDiv.style.borderRadius = "0px";
switch (this.config.glassShape) {
case "Circle":
this.glassDiv.style.borderRadius = "50%";
break;
case "Square":
break;
case "Rounded Square":
this.glassDiv.style.borderRadius = "20%";
break;
default:
this.glassDiv.style.borderRadius = "50%";
break;
}
}
if (this.glassCanvas) {
this.glassCanvas.width = this.config.glassSize;
this.glassCanvas.height = this.config.glassSize;
}
if (this.config.debugMode) {
if (!this.debugCanvas) this.createDebugCanvas();
if (this.state.active && this.debugCanvas) this.debugCanvas.style.display = "block";
} else {
if (this.debugCanvas) this.debugCanvas.style.display = "none";
}
}
/**
* Cleanup DOM elements.
*/
cleanup() {
if (this.glassDiv) this.glassDiv.remove();
if (this.debugCanvas) this.debugCanvas.remove();
const btn = document.querySelector(".magnify-toggle-btn");
if (btn) btn.remove();
}
/**
* Inject a quick toggle button into the ComfyUI menu.
*/
/**
* Inject a quick toggle button into the ComfyUI menu.
*/
injectMenuButton() {
const stopTime = Date.now() + 3e4;
const attemptInjection = () => {
const buttons = Array.from(document.querySelectorAll("button"));
let anchorBtn = buttons.find((b) => {
const title = (b.title || "").toLowerCase();
const aria = (b.getAttribute("aria-label") || "").toLowerCase();
const text = (b.textContent || "").toLowerCase();
return title.includes("map") && !title.includes("open") || aria.includes("map") && !aria.includes("open") || text.includes("map");
});
if (!anchorBtn) {
anchorBtn = buttons.find((b) => {
const title = (b.title || "").toLowerCase();
const aria = (b.getAttribute("aria-label") || "").toLowerCase();
return title.includes("link") || aria.includes("link");
});
}
if (anchorBtn && anchorBtn.parentElement) {
if (anchorBtn.parentElement.querySelector(".magnify-toggle-btn")) return true;
Logger.debug("Found menu anchor:", anchorBtn.title || anchorBtn.getAttribute("aria-label") || "Unknown Button");
const btn = document.createElement("button");
btn.className = anchorBtn.className + " magnify-toggle-btn";
const computed = window.getComputedStyle(anchorBtn);
btn.style.height = computed.height;
btn.style.minHeight = computed.minHeight;
btn.title = "Toggle Magnify Glass";
btn.innerHTML = Icons.magnifyGlass;
btn.style.display = "inline-flex";
btn.style.alignItems = "center";
btn.style.justifyContent = "center";
btn.style.padding = "0 8px";
btn.style.cursor = "pointer";
btn.style.border = anchorBtn.style.border || computed.border;
btn.style.borderRadius = anchorBtn.style.borderRadius || computed.borderRadius;
if (!btn.style.background) btn.style.background = computed.background;
if (!btn.style.color) btn.style.color = computed.color;
btn.addEventListener("click", () => {
if (this.onToggle) {
this.onToggle();
btn.classList.toggle("active");
btn.classList.toggle("p-highlight");
btn.classList.toggle("selected");
}
});
const isMinimap = (anchorBtn.title || "").toLowerCase().includes("map") || (anchorBtn.getAttribute("aria-label") || "").toLowerCase().includes("map");
if (isMinimap) {
if (anchorBtn.nextSibling) {
anchorBtn.parentElement.insertBefore(btn, anchorBtn.nextSibling);
} else {
anchorBtn.parentElement.appendChild(btn);
}
} else {
anchorBtn.parentElement.insertBefore(btn, anchorBtn);
}
Logger.debug("Menu toggle button injected successfully");
return true;
}
return false;
};
if (attemptInjection()) return;
const checkForMenu = setInterval(() => {
if (Date.now() > stopTime) {
console.warn(
"[MagnifyGlass] Menu injection timed out. Found buttons:",
Array.from(document.querySelectorAll("button")).map((b) => b.title || b.getAttribute("aria-label") || b.textContent || b.className).slice(0, 5)
);
clearInterval(checkForMenu);
return;
}
if (attemptInjection()) {
clearInterval(checkForMenu);
}
}, 100);
}
}
export {
UiManager
};
//# sourceMappingURL=UiManager.js.map
File diff suppressed because one or more lines are too long
+329
View File
@@ -0,0 +1,329 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { Logger } from "../shared/logger.js";
class WebGLRenderer {
constructor(config, state, ui) {
__publicField(this, "config");
__publicField(this, "state");
__publicField(this, "ui");
__publicField(this, "gl");
__publicField(this, "program");
__publicField(this, "texture");
__publicField(this, "positionBuffer");
__publicField(this, "texCoordBuffer");
__publicField(this, "uniformLocations");
__publicField(this, "attributeLocations");
__publicField(this, "currentFilteringMode");
// Dirty flag optimization
__publicField(this, "lastCanvasVersion");
__publicField(this, "lastSourceX");
__publicField(this, "lastSourceY");
__publicField(this, "lastSourceWidth");
__publicField(this, "lastSourceHeight");
__publicField(this, "textureUploadSkipCount");
__publicField(this, "vertexShaderSource");
__publicField(this, "fragmentShaderSource");
this.config = config;
this.state = state;
this.ui = ui;
this.gl = null;
this.program = null;
this.texture = null;
this.positionBuffer = null;
this.texCoordBuffer = null;
this.uniformLocations = null;
this.attributeLocations = null;
this.currentFilteringMode = null;
this.lastCanvasVersion = -1;
this.lastSourceX = -1;
this.lastSourceY = -1;
this.lastSourceWidth = -1;
this.lastSourceHeight = -1;
this.textureUploadSkipCount = 0;
this.vertexShaderSource = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;
void main() {
gl_Position = vec4(a_position, 0.0, 1.0);
v_texCoord = a_texCoord;
}
`;
this.fragmentShaderSource = `
precision mediump float;
varying vec2 v_texCoord;
uniform sampler2D u_sourceTexture;
uniform vec2 u_textureOffset;
uniform vec2 u_textureRepeat;
uniform float u_glassSize;
void main() {
vec2 sampleCoord = u_textureOffset + v_texCoord * u_textureRepeat;
vec4 color = texture2D(u_sourceTexture, sampleCoord);
gl_FragColor = color;
}
`;
this.initialize();
}
/**
* Initialize WebGL context and resources.
*/
initialize() {
if (!this.ui.glassCanvas) return;
this.gl = this.ui.glassCanvas.getContext("webgl", { preserveDrawingBuffer: true });
if (!this.gl) {
this.gl = this.ui.glassCanvas.getContext("webgl2", { preserveDrawingBuffer: true });
}
if (!this.gl) {
const isFirefox = navigator.userAgent.toLowerCase().includes("firefox");
const browserInstructions = isFirefox ? "Firefox: Go to about:config, search for 'webgl.disabled' and set it to 'false', then restart Firefox." : "Check your browser settings to ensure WebGL is enabled.";
console.error("ComfyUI Magnifying Glass ERROR: WebGL not supported or context creation failed.");
console.error(`To fix: ${browserInstructions}`);
this.showWebGLError(browserInstructions);
return;
}
this.program = this.createShaderProgram(this.gl, this.vertexShaderSource, this.fragmentShaderSource);
if (!this.program) return;
this.positionBuffer = this.gl.createBuffer();
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.positionBuffer);
const positions = [-1, -1, 1, -1, -1, 1, 1, 1];
this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(positions), this.gl.STATIC_DRAW);
this.texCoordBuffer = this.gl.createBuffer();
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.texCoordBuffer);
const texCoords = [0, 1, 1, 1, 0, 0, 1, 0];
this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(texCoords), this.gl.STATIC_DRAW);
this.texture = this.gl.createTexture();
this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);
this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR);
this.updateTextureFiltering(this.config.textureFiltering);
this.uniformLocations = {
sourceTexture: this.gl.getUniformLocation(this.program, "u_sourceTexture"),
textureOffset: this.gl.getUniformLocation(this.program, "u_textureOffset"),
textureRepeat: this.gl.getUniformLocation(this.program, "u_textureRepeat"),
glassSize: this.gl.getUniformLocation(this.program, "u_glassSize")
};
this.attributeLocations = {
position: this.gl.getAttribLocation(this.program, "a_position"),
texCoord: this.gl.getAttribLocation(this.program, "a_texCoord")
};
}
/**
* Update texture filtering mode.
* @param filteringModeString - "Linear" or "Nearest"
*/
updateTextureFiltering(filteringModeString) {
if (!this.gl || !this.texture) return;
let glFilterMode;
if (filteringModeString === "Nearest") {
glFilterMode = this.gl.NEAREST;
} else {
glFilterMode = this.gl.LINEAR;
}
if (this.currentFilteringMode === glFilterMode) return;
this.currentFilteringMode = glFilterMode;
this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, glFilterMode);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, glFilterMode);
this.gl.bindTexture(this.gl.TEXTURE_2D, null);
}
/**
* Check if renderer is valid and ready.
* @returns Boolean indicating if WebGL context and program are ready
*/
isValid() {
return this.gl !== null && this.program !== null;
}
/**
* Create a WebGL shader program.
* @param gl - WebGL context
* @param vsSource - Vertex shader source
* @param fsSource - Fragment shader source
* @returns WebGL program or null on failure
*/
createShaderProgram(gl, vsSource, fsSource) {
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
if (!vertexShader) return null;
gl.shaderSource(vertexShader, vsSource);
gl.compileShader(vertexShader);
if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
console.error("ComfyUI Magnifying Glass ERROR: Vertex shader compilation error:", gl.getShaderInfoLog(vertexShader));
gl.deleteShader(vertexShader);
return null;
}
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
if (!fragmentShader) {
gl.deleteShader(vertexShader);
return null;
}
gl.shaderSource(fragmentShader, fsSource);
gl.compileShader(fragmentShader);
if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
console.error("ComfyUI Magnifying Glass ERROR: Fragment shader compilation error:", gl.getShaderInfoLog(fragmentShader));
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
return null;
}
const program = gl.createProgram();
if (!program) {
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
return null;
}
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
console.error("ComfyUI Magnifying Glass ERROR: Shader program linking error:", gl.getProgramInfoLog(program));
gl.deleteProgram(program);
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
return null;
}
return program;
}
/**
* Render the magnified view.
* @param sourceCanvas - The source canvas to sample from
*/
render(sourceCanvas) {
var _a;
if (!this.gl || !this.program || !this.texture || !this.uniformLocations || !this.attributeLocations) return;
const app = window.app;
const currentCanvasVersion = ((_a = app == null ? void 0 : app.graph) == null ? void 0 : _a.change_counter) ?? -1;
const sourceChanged = this.lastSourceX !== this.state.sourceX || this.lastSourceY !== this.state.sourceY || this.lastSourceWidth !== this.state.sourceWidth || this.lastSourceHeight !== this.state.sourceHeight;
const canvasChanged = currentCanvasVersion !== this.lastCanvasVersion;
const needsTextureUpdate = canvasChanged || sourceChanged || this.lastCanvasVersion === -1;
this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);
if (needsTextureUpdate) {
try {
this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, sourceCanvas);
this.lastCanvasVersion = currentCanvasVersion;
this.lastSourceX = this.state.sourceX;
this.lastSourceY = this.state.sourceY;
this.lastSourceWidth = this.state.sourceWidth;
this.lastSourceHeight = this.state.sourceHeight;
if (this.config.debugMode && this.textureUploadSkipCount > 0) {
Logger.debug(`Texture uploaded after skipping ${this.textureUploadSkipCount} frames`);
}
this.textureUploadSkipCount = 0;
} catch (e) {
console.error("ComfyUI Magnifying Glass ERROR: Error in texImage2D:", e);
return;
}
} else {
this.textureUploadSkipCount++;
if (this.config.debugMode && this.textureUploadSkipCount % 60 === 0) {
Logger.debug(`Texture upload skipped (${this.textureUploadSkipCount} frames cached)`);
}
}
const uvX = this.state.sourceX / sourceCanvas.width;
const uvY = this.state.sourceY / sourceCanvas.height;
const uvWidth = this.state.sourceWidth / sourceCanvas.width;
const uvHeight = this.state.sourceHeight / sourceCanvas.height;
this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);
this.gl.clearColor(0, 0, 0, 0);
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
this.gl.useProgram(this.program);
this.gl.activeTexture(this.gl.TEXTURE0);
this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);
this.gl.uniform1i(this.uniformLocations.sourceTexture, 0);
this.gl.uniform2f(this.uniformLocations.textureOffset, uvX, uvY);
this.gl.uniform2f(this.uniformLocations.textureRepeat, uvWidth, uvHeight);
this.gl.uniform1f(this.uniformLocations.glassSize, this.config.glassSize);
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.positionBuffer);
this.gl.vertexAttribPointer(this.attributeLocations.position, 2, this.gl.FLOAT, false, 0, 0);
this.gl.enableVertexAttribArray(this.attributeLocations.position);
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.texCoordBuffer);
this.gl.vertexAttribPointer(this.attributeLocations.texCoord, 2, this.gl.FLOAT, false, 0, 0);
this.gl.enableVertexAttribArray(this.attributeLocations.texCoord);
this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4);
}
/**
* Check for WebGL errors.
* @param label - Debug label
* @returns True if error occurred
*/
checkWebGLError(label) {
if (!this.gl) return false;
const err = this.gl.getError();
if (err !== this.gl.NO_ERROR) {
console.error(`ComfyUI Magnifying Glass ERROR: WebGL Error (${label}):`, err);
return true;
}
return false;
}
/**
* Update viewport when glass size changes.
*/
updateViewport() {
if (this.gl) {
this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);
}
}
/**
* Show WebGL error notification to user.
* @param instructions - Browser-specific instructions to fix
*/
showWebGLError(instructions) {
const toast = document.createElement("div");
toast.id = "magnifyglass-webgl-error";
toast.style.cssText = `
position: fixed;
bottom: 20px;
right: 20px;
max-width: 400px;
padding: 16px 20px;
background: linear-gradient(135deg, #ff4444 0%, #cc3333 100%);
color: white;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
font-family: system-ui, -apple-system, sans-serif;
font-size: 14px;
line-height: 1.5;
z-index: 100000;
animation: slideIn 0.3s ease-out;
`;
toast.innerHTML = `
<div style="display: flex; align-items: flex-start; gap: 12px;">
<span style="font-size: 24px;">⚠️</span>
<div>
<strong style="display: block; margin-bottom: 6px;">MagnifyGlass: WebGL Disabled</strong>
<span style="opacity: 0.9;">${instructions}</span>
<button onclick="this.parentElement.parentElement.parentElement.remove()"
style="display: block; margin-top: 10px; padding: 6px 12px; background: rgba(255,255,255,0.2);
border: 1px solid rgba(255,255,255,0.3); border-radius: 4px; color: white;
cursor: pointer; font-size: 12px;">
Dismiss
</button>
</div>
</div>
`;
if (!document.getElementById("magnifyglass-toast-style")) {
const style = document.createElement("style");
style.id = "magnifyglass-toast-style";
style.textContent = `
@keyframes slideIn {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
`;
document.head.appendChild(style);
}
document.body.appendChild(toast);
setTimeout(() => {
if (toast.parentElement) {
toast.style.animation = "slideIn 0.3s ease-out reverse";
setTimeout(() => toast.remove(), 300);
}
}, 15e3);
}
}
export {
WebGLRenderer
};
//# sourceMappingURL=WebGLRenderer.js.map
File diff suppressed because one or more lines are too long
+15
View File
@@ -0,0 +1,15 @@
import { MagnifyGlass } from "./magnify-glass/MagnifyGlass.js";
import { app } from "/scripts/app.js";
import { Logger } from "./shared/logger.js";
import { initSidebar } from "./sidebar/sidebar.js";
app.registerExtension({
name: "comfyui.magnify.glass",
init() {
const magnifyGlass = new MagnifyGlass();
magnifyGlass.init();
window.comfyUIMagnifyGlass = magnifyGlass;
initSidebar();
Logger.info("Magnify Glass extension initialized");
}
});
//# sourceMappingURL=magnify_glass.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"magnify_glass.js","sources":["../src/magnify_glass.ts"],"sourcesContent":["/**\n * ComfyUI Magnify Glass - Main Entry Point\n * \n * Initializes the Magnify Glass extension.\n */\n\nimport { MagnifyGlass } from './magnify-glass';\nimport { Logger } from './shared/logger';\nimport { initSidebar } from './sidebar';\n// @ts-ignore\nimport { app } from \"/scripts/app.js\";\n\n// Global declaration handled in comfyui.d.ts\n\n// We rely on the global 'app' object provided by ComfyUI\n// Register extension\napp.registerExtension({\n name: \"comfyui.magnify.glass\",\n init() {\n // Initialize the magnify glass\n const magnifyGlass = new MagnifyGlass();\n magnifyGlass.init();\n\n // Expose to window for other extensions (like info panel) to access\n window.comfyUIMagnifyGlass = magnifyGlass;\n\n // Initialize sidebar\n initSidebar();\n\n Logger.info('Magnify Glass extension initialized');\n }\n});\n"],"names":[],"mappings":";;;;AAgBA,IAAI,kBAAkB;AAAA,EAClB,MAAM;AAAA,EACN,OAAO;AAEH,UAAM,eAAe,IAAI,aAAA;AACzB,iBAAa,KAAA;AAGb,WAAO,sBAAsB;AAG7B,gBAAA;AAEA,WAAO,KAAK,qCAAqC;AAAA,EACrD;AACJ,CAAC;"}
+31
View File
@@ -0,0 +1,31 @@
import { app } from "/scripts/app.js";
import { Logger } from "./shared/logger.js";
import { InfoPanel } from "./info-panel/InfoPanel.js";
app.registerExtension({
name: "comfyui.magnify.info.panel",
init() {
const checkDependencies = () => {
if (window.comfyUIMagnifyGlass) {
initializeInfoPanel();
} else {
setTimeout(checkDependencies, 100);
}
};
checkDependencies();
}
});
function initializeInfoPanel() {
const magnifyGlass = window.comfyUIMagnifyGlass;
if (!magnifyGlass) {
Logger.error("Failed to find MagnifyGlass instance.");
return;
}
try {
const infoPanel = new InfoPanel(magnifyGlass);
window.infoPanelManager = infoPanel;
Logger.info("Info Panel extension initialized");
} catch (e) {
Logger.error("Error during initialization:", e);
}
}
//# sourceMappingURL=magnify_info_panel.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"magnify_info_panel.js","sources":["../src/magnify_info_panel.ts"],"sourcesContent":["/**\n * ComfyUI Magnify Info Panel - Main Entry Point\n * \n * Initializes the Info Panel extension.\n */\n\nimport { InfoPanel } from './info-panel';\nimport { Logger } from './shared/logger';\n// @ts-ignore\nimport { app } from \"/scripts/app.js\";\n\n// We rely on the global 'app' object provided by ComfyUI\n// No need to import it as it's global, but TypeScript needs to know about it.\n// We handled this in types/comfyui.d.ts\n\napp.registerExtension({\n name: \"comfyui.magnify.info.panel\",\n init() {\n // Wait for magnify glass to be available\n const checkDependencies = () => {\n if (window.comfyUIMagnifyGlass) {\n initializeInfoPanel();\n } else {\n setTimeout(checkDependencies, 100);\n }\n };\n\n checkDependencies();\n }\n});\n\nfunction initializeInfoPanel() {\n const magnifyGlass = window.comfyUIMagnifyGlass;\n if (!magnifyGlass) {\n Logger.error('Failed to find MagnifyGlass instance.');\n return;\n }\n\n try {\n // Initialize the info panel\n const infoPanel = new InfoPanel(magnifyGlass);\n\n // Expose orchestrator globally if needed\n window.infoPanelManager = infoPanel as any;\n\n // CSS is loaded by UIManager.injectStyles() - no need to load separately\n\n Logger.info('Info Panel extension initialized');\n } catch (e) {\n Logger.error('Error during initialization:', e);\n }\n}\n\n"],"names":[],"mappings":";;;AAeA,IAAI,kBAAkB;AAAA,EAClB,MAAM;AAAA,EACN,OAAO;AAEH,UAAM,oBAAoB,MAAM;AAC5B,UAAI,OAAO,qBAAqB;AAC5B,4BAAA;AAAA,MACJ,OAAO;AACH,mBAAW,mBAAmB,GAAG;AAAA,MACrC;AAAA,IACJ;AAEA,sBAAA;AAAA,EACJ;AACJ,CAAC;AAED,SAAS,sBAAsB;AAC3B,QAAM,eAAe,OAAO;AAC5B,MAAI,CAAC,cAAc;AACf,WAAO,MAAM,uCAAuC;AACpD;AAAA,EACJ;AAEA,MAAI;AAEA,UAAM,YAAY,IAAI,UAAU,YAAY;AAG5C,WAAO,mBAAmB;AAI1B,WAAO,KAAK,kCAAkC;AAAA,EAClD,SAAS,GAAG;AACR,WAAO,MAAM,gCAAgC,CAAC;AAAA,EAClD;AACJ;"}
+63
View File
@@ -0,0 +1,63 @@
const GLASS_POSITIONS = [
"Top",
"Bottom",
"Left",
"Right",
"Top-Left",
"Top-Right",
"Bottom-Left",
"Bottom-Right"
];
const GLASS_SHAPES = [
"Circle",
"Square",
"Rounded Square"
];
const PANEL_POSITIONS = [
"Top",
"Bottom",
"Left",
"Right"
];
const ACTIVATION_KEYS = ["x", "z", "m", "q", "v", "c"];
const RESET_KEYS = ["r", "o", "p", "k", "l"];
const TOGGLE_FOLLOW_KEYS = ["f", "g", "h", "j", "k"];
const DEFAULT_PADDING = 4;
const DEFAULT_GLASS_Y_OFFSET = 110;
const DEFAULT_GLASS_SIZE = 300;
const DEFAULT_ZOOM_FACTOR = 300;
const DEFAULT_BORDER_WIDTH = 1;
const DEFAULT_BORDER_COLOR = "#6b7280";
const DEFAULT_OFFSET_STEP = 5;
const DEFAULT_PANEL_WIDTH = 300;
const DEFAULT_PANEL_MAX_HEIGHT = 300;
const DEFAULT_PANEL_OPACITY = 100;
const Z_INDEX = {
GLASS: 98999,
DEBUG: 99e3
};
const STORAGE_KEYS = {
OFFSET_X: "comfyui_magnify_offset_x",
OFFSET_Y: "comfyui_magnify_offset_y"
};
export {
ACTIVATION_KEYS,
DEFAULT_BORDER_COLOR,
DEFAULT_BORDER_WIDTH,
DEFAULT_GLASS_SIZE,
DEFAULT_GLASS_Y_OFFSET,
DEFAULT_OFFSET_STEP,
DEFAULT_PADDING,
DEFAULT_PANEL_MAX_HEIGHT,
DEFAULT_PANEL_OPACITY,
DEFAULT_PANEL_WIDTH,
DEFAULT_ZOOM_FACTOR,
GLASS_POSITIONS,
GLASS_SHAPES,
PANEL_POSITIONS,
RESET_KEYS,
STORAGE_KEYS,
TOGGLE_FOLLOW_KEYS,
Z_INDEX
};
//# sourceMappingURL=constants.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"constants.js","sources":["../../src/shared/constants.ts"],"sourcesContent":["/**\n * ComfyUI MagnifyGlass - Shared Constants\n * \n * Configuration constants shared between magnify glass and info panel modules.\n */\n\n// Glass positioning options\nexport const GLASS_POSITIONS = [\n \"Top\",\n \"Bottom\",\n \"Left\",\n \"Right\",\n \"Top-Left\",\n \"Top-Right\",\n \"Bottom-Left\",\n \"Bottom-Right\"\n] as const;\n\nexport type GlassPosition = typeof GLASS_POSITIONS[number];\n\n// Glass shape options\nexport const GLASS_SHAPES = [\n \"Circle\",\n \"Square\",\n \"Rounded Square\"\n] as const;\n\nexport type GlassShape = typeof GLASS_SHAPES[number];\n\n// Texture filtering modes\nexport const TEXTURE_FILTERS = [\n \"Linear\",\n \"Nearest\"\n] as const;\n\nexport type TextureFilter = typeof TEXTURE_FILTERS[number];\n\n// Info panel positions relative to glass\nexport const PANEL_POSITIONS = [\n \"Top\",\n \"Bottom\",\n \"Left\",\n \"Right\"\n] as const;\n\nexport type PanelPosition = typeof PANEL_POSITIONS[number];\n\n// Available keys for settings\nexport const ACTIVATION_KEYS = [\"x\", \"z\", \"m\", \"q\", \"v\", \"c\"] as const;\nexport const RESET_KEYS = [\"r\", \"o\", \"p\", \"k\", \"l\"] as const;\nexport const TOGGLE_FOLLOW_KEYS = [\"f\", \"g\", \"h\", \"j\", \"k\"] as const;\n\n// UI Constants\nexport const DEFAULT_PADDING = 4;\nexport const DEFAULT_GLASS_Y_OFFSET = 110; // Starting Y position offset (below top bar with 3px gap)\nexport const DEFAULT_GLASS_SIZE = 300;\nexport const DEFAULT_ZOOM_FACTOR = 300; // 3x as percentage\nexport const DEFAULT_BORDER_WIDTH = 1;\nexport const DEFAULT_BORDER_COLOR = \"#6b7280\";\nexport const DEFAULT_OFFSET_STEP = 5;\n\n// Panel Constants\nexport const DEFAULT_PANEL_WIDTH = 300;\nexport const DEFAULT_PANEL_MAX_HEIGHT = 300;\nexport const DEFAULT_PANEL_OPACITY = 100;\n\n// Z-Index hierarchy\nexport const Z_INDEX = {\n GLASS: 98999,\n DEBUG: 99000,\n PANEL: 99999,\n CONTROLS: 99998\n} as const;\n\n// Animation durations (ms)\nexport const ANIMATION = {\n PANEL_TRANSITION: 300,\n AUTO_COLLAPSE_DELAY: 1500,\n THEME_DETECTION_INTERVAL: 2000\n} as const;\n\n// LocalStorage keys\nexport const STORAGE_KEYS = {\n OFFSET_X: 'comfyui_magnify_offset_x',\n OFFSET_Y: 'comfyui_magnify_offset_y'\n} as const;\n"],"names":[],"mappings":"AAOO,MAAM,kBAAkB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ;AAKO,MAAM,eAAe;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AACJ;AAaO,MAAM,kBAAkB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ;AAKO,MAAM,kBAAkB,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG;AACrD,MAAM,aAAa,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG;AAC3C,MAAM,qBAAqB,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG;AAGnD,MAAM,kBAAkB;AACxB,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;AAC7B,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;AAG5B,MAAM,sBAAsB;AAC5B,MAAM,2BAA2B;AACjC,MAAM,wBAAwB;AAG9B,MAAM,UAAU;AAAA,EACnB,OAAO;AAAA,EACP,OAAO;AAGX;AAUO,MAAM,eAAe;AAAA,EACxB,UAAU;AAAA,EACV,UAAU;AACd;"}
+61
View File
@@ -0,0 +1,61 @@
const Icons = {
// Magnify glass icon - used for header and glass toggle
magnifyGlass: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8"/>
<line x1="21" y1="21" x2="16.65" y2="16.65"/>
</svg>`,
// Unlock icon - panel is floating/following cursor
unlock: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
<path d="M7 11V7a5 5 0 0 1 9.9-1"/>
</svg>`,
// Lock icon - panel is pinned
lock: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
<path d="M7 11V7a5 5 0 0 1 10 0v4"/>
</svg>`,
// Pin icon - lock panel position
pin: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="17" x2="12" y2="22"/>
<path d="M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z"/>
</svg>`,
// Eye icon - toggle visibility
eye: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
<circle cx="12" cy="12" r="3"/>
</svg>`,
// Camera/image icon - media section
camera: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
<circle cx="12" cy="13" r="4"/>
</svg>`,
// Location/map pin icon - empty state
mapPin: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
<circle cx="12" cy="10" r="3"/>
</svg>`,
// Chevron right - expand icon
chevronRight: `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="9 18 15 12 9 6"/>
</svg>`,
// Minus icon - minimize button
minus: `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="5" y1="12" x2="19" y2="12"/>
</svg>`,
// Inspector/info icon
info: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"/>
<line x1="12" y1="16" x2="12" y2="12"/>
<line x1="12" y1="8" x2="12.01" y2="8"/>
</svg>`,
// Box/node icon
box: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
<polyline points="3.27 6.96 12 12.01 20.73 6.96"/>
<line x1="12" y1="22.08" x2="12" y2="12"/>
</svg>`
};
export {
Icons
};
//# sourceMappingURL=icons.js.map

Some files were not shown because too many files have changed in this diff Show More