├── .gitignore ├── LICENSE ├── README.md ├── context_menu.html ├── context_menu.js ├── examples ├── basic_flow.json ├── contextmenu_for_button.json ├── contextmenu_in_svg_drawing.json └── hierarchical_contextmenu.json ├── icons └── menu.png ├── lib ├── contextmenu.css └── contextmenu.js └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > [!CAUTION] 2 | > **This third-party ui node was developed for the Node-RED AngularJs [dashboard](https://flows.nodered.org/node/node-red-dashboard), which is end of life. 3 | > Due to free time constraints, this old ui node won't be supported anymore!!** 4 | 5 | # node-red-contrib-ui-contextmenu 6 | A Node-RED node to display a popup contextmenu in the Node-RED dashboard 7 | 8 | Special thanks to [Stephen McLaughlin](https://github.com/Steve-Mcl), my partner in crime for this node! 9 | 10 | ## Install 11 | Run the following npm command in your Node-RED user directory (typically ~/.node-red): 12 | ``` 13 | npm install node-red-contrib-ui-contextmenu 14 | ``` 15 | :warning: ***CAUTION:*** 16 | + It is advised to use ***Dashboard version 2.19.4 or above***, to make sure the contextmenu doesn't appear automatically after deploy or refresh. 17 | + The context menu will ***only appear when its dashboard group (see config screen) is currently visible***! This is important when being used in combination with other nodes: e.g. an SVG node and ContextMenu node always need to be on the same dashboard group, otherwise the contextmenu will never appear! 18 | + The output messages from the ***SVG node 2.x.x contains a breaking change***, which will cause context menus not appearing anymore! See [readme](https://github.com/bartbutenaers/node-red-contrib-ui-svg/) of the SVG node for guidelines. 19 | 20 | Remark: all below examples are also available via the Import menu of the Node-RED flow editor. 21 | 22 | ## Node usage 23 | 24 | There are a few common ways to use this node: 25 | 26 | + Basically this node can be used to display a context menu (on top of any other dashboard widget), totally independent of other nodes. The following flow demonstrates how to show a contextmenu at some location. Both the location and the menu structure can be fixed or dynamic (via an input message): 27 | 28 | ![Basic flow](https://user-images.githubusercontent.com/14224149/87234469-909cd580-c3d1-11ea-9a1b-862797a2211f.png) 29 | 30 | ``` 31 | [{"id":"98f5ee2c.61f16","type":"inject","z":"86187643.ae75e8","name":"Inject menu + position","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"showConfirmation":false,"confirmationLabel":"","x":280,"y":840,"wires":[["131ffbe2.c2f544"]]},{"id":"51a8f9b.d4a2008","type":"change","z":"86187643.ae75e8","name":"","rules":[{"t":"set","p":"position","pt":"msg","to":"{\"x\":100,\"y\":150}","tot":"json"}],"action":"","property":"","from":"","to":"","reg":false,"x":740,"y":840,"wires":[["dc8a767c.3a3d38"]]},{"id":"131ffbe2.c2f544","type":"change","z":"86187643.ae75e8","name":"","rules":[{"t":"set","p":"menu","pt":"msg","to":"[{\"text\":\"Options\",\"icon\":\"fa-list\",\"sub\":[{\"text\":\"Edit\",\"icon\":\"fa-edit\",\"topic\":\"edit\",\"payload\":[1,2,3,4,5],\"payloadType\":\"JSON\",\"outputField\":\"editArray\"},{\"text\":\"Cut\",\"icon\":\"fa-cut\",\"enabled\":true,\"topic\":\"cut\",\"payload\":\"true\",\"payloadType\":\"bool\"}]},{\"text\":\"---\"},{\"text\":\"Delete\",\"icon\":\"fa-trash\",\"enabled\":true,\"payload\":\"12\",\"payloadType\":\"num\"},{\"text\":\"---\"},{\"text\":\"Quit\",\"icon\":\"fa-times\",\"enabled\":false}]","tot":"json"}],"action":"","property":"","from":"","to":"","reg":false,"x":520,"y":840,"wires":[["51a8f9b.d4a2008"]]},{"id":"e5e8a905.5a2448","type":"inject","z":"86187643.ae75e8","name":"Inject menu","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"showConfirmation":false,"confirmationLabel":"","x":530,"y":760,"wires":[["7b5faf00.a6b4a"]]},{"id":"912cb88c.2b6e28","type":"inject","z":"86187643.ae75e8","name":"Inject nothing","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"showConfirmation":false,"confirmationLabel":"","x":750,"y":720,"wires":[["c6b11b3e.1d3508"]]},{"id":"7b5faf00.a6b4a","type":"change","z":"86187643.ae75e8","name":"","rules":[{"t":"set","p":"menu","pt":"msg","to":"[{\"text\":\"Options\",\"icon\":\"fa-list\",\"sub\":[{\"text\":\"Edit\",\"icon\":\"fa-edit\",\"topic\":\"edit\",\"payload\":[1,2,3,4,5],\"payloadType\":\"JSON\",\"outputField\":\"editArray\"},{\"text\":\"Cut\",\"icon\":\"fa-cut\",\"enabled\":true,\"topic\":\"cut\",\"payload\":\"true\",\"payloadType\":\"bool\"}]},{\"text\":\"---\"},{\"text\":\"Delete\",\"icon\":\"fa-trash\",\"enabled\":true,\"payload\":\"12\",\"payloadType\":\"num\"},{\"text\":\"---\"},{\"text\":\"Quit\",\"icon\":\"fa-times\",\"enabled\":false}]","tot":"json"}],"action":"","property":"","from":"","to":"","reg":false,"x":740,"y":760,"wires":[["a1697f44.2f4c8"]]},{"id":"c6b11b3e.1d3508","type":"ui_context_menu","z":"86187643.ae75e8","group":"22787703.a0e968","order":5,"width":0,"height":-1,"fontSize":16,"inputPositionXField":"50","inputPositionXType":"num","inputPositionYField":"60","inputPositionYType":"num","outputField":"payload","inputMenuField":"menu","inputMenuType":"fixed","menuItems":[{"id":"myid","icon":"fa-glass","label":"mylabel","topic":"mytopic","payload":"mypayload","payloadType":"str","visible":true,"enabled":true}],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","intervalLength":0,"intervalUnit":"secs","startTimerAtOpen":false,"startTimerAtLeave":true,"stopTimerAtEnter":true,"name":"","x":960,"y":720,"wires":[[]]},{"id":"a1697f44.2f4c8","type":"ui_context_menu","z":"86187643.ae75e8","group":"22787703.a0e968","order":5,"width":0,"height":-1,"fontSize":16,"inputPositionXField":"50","inputPositionXType":"num","inputPositionYField":"60","inputPositionYType":"num","outputField":"payload","inputMenuField":"menu","inputMenuType":"msg","menuItems":[],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","intervalLength":0,"intervalUnit":"secs","startTimerAtOpen":false,"startTimerAtLeave":true,"stopTimerAtEnter":true,"name":"","x":960,"y":760,"wires":[[]]},{"id":"66f558a1.128238","type":"inject","z":"86187643.ae75e8","name":"Inject position","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"showConfirmation":false,"confirmationLabel":"","x":530,"y":800,"wires":[["1d3334da.ce9ffb"]]},{"id":"75ccccc.2eca634","type":"ui_context_menu","z":"86187643.ae75e8","group":"22787703.a0e968","order":5,"width":0,"height":-1,"fontSize":16,"inputPositionXField":"position.x","inputPositionXType":"msg","inputPositionYField":"position.y","inputPositionYType":"msg","outputField":"payload","inputMenuField":"menu","inputMenuType":"fixed","menuItems":[{"id":"myid2","icon":"fa-search","label":"mylabel2","topic":"mytopic2","payload":"mypayload2","payloadType":"str","visible":true,"enabled":true}],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","intervalLength":0,"intervalUnit":"secs","startTimerAtOpen":false,"startTimerAtLeave":true,"stopTimerAtEnter":true,"name":"","x":960,"y":800,"wires":[[]]},{"id":"dc8a767c.3a3d38","type":"ui_context_menu","z":"86187643.ae75e8","group":"22787703.a0e968","order":5,"width":0,"height":-1,"fontSize":16,"inputPositionXField":"position.x","inputPositionXType":"msg","inputPositionYField":"position.y","inputPositionYType":"msg","outputField":"payload","inputMenuField":"menu","inputMenuType":"msg","menuItems":[],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","intervalLength":0,"intervalUnit":"secs","startTimerAtOpen":false,"startTimerAtLeave":true,"stopTimerAtEnter":true,"name":"","x":960,"y":840,"wires":[[]]},{"id":"1d3334da.ce9ffb","type":"change","z":"86187643.ae75e8","name":"","rules":[{"t":"set","p":"position","pt":"msg","to":"{\"x\":100,\"y\":150}","tot":"json"}],"action":"","property":"","from":"","to":"","reg":false,"x":740,"y":800,"wires":[["75ccccc.2eca634"]]},{"id":"22787703.a0e968","type":"ui_group","z":"","name":"Web push notifications","tab":"80f0e178.bbf4a","order":1,"disp":true,"width":"6","collapse":false},{"id":"80f0e178.bbf4a","type":"ui_tab","z":"","name":"Home","icon":"dashboard","order":1,"disabled":false,"hidden":false}] 32 | ``` 33 | 34 | + Initially we implemented this node to be used in combination with our [node-red-contrib-ui-svg](https://github.com/bartbutenaers/node-red-contrib-ui-svg) node. The following flow explains how a context menu can be displayed on top of a vector graphics drawing: 35 | 36 | ![SVG flow](https://user-images.githubusercontent.com/14224149/87234469-909cd580-c3d1-11ea-9a1b-862797a2211f.png) 37 | ``` 38 | [{"id":"2d30cf4e.41547","type":"ui_svg_graphics","z":"86187643.ae75e8","group":"2908388b.8114b8","order":1,"width":"14","height":"10","svgString":"\n \n \n fa-lightbulb-o \n","clickableShapes":[{"targetId":"#light_bulb_kitchen","action":"click","payload":"light_icon_clicked","payloadType":"str","topic":"light_icon_clicked"}],"smilAnimations":[],"bindings":[{"selector":"#banner","bindSource":"payload.title","bindType":"text","attribute":""},{"selector":"#camera_living","bindSource":"payload.position.x","bindType":"attr","attribute":"x"},{"selector":"#camera_living","bindSource":"payload.camera.colour","bindType":"attr","attribute":"fill"}],"showCoordinates":false,"autoFormatAfterEdit":false,"showBrowserErrors":false,"outputField":"my_output_field","editorUrl":"http://drawsvg.org/drawsvg.html","directory":"","panning":"disabled","zooming":"disabled","panOnlyWhenZoomed":false,"doubleClickZoomEnabled":false,"mouseWheelZoomEnabled":false,"name":"","x":600,"y":1480,"wires":[["24952289.cacf1e","2e6ffce7.748b34"]]},{"id":"24952289.cacf1e","type":"debug","z":"86187643.ae75e8","name":"Clicked SVG shape","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":830,"y":1540,"wires":[]},{"id":"2e6ffce7.748b34","type":"ui_context_menu","z":"86187643.ae75e8","group":"2908388b.8114b8","order":5,"width":0,"height":-1,"fontSize":16,"inputPositionXField":"event.pageX","inputPositionXType":"msg","inputPositionYField":"event.pageY","inputPositionYType":"msg","outputField":"payload","inputMenuField":"","inputMenuType":"fixed","menuItems":[{"id":"ON","icon":"fa-toggle-on","label":"Light on","topic":"light_kitchen_on","payload":"light_kitchen_on","payloadType":"str","visible":true,"enabled":true},{"id":"OFF","icon":"fa-toggle-off","label":"Light off","topic":"light_kitchen_off","payload":"light_kitchen_off","payloadType":"str","visible":true,"enabled":true}],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","intervalLength":"0","intervalUnit":"secs","startTimerAtOpen":false,"startTimerAtLeave":true,"stopTimerAtEnter":true,"name":"","x":820,"y":1480,"wires":[["14b0feb6.5bea51"]]},{"id":"14b0feb6.5bea51","type":"debug","z":"86187643.ae75e8","name":"Clicked menu item","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":1050,"y":1480,"wires":[]},{"id":"2908388b.8114b8","type":"ui_group","z":"","name":"Floorplan test","tab":"a28ff08f.3a822","order":1,"disp":true,"width":"14","collapse":false},{"id":"a28ff08f.3a822","type":"ui_tab","z":"","name":"SVG","icon":"dashboard","disabled":false,"hidden":false}] 39 | ``` 40 | 41 | 1. The SVG node display a vector graphics drawing in the Node-RED dashboard, including a clickable light-bulb icon. 42 | 1. As soon as the user clicks the light-bulb icon, the SVG node will send an output message (incl. ```msg.event.pageX``` and ```msg.event.pageY``` which define the mouse click position)! 43 | 1. The message enters the contextmenu-node and will trigger a contextmenu popup displayed at the mouse click position. Remark: it would make more sense to determine the list of context menu items, based on the ```msg.topic``` which contains the information about which SVG element has been clicked). 44 | 1. As soon as the user clicks on one of the menu items, the contextmenu-node will send an output message (containing information about the clicked menu item). 45 | 1. The next nodes in the flow can handle the clicked menu item ... 46 | 47 | A short demo to demonstrate the result: 48 | 49 | ![contextmenu_demo](https://user-images.githubusercontent.com/14224149/65722808-587c0e80-e0ad-11e9-91cb-8ad14510f03f.gif) 50 | 51 | + Other UI nodes (like Button and node-red-contrib-ui-state-trail nodes) also have a ```msg.event``` in their output messages, which means a contextmenu can be displayed when such a UI node is being clicked. 52 | 53 | Thanks to [Paul Reed](https://github.com/Paul-Reed) for demonstrating how to use a contextmenu - in combination with a dashboard button - to create a hierarchical dashboard menu: 54 | 55 | ![contextmenu_paul_reed](https://user-images.githubusercontent.com/14224149/87257213-70d0e480-c499-11ea-816b-1ebf196e6254.gif) 56 | 57 | The following (simplified) flow explains how to accomplish something like this, based on the bounding box of the clicked element: 58 | 59 | ![bbox flow](https://user-images.githubusercontent.com/14224149/87257236-c86f5000-c499-11ea-980f-c83562c9713f.png) 60 | ``` 61 | [{"id":"45f42449.b3c8dc","type":"ui_button","z":"86187643.ae75e8","name":"","group":"2908388b.8114b8","order":9,"width":"1","height":"1","passthru":false,"label":"","tooltip":"","color":"","bgcolor":"","icon":"fa-bars","payload":"button_clicked","payloadType":"str","topic":"","x":590,"y":1640,"wires":[["5b2478ff.043158"]]},{"id":"5b2478ff.043158","type":"change","z":"86187643.ae75e8","name":"Get X and Y from bbox","rules":[{"t":"set","p":"position.x","pt":"msg","to":"event.bbox[2]-9","tot":"jsonata"},{"t":"set","p":"position.y","pt":"msg","to":"event.bbox[3]+18","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":780,"y":1640,"wires":[["b3b5bcfc.cf079"]]},{"id":"b3b5bcfc.cf079","type":"ui_context_menu","z":"86187643.ae75e8","group":"2908388b.8114b8","order":5,"width":0,"height":-1,"fontSize":16,"inputPositionXField":"position.x","inputPositionXType":"msg","inputPositionYField":"position.y","inputPositionYType":"msg","outputField":"payload","inputMenuField":"","inputMenuType":"fixed","menuItems":[{"id":"ZOOM_OUT","icon":"fa-search-minus","label":"Light on","topic":"zoom out","payload":"zoom out","payloadType":"str","visible":true,"enabled":true},{"id":"ZOOM_IN","icon":"fa-search-plus","label":"Light off","topic":"zoom in","payload":"zoom in","payloadType":"str","visible":true,"enabled":true}],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","intervalLength":"0","intervalUnit":"secs","startTimerAtOpen":false,"startTimerAtLeave":true,"stopTimerAtEnter":true,"name":"","x":1000,"y":1640,"wires":[[]]},{"id":"2908388b.8114b8","type":"ui_group","z":"","name":"Floorplan test","tab":"a28ff08f.3a822","order":1,"disp":true,"width":"14","collapse":false},{"id":"a28ff08f.3a822","type":"ui_tab","z":"","name":"SVG","icon":"dashboard","disabled":false,"hidden":false}] 62 | ``` 63 | Remark: in this case it might be useful to hide the standard Node-RED dashboard hamburger menu icon: 64 | 65 | ![Hide titlebar](https://user-images.githubusercontent.com/14224149/88464796-e8e9d200-cebd-11ea-9ad4-75b5dbfba5a4.png) 66 | 67 | ## Node properties 68 | 69 | ### Font size 70 | The font size of the menu items 71 | 72 | ### X/Y coordinate 73 | Specify how the position of the context menu on the screen will be specified: 74 | 75 | + *Msg*: The input message must contain the X/Y coordinate number in the specified msg field. This way the the menu position can be updated dynamically. 76 | 77 | + *Num*: The fixed X/Y coordinate number must be specified on the config screen. 78 | 79 | ### Output To 80 | Specify where the payload output from clicking a menu item should appear in the `msg`. 81 | NOTE: for a *msg based menu*, this can be set per menu item via the property `outputField` (see Message Based example below) 82 | 83 | ### Menu 84 | Specify how the menu items of the context menu will be specified: 85 | 86 | + ***Fixed***: A table will be displayed, to enter the menu items. The following properties can be set for every menu item: 87 | + *ID*: The id of the menu item (which won't be displayed). 88 | + *Label*: The label that will be displayed in the context menu. Set the Label to "---" to create a seperator (all other fields can be left blank). 89 | + *Icon*: The FontAwesome icon that will be displayed in the context menu. 90 | + *Topic*: The `msg.topic` that will be send in the output message. 91 | + *Payload*: The `msg.payload` that will be send in the output message. NOTE: if the "Output to" field is set to something other than "payload", then the output will appear in that property of `msg` 92 | 93 | + ***Msg***: the input message must contain the menu (as a JSON array of menu items) in the specified msg field. This way the the menu structure can be updated dynamically. 94 | 95 | An example input message: 96 | ``` 97 | "menu": [ 98 | { 99 | "text": "Options", 100 | "icon": "fa-list", 101 | "sub": [ 102 | { 103 | "text": "Edit", 104 | "icon": "fa-edit", 105 | "topic": "edit", 106 | "payload": [ 1, 2, 3, 4, 5 ], 107 | "payloadType": "JSON", 108 | "outputField" : "editArray" 109 | }, 110 | { 111 | "text": "Cut", 112 | "icon": "fa-cut", 113 | "enabled": true, 114 | "topic": "cut", 115 | "payload": "true", 116 | "payloadType": "bool" 117 | } 118 | ] 119 | }, 120 | { 121 | "text": "---" 122 | }, 123 | { 124 | "text": "Delete", 125 | "icon": "fa-trash", 126 | "enabled": true, 127 | "payload": "12", 128 | "payloadType": "num" 129 | }, 130 | { 131 | "text": "---" 132 | }, 133 | { 134 | "text": "Quit", 135 | "icon": "fa-times", 136 | "enabled": false 137 | } 138 | ] 139 | ``` 140 | 141 | Example flow with nested sub-menu: 142 | 143 | ![nested menu flow](https://user-images.githubusercontent.com/14224149/66081594-9626de80-e568-11e9-96b0-0c70006202d4.png) 144 | 145 | ``` 146 | [{"id":"fd05877e.cb0588","type":"ui_svg_graphics","z":"60ad596.8120ba8","group":"9f5b4cff.15cd3","order":1,"width":"14","height":"10","svgString":"\n \n \n ","clickableShapes":[{"targetId":"#mycircle","action":"click","payload":"camera_living","payloadType":"str","topic":"camera_living"}],"smilAnimations":[],"bindings":[{"selector":"#banner","bindSource":"payload.title","bindType":"text","attribute":""},{"selector":"#camera_living","bindSource":"payload.position.x","bindType":"attr","attribute":"x"},{"selector":"#camera_living","bindSource":"payload.camera.colour","bindType":"attr","attribute":"fill"}],"showCoordinates":false,"autoFormatAfterEdit":false,"outputField":"","editorUrl":"http://drawsvg.org/drawsvg.html","directory":"","name":"","x":920,"y":120,"wires":[["a4c84c93.c001d"]]},{"id":"c65edd5a.1c031","type":"ui_context_menu","z":"60ad596.8120ba8","group":"9f5b4cff.15cd3","order":5,"width":0,"height":-1,"fontSize":16,"position":"msg","outputField":"payload","xCoordinate":50,"yCoordinate":50,"menu":"msg","menuItems":[],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","name":"","x":1360,"y":120,"wires":[[]]},{"id":"a4c84c93.c001d","type":"change","z":"60ad596.8120ba8","name":"","rules":[{"t":"set","p":"menu","pt":"msg","to":"[{\"text\":\"Options\",\"icon\":\"fa-list\",\"sub\":[{\"text\":\"Edit\",\"icon\":\"fa-edit\",\"topic\":\"edit\",\"payload\":[1,2,3,4,5],\"payloadType\":\"JSON\",\"outputField\":\"editArray\"},{\"text\":\"Cut\",\"icon\":\"fa-cut\",\"enabled\":true,\"topic\":\"cut\",\"payload\":\"true\",\"payloadType\":\"bool\"}]},{\"text\":\"---\"},{\"text\":\"Delete\",\"icon\":\"fa-trash\",\"enabled\":true,\"payload\":\"12\",\"payloadType\":\"num\"},{\"text\":\"---\"},{\"text\":\"Quit\",\"icon\":\"fa-times\",\"enabled\":false}]","tot":"json"}],"action":"","property":"","from":"","to":"","reg":false,"x":1140,"y":120,"wires":[["c65edd5a.1c031"]]},{"id":"9f5b4cff.15cd3","type":"ui_group","z":"","name":"Floorplan test","tab":"dabfe25b.13bc1","disp":true,"width":"14","collapse":false},{"id":"dabfe25b.13bc1","type":"ui_tab","z":"","name":"SVG","icon":"dashboard","disabled":false,"hidden":false}] 147 | ``` 148 | 149 | + Nested menus are possible when the menu is supplied via *"msg"*: 150 | + *text*: The label that will be displayed in the context menu. NOTE: To create a separator, use "---" as the text value (all other fields can be left blank). 151 | + *icon*: (optional) The FontAwesome icon that will be displayed in the context menu. 152 | + *sub*: (optional) An array of sub menu items 153 | + *topic*: (optional) The `msg.topic` that will be send in the output message. If left empty, `topic` will default the the `path` of this menu item. 154 | + *payload*: The `msg.payload` that will be send in the output message. If left empty, `message` will default the the `text` of this menu item. 155 | + *payloadType*: The type of `msg.payload`. Allowable types are 'JSON', 'str', 'bool', 'num'. `payload` will be converted to this type. 156 | + *outputField*: (optional) It is possible to override the "Output to" field. This property will permit the `payload` to be send to an alternative property of `msg` 157 | + ** *text* is the only** mandatory field. 158 | 159 | The message-based approach has the advantage that it offers ***nested menu items***, which is currently not available in the config screen! 160 | 161 | The label an icon are both optional. This means you can use both or only one of them, to achieve various effects. 162 | 163 | ### Auto hide 164 | + When this value is ```0``` the context menu will stay visible, until a menu item is selected or outside the menu is being clicked. 165 | + When this value is e.g. 3 seconds this means that the context menu will automatically disappear when the context menu is out of focus during at least 3 seconds. 166 | + So as long as the mouse cursors is on top of the menu, the user has time to think about which action he wants to perform. 167 | + As soon as the mouse cursor leaves the context menu, the timer will start counting. 168 | + But when the mouse cursor enters the context menu again, the timer will be reset. This way the users has again extra time to think about the action he wants to perform. 169 | + When the mouse cursor is away from the context menu for the specified time interval, the context menu will automatically be hidden. 170 | 171 | Demo of auto hide in 3 seconds (notice the timer status in the console): 172 | 173 | ![contextmenu_timer](https://user-images.githubusercontent.com/14224149/66244476-e50b7a00-e708-11e9-870c-36bde4e9a888.gif) 174 | 175 | 176 | ### Colors 177 | Specify how the colors of the context menu should look like: 178 | 179 | + *Native*: The default CSS colors of this node will be used. 180 | + *Match dashboard theme*: The colors of the currently selected dashboard theme will be used. 181 | + *Custom*: Three color pickers will be displayed, which allow you to specify your custom colors. 182 | 183 | ![Custom colors](https://user-images.githubusercontent.com/14224149/66244438-b8576280-e708-11e9-9931-2399e414ef7c.png) 184 | 185 | Demo for the dashboard's built-in *dark* theme (menu1=custom, menu2=theme, menu2=native): 186 | 187 | ![demo_dark_theme](https://user-images.githubusercontent.com/14224149/67512913-176e1e80-f69a-11e9-8618-38edb8447d9d.gif) 188 | 189 | Demo for the dashboard's built-in *light* theme (menu1=custom, menu2=theme, menu2=native): 190 | 191 | ![demo_light_theme](https://user-images.githubusercontent.com/14224149/67512904-150bc480-f69a-11e9-9981-c49aa4e7cbeb.gif) 192 | 193 | ### Output message 194 | As soon as a menu item has been clicked, an output message will be send. It is up to the next nodes in the flow, to determine how the menu item should be handled. 195 | 196 | The output message will contain following fields: 197 | + *payload*: This will contain the payload value that has been specified in the menu item, or by default a string containing the key of clicked item. NOTE: if the "Output to" field is set to something other than "payload", then the output will appear in that property of `msg`. This can also be overriden per menu item by setting `outputField` in the menu item 198 | + *topic*: This will contain the topic value that has been specified in the menu item, or by default a string containing the path of menu clicked item. 199 | + *sourceMsg*: This will contain original input message, that has triggered the contextmenu to be displayed. 200 | 201 | -------------------------------------------------------------------------------- /context_menu.html: -------------------------------------------------------------------------------- 1 | 13 | 14 | 1021 | 1022 | 1122 | 1268 | -------------------------------------------------------------------------------- /context_menu.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Bart Butenaers, Stephen McLaughlin 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | **/ 16 | var path = require('path'); 17 | module.exports = function(RED) { 18 | var settings = RED.settings; 19 | 20 | function setResult(msg, field, value) { 21 | field = field ? field : "payload"; 22 | const keys = field.split('.'); 23 | const lastKey = keys.pop(); 24 | const lastObj = keys.reduce((obj, key) => obj[key] = obj[key] || {}, msg); 25 | lastObj[lastKey] = value; 26 | }; 27 | 28 | // Version 4.0 : https://stackoverflow.com/questions/5560248/programmatically-lighten-or-darken-a-hex-color-or-rgb-and-blend-colors 29 | 30 | /** 31 | * pSBC = perform Shading, Blending, Conversion. See examples below.. 32 | * 33 | * @param {Number} p - Percent or adjust -1.0 ~ 1.0 34 | * @param {String|Object} c0 - From colour 35 | * @param {String|Object|Boolean} c1 - To Color 36 | * @param {Boolean} l - Linear / Log blending. true for Linear Blending, false for log blending 37 | * @returns new color string. This can be either #xxxxxx?? or RBG(x,x,x,?) depending on input 38 | * @example 39 | * let color1 = "rgb(20,60,200)"; 40 | * let color2 = "rgba(20,60,200,0.67423)"; 41 | * let color3 = "#67DAF0"; 42 | * let color4 = "#5567DAF0"; 43 | * let color5 = "#F3A"; 44 | * let color6 = "#F3A9"; 45 | * let color7 = "rgb(200,60,20)"; 46 | * let color8 = "rgba(200,60,20,0.98631)"; 47 | * 48 | * // ########## Log Blending ########## // 49 | * // Shade (Lighten or Darken) 50 | * pSBC ( 0.42, color1 ); // rgb(20,60,200) + [42% Lighter] => rgb(166,171,225) 51 | * pSBC ( -0.4, color5 ); // #F3A + [40% Darker] => #c62884 52 | * pSBC ( 0.42, color8 ); // rgba(200,60,20,0.98631) + [42% Lighter] => rgba(225,171,166,0.98631) 53 | * 54 | * // Shade with Conversion (use "c" as your "to" color) 55 | * pSBC ( 0.42, color2, "c" ); // rgba(20,60,200,0.67423) + [42% Lighter] + [Convert] => #a6abe1ac 56 | * 57 | * // RGB2Hex & Hex2RGB Conversion Only (set percentage to zero) 58 | * pSBC ( 0, color6, "c" ); // #F3A9 + [Convert] => rgba(255,51,170,0.6) 59 | * 60 | * // Blending 61 | * pSBC ( -0.5, color2, color8 ); // rgba(20,60,200,0.67423) + rgba(200,60,20,0.98631) + [50% Blend] => rgba(142,60,142,0.83) 62 | * pSBC ( 0.7, color2, color7 ); // rgba(20,60,200,0.67423) + rgb(200,60,20) + [70% Blend] => rgba(168,60,111,0.67423) 63 | * pSBC ( 0.25, color3, color7 ); // #67DAF0 + rgb(200,60,20) + [25% Blend] => rgb(134,191,208) 64 | * pSBC ( 0.75, color7, color3 ); // rgb(200,60,20) + #67DAF0 + [75% Blend] => #86bfd0 65 | * 66 | * // ########## Linear Blending ########## // 67 | * // Shade (Lighten or Darken) 68 | * pSBC ( 0.42, color1, false, true ); // rgb(20,60,200) + [42% Lighter] => rgb(119,142,223) 69 | * pSBC ( -0.4, color5, false, true ); // #F3A + [40% Darker] => #991f66 70 | * pSBC ( 0.42, color8, false, true ); // rgba(200,60,20,0.98631) + [42% Lighter] => rgba(223,142,119,0.98631) 71 | * 72 | * // Shade with Conversion (use "c" as your "to" color) 73 | * pSBC ( 0.42, color2, "c", true ); // rgba(20,60,200,0.67423) + [42% Lighter] + [Convert] => #778edfac 74 | * 75 | * // RGB2Hex & Hex2RGB Conversion Only (set percentage to zero) 76 | * pSBC ( 0, color6, "c", true ); // #F3A9 + [Convert] => rgba(255,51,170,0.6) 77 | * 78 | * // Blending 79 | * pSBC ( -0.5, color2, color8, true ); // rgba(20,60,200,0.67423) + rgba(200,60,20,0.98631) + [50% Blend] => rgba(110,60,110,0.83) 80 | * pSBC ( 0.7, color2, color7, true ); // rgba(20,60,200,0.67423) + rgb(200,60,20) + [70% Blend] => rgba(146,60,74,0.67423) 81 | * pSBC ( 0.25, color3, color7, true ); // #67DAF0 + rgb(200,60,20) + [25% Blend] => rgb(127,179,185) 82 | * pSBC ( 0.75, color7, color3, true ); // rgb(200,60,20) + #67DAF0 + [75% Blend] => #7fb3b9 83 | */ 84 | const pSBC=(p,c0,c1,l)=>{ 85 | let r,g,b,P,f,t,h,i=parseInt,m=Math.round,a=typeof(c1)=="string"; 86 | if(typeof(p)!="number"||p<-1||p>1||typeof(c0)!="string"||(c0[0]!='r'&&c0[0]!='#')||(c1&&!a))return null; 87 | if(!this.pSBCr)this.pSBCr=(d)=>{ 88 | let n=d.length,x={}; 89 | if(n>9){ 90 | [r,g,b,a]=d=d.split(","),n=d.length; 91 | if(n<3||n>4)return null; 92 | x.r=i(r[3]=="a"?r.slice(5):r.slice(4)),x.g=i(g),x.b=i(b),x.a=a?parseFloat(a):-1 93 | }else{ 94 | if(n==8||n==6||n<4)return null; 95 | if(n<6)d="#"+d[1]+d[1]+d[2]+d[2]+d[3]+d[3]+(n>4?d[4]+d[4]:""); 96 | d=i(d.slice(1),16); 97 | if(n==9||n==5)x.r=d>>24&255,x.g=d>>16&255,x.b=d>>8&255,x.a=m((d&255)/0.255)/1000; 98 | else x.r=d>>16,x.g=d>>8&255,x.b=d&255,x.a=-1 99 | }return x}; 100 | h=c0.length>9,h=a?c1.length>9?true:c1=="c"?!h:false:h,f=pSBCr(c0),P=p<0,t=c1&&c1!="c"?pSBCr(c1):P?{r:0,g:0,b:0,a:-1}:{r:255,g:255,b:255,a:-1},p=P?p*-1:p,P=1-p; 101 | if(!f||!t)return null; 102 | if(l)r=m(P*f.r+p*t.r),g=m(P*f.g+p*t.g),b=m(P*f.b+p*t.b); 103 | else r=m((P*f.r**2+p*t.r**2)**0.5),g=m((P*f.g**2+p*t.g**2)**0.5),b=m((P*f.b**2+p*t.b**2)**0.5); 104 | a=f.a,t=t.a,f=a>=0||t>=0,a=f?a<0?t:t<0?a:a*P+t*p:0; 105 | if(h)return"rgb"+(f?"a(":"(")+r+","+g+","+b+(f?","+m(a*1000)/1000:"")+")"; 106 | else return"#"+(4294967296+r*16777216+g*65536+b*256+(f?m(a*255):0)).toString(16).slice(1,f?undefined:-2) 107 | } 108 | //https://awik.io/determine-color-bright-dark-using-javascript/ 109 | function lightOrDark(color) { 110 | var r, g, b, hsp;// Variables for red, green, blue values 111 | // Check the format of the color, HEX or RGB? 112 | if (color.match(/^rgb/)) { 113 | // If HEX --> store the red, green, blue values in separate variables 114 | color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/); 115 | r = color[1]; g = color[2]; b = color[3]; 116 | } else { 117 | // If RGB --> Convert it to HEX: http://gist.github.com/983661 118 | color = +("0x" + color.slice(1).replace( 119 | color.length < 5 && /./g, '$&$&')); 120 | r = color >> 16; g = color >> 8 & 255; b = color & 255; 121 | } 122 | // HSP (Highly Sensitive Poo) equation from http://alienryderflex.com/hsp.html 123 | hsp = Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b) ); 124 | if (hsp>127.5) { 125 | return 'light'; 126 | } else { 127 | return 'dark'; 128 | } 129 | } 130 | function HTML(node) { 131 | // Migrate existing nodes (containing the old 'position' field), which have no typedinputs for the location yet. 132 | // Do this migration server-side, so the beforeEmit function can used the migrated config. 133 | switch (node.config.position) { 134 | case "fixed": 135 | // Copy the obsolete x and y coordinates to the new typedinputs 136 | node.config.inputPositionXField = node.config.xCoordinate; 137 | node.config.inputPositionYField = node.config.yCoordinate; 138 | node.config.inputPositionXType = 'num'; 139 | node.config.inputPositionYType = 'num'; 140 | break; 141 | case "msg": 142 | // Copy the obsolete msg.position field where the location was being expected to arrive in the past 143 | node.config.inputPositionXField = "position.x"; 144 | node.config.inputPositionYField = "position.y"; 145 | node.config.inputPositionXType = 'msg'; 146 | node.config.inputPositionYType = 'msg'; 147 | break; 148 | default: 149 | // Recent node, so no migration needed 150 | } 151 | 152 | delete node.config.position; 153 | delete node.config.xCoordinate; 154 | delete node.config.yCoordinate; 155 | 156 | // Migrate existing nodes (containing the old 'position' field), which have no typedinput for the menu yet 157 | switch (node.config.menu) { 158 | case "fixed": 159 | node.config.inputMenuType = 'fixed'; 160 | break; 161 | case "msg": 162 | // Copy the obsolete msg.menu field where the menu was being expected to arrive in the past 163 | node.config.inputMenuField = "menu"; 164 | node.config.inputMenuType = 'msg'; 165 | break; 166 | default: 167 | // Recent node, so no migration needed 168 | } 169 | 170 | delete node.config.menu; 171 | 172 | 173 | 174 | // The configuration is a Javascript object, which needs to be converted to a JSON string 175 | var configAsJson = JSON.stringify(node.config); 176 | var className = "custom-" + node.id.replace(".",""); 177 | var style = ""; 178 | //generate custom styles if user has selected non-native 179 | if(node.colors !== "native"){ 180 | let cm_ul_color = node.textColor || "#0";//text colour 181 | let cm_ul_background_color = node.backgroundColor || "#ffffff"; //fill colour 182 | let cm_ul_box_shadow = "0 0 5px " + (node.borderColor || "#626262");//border colour 183 | let cm_li_hover_color = node.hoverColor || "#b0b0b0";//hover colour 184 | let cm_li_disabled_color = node.disabledColor || "#777"; 185 | 186 | style = String.raw` 187 | ` 203 | } 204 | var html = style + " \ 205 | "; 207 | return html; 208 | }; 209 | 210 | 211 | var ui = undefined; 212 | function ContextMenuNode(config) { 213 | var node = this; 214 | node.config = config; 215 | node.outputField = config.outputField; 216 | 217 | if(ui === undefined) { 218 | ui = RED.require("node-red-dashboard")(RED); 219 | } 220 | node.colors = config.colors || "native"; 221 | node.textColor = config.textColor || "#0"; 222 | node.backgroundColor = config.backgroundColor || "#ffffff"; 223 | node.hoverColor = config.borderColor || "#626262"; 224 | 225 | // When the user has selected to use theme colors, then just that ... 226 | if (node.colors === "theme") { 227 | if(ui.getTheme){ 228 | var theme = ui.getTheme(); 229 | node.textColor = theme["widget-textColor"].value || node.textColor; 230 | node.backgroundColor = theme["group-backgroundColor"].value || node.backgroundColor; 231 | node.hoverColor = theme["widget-backgroundColor"].value || node.borderColor; 232 | } else { 233 | node.colors = "native"//default to native 234 | node.warn("ui.getTheme() not avaiable. Check dashboard version is up to date"); 235 | //TODO: consider removing theme option from dropdown if not available? 236 | //Currently, native colors will be used if old dashboard present. 237 | } 238 | } 239 | 240 | if(node.colors !== "native"){ 241 | let ColDif = lightOrDark(node.hoverColor) == "light" ? -0.1/*10% darker*/ : 0.1/*10% lighter*/ 242 | node.borderColor = pSBC(ColDif, node.hoverColor ); //lighten/darken border color 10% to hover color 243 | node.disabledColor = pSBC(0.5, node.textColor, node.backgroundColor ); //blend 50% from textColor towards background color 244 | } 245 | 246 | RED.nodes.createNode(this, config); 247 | 248 | var html = HTML(node); 249 | 250 | var done = ui.addWidget({ 251 | node: node, 252 | group: config.group, 253 | order: config.order || 0, 254 | width: config.width, 255 | height: config.height, 256 | format: html, 257 | templateScope: "local", 258 | emitOnlyNewValues: false, 259 | forwardInputMessages: false, 260 | storeFrontEndInputAsState: false, 261 | // Avoid contextmenu to appear automatically after deploy. 262 | // (see https://github.com/node-red/node-red-dashboard/pull/558) 263 | persistantFrontEndValue: false, 264 | convertBack: function (value) { 265 | return value; 266 | }, 267 | beforeEmit: function(msg, value) { 268 | // ****************************************************************************************** 269 | // Server side validation of input messages. 270 | // ****************************************************************************************** 271 | // Would like to ignore invalid input messages, but that seems not to possible in UI nodes: 272 | // See https://discourse.nodered.org/t/custom-ui-node-not-visible-in-dashboard-sidebar/9666 273 | // We will workaround it by sending msg.invalid_message=true to the dashboard. 274 | 275 | var newMsg = {}; 276 | 277 | if (msg) { 278 | // Copy the socket id from the original input message. Otherwise the context menu will popup 279 | // in ALL dashboard sessions that are currently open. 280 | // See https://discourse.nodered.org/t/dashboard-socket-id-bug/6229/6?u=bartbutenaers 281 | newMsg.socketid = msg.socketid; 282 | } 283 | 284 | if (config.inputPositionXType === "msg") { 285 | try { 286 | // Get the x position from the specified message field 287 | newMsg.x = RED.util.getMessageProperty(msg, config.inputPositionXField); 288 | } 289 | catch(err) { 290 | node.error("Error getting x position from msg." + config.inputPositionXField + " : " + err.message); 291 | msg.invalid_message = true; 292 | return { msg: msg }; 293 | } 294 | 295 | if (isNaN(newMsg.x)) { 296 | node.error("The x position in msg." + config.inputPositionXField + " should be a number"); 297 | msg.invalid_message = true; 298 | return { msg: msg }; 299 | } 300 | } 301 | 302 | if (config.inputPositionYType === "msg") { 303 | try { 304 | // Get the y position from the specified message field 305 | newMsg.y = RED.util.getMessageProperty(msg, config.inputPositionYField); 306 | } 307 | catch(err) { 308 | node.error("Error getting y position from msg." + config.inputPositionYField + " : " + err.message); 309 | msg.invalid_message = true; 310 | return { msg: msg }; 311 | } 312 | 313 | if (isNaN(newMsg.y)) { 314 | node.error("The y position in msg." + config.inputPositionYField + " should be a number"); 315 | msg.invalid_message = true; 316 | return { msg: msg }; 317 | } 318 | } 319 | 320 | if (config.inputMenuType === "msg") { 321 | try { 322 | // Get the menu from the specified message field 323 | newMsg.menu = RED.util.getMessageProperty(msg, config.inputMenuField); 324 | } 325 | catch(err) { 326 | node.error("Error getting the menu from msg." + config.inputMenuField + " : " + err.message); 327 | msg.invalid_message = true; 328 | return { msg: msg }; 329 | } 330 | 331 | if (typeof newMsg.menu != "object" ) { 332 | node.error("When using message based menu items, the msg.menu should contain an object containing menu items"); 333 | msg.invalid_message = true; 334 | return { msg: msg }; 335 | } 336 | } 337 | 338 | // Keep the original input message 339 | newMsg.sourceMsg = msg; 340 | 341 | // Seem that all the specified msg fields are available, so send a message to the client (containing msg.x, msg.y, msg.z). 342 | // This way the message has been flattened, so the client doesn't need to access the nested msg properties. 343 | // See https://discourse.nodered.org/t/red-in-ui-nodes/29824/2 344 | return { msg: newMsg }; 345 | }, 346 | beforeSend: function (msg, orig) { 347 | try { 348 | if (!orig || !orig.msg) { 349 | return;//TODO: what to do if empty? Currently, halt flow by returning nothing 350 | } 351 | var newMsg = { 352 | menuId: orig.msg.menuItem.id, 353 | menuindex: orig.msg.menuItem.index, 354 | topic: orig.msg.menuItem.topic, 355 | payload: orig.msg.menuItem.payload, 356 | sourceMsg: orig.msg.sourceMsg // The original input message 357 | }; 358 | RED.util.evaluateNodeProperty(orig.msg.menuItem.payload,orig.msg.menuItem.payloadType,node,orig.msg,(err,value) => { 359 | if (err) { 360 | throw err;//TODO: is this an error object? or should I create new Error(err)? 361 | } else { 362 | setResult(newMsg, node.outputField || orig.msg.menuItem.outputField, value); 363 | } 364 | }); 365 | return newMsg; 366 | } catch (error) { 367 | node.error(error); 368 | } 369 | 370 | }, 371 | initController: function($scope, events) { 372 | // Remark: all client-side functions should be added here! 373 | // If added above, it will be server-side functions which are not available at the client-side ... 374 | console.log("ui_context_menu: ui_contextmenu.initController()") 375 | 376 | //IE 377 | if (!String.prototype.endsWith) { 378 | String.prototype.endsWith = function(searchString, position) { 379 | var subjectString = this.toString(); 380 | if (typeof position !== 'number' || !isFinite(position) 381 | || Math.floor(position) !== position || position > subjectString.length) { 382 | position = subjectString.length; 383 | } 384 | position -= searchString.length; 385 | var lastIndex = subjectString.indexOf(searchString, position); 386 | return lastIndex !== -1 && lastIndex === position; 387 | }; 388 | } 389 | 390 | //https://stackoverflow.com/questions/14919894/getscript-but-for-stylesheets-in-jquery 391 | function loadJavascriptAndCssFiles(urls, successCallback, failureCallback) { 392 | $.when.apply($, 393 | $.map(urls, function(url) { 394 | if(url.endsWith(".css")) { 395 | return $.get(url, function(css) { 396 | $("").appendTo("head"); 397 | }); 398 | } else { 399 | return $.getScript(url); 400 | } 401 | }) 402 | ).then(function() { 403 | if (typeof successCallback === 'function') successCallback(); 404 | }).fail(function() { 405 | if (typeof failureCallback === 'function') failureCallback(); 406 | }); 407 | } 408 | 409 | // Adjust a colour with a specified amount 410 | // See https://stackoverflow.com/a/57401891 411 | function adjust(color, amount) { 412 | return '#' + color.replace(/^#/, '').replace(/../g, color => ('0'+Math.min(255, Math.max(0, parseInt(color, 16) + amount)).toString(16)).substr(-2)); 413 | } 414 | 415 | function getPosition(scope, msg) { 416 | var xp = 0,yp = 0; 417 | 418 | switch ($scope.config.inputPositionXType) { 419 | case "num": 420 | // Get the x coordinate from the config screen 421 | xp = $scope.config.inputPositionXField; 422 | break; 423 | case "msg": 424 | // Get the x coordinate from the specified message field 425 | xp = msg.x; 426 | break; 427 | } 428 | 429 | switch ($scope.config.inputPositionYType) { 430 | case "num": 431 | // Get the y coordinate from the config screen 432 | yp = $scope.config.inputPositionYField; 433 | break; 434 | case "msg": 435 | // Get the y coordinate from the specified message field 436 | yp = msg.y; 437 | break; 438 | } 439 | 440 | return {clientX: parseInt(xp), clientY: parseInt(yp)}; 441 | } 442 | 443 | $scope.flag = true; 444 | 445 | $scope.init = function (config) { 446 | console.log("ui_context_menu: ui_contextmenu.initController > $scope.init()") 447 | $scope.config = config; 448 | $scope.contextmenuItems = null; 449 | 450 | // Migrate older nodes, which had no auto hide functionality 451 | if(!$scope.config.hasOwnProperty('intervalLength')) { 452 | $scope.config.intervalLength = 0; 453 | } 454 | if(!$scope.config.hasOwnProperty('intervalUnit')) { 455 | $scope.config.intervalUnit = "secs"; 456 | } 457 | if(!$scope.config.hasOwnProperty('startTimerAtOpen')) { 458 | $scope.config.startTimerAtOpen = false; 459 | } 460 | if(!$scope.config.hasOwnProperty('startTimerAtLeave')) { 461 | $scope.config.startTimerAtLeave = true; 462 | } 463 | if(!$scope.config.hasOwnProperty('stopTimerAtEnter')) { 464 | $scope.config.stopTimerAtEnter = true; 465 | } 466 | 467 | // Convert the 'intervalLength' value to milliseconds (based on the selected time unit) 468 | switch($scope.config.intervalUnit) { 469 | case "msecs": 470 | $scope.intervalLengthMsecs = $scope.config.intervalLength; 471 | break; 472 | case "secs": 473 | $scope.intervalLengthMsecs = $scope.config.intervalLength * 1000; 474 | break; 475 | case "mins": 476 | $scope.intervalLengthMsecs = $scope.config.intervalLength * 1000 * 60; 477 | break; 478 | } 479 | 480 | var options = { 481 | default_text: "", 482 | allow_blank_item: true, 483 | callback: function(evt, item) { 484 | let menuItem = { 485 | index: item.index, 486 | id: item.id || item.path, 487 | icon: item.icon, 488 | enabled: item.enabled === false ? false : true, 489 | visible: item.visible === false ? false : true, 490 | label: item.label || item.text, 491 | text: item.label || item.text, 492 | payload: item.payload || item.text, 493 | payloadType: item.payloadType || "str", 494 | topic: item.topic || item.path, 495 | outputField: item.outputField 496 | } 497 | 498 | // Show the clicked menu item and the last received msg to the server 499 | $scope.send({ menuItem: menuItem, sourceMsg : $scope.msg.sourceMsg || {} }); 500 | } 501 | } 502 | 503 | if($scope.config.fontSize) { 504 | options.fontSize = $scope.config.fontSize + "px"; 505 | } 506 | 507 | if (!$scope.contextMenu) { 508 | // The ContextMenu instance creates a container, which is a DIV element that contains an UL list (of menu items). 509 | // Since there is no ContextMenu instance (anymore), all old containers should be removed from the DOM. 510 | // These containers are added directly under the 'body', so we have to make sure we don't delete similar other nodes. 511 | // Therefore we delete DIV elements with id starting with 'cm_' and class 'cm_container'. 512 | var contextMenuContainers = document.querySelectorAll("div[id^='cm_'].cm_container"); 513 | Array.prototype.forEach.call( contextMenuContainers, function( node ) { 514 | node.parentNode.removeChild( node ); 515 | }); 516 | 517 | try { 518 | // Only load the context menu libraries from the server, when not loaded yet 519 | if(window.ContextMenu){ 520 | $scope.contextMenu = new ContextMenu([],options); 521 | } 522 | else { 523 | var urls = [ 524 | 'ui_context_menu/contextmenu.js', 525 | 'ui_context_menu/contextmenu.css' 526 | ]; 527 | loadJavascriptAndCssFiles(urls, 528 | function(){ 529 | //success 530 | $scope.contextMenu = new ContextMenu([],options); 531 | }, 532 | function(){ 533 | //fail 534 | }); 535 | } 536 | } 537 | catch (error) { 538 | console.error(error) 539 | } 540 | } 541 | 542 | } 543 | 544 | $scope.$watch('msg', function(msg) { 545 | // Ignore undefined messages. 546 | if (!msg) { 547 | return; 548 | } 549 | 550 | // Ignore messages which have been flagged invalid (by our server side validations). 551 | if (msg.invalid_message) { 552 | return; 553 | } 554 | 555 | //prevent client side replays from showing the menu when switching dashboard tabs 556 | if(msg._ui_cm_already_seen){ 557 | console.log("ui_context_menu: msg already seen - exiting!") 558 | return; 559 | } 560 | msg._ui_cm_already_seen = true; 561 | 562 | if (!$scope.config) { 563 | console.log("ui_context_menu: $scope.config is empty :(") 564 | return; 565 | } 566 | 567 | var showOptions = getPosition($scope, msg);//determine postion top/left 568 | 569 | if (!showOptions) { 570 | return; 571 | } 572 | 573 | showOptions.target = document; 574 | 575 | console.log("ui_context_menu: msg received") 576 | 577 | switch($scope.config.inputMenuType) { 578 | case "msg": 579 | // Get the input value from the specified message field 580 | $scope.contextmenuItems = msg.menu; 581 | break; 582 | case "fixed": 583 | if ($scope.config.menuItems && !$scope.contextmenuItems){ 584 | //As the menu is fixed items, generate a compatable contextmenuItems object from $scope.config.menuItems 585 | $scope.contextmenuItems = []; 586 | var index = 0; 587 | $scope.config.menuItems.forEach(function(menuItem) { 588 | var id=menuItem.id || index; 589 | if(menuItem.label.startsWith("--")){ 590 | $scope.contextmenuItems.push({text: "---"}); 591 | } else { 592 | $scope.contextmenuItems.push({ 593 | index: index, 594 | id: menuItem.id, 595 | icon: menuItem.icon, 596 | enabled: menuItem.enabled, 597 | visible: menuItem.visible, 598 | label: menuItem.label, 599 | text: menuItem.label, 600 | payload: menuItem.payload, 601 | payloadType: menuItem.payloadType, 602 | topic: menuItem.topic, 603 | outputField: menuItem.outputField 604 | }) 605 | } 606 | index++; 607 | }); 608 | } 609 | break; 610 | } 611 | 612 | if($scope.contextMenu) { 613 | $scope.contextMenu.menu = $scope.contextmenuItems; 614 | $scope.contextMenu.reload(); 615 | $scope.contextMenu.display(showOptions); 616 | 617 | // If a timer of the previous context menu exist, then remove it to make sure it doesn't hide our new contextmenu 618 | if ($scope.autoHideTimer) { 619 | clearTimeout($scope.autoHideTimer); 620 | $scope.autoHideTimer = null; 621 | } 622 | 623 | var contextMenuNum = $scope.contextMenu.num; 624 | var contextMenuDiv = document.getElementById('cm_' + contextMenuNum); 625 | var ulElements = contextMenuDiv.querySelectorAll('ul'); 626 | 627 | // Make sure the contextmenu is always on top, by adding a super high z-index. 628 | contextMenuDiv.style["z-index"] = 999999; 629 | 630 | // When the auto hide interval is 0, then there is no auto hiding. 631 | // Otherwise the context menu should be hidden after the specified interval. 632 | // We will start counting the seconds, from the moment on the context menu has been left ... 633 | if ($scope.intervalLengthMsecs > 0) { 634 | // When required, start the timer immediately 635 | if ($scope.config.startTimerAtOpen) { 636 | if (!$scope.autoHideTimer) { 637 | $scope.autoHideTimer = setTimeout(function() { 638 | $scope.contextMenu.hide(); 639 | $scope.autoHideTimer = null; 640 | }, $scope.intervalLengthMsecs); 641 | } 642 | } 643 | 644 | // When required, start the timer when the mouse leaves the context menu. 645 | if ($scope.config.startTimerAtLeave) { 646 | for (var i = 0; i < ulElements.length; i++) { 647 | ulElements[i].addEventListener('mouseleave', function() { 648 | if (!$scope.autoHideTimer) { 649 | $scope.autoHideTimer = setTimeout(function() { 650 | $scope.contextMenu.hide(); 651 | $scope.autoHideTimer = null; 652 | }, $scope.intervalLengthMsecs); 653 | } 654 | }); 655 | } 656 | } 657 | 658 | // When required, stop the timer when the mouse enters the context menu again. 659 | if ($scope.config.stopTimerAtEnter) { 660 | for (var i = 0; i < ulElements.length; i++) { 661 | ulElements[i].addEventListener('mouseenter', function() { 662 | if ($scope.autoHideTimer) { 663 | clearTimeout($scope.autoHideTimer); 664 | $scope.autoHideTimer = null; 665 | } 666 | }); 667 | } 668 | } 669 | } 670 | 671 | // Only override the CSS colors when no 'native' colors selected 672 | if ($scope.config.colors !== "native") { 673 | $scope.config.cls = "custom-" + $scope.config.id.replace(".",""); //compute the clas name 674 | $(contextMenuDiv).addClass($scope.config.cls); //add class name 675 | } 676 | } 677 | }); 678 | } 679 | }); 680 | 681 | 682 | node.on("close", function() { 683 | if (done) { 684 | done(); 685 | } 686 | }); 687 | } 688 | 689 | RED.nodes.registerType("ui_context_menu", ContextMenuNode); 690 | 691 | // By default the UI path in the settings.js file will be in comment: 692 | // //ui: { path: "ui" }, 693 | // But as soon as the user has specified a custom UI path there, we will need to use that path: 694 | // ui: { path: "mypath" }, 695 | var uiPath = (RED.settings.ui || {}).path; 696 | 697 | // When there was no ui path specified (i.e. '//ui: { path: "ui" }' not commented out in the settings.js file), then 698 | // we need to apply the default 'ui' path. However, when an empty ui path has been specified (i.e. '//ui: { path: "" }'), then 699 | // we should also use an empty ui path... See https://github.com/bartbutenaers/node-red-contrib-ui-svg/issues/86 700 | if (uiPath == undefined) { 701 | uiPath = 'ui'; 702 | } 703 | 704 | // Create the complete server-side path 705 | uiPath = '/' + uiPath + '/ui_context_menu/*'; 706 | 707 | // Replace a sequence of multiple slashes (e.g. // or ///) by a single one 708 | uiPath = uiPath.replace(/\/+/g, '/'); 709 | 710 | RED.httpNode.get(uiPath, function (req, res) { 711 | var options = { 712 | root: __dirname + '/lib/', 713 | dotfiles: 'deny' 714 | }; 715 | res.sendFile(req.params[0], options) 716 | }); 717 | } 718 | -------------------------------------------------------------------------------- /examples/basic_flow.json: -------------------------------------------------------------------------------- 1 | [{"id":"98f5ee2c.61f16","type":"inject","z":"86187643.ae75e8","name":"Inject menu + position","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"showConfirmation":false,"confirmationLabel":"","x":280,"y":840,"wires":[["131ffbe2.c2f544"]]},{"id":"51a8f9b.d4a2008","type":"change","z":"86187643.ae75e8","name":"","rules":[{"t":"set","p":"position","pt":"msg","to":"{\"x\":100,\"y\":150}","tot":"json"}],"action":"","property":"","from":"","to":"","reg":false,"x":740,"y":840,"wires":[["dc8a767c.3a3d38"]]},{"id":"131ffbe2.c2f544","type":"change","z":"86187643.ae75e8","name":"","rules":[{"t":"set","p":"menu","pt":"msg","to":"[{\"text\":\"Options\",\"icon\":\"fa-list\",\"sub\":[{\"text\":\"Edit\",\"icon\":\"fa-edit\",\"topic\":\"edit\",\"payload\":[1,2,3,4,5],\"payloadType\":\"JSON\",\"outputField\":\"editArray\"},{\"text\":\"Cut\",\"icon\":\"fa-cut\",\"enabled\":true,\"topic\":\"cut\",\"payload\":\"true\",\"payloadType\":\"bool\"}]},{\"text\":\"---\"},{\"text\":\"Delete\",\"icon\":\"fa-trash\",\"enabled\":true,\"payload\":\"12\",\"payloadType\":\"num\"},{\"text\":\"---\"},{\"text\":\"Quit\",\"icon\":\"fa-times\",\"enabled\":false}]","tot":"json"}],"action":"","property":"","from":"","to":"","reg":false,"x":520,"y":840,"wires":[["51a8f9b.d4a2008"]]},{"id":"e5e8a905.5a2448","type":"inject","z":"86187643.ae75e8","name":"Inject menu","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"showConfirmation":false,"confirmationLabel":"","x":530,"y":760,"wires":[["7b5faf00.a6b4a"]]},{"id":"912cb88c.2b6e28","type":"inject","z":"86187643.ae75e8","name":"Inject nothing","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"showConfirmation":false,"confirmationLabel":"","x":750,"y":720,"wires":[["c6b11b3e.1d3508"]]},{"id":"7b5faf00.a6b4a","type":"change","z":"86187643.ae75e8","name":"","rules":[{"t":"set","p":"menu","pt":"msg","to":"[{\"text\":\"Options\",\"icon\":\"fa-list\",\"sub\":[{\"text\":\"Edit\",\"icon\":\"fa-edit\",\"topic\":\"edit\",\"payload\":[1,2,3,4,5],\"payloadType\":\"JSON\",\"outputField\":\"editArray\"},{\"text\":\"Cut\",\"icon\":\"fa-cut\",\"enabled\":true,\"topic\":\"cut\",\"payload\":\"true\",\"payloadType\":\"bool\"}]},{\"text\":\"---\"},{\"text\":\"Delete\",\"icon\":\"fa-trash\",\"enabled\":true,\"payload\":\"12\",\"payloadType\":\"num\"},{\"text\":\"---\"},{\"text\":\"Quit\",\"icon\":\"fa-times\",\"enabled\":false}]","tot":"json"}],"action":"","property":"","from":"","to":"","reg":false,"x":740,"y":760,"wires":[["a1697f44.2f4c8"]]},{"id":"c6b11b3e.1d3508","type":"ui_context_menu","z":"86187643.ae75e8","group":"22787703.a0e968","order":5,"width":0,"height":-1,"fontSize":16,"inputPositionXField":"50","inputPositionXType":"num","inputPositionYField":"60","inputPositionYType":"num","outputField":"payload","inputMenuField":"menu","inputMenuType":"fixed","menuItems":[{"id":"myid","icon":"fa-glass","label":"mylabel","topic":"mytopic","payload":"mypayload","payloadType":"str","visible":true,"enabled":true}],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","intervalLength":0,"intervalUnit":"secs","startTimerAtOpen":false,"startTimerAtLeave":true,"stopTimerAtEnter":true,"name":"","x":960,"y":720,"wires":[[]]},{"id":"a1697f44.2f4c8","type":"ui_context_menu","z":"86187643.ae75e8","group":"22787703.a0e968","order":5,"width":0,"height":-1,"fontSize":16,"inputPositionXField":"50","inputPositionXType":"num","inputPositionYField":"60","inputPositionYType":"num","outputField":"payload","inputMenuField":"menu","inputMenuType":"msg","menuItems":[],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","intervalLength":0,"intervalUnit":"secs","startTimerAtOpen":false,"startTimerAtLeave":true,"stopTimerAtEnter":true,"name":"","x":960,"y":760,"wires":[[]]},{"id":"66f558a1.128238","type":"inject","z":"86187643.ae75e8","name":"Inject position","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"showConfirmation":false,"confirmationLabel":"","x":530,"y":800,"wires":[["1d3334da.ce9ffb"]]},{"id":"75ccccc.2eca634","type":"ui_context_menu","z":"86187643.ae75e8","group":"22787703.a0e968","order":5,"width":0,"height":-1,"fontSize":16,"inputPositionXField":"position.x","inputPositionXType":"msg","inputPositionYField":"position.y","inputPositionYType":"msg","outputField":"payload","inputMenuField":"menu","inputMenuType":"fixed","menuItems":[{"id":"myid2","icon":"fa-search","label":"mylabel2","topic":"mytopic2","payload":"mypayload2","payloadType":"str","visible":true,"enabled":true}],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","intervalLength":0,"intervalUnit":"secs","startTimerAtOpen":false,"startTimerAtLeave":true,"stopTimerAtEnter":true,"name":"","x":960,"y":800,"wires":[[]]},{"id":"dc8a767c.3a3d38","type":"ui_context_menu","z":"86187643.ae75e8","group":"22787703.a0e968","order":5,"width":0,"height":-1,"fontSize":16,"inputPositionXField":"position.x","inputPositionXType":"msg","inputPositionYField":"position.y","inputPositionYType":"msg","outputField":"payload","inputMenuField":"menu","inputMenuType":"msg","menuItems":[],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","intervalLength":0,"intervalUnit":"secs","startTimerAtOpen":false,"startTimerAtLeave":true,"stopTimerAtEnter":true,"name":"","x":960,"y":840,"wires":[[]]},{"id":"1d3334da.ce9ffb","type":"change","z":"86187643.ae75e8","name":"","rules":[{"t":"set","p":"position","pt":"msg","to":"{\"x\":100,\"y\":150}","tot":"json"}],"action":"","property":"","from":"","to":"","reg":false,"x":740,"y":800,"wires":[["75ccccc.2eca634"]]},{"id":"22787703.a0e968","type":"ui_group","z":"","name":"Web push notifications","tab":"80f0e178.bbf4a","order":1,"disp":true,"width":"6","collapse":false},{"id":"80f0e178.bbf4a","type":"ui_tab","z":"","name":"Home","icon":"dashboard","order":1,"disabled":false,"hidden":false}] 2 | -------------------------------------------------------------------------------- /examples/contextmenu_for_button.json: -------------------------------------------------------------------------------- 1 | [{"id":"45f42449.b3c8dc","type":"ui_button","z":"86187643.ae75e8","name":"","group":"2908388b.8114b8","order":9,"width":"1","height":"1","passthru":false,"label":"","tooltip":"","color":"","bgcolor":"","icon":"fa-bars","payload":"button_clicked","payloadType":"str","topic":"","x":590,"y":1640,"wires":[["5b2478ff.043158"]]},{"id":"5b2478ff.043158","type":"change","z":"86187643.ae75e8","name":"Get X and Y from bbox","rules":[{"t":"set","p":"position.x","pt":"msg","to":"event.bbox[2]-9","tot":"jsonata"},{"t":"set","p":"position.y","pt":"msg","to":"event.bbox[3]+18","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":780,"y":1640,"wires":[["b3b5bcfc.cf079"]]},{"id":"b3b5bcfc.cf079","type":"ui_context_menu","z":"86187643.ae75e8","group":"2908388b.8114b8","order":5,"width":0,"height":-1,"fontSize":16,"inputPositionXField":"position.x","inputPositionXType":"msg","inputPositionYField":"position.y","inputPositionYType":"msg","outputField":"payload","inputMenuField":"","inputMenuType":"fixed","menuItems":[{"id":"ZOOM_OUT","icon":"fa-search-minus","label":"Light on","topic":"zoom out","payload":"zoom out","payloadType":"str","visible":true,"enabled":true},{"id":"ZOOM_IN","icon":"fa-search-plus","label":"Light off","topic":"zoom in","payload":"zoom in","payloadType":"str","visible":true,"enabled":true}],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","intervalLength":"0","intervalUnit":"secs","startTimerAtOpen":false,"startTimerAtLeave":true,"stopTimerAtEnter":true,"name":"","x":1000,"y":1640,"wires":[[]]},{"id":"2908388b.8114b8","type":"ui_group","z":"","name":"Floorplan test","tab":"a28ff08f.3a822","order":1,"disp":true,"width":"14","collapse":false},{"id":"a28ff08f.3a822","type":"ui_tab","z":"","name":"SVG","icon":"dashboard","disabled":false,"hidden":false}] 2 | -------------------------------------------------------------------------------- /examples/contextmenu_in_svg_drawing.json: -------------------------------------------------------------------------------- 1 | [{"id":"2d30cf4e.41547","type":"ui_svg_graphics","z":"86187643.ae75e8","group":"2908388b.8114b8","order":1,"width":"14","height":"10","svgString":"\n \n \n fa-lightbulb-o \n","clickableShapes":[{"targetId":"#light_bulb_kitchen","action":"click","payload":"light_icon_clicked","payloadType":"str","topic":"light_icon_clicked"}],"smilAnimations":[],"bindings":[{"selector":"#banner","bindSource":"payload.title","bindType":"text","attribute":""},{"selector":"#camera_living","bindSource":"payload.position.x","bindType":"attr","attribute":"x"},{"selector":"#camera_living","bindSource":"payload.camera.colour","bindType":"attr","attribute":"fill"}],"showCoordinates":false,"autoFormatAfterEdit":false,"showBrowserErrors":false,"outputField":"my_output_field","editorUrl":"http://drawsvg.org/drawsvg.html","directory":"","panning":"disabled","zooming":"disabled","panOnlyWhenZoomed":false,"doubleClickZoomEnabled":false,"mouseWheelZoomEnabled":false,"name":"","x":600,"y":1480,"wires":[["24952289.cacf1e","2e6ffce7.748b34"]]},{"id":"24952289.cacf1e","type":"debug","z":"86187643.ae75e8","name":"Clicked SVG shape","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":830,"y":1540,"wires":[]},{"id":"2e6ffce7.748b34","type":"ui_context_menu","z":"86187643.ae75e8","group":"2908388b.8114b8","order":5,"width":0,"height":-1,"fontSize":16,"inputPositionXField":"event.pageX","inputPositionXType":"msg","inputPositionYField":"event.pageY","inputPositionYType":"msg","outputField":"payload","inputMenuField":"","inputMenuType":"fixed","menuItems":[{"id":"ON","icon":"fa-toggle-on","label":"Light on","topic":"light_kitchen_on","payload":"light_kitchen_on","payloadType":"str","visible":true,"enabled":true},{"id":"OFF","icon":"fa-toggle-off","label":"Light off","topic":"light_kitchen_off","payload":"light_kitchen_off","payloadType":"str","visible":true,"enabled":true}],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","intervalLength":"0","intervalUnit":"secs","startTimerAtOpen":false,"startTimerAtLeave":true,"stopTimerAtEnter":true,"name":"","x":820,"y":1480,"wires":[["14b0feb6.5bea51"]]},{"id":"14b0feb6.5bea51","type":"debug","z":"86187643.ae75e8","name":"Clicked menu item","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":1050,"y":1480,"wires":[]},{"id":"2908388b.8114b8","type":"ui_group","z":"","name":"Floorplan test","tab":"a28ff08f.3a822","order":1,"disp":true,"width":"14","collapse":false},{"id":"a28ff08f.3a822","type":"ui_tab","z":"","name":"SVG","icon":"dashboard","disabled":false,"hidden":false}] 2 | -------------------------------------------------------------------------------- /examples/hierarchical_contextmenu.json: -------------------------------------------------------------------------------- 1 | [{"id":"fd05877e.cb0588","type":"ui_svg_graphics","z":"60ad596.8120ba8","group":"9f5b4cff.15cd3","order":1,"width":"14","height":"10","svgString":"\n \n \n ","clickableShapes":[{"targetId":"#mycircle","action":"click","payload":"camera_living","payloadType":"str","topic":"camera_living"}],"smilAnimations":[],"bindings":[{"selector":"#banner","bindSource":"payload.title","bindType":"text","attribute":""},{"selector":"#camera_living","bindSource":"payload.position.x","bindType":"attr","attribute":"x"},{"selector":"#camera_living","bindSource":"payload.camera.colour","bindType":"attr","attribute":"fill"}],"showCoordinates":false,"autoFormatAfterEdit":false,"outputField":"","editorUrl":"http://drawsvg.org/drawsvg.html","directory":"","name":"","x":920,"y":120,"wires":[["a4c84c93.c001d"]]},{"id":"c65edd5a.1c031","type":"ui_context_menu","z":"60ad596.8120ba8","group":"9f5b4cff.15cd3","order":5,"width":0,"height":-1,"fontSize":16,"position":"msg","outputField":"payload","xCoordinate":50,"yCoordinate":50,"menu":"msg","menuItems":[],"colors":"native","textColor":"#000000","backgroundColor":"#ffffff","borderColor":"#626262","name":"","x":1360,"y":120,"wires":[[]]},{"id":"a4c84c93.c001d","type":"change","z":"60ad596.8120ba8","name":"","rules":[{"t":"set","p":"menu","pt":"msg","to":"[{\"text\":\"Options\",\"icon\":\"fa-list\",\"sub\":[{\"text\":\"Edit\",\"icon\":\"fa-edit\",\"topic\":\"edit\",\"payload\":[1,2,3,4,5],\"payloadType\":\"JSON\",\"outputField\":\"editArray\"},{\"text\":\"Cut\",\"icon\":\"fa-cut\",\"enabled\":true,\"topic\":\"cut\",\"payload\":\"true\",\"payloadType\":\"bool\"}]},{\"text\":\"---\"},{\"text\":\"Delete\",\"icon\":\"fa-trash\",\"enabled\":true,\"payload\":\"12\",\"payloadType\":\"num\"},{\"text\":\"---\"},{\"text\":\"Quit\",\"icon\":\"fa-times\",\"enabled\":false}]","tot":"json"}],"action":"","property":"","from":"","to":"","reg":false,"x":1140,"y":120,"wires":[["c65edd5a.1c031"]]},{"id":"9f5b4cff.15cd3","type":"ui_group","z":"","name":"Floorplan test","tab":"dabfe25b.13bc1","disp":true,"width":"14","collapse":false},{"id":"dabfe25b.13bc1","type":"ui_tab","z":"","name":"SVG","icon":"dashboard","disabled":false,"hidden":false}] 2 | -------------------------------------------------------------------------------- /icons/menu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bartbutenaers/node-red-contrib-ui-contextmenu/c70d825c721e0bd224610095fd97fe87fcba9a93/icons/menu.png -------------------------------------------------------------------------------- /lib/contextmenu.css: -------------------------------------------------------------------------------- 1 | .cm_container{ 2 | position: fixed; 3 | opacity: 0; 4 | transform: scale(0); 5 | transition: transform 0.1s; 6 | transform-origin: top left; 7 | padding: 0; 8 | } 9 | 10 | .cm_container.display{ 11 | opacity: 1; 12 | transform: scale(1); 13 | } 14 | 15 | .cm_container, .cm_container *{ 16 | box-sizing: border-box; 17 | } 18 | 19 | .cm_container *{ 20 | position: relative; 21 | } 22 | 23 | .cm_container ul{ 24 | list-style-type: none; 25 | padding: 0; 26 | margin: 0; 27 | background-color: #ffffff; 28 | box-shadow: 0 0 5px #626262; 29 | border-radius: 1px; 30 | } 31 | 32 | .cm_container li{ 33 | /* padding: 5px 10px; */ 34 | padding: 5px 5px 5px 5px; 35 | padding-right: 1.7em; 36 | cursor: pointer; 37 | white-space: nowrap; 38 | } 39 | 40 | .cm_container li:hover{ 41 | background-color: #b0b0b0; 42 | } 43 | 44 | .cm_container li .cm_icon_span{ 45 | width: 1.5em; 46 | height: 1.2em; 47 | /* vertical-align: bottom; */ 48 | display: inline-block; 49 | margin-right: 5px; 50 | padding-right: 5px; 51 | text-align: center; 52 | } 53 | 54 | .cm_container li .cm_sub_span{ 55 | width: 1em; 56 | display: inline-block; 57 | text-align: center; 58 | position: absolute; 59 | /* top: 50%; */ 60 | right: 0.5em; 61 | /* transform: translateY(-50%); */ 62 | } 63 | 64 | .cm_container li > ul{ 65 | position: absolute; 66 | top: 0; 67 | left: 96%; 68 | opacity: 0; 69 | visibility: hidden; 70 | transition: 0.2s 0.4s; 71 | } 72 | 73 | .cm_container li:hover > ul{ 74 | opacity: 1; 75 | visibility: visible; 76 | transition-delay: 0s; /* react immediately on hover */ 77 | } 78 | 79 | .cm_container li.cm_divider{ 80 | border-bottom: 1px solid #dfdfdf; 81 | margin: 5px; 82 | padding: 0; 83 | cursor: default; 84 | } 85 | 86 | .cm_container li.cm_divider:hover{ 87 | background-color: inherit; 88 | } 89 | 90 | .cm_container.cm_border_right > ul{ 91 | left: -88%; 92 | } 93 | 94 | .cm_container > ul ul.cm_sub_fly_left{ 95 | /* left: -88%; */ 96 | left: unset; 97 | right: 82%; 98 | } 99 | .cm_container > ul ul.cm_sub_fly_right{ 100 | left: 96%; 101 | } 102 | .cm_container > ul ul.cm_sub_fly_up{ 103 | top: unset; 104 | bottom: 0; 105 | } 106 | .cm_container > ul ul.cm_sub_fly_down{ 107 | top: 0; 108 | bottom: unset; 109 | } 110 | 111 | .cm_container.cm_border_bottom > ul{ 112 | top: unset; 113 | bottom: 0; 114 | } 115 | 116 | .cm_container li[disabled=""]{ 117 | color: #777; 118 | cursor: default; 119 | } 120 | 121 | .cm_container li[disabled=""]:hover{ 122 | background-color: inherit; 123 | } -------------------------------------------------------------------------------- /lib/contextmenu.js: -------------------------------------------------------------------------------- 1 | //adapted from https://raw.githubusercontent.com/dsaul/contextmenujs/master/contextmenu.js 2 | 3 | /* 4 | MIT License 5 | 6 | Copyright (c) 2018 Matthias Thalmann 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be included in all 16 | copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | SOFTWARE. 25 | */ 26 | 27 | /* Changes.... 28 | - permit icon to be font-awesome 29 | - permit visible option 30 | - check preventDefault before calling 31 | - convert text --- to separator 32 | - add callback to options 33 | - add path (pseudo topic / key) 34 | - ContextUtil is now a var (instead of const) to avoid "Identifier 'ContextUtil' has already been declared" 35 | */ 36 | 37 | function ContextMenu(menu, options){ 38 | console.log("ContextMenu()") 39 | var self = this; 40 | this.num = ContextMenu.count++; 41 | 42 | this.menu = menu; 43 | this.contextTarget = null; 44 | 45 | if(!(menu instanceof Array)){ 46 | throw new Error("Parameter 1 must be of type Array"); 47 | } 48 | 49 | if(typeof options !== "undefined"){ 50 | if(typeof options !== "object"){ 51 | throw new Error("Parameter 2 must be of type object"); 52 | } 53 | }else{ 54 | options = {}; 55 | } 56 | 57 | window.addEventListener("resize", function(){ 58 | if(ContextUtil.getProperty(options, "close_on_resize", true)){ 59 | self.hide(); 60 | } 61 | }); 62 | 63 | this.setOptions = function(_options){ 64 | if(typeof _options === "object"){ 65 | options = _options; 66 | }else{ 67 | throw new Error("Parameter 1 must be of type object") 68 | } 69 | } 70 | 71 | this.changeOption = function(option, value){ 72 | if(typeof option === "string"){ 73 | if(typeof value !== "undefined"){ 74 | options[option] = value; 75 | }else{ 76 | throw new Error("Parameter 2 must be set"); 77 | } 78 | }else{ 79 | throw new Error("Parameter 1 must be of type string"); 80 | } 81 | } 82 | 83 | this.getOptions = function(){ 84 | return options; 85 | } 86 | 87 | this.reload = function(){ 88 | if(document.getElementById('cm_' + this.num) == null){ 89 | var cnt = document.createElement("div"); 90 | cnt.className = "cm_container"; 91 | cnt.id = "cm_" + this.num; 92 | 93 | document.body.appendChild(cnt); 94 | } 95 | 96 | var container = document.getElementById('cm_' + this.num); 97 | container.innerHTML = ""; 98 | var ulli = renderLevel(this.menu,"",0); 99 | if(ulli){ 100 | if(options.fontSize) 101 | ulli.style.fontSize = options.fontSize; 102 | container.appendChild(ulli); 103 | } 104 | } 105 | 106 | function renderLevel(level, path, depth){ 107 | var ul_outer = document.createElement("ul"); 108 | // if(depth){ 109 | // ul_outer.classList.add("cm_sub"); 110 | // if(depth % 2){ 111 | // ul_outer.classList.add("cm_sub_odd"); 112 | // } else { 113 | // ul_outer.classList.add("cm_sub_even"); 114 | // } 115 | // } 116 | level.path = path; 117 | level.forEach(function(item){ 118 | var text = ContextUtil.getProperty(item, "text", ""); 119 | if(!text){ 120 | return; 121 | } 122 | item.path = level.path; 123 | if(item.path) item.path += "/" 124 | item.path += text; 125 | var li = document.createElement("li"); 126 | li.menu = self; 127 | if(text.startsWith("---") ) { 128 | li.className = "cm_divider"; 129 | } else if(typeof item.type === "undefined"){ 130 | var icon_span = document.createElement("span"); 131 | icon_span.className = 'cm_icon_span'; 132 | 133 | if(ContextUtil.getProperty(item, "icon", "") != ""){ 134 | var icon = ContextUtil.getProperty(item, "icon", ""); 135 | if(icon.startsWith("fa-")){ 136 | icon = "";//assume fa. 137 | } else if(icon.startsWith("fa ") || icon.startsWith("fas ")){ 138 | icon = ""; 139 | } 140 | icon_span.innerHTML = icon; 141 | }else{ 142 | icon_span.innerHTML = ContextUtil.getProperty(options, "default_icon", ""); 143 | } 144 | 145 | var text_span = document.createElement("span"); 146 | text_span.className = 'cm_text'; 147 | 148 | if(ContextUtil.getProperty(item, "text", "") != ""){ 149 | text_span.innerHTML = text; 150 | }else{ 151 | text_span.innerHTML = ContextUtil.getProperty(options, "default_text", "item"); 152 | } 153 | 154 | var sub_span = document.createElement("span"); 155 | sub_span.className = 'cm_sub_span'; 156 | 157 | if(typeof item.sub !== "undefined"){ 158 | if(ContextUtil.getProperty(options, "sub_icon", "") != ""){ 159 | sub_span.innerHTML = ContextUtil.getProperty(options, "sub_icon", ""); 160 | }else{ 161 | sub_span.innerHTML = '›'; 162 | } 163 | } 164 | 165 | li.appendChild(icon_span); 166 | li.appendChild(text_span); 167 | li.appendChild(sub_span); 168 | 169 | var visibility = ContextUtil.getProperty(item, "visible", true); 170 | li.style.display = visibility ? "inherit" : "none"; 171 | 172 | if(!ContextUtil.getProperty(item, "enabled", true)){ 173 | li.setAttribute("disabled", ""); 174 | }else{ 175 | if(typeof item.events === "object"){ 176 | var keys = Object.keys(item.events); 177 | 178 | for(var i = 0; i < keys.length; i++){ 179 | li.addEventListener(keys[i], item.events[keys[i]]); 180 | } 181 | } 182 | 183 | if(options.callback && !item.sub){ 184 | li.addEventListener("click", function(e){ 185 | console.log("ui_contextmenu: Item Clicked") 186 | //e.stopPropagation(); 187 | options.callback(e, item); 188 | if(ContextUtil.getProperty(options, "close_on_click", true)){ 189 | document.body.dispatchEvent(new CustomEvent("contextmenu-close-all")); 190 | } 191 | }) 192 | } 193 | 194 | if(typeof item.sub !== "undefined"){ 195 | var liSub = renderLevel(item.sub, item.path, depth+1); 196 | if(liSub){ 197 | li.appendChild(liSub); 198 | } 199 | } 200 | } 201 | }else{ 202 | if(item.type == ContextMenu.DIVIDER){ 203 | li.className = "cm_divider"; 204 | } 205 | } 206 | 207 | ul_outer.appendChild(li); 208 | }); 209 | 210 | return ul_outer; 211 | } 212 | 213 | 214 | function updatePosition(ul, depth, posX, posY, windowWidth, windowHeight, zindex){ 215 | console.log(`updatePosition(ul,depth=${depth},posX=${posX},posY=${posY},windowWidth=${windowWidth},windowHeight=${windowHeight},zindex=${zindex})`) 216 | ul = $(ul); 217 | ul.css("z-index", zindex); 218 | let pad = 4; 219 | let w = ul.width(); 220 | let h = ul.height(); 221 | if(depth === 0){ 222 | posX += w + pad; 223 | posY += h + pad; 224 | } else { 225 | let offsetY = ul.parent().height() 226 | if((posX + w + pad) > windowWidth){ 227 | ul.removeClass("cm_sub_fly_right"); 228 | ul.addClass("cm_sub_fly_left"); 229 | posX -= (w*0.82); 230 | } else { 231 | ul.removeClass("cm_sub_fly_left"); 232 | ul.addClass("cm_sub_fly_right"); 233 | posX += (w*0.96); 234 | } 235 | if((posY + h + pad) > windowHeight){ 236 | ul.removeClass("cm_sub_fly_down"); 237 | ul.addClass("cm_sub_fly_up"); 238 | 239 | posY = (posY - h) + offsetY; 240 | } else { 241 | ul.removeClass("cm_sub_fly_up"); 242 | ul.addClass("cm_sub_fly_down"); 243 | posY = (posY + h) - offsetY; 244 | } 245 | } 246 | 247 | let children = $(ul).children(); 248 | children.each(function(idx, item){ 249 | if(item.tagName === "LI"){ 250 | let lichildren = $(item).children(); 251 | lichildren.each(function(idx, childitem){ 252 | if(childitem.tagName === "UL"){ 253 | updatePosition(childitem, depth + 1, posX, posY, windowWidth, windowHeight, zindex + 1); 254 | } 255 | }) 256 | } 257 | }) 258 | 259 | } 260 | 261 | this.display = function (e, target) { 262 | console.log("ContextMenu.display()") 263 | document.body.dispatchEvent(new CustomEvent("contextmenu-close-all")); 264 | 265 | if(typeof target !== "undefined"){ 266 | self.contextTarget = target; 267 | }else{ 268 | self.contextTarget = e.target; 269 | } 270 | 271 | var menu = document.getElementById('cm_' + this.num); 272 | 273 | updatePositionsBeforeDisplay(menu, e, options.zIndex || 9000); 274 | 275 | function updatePositionsBeforeDisplay(menu, e, zindex){ 276 | var clickCoords = {x: e.clientX, y: e.clientY}; 277 | var clickCoordsX = clickCoords.x || 0; 278 | var clickCoordsY = clickCoords.y || 0; 279 | 280 | var menuWidth = menu.offsetWidth + 4; 281 | var menuHeight = menu.offsetHeight + 4; 282 | 283 | var windowWidth = window.innerWidth; 284 | var windowHeight = window.innerHeight; 285 | var mouseOffset = parseInt(ContextUtil.getProperty(options, "mouse_offset", 2)); 286 | 287 | var ml, mt; 288 | if((windowWidth - clickCoordsX) < menuWidth){ 289 | ml = windowWidth - menuWidth; 290 | if(ml<0) ml = 0; 291 | menu.style.left = ml + "px"; 292 | }else{ 293 | ml = (clickCoordsX + mouseOffset); 294 | menu.style.left = (clickCoordsX + mouseOffset) + "px"; 295 | } 296 | 297 | if((windowHeight - clickCoordsY) < menuHeight){ 298 | mt = windowHeight - menuHeight; 299 | if(mt { // Animation frame allows using click to open it as well. 331 | window.addEventListener("click", documentClick); 332 | document.body.addEventListener("contextmenu-close-all", documentClick); 333 | }); 334 | } 335 | 336 | if(e.preventDefault) e.preventDefault(); 337 | } 338 | 339 | this.hide = function(){ 340 | let e = document.getElementById('cm_' + this.num); 341 | if (e) { // In case the node was removed by somethign else. 342 | e.classList.remove("display"); 343 | e.style.pointerEvents = "none"; 344 | window.removeEventListener("click", documentClick); 345 | document.body.removeEventListener("contextmenu-close-all", documentClick); 346 | } 347 | } 348 | 349 | function documentClick(event){ 350 | //ensure event came from outside the menu (prevent closing menu if clicking self) 351 | if (event && event.target.closest('#cm_' + self.num)) { 352 | //clicked self - dont hide 353 | } else { 354 | self.hide(); 355 | } 356 | } 357 | 358 | this.reload(); 359 | } 360 | 361 | ContextMenu.count = 0; 362 | ContextMenu.DIVIDER = "cm_divider"; 363 | 364 | var ContextUtil = { 365 | getProperty: function(options, opt, def){ 366 | if(typeof options[opt] !== "undefined"){ 367 | return options[opt]; 368 | }else{ 369 | return def; 370 | } 371 | }, 372 | 373 | getSizes: function(obj){ 374 | var lis = obj.getElementsByTagName('li'); 375 | 376 | var width_def = 0; 377 | var height_def = 0; 378 | 379 | for(var i = 0; i < lis.length; i++){ 380 | var li = lis[i]; 381 | 382 | if(li.offsetWidth > width_def){ 383 | width_def = li.offsetWidth; 384 | } 385 | 386 | if(li.offsetHeight > height_def){ 387 | height_def = li.offsetHeight; 388 | } 389 | } 390 | 391 | var width = width_def; 392 | var height = height_def; 393 | 394 | for(var i = 0; i < lis.length; i++){ 395 | var li = lis[i]; 396 | 397 | var ul = li.getElementsByTagName('ul'); 398 | if(typeof ul[0] !== "undefined"){ 399 | var ul_size = ContextUtil.getSizes(ul[0]); 400 | 401 | if(width_def + ul_size.width > width){ 402 | width = width_def + ul_size.width; 403 | } 404 | 405 | if(height_def + ul_size.height > height){ 406 | height = height_def + ul_size.height; 407 | } 408 | } 409 | } 410 | 411 | return { 412 | "width": width, 413 | "height": height 414 | }; 415 | } 416 | }; 417 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-red-contrib-ui-contextmenu", 3 | "version": "2.0.1", 4 | "description": "A Node-RED widget to show a popup contextmenu in a Node-RED dashboard", 5 | "dependencies": { 6 | }, 7 | "author": { 8 | "name": "Bart Butenaers" 9 | }, 10 | "contributors": [ 11 | { 12 | "name": "Stephen McLaughlin", 13 | "url": "https://github.com/Steve-Mcl" 14 | } 15 | ], 16 | "license": "Apache-2.0", 17 | "keywords": [ 18 | "node-red", 19 | "context menu", 20 | "menu", 21 | "dashboard", 22 | "interactive" 23 | ], 24 | "bugs": { 25 | "url": "https://github.com/bartbutenaers/node-red-contrib-ui-contextmenu/issues" 26 | }, 27 | "homepage": "https://github.com/bartbutenaers/node-red-contrib-ui-contextmenu", 28 | "repository": { 29 | "type": "git", 30 | "url": "https://github.com/bartbutenaers/node-red-contrib-ui-contextmenu.git" 31 | }, 32 | "node-red": { 33 | "nodes": { 34 | "ui_context_menu": "context_menu.js" 35 | } 36 | } 37 | } 38 | --------------------------------------------------------------------------------