1+ const menuItems = [ ] ;
2+ const defaultClass = "my-dropdown" ;
3+ const stack = [ ] ;
4+
5+ export function ddm_AddItem ( text , url , level = "" ) {
6+ const item = { text, url, children : [ ] } ;
7+ const depth = level . length ;
8+
9+ if ( depth === 0 ) {
10+ menuItems . push ( item ) ;
11+ } else {
12+ const parent = stack [ depth - 1 ] ;
13+ if ( ! parent ) throw new Error ( "Parent not found for depth " + depth ) ;
14+ parent . children . push ( item ) ;
15+ }
16+
17+ stack [ depth ] = item ;
18+ stack . length = depth + 1 ;
19+ }
20+
21+ export function ddm_ResetMenu ( ) {
22+ menuItems . length = 0 ;
23+ stack . length = 0 ;
24+ }
25+
26+ export function ddm_Render ( className = defaultClass , appendMenuCSS = true ) {
27+ function renderNode ( items ) {
28+ let html = `<ul class="${ className } ">` ;
29+ for ( const item of items ) {
30+ html += `<li><a href="${ item . url } ">${ item . text } </a>` ;
31+ if ( item . children . length > 0 ) {
32+ html += `<span class="ddm-toggle" onclick="ddm_ToggleSubmenu(event, this)">[+]</span> ` ;
33+ }
34+ if ( item . children . length > 0 ) {
35+ html += renderNode ( item . children ) ;
36+ }
37+ html += `</li>` ;
38+ }
39+ html += `</ul>` ;
40+ return html ;
41+ }
42+
43+ if ( appendMenuCSS ) ddm_InjectMenuCSS ( className ) ;
44+
45+ if ( ! window . ddm_ToggleSubmenu ) {
46+ window . ddm_ToggleSubmenu = function ( event , toggleSpan ) {
47+ event . preventDefault ( ) ;
48+ const li = toggleSpan . parentElement ;
49+ const submenu = li . querySelector ( "ul" ) ;
50+ if ( ! submenu ) return ;
51+ if ( submenu . style . display === "block" ) {
52+ submenu . style . display = "none" ;
53+ toggleSpan . textContent = "[+]" ;
54+ } else {
55+ submenu . style . display = "block" ;
56+ toggleSpan . textContent = "[-]" ;
57+ }
58+ } ;
59+ }
60+
61+ return renderNode ( menuItems ) ;
62+ }
63+
64+ export function ddm_GetMenuCSS ( className = defaultClass ) {
65+ return `
66+ .${ className } {
67+ list-style: none;
68+ padding: 0;
69+ margin: 0;
70+ }
71+
72+ .${ className } li {
73+ position: relative;
74+ margin: 2px 0;
75+ }
76+
77+ .${ className } li ul {
78+ display: none;
79+ padding-left: 15px;
80+ margin: 2px 0;
81+ list-style: none;
82+ }
83+
84+ .${ className } a {
85+ display: inline-block;
86+ padding: 5px 10px;
87+ text-decoration: none;
88+ background: #f0f0f0;
89+ color: #333;
90+ }
91+
92+ .${ className } li ul a {
93+ background: #e0e0e0;
94+ }
95+
96+ .${ className } .ddm-toggle {
97+ cursor: pointer;
98+ font-weight: bold;
99+ margin-right: 5px;
100+ }
101+ ` ;
102+ }
103+
104+ export function ddm_InjectMenuCSS ( className = defaultClass ) {
105+ const style = document . createElement ( "style" ) ;
106+ style . textContent = ddm_GetMenuCSS ( className ) ;
107+ document . head . appendChild ( style ) ;
108+ }
0 commit comments