ComponentGroup.swift 13 KB

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