Coverage for fastblocks / adapters / icons / lucide.py: 78%

102 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-02 20:00 -0800

1"""Lucide icons adapter implementation.""" 

2 

3from contextlib import suppress 

4from typing import Any 

5from uuid import UUID 

6 

7from oneiric.core.resolution import Resolver 

8 

9# Oneiric resolver for dependency injection 

10depends = Resolver() 

11 

12from ._base import IconsBase, IconsBaseSettings 

13 

14 

15class LucideIconsSettings(IconsBaseSettings): 

16 """Lucide-specific settings.""" 

17 

18 version: str = "0.263.1" 

19 cdn_url: str = "https://unpkg.com/lucide@{version}/dist/umd/lucide.js" 

20 css_url: str = "https://unpkg.com/lucide-static@{version}/font/lucide.css" 

21 use_svg: bool = True # Use SVG icons vs icon font 

22 

23 

24class LucideIcons(IconsBase): 

25 """Lucide icons adapter implementation.""" 

26 

27 # Required ACB 0.19.0+ metadata 

28 MODULE_ID: UUID = UUID("01937d86-4f2a-7b3c-8d9e-f3b4d3c2d1a2") # Static UUID7 

29 MODULE_STATUS = "stable" 

30 

31 # Icon mapping for common icons (Lucide naming) 

32 ICON_MAPPINGS = { 

33 "home": "home", 

34 "user": "user", 

35 "users": "users", 

36 "settings": "settings", 

37 "edit": "edit", 

38 "delete": "trash-2", 

39 "save": "save", 

40 "search": "search", 

41 "add": "plus", 

42 "remove": "minus", 

43 "check": "check", 

44 "close": "x", 

45 "arrow_up": "arrow-up", 

46 "arrow_down": "arrow-down", 

47 "arrow_left": "arrow-left", 

48 "arrow_right": "arrow-right", 

49 "chevron_up": "chevron-up", 

50 "chevron_down": "chevron-down", 

51 "chevron_left": "chevron-left", 

52 "chevron_right": "chevron-right", 

53 "heart": "heart", 

54 "star": "star", 

55 "bookmark": "bookmark", 

56 "share": "share", 

57 "download": "download", 

58 "upload": "upload", 

59 "file": "file", 

60 "folder": "folder", 

61 "image": "image", 

62 "video": "video", 

63 "music": "music", 

64 "calendar": "calendar", 

65 "clock": "clock", 

66 "bell": "bell", 

67 "email": "mail", 

68 "phone": "phone", 

69 "location": "map-pin", 

70 "link": "link", 

71 "external_link": "external-link", 

72 "info": "info", 

73 "warning": "alert-triangle", 

74 "error": "alert-circle", 

75 "success": "check-circle", 

76 "menu": "menu", 

77 "grid": "grid-3x3", 

78 "list": "list", 

79 "lock": "lock", 

80 "unlock": "unlock", 

81 "eye": "eye", 

82 "eye_slash": "eye-off", 

83 "shopping_cart": "shopping-cart", 

84 "credit_card": "credit-card", 

85 "print": "printer", 

86 "question": "help-circle", 

87 "help": "help-circle", 

88 "refresh": "refresh-cw", 

89 "copy": "copy", 

90 "cut": "scissors", 

91 "paste": "clipboard", 

92 "undo": "undo", 

93 "redo": "redo", 

94 "maximize": "maximize", 

95 "minimize": "minimize", 

96 "filter": "filter", 

97 "sort": "arrow-up-down", 

98 "play": "play", 

99 "pause": "pause", 

100 "stop": "square", 

101 "volume": "volume-2", 

102 "volume_off": "volume-x", 

103 "fullscreen": "maximize", 

104 "zoom_in": "zoom-in", 

105 "zoom_out": "zoom-out", 

106 } 

107 

108 def __init__(self) -> None: 

109 """Initialize Lucide adapter.""" 

110 super().__init__() 

111 self.settings = LucideIconsSettings() 

112 

113 # Register with Oneiric resolver (fail gracefully if not supported) 

114 with suppress(Exception): 

115 # Register with Oneiric resolver (fail gracefully if not supported) 

116 pass 

117 with suppress(Exception): 

118 depends.set(self) 

119 

120 def get_stylesheet_links(self) -> list[str]: 

121 """Generate Lucide stylesheet/script link tags.""" 

122 links = [] 

123 

124 if self.settings.use_svg: 

125 # Use JavaScript library for SVG icons 

126 js_url = self.settings.cdn_url.format(version=self.settings.version) 

127 links.append(f'<script src="{js_url}"></script>') 

128 else: 

129 # Use icon font CSS 

130 css_url = self.settings.css_url.format(version=self.settings.version) 

131 links.append(f'<link rel="stylesheet" href="{css_url}">') 

132 

133 return links 

134 

135 def get_icon_class(self, icon_name: str) -> str: 

136 """Get Lucide-specific class names for icons.""" 

137 # Map common names to Lucide names 

138 lucide_name = self.ICON_MAPPINGS.get(icon_name, icon_name) 

139 

140 if self.settings.use_svg: 

141 # For SVG mode, return data attribute for JavaScript initialization 

142 return f"lucide-{lucide_name}" 

143 # For icon font mode 

144 return f"lucide lucide-{lucide_name}" 

145 

146 def get_icon_tag(self, icon_name: str, **attributes: Any) -> str: 

147 """Generate complete icon tags with Lucide classes.""" 

148 # Map common names to Lucide names 

149 lucide_name = self.ICON_MAPPINGS.get(icon_name, icon_name) 

150 

151 if self.settings.use_svg: 

152 return self._get_svg_icon_tag(lucide_name, **attributes) 

153 

154 return self._get_font_icon_tag(lucide_name, **attributes) 

155 

156 @staticmethod 

157 def _get_svg_icon_tag(icon_name: str, **attributes: Any) -> str: 

158 """Generate SVG icon tag for JavaScript initialization.""" 

159 # Convert class_ to class (Python keyword handling) 

160 if "class_" in attributes: 

161 attributes["class"] = attributes.pop("class_") 

162 

163 # Convert stroke_width to stroke-width (HTML attribute naming) 

164 if "stroke_width" in attributes: 

165 attributes["stroke-width"] = attributes.pop("stroke_width") 

166 

167 # Handle aria_label parameter (use hyphen in HTML) 

168 if "aria_label" in attributes: 

169 # User-provided aria-label should be used instead of auto-generated 

170 attributes["aria-label"] = attributes.pop("aria_label") 

171 

172 # Build attributes string 

173 attr_parts = [f'data-lucide="{icon_name}"'] 

174 

175 # Handle size attributes 

176 size = attributes.pop("size", None) 

177 if size: 

178 attr_parts.extend((f'width="{size}"', f'height="{size}"')) 

179 

180 # Handle other attributes 

181 for key, value in attributes.items(): 

182 if key in ("class", "id", "style", "stroke-width", "color", "title"): 

183 attr_parts.append(f'{key}="{value}"') 

184 elif key.startswith(("data-", "aria-")): 

185 attr_parts.append(f'{key}="{value}"') 

186 

187 # Add accessibility 

188 if "aria-label" not in attributes: 

189 attr_parts.append(f'aria-label="{icon_name} icon"') 

190 

191 attrs_str = " ".join(attr_parts) 

192 return f"<i {attrs_str}></i>" 

193 

194 @staticmethod 

195 def _get_font_icon_tag(icon_name: str, **attributes: Any) -> str: 

196 """Generate font icon tag.""" 

197 # Convert class_ to class (Python keyword handling) 

198 if "class_" in attributes: 

199 attributes["class"] = attributes.pop("class_") 

200 

201 # Handle aria_label parameter (use hyphen in HTML) 

202 if "aria_label" in attributes: 

203 # User-provided aria-label should be used instead of auto-generated 

204 attributes["aria-label"] = attributes.pop("aria_label") 

205 

206 icon_class = f"lucide lucide-{icon_name}" 

207 

208 # Add any additional classes 

209 if "class" in attributes: 

210 icon_class = f"{icon_class} {attributes.pop('class')}" 

211 

212 # Build attributes string 

213 attr_parts = [f'class="{icon_class}"'] 

214 

215 # Handle common attributes 

216 for key, value in attributes.items(): 

217 if key in ("id", "style", "title"): 

218 attr_parts.append(f'{key}="{value}"') 

219 elif key.startswith(("data-", "aria-")): 

220 attr_parts.append(f'{key}="{value}"') 

221 

222 # Add accessibility 

223 if "aria-label" not in attributes: 

224 attr_parts.append(f'aria-label="{icon_name} icon"') 

225 

226 attrs_str = " ".join(attr_parts) 

227 return f"<i {attrs_str}></i>" 

228 

229 def get_initialization_script(self) -> str: 

230 """Generate JavaScript initialization script for SVG mode.""" 

231 if not self.settings.use_svg: 

232 return "" 

233 

234 return """ 

235<script> 

236 document.addEventListener('DOMContentLoaded', function() { 

237 if (typeof lucide !== 'undefined') { 

238 lucide.createIcons(); 

239 } 

240 }); 

241</script> 

242""" 

243 

244 def get_icon_with_text( 

245 self, icon_name: str, text: str, position: str = "left", **attributes: Any 

246 ) -> str: 

247 """Generate icon with text combination.""" 

248 icon_tag = self.get_icon_tag(icon_name, **attributes) 

249 

250 if position == "right": 

251 return f"{text} {icon_tag}" 

252 

253 return f"{icon_tag} {text}" 

254 

255 def get_icon_button(self, icon_name: str, **attributes: Any) -> str: 

256 icon_tag = self.get_icon_tag(icon_name) 

257 

258 # Extract button-specific attributes 

259 button_class = attributes.pop("button_class", "btn") 

260 button_attrs = { 

261 k: v 

262 for k, v in attributes.items() 

263 if k in ("id", "style", "onclick", "type", "disabled") 

264 } 

265 

266 # Build button attributes 

267 attr_parts = [f'class="{button_class}"'] 

268 for key, value in button_attrs.items(): 

269 attr_parts.append(f'{key}="{value}"') 

270 

271 attrs_str = " ".join(attr_parts) 

272 return f"<button {attrs_str}>{icon_tag}</button>" 

273 

274 

275IconsSettings = LucideIconsSettings 

276Icons = LucideIcons 

277 

278# Register with Oneiric resolver (fail gracefully if not supported) 

279with suppress(Exception): 

280 depends.set(Icons, "lucide") 

281 

282__all__ = ["LucideIcons", "LucideIconsSettings", "IconsSettings", "Icons"]