ComponentGroup.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. //
  2. // ComponentGroup.swift
  3. // KMComponentLibrary
  4. //
  5. // Created by Niehaoyu on 2024/9/3.
  6. //
  7. import Cocoa
  8. import AppKit
  9. @objc public protocol ComponentGroupDelegate: AnyObject {
  10. @objc optional func componentGroupDidSelect(group: ComponentGroup?, menuItemProperty: ComponentMenuitemProperty?)
  11. @objc optional func componentGroupDidDismiss(group: ComponentGroup?)
  12. }
  13. public class ComponentGroup: NSView, NibLoadable {
  14. @IBOutlet var contendBox: NSBox!
  15. @IBOutlet var scrollView: NSScrollView!
  16. @IBOutlet var collectionView: NSCollectionView!
  17. var superBGView: ComponentBaseView = ComponentBaseView(frame: CGRectZero)
  18. // MARK: Private Property
  19. private var localMonitor: Any?
  20. private var globalMonitor: Any?
  21. private var _shadowInfo : ComponentShadowInfo?
  22. public var menuItemArr: [ComponentMenuitemProperty] = []
  23. public var clickedAutoHide = true //点击Item后,是否自动隐藏
  24. var subGroupView: ComponentGroup!
  25. weak open var groupDelegate: ComponentGroupDelegate?
  26. deinit {
  27. NotificationCenter.default.removeObserver(self)
  28. }
  29. public override func draw(_ dirtyRect: NSRect) {
  30. super.draw(dirtyRect)
  31. // Drawing code here.
  32. if shadowInfo != nil {
  33. let shadow = NSShadow()
  34. shadow.shadowColor = shadowInfo?.shadowColor
  35. shadow.shadowOffset = shadowInfo?.shadowOffset ?? CGSizeZero
  36. shadow.shadowBlurRadius = shadowInfo?.shadowBlurRadius ?? 0
  37. shadow.set()
  38. let cornerRadius: CGFloat = shadowInfo?.cornerRadius ?? 0
  39. let roundedRect = NSBezierPath(roundedRect: bounds, xRadius: cornerRadius, yRadius: cornerRadius)
  40. if let color = shadowInfo?.color {
  41. color.setFill()
  42. roundedRect.fill()
  43. }
  44. }
  45. }
  46. public override func removeFromSuperview() {
  47. super.removeFromSuperview()
  48. clearMonitor()
  49. }
  50. public required init?(coder decoder: NSCoder) {
  51. super.init(coder: decoder)
  52. }
  53. override init(frame frameRect: NSRect) {
  54. super.init(frame: frameRect)
  55. }
  56. public override func awakeFromNib() {
  57. super.awakeFromNib()
  58. shadowInfo = ComponentLibrary.shared.configShadowInfoWithKey("")
  59. if let value = ComponentLibrary.shared.getComponentValueFromKey("colorBg/popup") {
  60. let currentValue = value as! [String : Any]
  61. contendBox.fillColor = ComponentLibrary.shared.getColor(rgbaDict: currentValue)
  62. } else {
  63. contendBox.fillColor = NSColor.clear
  64. }
  65. contendBox.borderColor = NSColor.clear
  66. contendBox.borderWidth = 0
  67. scrollView.scrollerStyle = .overlay
  68. collectionView.delegate = self
  69. collectionView.dataSource = self
  70. collectionView.backgroundColors = [NSColor.clear]
  71. collectionView.wantsLayer = true
  72. collectionView.layer?.backgroundColor = NSColor.clear.cgColor
  73. collectionView.register(ComponentGroupItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "componentGroupItemID"))
  74. }
  75. //MARK: - Setter and Getter
  76. public var shadowInfo : ComponentShadowInfo? {
  77. get {
  78. return _shadowInfo
  79. }
  80. set {
  81. _shadowInfo = newValue
  82. display()
  83. }
  84. }
  85. //MARK: - Public Method
  86. public func updateGroupInfo(_ arr: [ComponentMenuitemProperty]) {
  87. menuItemArr.removeAll()
  88. for item in arr {
  89. menuItemArr.append(item)
  90. }
  91. reloadData()
  92. }
  93. public func reloadData() {
  94. collectionView.reloadData()
  95. }
  96. //MARK: - SubGroupView
  97. func removeSubGroupView() {
  98. if subGroupView != nil {
  99. subGroupView.removeGroupView()
  100. subGroupView = nil
  101. }
  102. }
  103. //MARK: - Show
  104. public func showWithPoint(_ point: CGPoint, relativeTo positioningView: NSView?) {
  105. let screenRect = NSScreen.main!.frame
  106. let contentWindow: NSWindow = NSWindow(contentRect: screenRect,
  107. styleMask: [.borderless],
  108. backing: .buffered, defer: false)
  109. contentWindow.level = .statusBar
  110. contentWindow.backgroundColor = NSColor.clear
  111. contentWindow.makeKeyAndOrderFront(nil)
  112. if let subView = positioningView {
  113. var rect = frame
  114. rect.origin.x = point.x
  115. rect.origin.y = point.y
  116. rect.origin.x += subView.window?.frame.origin.x ?? 0
  117. rect.origin.y += subView.window?.frame.origin.y ?? 0
  118. if(rect.origin.y < 0) {
  119. rect.origin.y = 0
  120. }
  121. if(CGRectGetMaxX(rect) > CGRectGetMaxX(screenRect)) {
  122. rect.origin.x = CGRectGetMaxX(screenRect) - rect.width
  123. }
  124. frame = rect
  125. contentWindow.contentView?.addSubview(self)
  126. clearMonitor()
  127. addMonitor()
  128. }
  129. }
  130. public func removeGroupView() {
  131. superBGView.removeFromSuperview()
  132. removeFromSuperview()
  133. clearMonitor()
  134. window?.close()
  135. }
  136. //MARK: - subGroupView
  137. func showSubGroupView(itemView: ComponentGroupItem) {
  138. if subGroupView == nil {
  139. subGroupView = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
  140. }
  141. var viewHeight: CGFloat = 8
  142. for property in itemView.properties.subPropertys {
  143. if property.type == .divider {
  144. viewHeight += 8
  145. } else if property.type == .normal {
  146. viewHeight += 36
  147. } else if property.type == .header {
  148. viewHeight += 36
  149. }
  150. }
  151. subGroupView?.frame = CGRectMake(0, 0, 160, viewHeight)
  152. subGroupView.updateGroupInfo(itemView.properties.subPropertys)
  153. var point = CGPoint(x: 0, y: 0)
  154. if let subViewRect = itemView.view.superview?.convert(itemView.view.frame, to: itemView.view.window?.contentView) {
  155. point.x = CGRectGetMaxX(subViewRect)
  156. point.y = CGRectGetMaxY(subViewRect) - viewHeight
  157. }
  158. guard let subView = itemView.view.window?.contentView else {
  159. return
  160. }
  161. if point.x + CGRectGetWidth(self.subGroupView.frame) > CGRectGetWidth(subView.frame) - 10 {
  162. if let selfConvertPoint = superview?.convert(self.frame.origin, to: subView) {
  163. point.x = selfConvertPoint.x - CGRectGetWidth(self.subGroupView.frame)
  164. }
  165. }
  166. subGroupView.showWithPoint(point, relativeTo: self)
  167. }
  168. //MARK: - Private Method
  169. func addMonitor() {
  170. if globalMonitor == nil {
  171. globalMonitor = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown], handler: { (event) in
  172. if event.type == .leftMouseDown {
  173. self.leftMouseDownAction()
  174. }
  175. })
  176. }
  177. if localMonitor == nil {
  178. localMonitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .scrollWheel], handler: { (event) in
  179. if event.type == .leftMouseDown {
  180. let point = self.convert(event.locationInWindow, from: nil)
  181. if CGRectContainsPoint(self.bounds, point) {
  182. } else {
  183. self.leftMouseDownAction()
  184. }
  185. } else if event.type == .scrollWheel {
  186. let point = self.convert(event.locationInWindow, from: nil)
  187. if CGRectContainsPoint(self.bounds, point) {
  188. } else {
  189. self.leftMouseDownAction()
  190. }
  191. }
  192. return event
  193. })
  194. }
  195. }
  196. func clearMonitor() {
  197. if localMonitor != nil {
  198. NSEvent.removeMonitor(self.localMonitor as Any)
  199. localMonitor = nil
  200. }
  201. if globalMonitor != nil {
  202. NSEvent.removeMonitor(self.globalMonitor as Any)
  203. globalMonitor = nil
  204. }
  205. }
  206. func leftMouseDownAction() {
  207. groupDelegate?.componentGroupDidDismiss?(group: self)
  208. removeGroupView()
  209. }
  210. }
  211. //MARK: - NSCollectionViewDelegate
  212. extension ComponentGroup: NSCollectionViewDelegate {
  213. }
  214. extension ComponentGroup: NSCollectionViewDataSource {
  215. public func numberOfSections(in collectionView: NSCollectionView) -> Int {
  216. return 1
  217. }
  218. public func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
  219. return menuItemArr.count
  220. }
  221. public func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
  222. let itemView = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "componentGroupItemID"), for: indexPath) as! ComponentGroupItem
  223. if indexPath.item < menuItemArr.count {
  224. let properties = menuItemArr[indexPath.item]
  225. itemView.setUpWithProperties(properties)
  226. }
  227. itemView.clickHandle = {[weak self] view in
  228. DispatchQueue.main.async {
  229. let property = view.properties
  230. if self?.clickedAutoHide == true {
  231. self?.groupDelegate?.componentGroupDidDismiss?(group: self)
  232. self?.removeGroupView()
  233. }
  234. self?.groupDelegate?.componentGroupDidSelect?(group: self, menuItemProperty: property)
  235. }
  236. }
  237. itemView.mouseHandle = {[weak self] view, mouseState, event in
  238. guard let weakSelf = self else { return }
  239. if view.properties.subPropertys.isEmpty == false {
  240. if mouseState == .enter {
  241. self?.showSubGroupView(itemView: view)
  242. } else if mouseState == .move {
  243. let point = weakSelf.convert(event.locationInWindow, from: nil)
  244. }
  245. } else {
  246. self?.removeSubGroupView()
  247. }
  248. }
  249. return itemView
  250. }
  251. }
  252. extension ComponentGroup: NSCollectionViewDelegateFlowLayout {
  253. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
  254. var viewHeight: CGFloat = 36
  255. if indexPath.item < menuItemArr.count {
  256. let properties = menuItemArr[indexPath.item]
  257. if properties.type == .divider {
  258. viewHeight = 8
  259. }
  260. }
  261. return NSSize(width: NSWidth(self.collectionView.frame), height: viewHeight)
  262. }
  263. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> NSSize {
  264. return NSSize(width: 0, height: 0)
  265. }
  266. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForFooterInSection section: Int) -> NSSize {
  267. return NSSize(width: 0, height: 0)
  268. }
  269. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  270. return 0
  271. }
  272. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAt section: Int) -> NSEdgeInsets {
  273. return NSEdgeInsetsMake(0, 0, 0, 0)
  274. }
  275. public func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
  276. }
  277. }