( container: HTMLElement, position: LegendPosition = 'right' )
| 47 | }; |
| 48 | |
| 49 | export function createLegend( |
| 50 | container: HTMLElement, |
| 51 | position: LegendPosition = 'right' |
| 52 | ): Legend { |
| 53 | const computedPosition = getComputedStyle(container).position; |
| 54 | const didSetRelative = computedPosition === 'static'; |
| 55 | const previousInlinePosition = didSetRelative ? container.style.position : null; |
| 56 | |
| 57 | if (didSetRelative) { |
| 58 | container.style.position = 'relative'; |
| 59 | } |
| 60 | |
| 61 | const root = document.createElement('div'); |
| 62 | root.style.position = 'absolute'; |
| 63 | root.style.pointerEvents = 'none'; |
| 64 | root.style.userSelect = 'none'; |
| 65 | root.style.boxSizing = 'border-box'; |
| 66 | |
| 67 | // Theme-driven styling (set/update in update()). |
| 68 | root.style.padding = '8px'; |
| 69 | root.style.borderRadius = '8px'; |
| 70 | root.style.borderStyle = 'solid'; |
| 71 | root.style.borderWidth = '1px'; |
| 72 | root.style.maxHeight = 'calc(100% - 16px)'; |
| 73 | root.style.overflow = 'auto'; |
| 74 | |
| 75 | const list = document.createElement('div'); |
| 76 | list.style.display = 'flex'; |
| 77 | list.style.gap = '8px'; |
| 78 | root.appendChild(list); |
| 79 | |
| 80 | const applyPositionStyles = (p: LegendPosition): void => { |
| 81 | // Clear positional styles first so changing position is safe/idempotent. |
| 82 | root.style.top = ''; |
| 83 | root.style.right = ''; |
| 84 | root.style.bottom = ''; |
| 85 | root.style.left = ''; |
| 86 | root.style.maxWidth = ''; |
| 87 | |
| 88 | list.style.flexDirection = ''; |
| 89 | list.style.flexWrap = ''; |
| 90 | list.style.alignItems = ''; |
| 91 | |
| 92 | switch (p) { |
| 93 | case 'right': { |
| 94 | root.style.top = '8px'; |
| 95 | root.style.right = '8px'; |
| 96 | root.style.maxWidth = '40%'; |
| 97 | |
| 98 | list.style.flexDirection = 'column'; |
| 99 | list.style.flexWrap = 'nowrap'; |
| 100 | list.style.alignItems = 'flex-start'; |
| 101 | return; |
| 102 | } |
| 103 | case 'left': { |
| 104 | root.style.top = '8px'; |
| 105 | root.style.left = '8px'; |
| 106 | root.style.maxWidth = '40%'; |
no test coverage detected