diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..acf3180 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 pythongosssss + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..ae43dd2 --- /dev/null +++ b/__init__.py @@ -0,0 +1,25 @@ +import importlib.util +import glob +import os +import sys +from .pysssss import init, get_ext_dir + +NODE_CLASS_MAPPINGS = {} +NODE_DISPLAY_NAME_MAPPINGS = {} + +if init(): + py = get_ext_dir("py") + files = glob.glob(os.path.join(py, "*.py"), recursive=False) + for file in files: + name = os.path.splitext(file)[0] + spec = importlib.util.spec_from_file_location(name, file) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + if hasattr(module, "NODE_CLASS_MAPPINGS") and getattr(module, "NODE_CLASS_MAPPINGS") is not None: + NODE_CLASS_MAPPINGS.update(module.NODE_CLASS_MAPPINGS) + if hasattr(module, "NODE_DISPLAY_NAME_MAPPINGS") and getattr(module, "NODE_DISPLAY_NAME_MAPPINGS") is not None: + NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS) + +WEB_DIRECTORY = "./web" +__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"] diff --git a/__pycache__/__init__.cpython-310.pyc b/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..b513974 Binary files /dev/null and b/__pycache__/__init__.cpython-310.pyc differ diff --git a/__pycache__/pysssss.cpython-310.pyc b/__pycache__/pysssss.cpython-310.pyc new file mode 100644 index 0000000..0407882 Binary files /dev/null and b/__pycache__/pysssss.cpython-310.pyc differ diff --git a/__pycache__/string_function.cpython-310 - Copy.pyc b/__pycache__/string_function.cpython-310 - Copy.pyc new file mode 100644 index 0000000..1691afd Binary files /dev/null and b/__pycache__/string_function.cpython-310 - Copy.pyc differ diff --git a/__pycache__/string_function_tree.cpython-310.pyc b/__pycache__/string_function_tree.cpython-310.pyc new file mode 100644 index 0000000..1691afd Binary files /dev/null and b/__pycache__/string_function_tree.cpython-310.pyc differ diff --git a/example/tree.png b/example/tree.png new file mode 100644 index 0000000..7816ffd Binary files /dev/null and b/example/tree.png differ diff --git a/example/treenori.png b/example/treenori.png new file mode 100644 index 0000000..6be10d6 Binary files /dev/null and b/example/treenori.png differ diff --git a/py/__pycache__/string_function.cpython-310.pyc b/py/__pycache__/string_function.cpython-310.pyc new file mode 100644 index 0000000..08a32f6 Binary files /dev/null and b/py/__pycache__/string_function.cpython-310.pyc differ diff --git a/py/string_function.py b/py/string_function.py new file mode 100644 index 0000000..e92d48a --- /dev/null +++ b/py/string_function.py @@ -0,0 +1,100 @@ +import re + +class StringFunction: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "action": (["append", "replace"], {}), + "tidy_tags": (["yes", "no"], {}), + "text_a": ("STRING", {"multiline": True}), + "text_b": ("STRING", {"multiline": True}), + }, + "optional": { + "text_c": ("STRING", {"multiline": True}), + "text_d": ("STRING", {"multiline": True}), + "text_e": ("STRING", {"multiline": True}), + "text_f": ("STRING", {"multiline": True}), + "text_g": ("STRING", {"multiline": True}), + "text_h": ("STRING", {"multiline": True}), + "text_i": ("STRING", {"multiline": True}), + "text_j": ("STRING", {"multiline": True}), + "text_k": ("STRING", {"multiline": True}), + "text_l": ("STRING", {"multiline": True}), + "text_m": ("STRING", {"multiline": True}), + "text_n": ("STRING", {"multiline": True}), + "text_o": ("STRING", {"multiline": True}), + "text_p": ("STRING", {"multiline": True}), + "text_q": ("STRING", {"multiline": True}), + "text_r": ("STRING", {"multiline": True}), + } + } + + RETURN_TYPES = ("STRING",) + FUNCTION = "exec" + CATEGORY = "utils" + OUTPUT_NODE = True + + def exec(self, action, tidy_tags, text_a, text_b, text_c="", text_d="", text_e="", text_f="", text_g="", text_h="", + text_i="", text_j="", text_k="", text_l="", text_m="", text_n="", text_o="", text_p="", text_q="", text_r=""): + # Converted inputs are sent as the string of 'undefined' if not connected + if text_a == "undefined": + text_a = "" + if text_b == "undefined": + text_b = "" + if text_c == "undefined": + text_c = "" + if text_d == "undefined": + text_d = "" + if text_e == "undefined": + text_e = "" + if text_f == "undefined": + text_f = "" + if text_g == "undefined": + text_g = "" + if text_h == "undefined": + text_h = "" + if text_i == "undefined": + text_i = "" + if text_j == "undefined": + text_j = "" + if text_k == "undefined": + text_k = "" + if text_l == "undefined": + text_l = "" + if text_m == "undefined": + text_m = "" + if text_n == "undefined": + text_n = "" + if text_o == "undefined": + text_o = "" + if text_p == "undefined": + text_p = "" + if text_q == "undefined": + text_q = "" + if text_r == "undefined": + text_r = "" + + tidy_tags = tidy_tags == "yes" + out = "" + if action == "append": + out = (", " if tidy_tags else "").join(filter(None, [text_a, text_b, text_c, text_d, text_e, text_f, text_g, text_h, text_i, text_j, text_k, text_l, text_m, text_n, text_o, text_p, text_q, text_r])) + else: + if text_r is None: + text_r = "" + if text_b.startswith("/") and text_b.endswith("/"): + regex = text_b[1:-1] + out = re.sub(regex, text_r, text_a) + else: + out = text_a.replace(text_b, text_r) + if tidy_tags: + out = out.replace(" ", " ").replace(" ,", ",").replace(",,", ",").replace(",,", ",") + return {"ui": {"text": (out,)}, "result": (out,)} + +NODE_CLASS_MAPPINGS = { + "StringFunction": StringFunction, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "StringFunction": "String Function Tree", +} diff --git a/pysssss.json b/pysssss.json new file mode 100644 index 0000000..6ca0642 --- /dev/null +++ b/pysssss.json @@ -0,0 +1,4 @@ +{ + "name": "CustomScripts", + "logging": false +} diff --git a/pysssss.py b/pysssss.py new file mode 100644 index 0000000..70563ac --- /dev/null +++ b/pysssss.py @@ -0,0 +1,290 @@ +import asyncio +import os +import json +import shutil +import inspect +import aiohttp +from server import PromptServer +from tqdm import tqdm + +config = None + + +def is_logging_enabled(): + config = get_extension_config() + if "logging" not in config: + return False + return config["logging"] + + +def log(message, type=None, always=False, name=None): + if not always and not is_logging_enabled(): + return + + if type is not None: + message = f"[{type}] {message}" + + if name is None: + name = get_extension_config()["name"] + + print(f"(pysssss:{name}) {message}") + + +def get_ext_dir(subpath=None, mkdir=False): + dir = os.path.dirname(__file__) + if subpath is not None: + dir = os.path.join(dir, subpath) + + dir = os.path.abspath(dir) + + if mkdir and not os.path.exists(dir): + os.makedirs(dir) + return dir + + +def get_comfy_dir(subpath=None, mkdir=False): + dir = os.path.dirname(inspect.getfile(PromptServer)) + if subpath is not None: + dir = os.path.join(dir, subpath) + + dir = os.path.abspath(dir) + + if mkdir and not os.path.exists(dir): + os.makedirs(dir) + return dir + + +def get_web_ext_dir(): + config = get_extension_config() + name = config["name"] + dir = get_comfy_dir("web/extensions/pysssss") + if not os.path.exists(dir): + os.makedirs(dir) + dir = os.path.join(dir, name) + return dir + + +def get_extension_config(reload=False): + global config + if reload == False and config is not None: + return config + + config_path = get_ext_dir("pysssss.json") + if not os.path.exists(config_path): + log("Missing pysssss.json, this extension may not work correctly. Please reinstall the extension.", + type="ERROR", always=True, name="???") + print(f"Extension path: {get_ext_dir()}") + return {"name": "Unknown", "version": -1} + with open(config_path, "r") as f: + config = json.loads(f.read()) + return config + + +def link_js(src, dst): + src = os.path.abspath(src) + dst = os.path.abspath(dst) + if os.name == "nt": + try: + import _winapi + _winapi.CreateJunction(src, dst) + return True + except: + pass + try: + os.symlink(src, dst) + return True + except: + import logging + logging.exception('') + return False + + +def is_junction(path): + if os.name != "nt": + return False + try: + return bool(os.readlink(path)) + except OSError: + return False + + +def install_js(): + src_dir = get_ext_dir("web/js") + if not os.path.exists(src_dir): + log("No JS") + return + + should_install = should_install_js() + if should_install: + log("it looks like you're running an old version of ComfyUI that requires manual setup of web files, it is recommended you update your installation.", "warning", True) + dst_dir = get_web_ext_dir() + linked = os.path.islink(dst_dir) or is_junction(dst_dir) + if linked or os.path.exists(dst_dir): + if linked: + if should_install: + log("JS already linked") + else: + os.unlink(dst_dir) + log("JS unlinked, PromptServer will serve extension") + elif not should_install: + shutil.rmtree(dst_dir) + log("JS deleted, PromptServer will serve extension") + return + + if not should_install: + log("JS skipped, PromptServer will serve extension") + return + + if link_js(src_dir, dst_dir): + log("JS linked") + return + + log("Copying JS files") + shutil.copytree(src_dir, dst_dir, dirs_exist_ok=True) + + +def should_install_js(): + return not hasattr(PromptServer.instance, "supports") or "custom_nodes_from_web" not in PromptServer.instance.supports + + +def init(check_imports=None): + log("Init") + + if check_imports is not None: + import importlib.util + for imp in check_imports: + spec = importlib.util.find_spec(imp) + if spec is None: + log(f"{imp} is required, please check requirements are installed.", + type="ERROR", always=True) + return False + + install_js() + return True + + +def get_async_loop(): + loop = None + try: + loop = asyncio.get_event_loop() + except: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + return loop + + +def get_http_session(): + loop = get_async_loop() + return aiohttp.ClientSession(loop=loop) + + +async def download(url, stream, update_callback=None, session=None): + close_session = False + if session is None: + close_session = True + session = get_http_session() + try: + async with session.get(url) as response: + size = int(response.headers.get('content-length', 0)) or None + + with tqdm( + unit='B', unit_scale=True, miniters=1, desc=url.split('/')[-1], total=size, + ) as progressbar: + perc = 0 + async for chunk in response.content.iter_chunked(2048): + stream.write(chunk) + progressbar.update(len(chunk)) + if update_callback is not None and progressbar.total is not None and progressbar.total != 0: + last = perc + perc = round(progressbar.n / progressbar.total, 2) + if perc != last: + last = perc + await update_callback(perc) + finally: + if close_session and session is not None: + await session.close() + + +async def download_to_file(url, destination, update_callback=None, is_ext_subpath=True, session=None): + if is_ext_subpath: + destination = get_ext_dir(destination) + with open(destination, mode='wb') as f: + download(url, f, update_callback, session) + + +def wait_for_async(async_fn, loop=None): + res = [] + + async def run_async(): + r = await async_fn() + res.append(r) + + if loop is None: + try: + loop = asyncio.get_event_loop() + except: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + + loop.run_until_complete(run_async()) + + return res[0] + + +def update_node_status(client_id, node, text, progress=None): + if client_id is None: + client_id = PromptServer.instance.client_id + + if client_id is None: + return + + PromptServer.instance.send_sync("pysssss/update_status", { + "node": node, + "progress": progress, + "text": text + }, client_id) + + +async def update_node_status_async(client_id, node, text, progress=None): + if client_id is None: + client_id = PromptServer.instance.client_id + + if client_id is None: + return + + await PromptServer.instance.send("pysssss/update_status", { + "node": node, + "progress": progress, + "text": text + }, client_id) + + +def get_config_value(key, default=None, throw=False): + split = key.split(".") + obj = get_extension_config() + for s in split: + if s in split: + obj = obj[s] + else: + if throw: + raise KeyError("Configuration key missing: " + key) + else: + return default + return obj + + +def is_inside_dir(root_dir, check_path): + root_dir = os.path.abspath(root_dir) + if not os.path.isabs(check_path): + check_path = os.path.abspath(os.path.join(root_dir, check_path)) + return os.path.commonpath([check_path, root_dir]) == root_dir + + +def get_child_dir(root_dir, child_path, throw_if_outside=True): + child_path = os.path.abspath(os.path.join(root_dir, child_path)) + if is_inside_dir(root_dir, child_path): + return child_path + if throw_if_outside: + raise NotADirectoryError( + "Saving outside the target folder is not allowed.") + return None diff --git a/web/js/assets/canvas2svg.js b/web/js/assets/canvas2svg.js new file mode 100644 index 0000000..03dc392 --- /dev/null +++ b/web/js/assets/canvas2svg.js @@ -0,0 +1,1192 @@ +/*!! + * Canvas 2 Svg v1.0.19 + * A low level canvas to SVG converter. Uses a mock canvas context to build an SVG document. + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/mit-license.php + * + * Author: + * Kerry Liu + * + * Copyright (c) 2014 Gliffy Inc. + */ + +;(function() { + "use strict"; + + var STYLES, ctx, CanvasGradient, CanvasPattern, namedEntities; + + //helper function to format a string + function format(str, args) { + var keys = Object.keys(args), i; + for (i=0; i 1) { + options = defaultOptions; + options.width = arguments[0]; + options.height = arguments[1]; + } else if( !o ) { + options = defaultOptions; + } else { + options = o; + } + + if(!(this instanceof ctx)) { + //did someone call this without new? + return new ctx(options); + } + + //setup options + this.width = options.width || defaultOptions.width; + this.height = options.height || defaultOptions.height; + this.enableMirroring = options.enableMirroring !== undefined ? options.enableMirroring : defaultOptions.enableMirroring; + + this.canvas = this; ///point back to this instance! + this.__document = options.document || document; + this.__canvas = this.__document.createElement("canvas"); + this.__ctx = this.__canvas.getContext("2d"); + + this.__setDefaultStyles(); + this.__stack = [this.__getStyleState()]; + this.__groupStack = []; + + //the root svg element + this.__root = this.__document.createElementNS("http://www.w3.org/2000/svg", "svg"); + this.__root.setAttribute("version", 1.1); + this.__root.setAttribute("xmlns", "http://www.w3.org/2000/svg"); + this.__root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); + this.__root.setAttribute("width", this.width); + this.__root.setAttribute("height", this.height); + + //make sure we don't generate the same ids in defs + this.__ids = {}; + + //defs tag + this.__defs = this.__document.createElementNS("http://www.w3.org/2000/svg", "defs"); + this.__root.appendChild(this.__defs); + + //also add a group child. the svg element can't use the transform attribute + this.__currentElement = this.__document.createElementNS("http://www.w3.org/2000/svg", "g"); + this.__root.appendChild(this.__currentElement); + }; + + + /** + * Creates the specified svg element + * @private + */ + ctx.prototype.__createElement = function (elementName, properties, resetFill) { + if (typeof properties === "undefined") { + properties = {}; + } + + var element = this.__document.createElementNS("http://www.w3.org/2000/svg", elementName), + keys = Object.keys(properties), i, key; + if(resetFill) { + //if fill or stroke is not specified, the svg element should not display. By default SVG's fill is black. + element.setAttribute("fill", "none"); + element.setAttribute("stroke", "none"); + } + for(i=0; i 0) { + var group = this.__createElement("g"); + parent.appendChild(group); + this.__currentElement = group; + } + + var transform = this.__currentElement.getAttribute("transform"); + if(transform) { + transform += " "; + } else { + transform = ""; + } + transform += t; + this.__currentElement.setAttribute("transform", transform); + }; + + /** + * scales the current element + */ + ctx.prototype.scale = function(x, y) { + if(y === undefined) { + y = x; + } + this.__addTransform(format("scale({x},{y})", {x:x, y:y})); + }; + + /** + * rotates the current element + */ + ctx.prototype.rotate = function(angle){ + var degrees = (angle * 180 / Math.PI); + this.__addTransform(format("rotate({angle},{cx},{cy})", {angle:degrees, cx:0, cy:0})); + }; + + /** + * translates the current element + */ + ctx.prototype.translate = function(x, y){ + this.__addTransform(format("translate({x},{y})", {x:x,y:y})); + }; + + /** + * applies a transform to the current element + */ + ctx.prototype.transform = function(a, b, c, d, e, f){ + this.__addTransform(format("matrix({a},{b},{c},{d},{e},{f})", {a:a, b:b, c:c, d:d, e:e, f:f})); + }; + + /** + * Create a new Path Element + */ + ctx.prototype.beginPath = function(){ + var path, parent; + + // Note that there is only one current default path, it is not part of the drawing state. + // See also: https://html.spec.whatwg.org/multipage/scripting.html#current-default-path + this.__currentDefaultPath = ""; + this.__currentPosition = {}; + + path = this.__createElement("path", {}, true); + parent = this.__closestGroupOrSvg(); + parent.appendChild(path); + this.__currentElement = path; + }; + + /** + * Helper function to apply currentDefaultPath to current path element + * @private + */ + ctx.prototype.__applyCurrentDefaultPath = function() { + if(this.__currentElement.nodeName === "path") { + var d = this.__currentDefaultPath; + this.__currentElement.setAttribute("d", d); + } else { + throw new Error("Attempted to apply path command to node " + this.__currentElement.nodeName); + } + }; + + /** + * Helper function to add path command + * @private + */ + ctx.prototype.__addPathCommand = function(command){ + this.__currentDefaultPath += " "; + this.__currentDefaultPath += command; + }; + + /** + * Adds the move command to the current path element, + * if the currentPathElement is not empty create a new path element + */ + ctx.prototype.moveTo = function(x,y){ + if(this.__currentElement.nodeName !== "path") { + this.beginPath(); + } + + // creates a new subpath with the given point + this.__currentPosition = {x: x, y: y}; + this.__addPathCommand(format("M {x} {y}", {x:x, y:y})); + }; + + /** + * Closes the current path + */ + ctx.prototype.closePath = function(){ + this.__addPathCommand("Z"); + }; + + /** + * Adds a line to command + */ + ctx.prototype.lineTo = function(x, y){ + this.__currentPosition = {x: x, y: y}; + if (this.__currentDefaultPath.indexOf('M') > -1) { + this.__addPathCommand(format("L {x} {y}", {x:x, y:y})); + } else { + this.__addPathCommand(format("M {x} {y}", {x:x, y:y})); + } + }; + + /** + * Add a bezier command + */ + ctx.prototype.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) { + this.__currentPosition = {x: x, y: y}; + this.__addPathCommand(format("C {cp1x} {cp1y} {cp2x} {cp2y} {x} {y}", + {cp1x:cp1x, cp1y:cp1y, cp2x:cp2x, cp2y:cp2y, x:x, y:y})); + }; + + /** + * Adds a quadratic curve to command + */ + ctx.prototype.quadraticCurveTo = function(cpx, cpy, x, y){ + this.__currentPosition = {x: x, y: y}; + this.__addPathCommand(format("Q {cpx} {cpy} {x} {y}", {cpx:cpx, cpy:cpy, x:x, y:y})); + }; + + + /** + * Return a new normalized vector of given vector + */ + var normalize = function(vector) { + var len = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]); + return [vector[0] / len, vector[1] / len]; + }; + + /** + * Adds the arcTo to the current path + * + * @see http://www.w3.org/TR/2015/WD-2dcontext-20150514/#dom-context-2d-arcto + */ + ctx.prototype.arcTo = function(x1, y1, x2, y2, radius) { + // Let the point (x0, y0) be the last point in the subpath. + var x0 = this.__currentPosition && this.__currentPosition.x; + var y0 = this.__currentPosition && this.__currentPosition.y; + + // First ensure there is a subpath for (x1, y1). + if (typeof x0 == "undefined" || typeof y0 == "undefined") { + return; + } + + // Negative values for radius must cause the implementation to throw an IndexSizeError exception. + if (radius < 0) { + throw new Error("IndexSizeError: The radius provided (" + radius + ") is negative."); + } + + // If the point (x0, y0) is equal to the point (x1, y1), + // or if the point (x1, y1) is equal to the point (x2, y2), + // or if the radius radius is zero, + // then the method must add the point (x1, y1) to the subpath, + // and connect that point to the previous point (x0, y0) by a straight line. + if (((x0 === x1) && (y0 === y1)) + || ((x1 === x2) && (y1 === y2)) + || (radius === 0)) { + this.lineTo(x1, y1); + return; + } + + // Otherwise, if the points (x0, y0), (x1, y1), and (x2, y2) all lie on a single straight line, + // then the method must add the point (x1, y1) to the subpath, + // and connect that point to the previous point (x0, y0) by a straight line. + var unit_vec_p1_p0 = normalize([x0 - x1, y0 - y1]); + var unit_vec_p1_p2 = normalize([x2 - x1, y2 - y1]); + if (unit_vec_p1_p0[0] * unit_vec_p1_p2[1] === unit_vec_p1_p0[1] * unit_vec_p1_p2[0]) { + this.lineTo(x1, y1); + return; + } + + // Otherwise, let The Arc be the shortest arc given by circumference of the circle that has radius radius, + // and that has one point tangent to the half-infinite line that crosses the point (x0, y0) and ends at the point (x1, y1), + // and that has a different point tangent to the half-infinite line that ends at the point (x1, y1), and crosses the point (x2, y2). + // The points at which this circle touches these two lines are called the start and end tangent points respectively. + + // note that both vectors are unit vectors, so the length is 1 + var cos = (unit_vec_p1_p0[0] * unit_vec_p1_p2[0] + unit_vec_p1_p0[1] * unit_vec_p1_p2[1]); + var theta = Math.acos(Math.abs(cos)); + + // Calculate origin + var unit_vec_p1_origin = normalize([ + unit_vec_p1_p0[0] + unit_vec_p1_p2[0], + unit_vec_p1_p0[1] + unit_vec_p1_p2[1] + ]); + var len_p1_origin = radius / Math.sin(theta / 2); + var x = x1 + len_p1_origin * unit_vec_p1_origin[0]; + var y = y1 + len_p1_origin * unit_vec_p1_origin[1]; + + // Calculate start angle and end angle + // rotate 90deg clockwise (note that y axis points to its down) + var unit_vec_origin_start_tangent = [ + -unit_vec_p1_p0[1], + unit_vec_p1_p0[0] + ]; + // rotate 90deg counter clockwise (note that y axis points to its down) + var unit_vec_origin_end_tangent = [ + unit_vec_p1_p2[1], + -unit_vec_p1_p2[0] + ]; + var getAngle = function(vector) { + // get angle (clockwise) between vector and (1, 0) + var x = vector[0]; + var y = vector[1]; + if (y >= 0) { // note that y axis points to its down + return Math.acos(x); + } else { + return -Math.acos(x); + } + }; + var startAngle = getAngle(unit_vec_origin_start_tangent); + var endAngle = getAngle(unit_vec_origin_end_tangent); + + // Connect the point (x0, y0) to the start tangent point by a straight line + this.lineTo(x + unit_vec_origin_start_tangent[0] * radius, + y + unit_vec_origin_start_tangent[1] * radius); + + // Connect the start tangent point to the end tangent point by arc + // and adding the end tangent point to the subpath. + this.arc(x, y, radius, startAngle, endAngle); + }; + + /** + * Sets the stroke property on the current element + */ + ctx.prototype.stroke = function(){ + if(this.__currentElement.nodeName === "path") { + this.__currentElement.setAttribute("paint-order", "fill stroke markers"); + } + this.__applyCurrentDefaultPath(); + this.__applyStyleToCurrentElement("stroke"); + }; + + /** + * Sets fill properties on the current element + */ + ctx.prototype.fill = function(){ + if(this.__currentElement.nodeName === "path") { + this.__currentElement.setAttribute("paint-order", "stroke fill markers"); + } + this.__applyCurrentDefaultPath(); + this.__applyStyleToCurrentElement("fill"); + }; + + /** + * Adds a rectangle to the path. + */ + ctx.prototype.rect = function(x, y, width, height){ + if(this.__currentElement.nodeName !== "path") { + this.beginPath(); + } + this.moveTo(x, y); + this.lineTo(x+width, y); + this.lineTo(x+width, y+height); + this.lineTo(x, y+height); + this.lineTo(x, y); + this.closePath(); + }; + + + /** + * adds a rectangle element + */ + ctx.prototype.fillRect = function(x, y, width, height){ + var rect, parent; + rect = this.__createElement("rect", { + x : x, + y : y, + width : width, + height : height + }, true); + parent = this.__closestGroupOrSvg(); + parent.appendChild(rect); + this.__currentElement = rect; + this.__applyStyleToCurrentElement("fill"); + }; + + /** + * Draws a rectangle with no fill + * @param x + * @param y + * @param width + * @param height + */ + ctx.prototype.strokeRect = function(x, y, width, height){ + var rect, parent; + rect = this.__createElement("rect", { + x : x, + y : y, + width : width, + height : height + }, true); + parent = this.__closestGroupOrSvg(); + parent.appendChild(rect); + this.__currentElement = rect; + this.__applyStyleToCurrentElement("stroke"); + }; + + + /** + * Clear entire canvas: + * 1. save current transforms + * 2. remove all the childNodes of the root g element + */ + ctx.prototype.__clearCanvas = function() { + var current = this.__closestGroupOrSvg(), + transform = current.getAttribute("transform"); + var rootGroup = this.__root.childNodes[1]; + var childNodes = rootGroup.childNodes; + for (var i = childNodes.length - 1; i >= 0; i--) { + if (childNodes[i]) { + rootGroup.removeChild(childNodes[i]); + } + } + this.__currentElement = rootGroup; + //reset __groupStack as all the child group nodes are all removed. + this.__groupStack = []; + if (transform) { + this.__addTransform(transform); + } + }; + + /** + * "Clears" a canvas by just drawing a white rectangle in the current group. + */ + ctx.prototype.clearRect = function(x, y, width, height) { + //clear entire canvas + if (x === 0 && y === 0 && width === this.width && height === this.height) { + this.__clearCanvas(); + return; + } + var rect, parent = this.__closestGroupOrSvg(); + rect = this.__createElement("rect", { + x : x, + y : y, + width : width, + height : height, + fill : "#FFFFFF" + }, true); + parent.appendChild(rect); + }; + + /** + * Adds a linear gradient to a defs tag. + * Returns a canvas gradient object that has a reference to it's parent def + */ + ctx.prototype.createLinearGradient = function(x1, y1, x2, y2){ + var grad = this.__createElement("linearGradient", { + id : randomString(this.__ids), + x1 : x1+"px", + x2 : x2+"px", + y1 : y1+"px", + y2 : y2+"px", + "gradientUnits" : "userSpaceOnUse" + }, false); + this.__defs.appendChild(grad); + return new CanvasGradient(grad, this); + }; + + /** + * Adds a radial gradient to a defs tag. + * Returns a canvas gradient object that has a reference to it's parent def + */ + ctx.prototype.createRadialGradient = function(x0, y0, r0, x1, y1, r1){ + var grad = this.__createElement("radialGradient", { + id : randomString(this.__ids), + cx : x1+"px", + cy : y1+"px", + r : r1+"px", + fx : x0+"px", + fy : y0+"px", + "gradientUnits" : "userSpaceOnUse" + }, false); + this.__defs.appendChild(grad); + return new CanvasGradient(grad, this); + + }; + + /** + * Parses the font string and returns svg mapping + * @private + */ + ctx.prototype.__parseFont = function() { + var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\'\"\sa-z]+?)\s*$/i; + var fontPart = regex.exec( this.font ); + var data = { + style : fontPart[1] || 'normal', + size : fontPart[4] || '10px', + family : fontPart[6] || 'sans-serif', + weight: fontPart[3] || 'normal', + decoration : fontPart[2] || 'normal', + href : null + }; + + //canvas doesn't support underline natively, but we can pass this attribute + if(this.__fontUnderline === "underline") { + data.decoration = "underline"; + } + + //canvas also doesn't support linking, but we can pass this as well + if(this.__fontHref) { + data.href = this.__fontHref; + } + + return data; + }; + + /** + * Helper to link text fragments + * @param font + * @param element + * @return {*} + * @private + */ + ctx.prototype.__wrapTextLink = function(font, element) { + if(font.href) { + var a = this.__createElement("a"); + a.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", font.href); + a.appendChild(element); + return a; + } + return element; + }; + + /** + * Fills or strokes text + * @param text + * @param x + * @param y + * @param action - stroke or fill + * @private + */ + ctx.prototype.__applyText = function(text, x, y, action) { + var font = this.__parseFont(), + parent = this.__closestGroupOrSvg(), + textElement = this.__createElement("text", { + "font-family" : font.family, + "font-size" : font.size, + "font-style" : font.style, + "font-weight" : font.weight, + "text-decoration" : font.decoration, + "x" : x, + "y" : y, + "text-anchor": getTextAnchor(this.textAlign), + "dominant-baseline": getDominantBaseline(this.textBaseline) + }, true); + + textElement.appendChild(this.__document.createTextNode(text)); + this.__currentElement = textElement; + this.__applyStyleToCurrentElement(action); + parent.appendChild(this.__wrapTextLink(font,textElement)); + }; + + /** + * Creates a text element + * @param text + * @param x + * @param y + */ + ctx.prototype.fillText = function(text, x, y){ + this.__applyText(text, x, y, "fill"); + }; + + /** + * Strokes text + * @param text + * @param x + * @param y + */ + ctx.prototype.strokeText = function(text, x, y){ + this.__applyText(text, x, y, "stroke"); + }; + + /** + * No need to implement this for svg. + * @param text + * @return {TextMetrics} + */ + ctx.prototype.measureText = function(text){ + this.__ctx.font = this.font; + return this.__ctx.measureText(text); + }; + + /** + * Arc command! + */ + ctx.prototype.arc = function(x, y, radius, startAngle, endAngle, counterClockwise) { + // in canvas no circle is drawn if no angle is provided. + if (startAngle === endAngle) { + return; + } + startAngle = startAngle % (2*Math.PI); + endAngle = endAngle % (2*Math.PI); + if(startAngle === endAngle) { + //circle time! subtract some of the angle so svg is happy (svg elliptical arc can't draw a full circle) + endAngle = ((endAngle + (2*Math.PI)) - 0.001 * (counterClockwise ? -1 : 1)) % (2*Math.PI); + } + var endX = x+radius*Math.cos(endAngle), + endY = y+radius*Math.sin(endAngle), + startX = x+radius*Math.cos(startAngle), + startY = y+radius*Math.sin(startAngle), + sweepFlag = counterClockwise ? 0 : 1, + largeArcFlag = 0, + diff = endAngle - startAngle; + + // https://github.com/gliffy/canvas2svg/issues/4 + if(diff < 0) { + diff += 2*Math.PI; + } + + if(counterClockwise) { + largeArcFlag = diff > Math.PI ? 0 : 1; + } else { + largeArcFlag = diff > Math.PI ? 1 : 0; + } + + this.lineTo(startX, startY); + this.__addPathCommand(format("A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}", + {rx:radius, ry:radius, xAxisRotation:0, largeArcFlag:largeArcFlag, sweepFlag:sweepFlag, endX:endX, endY:endY})); + + this.__currentPosition = {x: endX, y: endY}; + }; + + /** + * Generates a ClipPath from the clip command. + */ + ctx.prototype.clip = function(){ + var group = this.__closestGroupOrSvg(), + clipPath = this.__createElement("clipPath"), + id = randomString(this.__ids), + newGroup = this.__createElement("g"); + + this.__applyCurrentDefaultPath(); + group.removeChild(this.__currentElement); + clipPath.setAttribute("id", id); + clipPath.appendChild(this.__currentElement); + + this.__defs.appendChild(clipPath); + + //set the clip path to this group + group.setAttribute("clip-path", format("url(#{id})", {id:id})); + + //clip paths can be scaled and transformed, we need to add another wrapper group to avoid later transformations + // to this path + group.appendChild(newGroup); + + this.__currentElement = newGroup; + + }; + + /** + * Draws a canvas, image or mock context to this canvas. + * Note that all svg dom manipulation uses node.childNodes rather than node.children for IE support. + * http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-drawimage + */ + ctx.prototype.drawImage = function(){ + //convert arguments to a real array + var args = Array.prototype.slice.call(arguments), + image=args[0], + dx, dy, dw, dh, sx=0, sy=0, sw, sh, parent, svg, defs, group, + currentElement, svgImage, canvas, context, id; + + if(args.length === 3) { + dx = args[1]; + dy = args[2]; + sw = image.width; + sh = image.height; + dw = sw; + dh = sh; + } else if(args.length === 5) { + dx = args[1]; + dy = args[2]; + dw = args[3]; + dh = args[4]; + sw = image.width; + sh = image.height; + } else if(args.length === 9) { + sx = args[1]; + sy = args[2]; + sw = args[3]; + sh = args[4]; + dx = args[5]; + dy = args[6]; + dw = args[7]; + dh = args[8]; + } else { + throw new Error("Inavlid number of arguments passed to drawImage: " + arguments.length); + } + + parent = this.__closestGroupOrSvg(); + currentElement = this.__currentElement; + var translateDirective = "translate(" + dx + ", " + dy + ")"; + if(image instanceof ctx) { + //canvas2svg mock canvas context. In the future we may want to clone nodes instead. + //also I'm currently ignoring dw, dh, sw, sh, sx, sy for a mock context. + svg = image.getSvg().cloneNode(true); + if (svg.childNodes && svg.childNodes.length > 1) { + defs = svg.childNodes[0]; + while(defs.childNodes.length) { + id = defs.childNodes[0].getAttribute("id"); + this.__ids[id] = id; + this.__defs.appendChild(defs.childNodes[0]); + } + group = svg.childNodes[1]; + if (group) { + //save original transform + var originTransform = group.getAttribute("transform"); + var transformDirective; + if (originTransform) { + transformDirective = originTransform+" "+translateDirective; + } else { + transformDirective = translateDirective; + } + group.setAttribute("transform", transformDirective); + parent.appendChild(group); + } + } + } else if(image.nodeName === "CANVAS" || image.nodeName === "IMG") { + //canvas or image + svgImage = this.__createElement("image"); + svgImage.setAttribute("width", dw); + svgImage.setAttribute("height", dh); + svgImage.setAttribute("preserveAspectRatio", "none"); + + if(sx || sy || sw !== image.width || sh !== image.height) { + //crop the image using a temporary canvas + canvas = this.__document.createElement("canvas"); + canvas.width = dw; + canvas.height = dh; + context = canvas.getContext("2d"); + context.drawImage(image, sx, sy, sw, sh, 0, 0, dw, dh); + image = canvas; + } + svgImage.setAttribute("transform", translateDirective); + svgImage.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", + image.nodeName === "CANVAS" ? image.toDataURL() : image.getAttribute("src")); + parent.appendChild(svgImage); + } + }; + + /** + * Generates a pattern tag + */ + ctx.prototype.createPattern = function(image, repetition){ + var pattern = this.__document.createElementNS("http://www.w3.org/2000/svg", "pattern"), id = randomString(this.__ids), + img; + pattern.setAttribute("id", id); + pattern.setAttribute("width", image.width); + pattern.setAttribute("height", image.height); + if(image.nodeName === "CANVAS" || image.nodeName === "IMG") { + img = this.__document.createElementNS("http://www.w3.org/2000/svg", "image"); + img.setAttribute("width", image.width); + img.setAttribute("height", image.height); + img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", + image.nodeName === "CANVAS" ? image.toDataURL() : image.getAttribute("src")); + pattern.appendChild(img); + this.__defs.appendChild(pattern); + } else if(image instanceof ctx) { + pattern.appendChild(image.__root.childNodes[1]); + this.__defs.appendChild(pattern); + } + return new CanvasPattern(pattern, this); + }; + + ctx.prototype.setLineDash = function(dashArray) { + if (dashArray && dashArray.length > 0) { + this.lineDash = dashArray.join(","); + } else { + this.lineDash = null; + } + }; + + /** + * Not yet implemented + */ + ctx.prototype.drawFocusRing = function(){}; + ctx.prototype.createImageData = function(){}; + ctx.prototype.getImageData = function(){}; + ctx.prototype.putImageData = function(){}; + ctx.prototype.globalCompositeOperation = function(){}; + ctx.prototype.setTransform = function(){}; + + //add options for alternative namespace + if (typeof window === "object") { + window.C2S = ctx; + } + + // CommonJS/Browserify + if (typeof module === "object" && typeof module.exports === "object") { + module.exports = ctx; + } + +}()); diff --git a/web/js/assets/favicon-active.ico b/web/js/assets/favicon-active.ico new file mode 100644 index 0000000..64045ab Binary files /dev/null and b/web/js/assets/favicon-active.ico differ diff --git a/web/js/assets/favicon.ico b/web/js/assets/favicon.ico new file mode 100644 index 0000000..08df248 Binary files /dev/null and b/web/js/assets/favicon.ico differ diff --git a/web/js/assets/notify.mp3 b/web/js/assets/notify.mp3 new file mode 100644 index 0000000..5e3fdab Binary files /dev/null and b/web/js/assets/notify.mp3 differ diff --git a/web/js/common/autocomplete.css b/web/js/common/autocomplete.css new file mode 100644 index 0000000..e58900e --- /dev/null +++ b/web/js/common/autocomplete.css @@ -0,0 +1,57 @@ +.pysssss-autocomplete { + color: var(--descrip-text); + background-color: var(--comfy-menu-bg); + position: absolute; + font-family: sans-serif; + box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.4); + z-index: 9999; +} + +.pysssss-autocomplete-item { + cursor: pointer; + padding: 3px 7px; + display: flex; + border-left: 3px solid transparent; + align-items: center; +} + +.pysssss-autocomplete-item--selected { + border-left-color: dodgerblue; +} + +.pysssss-autocomplete-highlight { + font-weight: bold; + text-decoration: underline; + text-decoration-color: dodgerblue; +} + +.pysssss-autocomplete-priority { + margin-left: auto; + font-size: 10px; + color: #fff; + padding: 2px 4px 2px 14px; + position: relative; +} + +.pysssss-autocomplete-priority::after { + content: ""; + display: block; + background: rgba(255, 255, 255, 0.25); + width: calc(100% - 10px); + height: 100%; + position: absolute; + left: 10px; + top: 0; + border-radius: 5px; +} + +.pysssss-autocomplete-item-info { + margin-left: auto; + transition: filter 0.2s; + will-change: filter; + text-decoration: none; + padding-left: 10px; +} +.pysssss-autocomplete-item-info:hover { + filter: invert(1); +} diff --git a/web/js/common/autocomplete.js b/web/js/common/autocomplete.js new file mode 100644 index 0000000..ecfea7b --- /dev/null +++ b/web/js/common/autocomplete.js @@ -0,0 +1,576 @@ +import { $el } from "../../../../scripts/ui.js"; +import { addStylesheet } from "./utils.js"; + +addStylesheet(import.meta.url); + +/* + https://github.com/component/textarea-caret-position + The MIT License (MIT) + + Copyright (c) 2015 Jonathan Ong me@jongleberry.com + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +const getCaretCoordinates = (function () { + // We'll copy the properties below into the mirror div. + // Note that some browsers, such as Firefox, do not concatenate properties + // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), + // so we have to list every single property explicitly. + var properties = [ + "direction", // RTL support + "boxSizing", + "width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does + "height", + "overflowX", + "overflowY", // copy the scrollbar for IE + + "borderTopWidth", + "borderRightWidth", + "borderBottomWidth", + "borderLeftWidth", + "borderStyle", + + "paddingTop", + "paddingRight", + "paddingBottom", + "paddingLeft", + + // https://developer.mozilla.org/en-US/docs/Web/CSS/font + "fontStyle", + "fontVariant", + "fontWeight", + "fontStretch", + "fontSize", + "fontSizeAdjust", + "lineHeight", + "fontFamily", + + "textAlign", + "textTransform", + "textIndent", + "textDecoration", // might not make a difference, but better be safe + + "letterSpacing", + "wordSpacing", + + "tabSize", + "MozTabSize", + ]; + + var isBrowser = typeof window !== "undefined"; + var isFirefox = isBrowser && window.mozInnerScreenX != null; + + return function getCaretCoordinates(element, position, options) { + if (!isBrowser) { + throw new Error("textarea-caret-position#getCaretCoordinates should only be called in a browser"); + } + + var debug = (options && options.debug) || false; + if (debug) { + var el = document.querySelector("#input-textarea-caret-position-mirror-div"); + if (el) el.parentNode.removeChild(el); + } + + // The mirror div will replicate the textarea's style + var div = document.createElement("div"); + div.id = "input-textarea-caret-position-mirror-div"; + document.body.appendChild(div); + + var style = div.style; + var computed = window.getComputedStyle ? window.getComputedStyle(element) : element.currentStyle; // currentStyle for IE < 9 + var isInput = element.nodeName === "INPUT"; + + // Default textarea styles + style.whiteSpace = "pre-wrap"; + if (!isInput) style.wordWrap = "break-word"; // only for textarea-s + + // Position off-screen + style.position = "absolute"; // required to return coordinates properly + if (!debug) style.visibility = "hidden"; // not 'display: none' because we want rendering + + // Transfer the element's properties to the div + properties.forEach(function (prop) { + if (isInput && prop === "lineHeight") { + // Special case for s because text is rendered centered and line height may be != height + if (computed.boxSizing === "border-box") { + var height = parseInt(computed.height); + var outerHeight = + parseInt(computed.paddingTop) + + parseInt(computed.paddingBottom) + + parseInt(computed.borderTopWidth) + + parseInt(computed.borderBottomWidth); + var targetHeight = outerHeight + parseInt(computed.lineHeight); + if (height > targetHeight) { + style.lineHeight = height - outerHeight + "px"; + } else if (height === targetHeight) { + style.lineHeight = computed.lineHeight; + } else { + style.lineHeight = 0; + } + } else { + style.lineHeight = computed.height; + } + } else { + style[prop] = computed[prop]; + } + }); + + if (isFirefox) { + // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 + if (element.scrollHeight > parseInt(computed.height)) style.overflowY = "scroll"; + } else { + style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' + } + + div.textContent = element.value.substring(0, position); + // The second special handling for input type="text" vs textarea: + // spaces need to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037 + if (isInput) div.textContent = div.textContent.replace(/\s/g, "\u00a0"); + + var span = document.createElement("span"); + // Wrapping must be replicated *exactly*, including when a long word gets + // onto the next line, with whitespace at the end of the line before (#7). + // The *only* reliable way to do that is to copy the *entire* rest of the + // textarea's content into the created at the caret position. + // For inputs, just '.' would be enough, but no need to bother. + span.textContent = element.value.substring(position) || "."; // || because a completely empty faux span doesn't render at all + div.appendChild(span); + + var coordinates = { + top: span.offsetTop + parseInt(computed["borderTopWidth"]), + left: span.offsetLeft + parseInt(computed["borderLeftWidth"]), + height: parseInt(computed["lineHeight"]), + }; + + if (debug) { + span.style.backgroundColor = "#aaa"; + } else { + document.body.removeChild(div); + } + + return coordinates; + }; +})(); + +/* + Key functions from: + https://github.com/yuku/textcomplete + © Yuku Takahashi - This software is licensed under the MIT license. + + The MIT License (MIT) + + Copyright (c) 2015 Jonathan Ong me@jongleberry.com + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +const CHAR_CODE_ZERO = "0".charCodeAt(0); +const CHAR_CODE_NINE = "9".charCodeAt(0); + +class TextAreaCaretHelper { + constructor(el) { + this.el = el; + } + + #calculateElementOffset() { + const rect = this.el.getBoundingClientRect(); + const owner = this.el.ownerDocument; + if (owner == null) { + throw new Error("Given element does not belong to document"); + } + const { defaultView, documentElement } = owner; + if (defaultView == null) { + throw new Error("Given element does not belong to window"); + } + const offset = { + top: rect.top + defaultView.pageYOffset, + left: rect.left + defaultView.pageXOffset, + }; + if (documentElement) { + offset.top -= documentElement.clientTop; + offset.left -= documentElement.clientLeft; + } + return offset; + } + + #isDigit(charCode) { + return CHAR_CODE_ZERO <= charCode && charCode <= CHAR_CODE_NINE; + } + + #getLineHeightPx() { + const computedStyle = getComputedStyle(this.el); + const lineHeight = computedStyle.lineHeight; + // If the char code starts with a digit, it is either a value in pixels, + // or unitless, as per: + // https://drafts.csswg.org/css2/visudet.html#propdef-line-height + // https://drafts.csswg.org/css2/cascade.html#computed-value + if (this.#isDigit(lineHeight.charCodeAt(0))) { + const floatLineHeight = parseFloat(lineHeight); + // In real browsers the value is *always* in pixels, even for unit-less + // line-heights. However, we still check as per the spec. + return this.#isDigit(lineHeight.charCodeAt(lineHeight.length - 1)) + ? floatLineHeight * parseFloat(computedStyle.fontSize) + : floatLineHeight; + } + // Otherwise, the value is "normal". + // If the line-height is "normal", calculate by font-size + return this.#calculateLineHeightPx(this.el.nodeName, computedStyle); + } + + /** + * Returns calculated line-height of the given node in pixels. + */ + #calculateLineHeightPx(nodeName, computedStyle) { + const body = document.body; + if (!body) return 0; + + const tempNode = document.createElement(nodeName); + tempNode.innerHTML = " "; + Object.assign(tempNode.style, { + fontSize: computedStyle.fontSize, + fontFamily: computedStyle.fontFamily, + padding: "0", + }); + body.appendChild(tempNode); + + // Make sure textarea has only 1 row + if (tempNode instanceof HTMLTextAreaElement) { + tempNode.rows = 1; + } + + // Assume the height of the element is the line-height + const height = tempNode.offsetHeight; + body.removeChild(tempNode); + + return height; + } + + getCursorOffset() { + const elOffset = this.#calculateElementOffset(); + const elScroll = this.#getElScroll(); + const cursorPosition = this.#getCursorPosition(); + const lineHeight = this.#getLineHeightPx(); + const top = elOffset.top - elScroll.top + cursorPosition.top + lineHeight; + const left = elOffset.left - elScroll.left + cursorPosition.left; + const clientTop = this.el.getBoundingClientRect().top; + if (this.el.dir !== "rtl") { + return { top, left, lineHeight, clientTop }; + } else { + const right = document.documentElement ? document.documentElement.clientWidth - left : 0; + return { top, right, lineHeight, clientTop }; + } + } + + #getElScroll() { + return { top: this.el.scrollTop, left: this.el.scrollLeft }; + } + + #getCursorPosition() { + return getCaretCoordinates(this.el, this.el.selectionEnd); + } + + getBeforeCursor() { + return this.el.selectionStart !== this.el.selectionEnd ? null : this.el.value.substring(0, this.el.selectionEnd); + } + + getAfterCursor() { + return this.el.value.substring(this.el.selectionEnd); + } + + insertAtCursor(value, offset) { + if (this.el.selectionStart != null) { + const startPos = this.el.selectionStart; + const endPos = this.el.selectionEnd; + + this.el.value = + this.el.value.substring(0, startPos + offset) + value + this.el.value.substring(endPos, this.el.value.length); + this.el.selectionEnd = this.el.selectionStart = startPos + value.length + offset; + } else { + this.el.value += value; + } + } +} + +/*********************/ + +export class TextAreaAutoComplete { + static separator = ""; + static enabled = true; + + static groups = {}; + + /** @type {Record} */ + static words = {}; + + /** @type {HTMLTextAreaElement} */ + el; + + /** + * @param {HTMLTextAreaElement} el + */ + constructor(el) { + this.el = el; + this.helper = new TextAreaCaretHelper(el); + this.dropdown = $el("div.pysssss-autocomplete"); + + this.#setup(); + } + + #setup() { + this.el.addEventListener("keydown", this.#keyDown.bind(this)); + this.el.addEventListener("keypress", this.#keyPress.bind(this)); + this.el.addEventListener("keyup", this.#keyUp.bind(this)); + this.el.addEventListener("click", this.#hide.bind(this)); + this.el.addEventListener("blur", () => setTimeout(() => this.#hide(), 150)); + } + + /** + * @param {KeyboardEvent} e + */ + #keyDown(e) { + if (!TextAreaAutoComplete.enabled) return; + + if (this.dropdown.parentElement) { + // We are visible + switch (e.key) { + case "ArrowUp": + e.preventDefault(); + if (this.selected.index) { + this.#setSelected(this.currentWords[this.selected.index - 1].wordInfo); + } else { + this.#setSelected(this.currentWords[this.currentWords.length - 1].wordInfo); + } + break; + case "ArrowDown": + e.preventDefault(); + if (this.selected.index === this.currentWords.length - 1) { + this.#setSelected(this.currentWords[0].wordInfo); + } else { + this.#setSelected(this.currentWords[this.selected.index + 1].wordInfo); + } + break; + case "Tab": + e.preventDefault(); + this.#insertItem(); + break; + } + } + } + + /** + * @param {KeyboardEvent} e + */ + #keyPress(e) { + if (!TextAreaAutoComplete.enabled) return; + if (this.dropdown.parentElement) { + // We are visible + switch (e.key) { + case "Enter": + e.preventDefault(); + this.#insertItem(); + break; + } + } + + if (!e.defaultPrevented) { + this.#update(); + } + } + + #keyUp(e) { + if (!TextAreaAutoComplete.enabled) return; + if (this.dropdown.parentElement) { + // We are visible + switch (e.key) { + case "Escape": + e.preventDefault(); + this.#hide(); + break; + } + } else if (e.key === "ArrowUp" || e.key === "ArrowDown" || e.key === "ArrowLeft" || e.key === "ArrowRight") { + return; + } + if (!e.defaultPrevented) { + this.#update(); + } + } + + #setSelected(item) { + if (this.selected) { + this.selected.el.classList.remove("pysssss-autocomplete-item--selected"); + } + + this.selected = item; + this.selected.el.classList.add("pysssss-autocomplete-item--selected"); + } + + #insertItem() { + if (!this.selected) return; + this.selected.el.click(); + } + + #getFilteredWords(term) { + term = term.toLocaleLowerCase(); + + const priorityMatches = []; + const prefixMatches = []; + const includesMatches = []; + for (const word of Object.keys(TextAreaAutoComplete.words)) { + const lowerWord = word.toLocaleLowerCase(); + if (lowerWord === term) { + // Dont include exact matches + continue; + } + + const pos = lowerWord.indexOf(term); + if (pos === -1) { + // No match + continue; + } + + const wordInfo = TextAreaAutoComplete.words[word]; + if (wordInfo.priority) { + priorityMatches.push({ pos, wordInfo }); + } else if (pos) { + includesMatches.push({ pos, wordInfo }); + } else { + prefixMatches.push({ pos, wordInfo }); + } + } + + priorityMatches.sort( + (a, b) => + b.wordInfo.priority - a.wordInfo.priority || + a.wordInfo.text.length - b.wordInfo.text.length || + a.wordInfo.text.localeCompare(b.wordInfo.text) + ); + + const top = priorityMatches.length * 0.2; + return priorityMatches + .slice(0, top) + .concat(prefixMatches, priorityMatches.slice(top), includesMatches) + .slice(0, 20); + } + + #update() { + let before = this.helper.getBeforeCursor(); + if (before?.length) { + const m = before.match(/\b([\w-_:\\\/]+)$/); + if (m) { + before = m[0]; + } else { + before = null; + } + } + + if (!before) { + this.#hide(); + return; + } + + this.currentWords = this.#getFilteredWords(before); + if (!this.currentWords.length) { + this.#hide(); + return; + } + + this.dropdown.style.display = ""; + + let hasSelected = false; + const items = this.currentWords.map(({ wordInfo, pos }, i) => { + const parts = [ + $el("span", { + textContent: wordInfo.text.substr(0, pos), + }), + $el("span.pysssss-autocomplete-highlight", { + textContent: wordInfo.text.substr(pos, before.length), + }), + $el("span", { + textContent: wordInfo.text.substr(pos + before.length), + }), + ]; + + if (wordInfo.priority) { + parts.push( + $el("span.pysssss-autocomplete-priority", { + textContent: wordInfo.priority, + }) + ); + } + + if (wordInfo.info) { + parts.push( + $el("a.pysssss-autocomplete-item-info", { + textContent: "ℹ️", + title: "View info...", + onclick: (e) => { + e.stopPropagation(); + wordInfo.info(); + e.preventDefault(); + }, + }) + ); + } + const item = $el( + "div.pysssss-autocomplete-item", + { + onclick: () => { + this.el.focus(); + this.helper.insertAtCursor(wordInfo.text + TextAreaAutoComplete.separator, -before.length); + setTimeout(() => { + this.#update(); + }, 150); + }, + onmousemove: () => { + this.#setSelected(wordInfo); + }, + }, + parts + ); + + if (wordInfo === this.selected) { + hasSelected = true; + } + + wordInfo.index = i; + wordInfo.el = item; + + return item; + }); + + this.#setSelected(hasSelected ? this.selected : this.currentWords[0].wordInfo); + this.dropdown.replaceChildren(...items); + + if (!this.dropdown.parentElement) { + document.body.append(this.dropdown); + } + + const position = this.helper.getCursorOffset(); + this.dropdown.style.left = (position.left ?? 0) + "px"; + this.dropdown.style.top = (position.top ?? 0) + "px"; + } + + #hide() { + this.selected = null; + this.dropdown.remove(); + } + + static updateWords(id, words) { + const isUpdate = id in TextAreaAutoComplete.groups; + TextAreaAutoComplete.groups[id] = words; + if (isUpdate) { + // Remerge all words + TextAreaAutoComplete.words = Object.assign({}, ...Object.values(TextAreaAutoComplete.groups)); + } else { + // Just insert the new words + Object.assign(TextAreaAutoComplete.words, words); + } + } +} diff --git a/web/js/common/lightbox.css b/web/js/common/lightbox.css new file mode 100644 index 0000000..4357d9d --- /dev/null +++ b/web/js/common/lightbox.css @@ -0,0 +1,98 @@ +.pysssss-lightbox { + width: 100vw; + height: 100vh; + position: fixed; + top: 0; + left: 0; + z-index: 999; + background: rgba(0, 0, 0, 0.6); + display: flex; + align-items: center; + transition: opacity 0.2s; +} + +.pysssss-lightbox-prev, +.pysssss-lightbox-next { + height: 60px; + display: flex; + align-items: center; +} + +.pysssss-lightbox-prev:after, +.pysssss-lightbox-next:after { + border-style: solid; + border-width: 0.25em 0.25em 0 0; + display: inline-block; + height: 0.45em; + left: 0.15em; + position: relative; + top: 0.15em; + transform: rotate(-135deg) scale(0.75); + vertical-align: top; + width: 0.45em; + padding: 10px; + font-size: 20px; + margin: 0 10px 0 20px; + transition: color 0.2s; + flex-shrink: 0; + content: ""; +} + +.pysssss-lightbox-next:after { + transform: rotate(45deg) scale(0.75); + margin: 0 20px 0 0px; +} + +.pysssss-lightbox-main { + flex: auto; + text-align: center; +} + +.pysssss-lightbox-link { + display: inline-block; + position: relative; +} + +.pysssss-lightbox .lds-ring { + position: absolute; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); +} + +.pysssss-lightbox-img { + max-height: 90vh; + max-width: calc(100vw - 130px); + height: auto; + object-fit: contain; + border: 3px solid white; + border-radius: 4px; + transition: opacity 0.2s; + user-select: none; +} + +.pysssss-lightbox-img:hover { + border-color: dodgerblue; +} + +.pysssss-lightbox-close { + font-size: 80px; + line-height: 1ch; + height: 1ch; + width: 1ch; + position: absolute; + right: 10px; + top: 10px; + padding: 5px; +} + +.pysssss-lightbox-close:after { + content: "\00d7"; +} + +.pysssss-lightbox-close:hover, +.pysssss-lightbox-prev:hover, +.pysssss-lightbox-next:hover { + color: dodgerblue; + cursor: pointer; +} diff --git a/web/js/common/lightbox.js b/web/js/common/lightbox.js new file mode 100644 index 0000000..7e07445 --- /dev/null +++ b/web/js/common/lightbox.js @@ -0,0 +1,102 @@ +import { $el } from "../../../../scripts/ui.js"; +import { addStylesheet, getUrl, loadImage } from "./utils.js"; +import { createSpinner } from "./spinner.js"; + +addStylesheet(getUrl("lightbox.css", import.meta.url)); + +const $$el = (tag, name, ...args) => { + if (name) name = "-" + name; + return $el(tag + ".pysssss-lightbox" + name, ...args); +}; + +const ani = async (a, t, b) => { + a(); + await new Promise((r) => setTimeout(r, t)); + b(); +}; + +export class Lightbox { + constructor() { + this.el = $$el("div", "", { + parent: document.body, + onclick: (e) => { + e.stopImmediatePropagation(); + this.close(); + }, + style: { + display: "none", + opacity: 0, + }, + }); + this.closeBtn = $$el("div", "close", { + parent: this.el, + }); + this.prev = $$el("div", "prev", { + parent: this.el, + onclick: (e) => { + this.update(-1); + e.stopImmediatePropagation(); + }, + }); + this.main = $$el("div", "main", { + parent: this.el, + }); + this.next = $$el("div", "next", { + parent: this.el, + onclick: (e) => { + this.update(1); + e.stopImmediatePropagation(); + }, + }); + this.link = $$el("a", "link", { + parent: this.main, + target: "_blank", + }); + this.spinner = createSpinner(); + this.link.appendChild(this.spinner); + this.img = $$el("img", "img", { + style: { + opacity: 0, + }, + parent: this.link, + onclick: (e) => { + e.stopImmediatePropagation(); + }, + }); + } + + close() { + ani( + () => (this.el.style.opacity = 0), + 200, + () => (this.el.style.display = "none") + ); + } + + async show(images, index) { + this.images = images; + this.index = index || 0; + await this.update(0); + } + + async update(shift) { + this.index += shift; + + this.prev.style.visibility = this.index ? "unset" : "hidden"; + this.next.style.visibility = this.index === this.images.length - 1 ? "hidden" : "unset"; + + const img = this.images[this.index]; + this.el.style.display = "flex"; + this.el.clientWidth; // Force a reflow + this.el.style.opacity = 1; + this.img.style.opacity = 0; + this.spinner.style.display = "inline-block"; + await loadImage(img); + this.spinner.style.display = "none"; + this.link.href = img; + this.img.src = img; + this.img.style.opacity = 1; + } +} + +export const lightbox = new Lightbox(); diff --git a/web/js/common/modelInfoDialog.css b/web/js/common/modelInfoDialog.css new file mode 100644 index 0000000..9bfbf82 --- /dev/null +++ b/web/js/common/modelInfoDialog.css @@ -0,0 +1,86 @@ +.pysssss-model-info { + color: white; + font-family: sans-serif; + max-width: 90vw; +} +.pysssss-model-content { + display: flex; + flex-direction: column; + overflow: hidden; +} +.pysssss-model-info h2 { + text-align: center; + margin: 0 0 10px 0; +} +.pysssss-model-info main img { + max-height: 300px; + margin-left: 10px; + max-width: 50%; +} +.pysssss-model-info p { + margin: 5px 0; +} +.pysssss-model-info a { + color: dodgerblue; +} +.pysssss-model-info a:hover { + text-decoration: underline; +} +.pysssss-model-tags-list { + display: flex; + flex-wrap: wrap; + list-style: none; + gap: 10px; + max-height: 200px; + overflow: auto; + margin: 10px 0; + padding: 0; +} +.pysssss-model-tag { + background-color: rgb(128, 213, 247); + color: #000; + display: flex; + align-items: center; + gap: 5px; + border-radius: 5px; + padding: 2px 5px; + cursor: pointer; +} +.pysssss-model-tag--selected span::before { + content: "✅"; + position: absolute; + background-color: dodgerblue; + left: 0; + top: 0; + right: 0; + bottom: 0; + text-align: center; +} +.pysssss-model-tag:hover { + outline: 2px solid dodgerblue; +} +.pysssss-model-tag p { + margin: 0; +} +.pysssss-model-tag span { + text-align: center; + border-radius: 5px; + background-color: dodgerblue; + color: #fff; + padding: 2px; + position: relative; + min-width: 20px; + overflow: hidden; +} + +.pysssss-model-metadata .comfy-modal-content { + max-width: 100%; +} +.pysssss-model-metadata label { + margin-right: 1ch; + color: #ccc; +} + +.pysssss-model-metadata span { + color: dodgerblue; +} diff --git a/web/js/common/modelInfoDialog.js b/web/js/common/modelInfoDialog.js new file mode 100644 index 0000000..d360aec --- /dev/null +++ b/web/js/common/modelInfoDialog.js @@ -0,0 +1,198 @@ +import { $el, ComfyDialog } from "../../../../scripts/ui.js"; +import { api } from "../../../../scripts/api.js"; +import { addStylesheet } from "./utils.js"; + +addStylesheet(import.meta.url); + +class MetadataDialog extends ComfyDialog { + constructor() { + super(); + + this.element.classList.add("pysssss-model-metadata"); + } + show(metadata) { + super.show( + $el( + "div", + Object.keys(metadata).map((k) => + $el("div", [$el("label", { textContent: k }), $el("span", { textContent: metadata[k] })]) + ) + ) + ); + } +} + +export class ModelInfoDialog extends ComfyDialog { + constructor(name) { + super(); + this.name = name; + this.element.classList.add("pysssss-model-info"); + } + + get customNotes() { + return this.metadata["pysssss.notes"]; + } + + get hash() { + return this.metadata["pysssss.sha256"]; + } + + async show(type, value) { + const req = api.fetchApi("/pysssss/metadata/" + encodeURIComponent(`${type}/${value}`)); + this.info = $el("div"); + this.img = $el("img", { style: { display: "none" } }); + this.main = $el("main", { style: { display: "flex" } }, [this.info, this.img]); + this.content = $el("div.pysssss-model-content", [$el("h2", { textContent: this.name }), this.main]); + + const loading = $el("div", { textContent: "ℹ️ Loading...", parent: this.content }); + + super.show(this.content); + + this.metadata = await (await req).json(); + this.viewMetadata.style.cursor = this.viewMetadata.style.opacity = ""; + this.viewMetadata.removeAttribute("disabled"); + + loading.remove(); + this.addInfo(); + } + + createButtons() { + const btns = super.createButtons(); + this.viewMetadata = $el("button", { + type: "button", + textContent: "View raw metadata", + disabled: "disabled", + style: { + opacity: 0.5, + cursor: "not-allowed", + }, + onclick: (e) => { + if (this.metadata) { + new MetadataDialog().show(this.metadata); + } + }, + }); + + btns.unshift(this.viewMetadata); + return btns; + } + + getNoteInfo() { + if (this.customNotes) { + let notes = []; + // Extract links from notes + const r = new RegExp("(\\bhttps?:\\/\\/[^\\s]+)", "g"); + let end = 0; + let m; + do { + m = r.exec(this.customNotes); + let pos; + let fin = 0; + if (m) { + pos = m.index; + fin = m.index + m[0].length; + } else { + pos = this.customNotes.length; + } + + let pre = this.customNotes.substring(end, pos); + if (pre) { + pre = pre.replaceAll("\n", "
"); + notes.push( + $el("span", { + innerHTML: pre, + }) + ); + } + if (m) { + notes.push( + $el("a", { + href: m[0], + textContent: m[0], + target: "_blank", + }) + ); + } + + end = fin; + } while (m); + return $el("span", notes); + } else { + let last = this.name.lastIndexOf("."); + if (last === -1) { + last = this.name.length; + } + return `Add custom notes in ${this.name.substring(0, last) + ".txt"}`; + } + } + + addInfo() { + this.addInfoEntry("Notes", this.getNoteInfo()); + } + + addInfoEntry(name, value) { + return $el( + "p", + { + parent: this.info, + }, + [ + typeof name === "string" ? $el("label", { textContent: name + ": " }) : name, + typeof value === "string" ? $el("span", { textContent: value }) : value, + ] + ); + } + + async getCivitaiDetails() { + const req = await fetch("https://civitai.com/api/v1/model-versions/by-hash/" + this.hash); + if (req.status === 200) { + return await req.json(); + } else if (req.status === 404) { + throw new Error("Model not found"); + } else { + throw new Error(`Error loading info (${req.status}) ${req.statusText}`); + } + } + + addCivitaiInfo() { + const promise = this.getCivitaiDetails(); + const content = $el("span", { textContent: "ℹ️ Loading..." }); + + this.addInfoEntry( + $el("label", [ + $el("img", { + style: { + width: "18px", + position: "relative", + top: "3px", + margin: "0 5px 0 0", + }, + src: "https://civitai.com/favicon.ico", + }), + $el("span", { textContent: "Civitai: " }), + ]), + content + ); + + return promise + .then((info) => { + content.replaceChildren( + $el("a", { + href: "https://civitai.com/models/" + info.modelId, + textContent: "View " + info.model.name, + target: "_blank", + }) + ); + + if (info.images?.length) { + this.img.src = info.images[0].url; + this.img.style.display = ""; + } + + return info; + }) + .catch((err) => { + content.textContent = "⚠️ " + err.message; + }); + } +} diff --git a/web/js/common/spinner.css b/web/js/common/spinner.css new file mode 100644 index 0000000..9a29451 --- /dev/null +++ b/web/js/common/spinner.css @@ -0,0 +1,35 @@ +.lds-ring { + display: inline-block; + position: relative; + width: 80px; + height: 80px; +} +.lds-ring div { + box-sizing: border-box; + display: block; + position: absolute; + width: 64px; + height: 64px; + margin: 8px; + border: 5px solid #fff; + border-radius: 50%; + animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite; + border-color: #fff transparent transparent transparent; +} +.lds-ring div:nth-child(1) { + animation-delay: -0.45s; +} +.lds-ring div:nth-child(2) { + animation-delay: -0.3s; +} +.lds-ring div:nth-child(3) { + animation-delay: -0.15s; +} +@keyframes lds-ring { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} diff --git a/web/js/common/spinner.js b/web/js/common/spinner.js new file mode 100644 index 0000000..f01315d --- /dev/null +++ b/web/js/common/spinner.js @@ -0,0 +1,9 @@ +import { addStylesheet } from "./utils.js"; + +addStylesheet(import.meta.url); + +export function createSpinner() { + const div = document.createElement("div"); + div.innerHTML = `
`; + return div.firstElementChild; +} diff --git a/web/js/common/utils.js b/web/js/common/utils.js new file mode 100644 index 0000000..cd7539d --- /dev/null +++ b/web/js/common/utils.js @@ -0,0 +1,30 @@ +import { $el } from "../../../../scripts/ui.js"; + +export function addStylesheet(url) { + if (url.endsWith(".js")) { + url = url.substr(0, url.length - 2) + "css"; + } + $el("link", { + parent: document.head, + rel: "stylesheet", + type: "text/css", + href: url.startsWith("http") ? url : getUrl(url), + }); +} + +export function getUrl(path, baseUrl) { + if (baseUrl) { + return new URL(path, baseUrl).toString(); + } else { + return new URL("../" + path, import.meta.url).toString(); + } +} + +export async function loadImage(url) { + return new Promise((res, rej) => { + const img = new Image(); + img.onload = res; + img.onerror = rej; + img.src = url; + }); +} diff --git a/web/js/stringFunction.js b/web/js/stringFunction.js new file mode 100644 index 0000000..cc150df --- /dev/null +++ b/web/js/stringFunction.js @@ -0,0 +1,33 @@ +import { app } from "../../../scripts/app.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; + +// Displays input text on a node + +app.registerExtension({ + name: "pysssss.StringFunction", + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "StringFunction|pysssss") { + const onExecuted = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = function (message) { + onExecuted?.apply(this, arguments); + + if (this.widgets) { + const pos = this.widgets.findIndex((w) => w.name === "result"); + if (pos !== -1) { + for (let i = pos; i < this.widgets.length; i++) { + this.widgets[i].onRemove?.(); + } + this.widgets.length = pos; + } + } + + const w = ComfyWidgets["STRING"](this, "result", ["STRING", { multiline: true }], app).widget; + w.inputEl.readOnly = true; + w.inputEl.style.opacity = 0.6; + w.value = message.text; + + this.onResize?.(this.size); + }; + } + }, +});