Nessuna descrizione

DashboardView.swift 65KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. //
  2. // DashboardView.swift
  3. // App for Indeed
  4. //
  5. import Cocoa
  6. import QuartzCore
  7. private enum JobListingCardContext {
  8. case homeSearchResults
  9. case savedJobsPage
  10. }
  11. final class DashboardView: NSView, NSTextFieldDelegate {
  12. /// Indeed.com-inspired neutrals and brand blue (white surfaces, `#2557a7` accent, `#2d2d2d` / `#767676` text, `#d4d2d0` borders).
  13. private enum Theme {
  14. static let brandBlue = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 1)
  15. static let pageBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  16. static let chromeBackground = NSColor(srgbRed: 247 / 255, green: 247 / 255, blue: 247 / 255, alpha: 1)
  17. static let sidebarBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  18. static let mainHostBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  19. /// Subtitle on the welcome hero: readable blue-gray aligned with brand.
  20. static let welcomeSubtitleText = NSColor(srgbRed: 52 / 255, green: 92 / 255, blue: 142 / 255, alpha: 1)
  21. static let selectionFill = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 0.12)
  22. static let cardBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  23. static let toggleBackground = NSColor(srgbRed: 232 / 255, green: 232 / 255, blue: 232 / 255, alpha: 1)
  24. static let primaryText = NSColor(srgbRed: 45 / 255, green: 45 / 255, blue: 45 / 255, alpha: 1)
  25. static let secondaryText = NSColor(srgbRed: 118 / 255, green: 118 / 255, blue: 118 / 255, alpha: 1)
  26. static let tertiaryText = NSColor(srgbRed: 118 / 255, green: 118 / 255, blue: 118 / 255, alpha: 1)
  27. static let border = NSColor(srgbRed: 212 / 255, green: 210 / 255, blue: 208 / 255, alpha: 1)
  28. /// Job search bar outer stroke (charcoal).
  29. static let searchBarBorder = NSColor(srgbRed: 58 / 255, green: 58 / 255, blue: 58 / 255, alpha: 1)
  30. static let proCardFill = NSColor(srgbRed: 239 / 255, green: 244 / 255, blue: 252 / 255, alpha: 1)
  31. static let proCardBorder = NSColor(srgbRed: 212 / 255, green: 210 / 255, blue: 208 / 255, alpha: 1)
  32. static let proAccent = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 1)
  33. static let proCTABackground = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 1)
  34. static let proCTAText = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  35. /// Slightly lighter blue for the top of the search-bar “Find jobs” pill (reads less flat than a solid fill).
  36. static let findJobsCTAHighlight = NSColor(srgbRed: 54 / 255, green: 110 / 255, blue: 198 / 255, alpha: 1)
  37. /// Hover states: darker brand blue, deeper gradient top, stronger tints, and subtle neutral fills used across CTAs, toggles, and the sidebar.
  38. static let brandBlueHover = NSColor(srgbRed: 28 / 255, green: 70 / 255, blue: 140 / 255, alpha: 1)
  39. static let findJobsCTAHighlightHover = NSColor(srgbRed: 44 / 255, green: 94 / 255, blue: 178 / 255, alpha: 1)
  40. static let selectionFillHover = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 0.2)
  41. static let neutralHoverFill = NSColor(srgbRed: 240 / 255, green: 240 / 255, blue: 240 / 255, alpha: 1)
  42. static let sidebarRowHoverFill = NSColor(srgbRed: 0, green: 0, blue: 0, alpha: 0.04)
  43. }
  44. /// Multiline `NSTextField` often ignores `alignment` for wrapped runs; explicit paragraph alignment matches the title.
  45. private static func jobListingDescriptionAttributedString(_ plain: String) -> NSAttributedString {
  46. let paragraph = NSMutableParagraphStyle()
  47. paragraph.alignment = .left
  48. paragraph.lineBreakMode = .byWordWrapping
  49. paragraph.baseWritingDirection = .leftToRight
  50. let font = NSFont.systemFont(ofSize: 13, weight: .regular)
  51. return NSAttributedString(string: plain, attributes: [
  52. .font: font,
  53. .foregroundColor: Theme.secondaryText,
  54. .paragraphStyle: paragraph
  55. ])
  56. }
  57. private let contentStack = NSStackView()
  58. private let chromeContainer = NSView()
  59. private let sidebar = NSStackView()
  60. private let mainHost = NSView()
  61. private let mainOverlay = NSStackView()
  62. private let greetingLabel = NSTextField(labelWithString: "")
  63. private let subtitleLabel = NSTextField(labelWithString: "")
  64. private let searchBarShadowHost = NSView()
  65. private let searchCard = NSView()
  66. private let jobSearchIcon = NSImageView()
  67. private let jobKeywordsField = NSTextField()
  68. private let findJobsButton = HoverableButton()
  69. private let findJobsCTAHost = NSView()
  70. private let findJobsCTAChrome = HoverableView()
  71. private var findJobsCTAGradientLayer: CAGradientLayer?
  72. private let jobListingsScrollView = NSScrollView()
  73. /// Flipped so short result lists stay visually under the search bar instead of leaving a gap above the cards.
  74. private let jobListingsContainer = JobListingsDocumentView()
  75. private let jobListingsStack = NSStackView()
  76. /// Shown when a sidebar item other than Home is selected.
  77. private let nonHomeHost = NSView()
  78. private let nonHomeGenericContainer = NSView()
  79. private let nonHomeTitleLabel = NSTextField(labelWithString: "")
  80. private let nonHomeSubtitleLabel = NSTextField(wrappingLabelWithString: "")
  81. private let savedJobsPageContainer = NSView()
  82. private let savedJobsPageTitleLabel = NSTextField(labelWithString: "Saved Jobs")
  83. private let savedJobsPageSubtitleLabel = NSTextField(wrappingLabelWithString: "")
  84. private let savedJobsScrollView = NSScrollView()
  85. private let savedJobsDocumentView = JobListingsDocumentView()
  86. private let savedJobsStack = NSStackView()
  87. private var currentSidebarItems: [SidebarItem] = []
  88. private var selectedSidebarIndex: Int = 0
  89. /// Full list from `DashboardData`; results are shown after the user runs a search.
  90. private var catalogJobListings: [JobListing] = []
  91. /// Last successful search result set (used when removing a card with the dismiss control).
  92. private var lastSearchResults: [JobListing] = []
  93. private var lastNoResultsQuery: String?
  94. /// Most recently saved jobs appear first; persisted across launches.
  95. private var savedJobOrder: [JobListing] = []
  96. override init(frame frameRect: NSRect) {
  97. super.init(frame: frameRect)
  98. setupLayout()
  99. }
  100. required init?(coder: NSCoder) {
  101. super.init(coder: coder)
  102. setupLayout()
  103. }
  104. override func layout() {
  105. super.layout()
  106. updateSearchBarShadowPath()
  107. findJobsCTAGradientLayer?.frame = findJobsCTAChrome.bounds
  108. updateFindJobsCTAShadowPath()
  109. updateJobListingDescriptionWidths()
  110. }
  111. func render(_ data: DashboardData) {
  112. greetingLabel.stringValue = "Welcome"
  113. subtitleLabel.stringValue = data.subtitle
  114. currentSidebarItems = data.sidebarItems
  115. if selectedSidebarIndex >= currentSidebarItems.count {
  116. selectedSidebarIndex = max(0, currentSidebarItems.count - 1)
  117. }
  118. configureSidebar()
  119. catalogJobListings = data.jobListings
  120. savedJobOrder = Self.normalizedSavedJobs(SavedJobsStore.load())
  121. configureJobListings([], noResultsForQuery: nil)
  122. updateMainContentVisibility()
  123. }
  124. private func setupLayout() {
  125. wantsLayer = true
  126. layer?.backgroundColor = Theme.pageBackground.cgColor
  127. contentStack.orientation = .horizontal
  128. contentStack.spacing = 20
  129. contentStack.distribution = .fill
  130. contentStack.translatesAutoresizingMaskIntoConstraints = false
  131. contentStack.alignment = .height
  132. contentStack.edgeInsets = NSEdgeInsets(top: 24, left: 24, bottom: 24, right: 24)
  133. chromeContainer.translatesAutoresizingMaskIntoConstraints = false
  134. chromeContainer.wantsLayer = true
  135. chromeContainer.layer?.backgroundColor = Theme.chromeBackground.cgColor
  136. chromeContainer.layer?.cornerRadius = 0
  137. addSubview(chromeContainer)
  138. chromeContainer.addSubview(contentStack)
  139. sidebar.orientation = .vertical
  140. sidebar.spacing = 10
  141. sidebar.distribution = .fill
  142. sidebar.alignment = .leading
  143. sidebar.wantsLayer = true
  144. sidebar.layer?.backgroundColor = Theme.sidebarBackground.cgColor
  145. sidebar.layer?.cornerRadius = 16
  146. sidebar.edgeInsets = NSEdgeInsets(top: 18, left: 14, bottom: 18, right: 14)
  147. sidebar.translatesAutoresizingMaskIntoConstraints = false
  148. mainHost.translatesAutoresizingMaskIntoConstraints = false
  149. mainHost.wantsLayer = true
  150. mainHost.layer?.backgroundColor = Theme.mainHostBackground.cgColor
  151. mainHost.layer?.cornerRadius = 16
  152. mainHost.layer?.masksToBounds = true
  153. sidebar.setContentHuggingPriority(.required, for: .horizontal)
  154. mainHost.setContentHuggingPriority(.defaultLow, for: .horizontal)
  155. mainHost.addSubview(mainOverlay)
  156. configureNonHomePlaceholder()
  157. mainHost.addSubview(nonHomeHost)
  158. mainOverlay.orientation = .vertical
  159. mainOverlay.spacing = 0
  160. mainOverlay.alignment = .centerX
  161. mainOverlay.distribution = .fill
  162. mainOverlay.translatesAutoresizingMaskIntoConstraints = false
  163. mainOverlay.setContentHuggingPriority(.defaultLow, for: .vertical)
  164. greetingLabel.font = .systemFont(ofSize: 32, weight: .bold)
  165. greetingLabel.textColor = Theme.brandBlue
  166. greetingLabel.alignment = .center
  167. greetingLabel.maximumNumberOfLines = 1
  168. subtitleLabel.font = .systemFont(ofSize: 15, weight: .regular)
  169. subtitleLabel.textColor = Theme.welcomeSubtitleText
  170. subtitleLabel.alignment = .center
  171. subtitleLabel.maximumNumberOfLines = 2
  172. let topInset = NSView()
  173. topInset.translatesAutoresizingMaskIntoConstraints = false
  174. topInset.heightAnchor.constraint(equalToConstant: 32).isActive = true
  175. configureSearchBar()
  176. let titleBlock = NSStackView(views: [greetingLabel, subtitleLabel])
  177. titleBlock.orientation = .vertical
  178. titleBlock.spacing = 10
  179. titleBlock.alignment = .centerX
  180. let midSpacer = NSView()
  181. midSpacer.translatesAutoresizingMaskIntoConstraints = false
  182. midSpacer.heightAnchor.constraint(equalToConstant: 20).isActive = true
  183. let listingsTopSpacer = NSView()
  184. listingsTopSpacer.translatesAutoresizingMaskIntoConstraints = false
  185. listingsTopSpacer.heightAnchor.constraint(equalToConstant: 12).isActive = true
  186. jobListingsContainer.translatesAutoresizingMaskIntoConstraints = false
  187. jobListingsStack.orientation = .vertical
  188. jobListingsStack.spacing = 14
  189. // `.leading` keeps cards left-anchored; explicit width constraints below stretch each card across the full row.
  190. jobListingsStack.alignment = .leading
  191. jobListingsStack.distribution = .fill
  192. jobListingsStack.translatesAutoresizingMaskIntoConstraints = false
  193. jobListingsStack.setContentHuggingPriority(.defaultHigh, for: .vertical)
  194. jobListingsStack.setHuggingPriority(.defaultLow, for: .horizontal)
  195. jobListingsContainer.addSubview(jobListingsStack)
  196. NSLayoutConstraint.activate([
  197. jobListingsStack.leadingAnchor.constraint(equalTo: jobListingsContainer.leadingAnchor),
  198. jobListingsStack.trailingAnchor.constraint(equalTo: jobListingsContainer.trailingAnchor),
  199. jobListingsStack.topAnchor.constraint(equalTo: jobListingsContainer.topAnchor),
  200. jobListingsStack.bottomAnchor.constraint(equalTo: jobListingsContainer.bottomAnchor)
  201. ])
  202. jobListingsScrollView.translatesAutoresizingMaskIntoConstraints = false
  203. jobListingsScrollView.hasVerticalScroller = true
  204. jobListingsScrollView.hasHorizontalScroller = false
  205. jobListingsScrollView.autohidesScrollers = true
  206. jobListingsScrollView.drawsBackground = false
  207. jobListingsScrollView.borderType = .noBorder
  208. jobListingsScrollView.documentView = jobListingsContainer
  209. jobListingsScrollView.setContentHuggingPriority(.defaultLow, for: .vertical)
  210. jobListingsScrollView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  211. mainOverlay.addArrangedSubview(topInset)
  212. mainOverlay.addArrangedSubview(titleBlock)
  213. mainOverlay.addArrangedSubview(midSpacer)
  214. mainOverlay.addArrangedSubview(searchBarShadowHost)
  215. mainOverlay.addArrangedSubview(listingsTopSpacer)
  216. mainOverlay.addArrangedSubview(jobListingsScrollView)
  217. contentStack.addArrangedSubview(sidebar)
  218. contentStack.addArrangedSubview(mainHost)
  219. NSLayoutConstraint.activate([
  220. chromeContainer.leadingAnchor.constraint(equalTo: leadingAnchor),
  221. chromeContainer.trailingAnchor.constraint(equalTo: trailingAnchor),
  222. chromeContainer.topAnchor.constraint(equalTo: topAnchor),
  223. chromeContainer.bottomAnchor.constraint(equalTo: bottomAnchor),
  224. contentStack.leadingAnchor.constraint(equalTo: chromeContainer.leadingAnchor),
  225. contentStack.trailingAnchor.constraint(equalTo: chromeContainer.trailingAnchor),
  226. contentStack.topAnchor.constraint(equalTo: chromeContainer.topAnchor),
  227. contentStack.bottomAnchor.constraint(equalTo: chromeContainer.bottomAnchor),
  228. sidebar.widthAnchor.constraint(equalToConstant: 218),
  229. mainHost.widthAnchor.constraint(greaterThanOrEqualToConstant: 720),
  230. mainOverlay.leadingAnchor.constraint(equalTo: mainHost.leadingAnchor),
  231. mainOverlay.trailingAnchor.constraint(equalTo: mainHost.trailingAnchor),
  232. mainOverlay.topAnchor.constraint(equalTo: mainHost.topAnchor),
  233. mainOverlay.bottomAnchor.constraint(equalTo: mainHost.bottomAnchor, constant: -24),
  234. nonHomeHost.leadingAnchor.constraint(equalTo: mainHost.leadingAnchor),
  235. nonHomeHost.trailingAnchor.constraint(equalTo: mainHost.trailingAnchor),
  236. nonHomeHost.topAnchor.constraint(equalTo: mainHost.topAnchor),
  237. nonHomeHost.bottomAnchor.constraint(equalTo: mainHost.bottomAnchor, constant: -24),
  238. searchBarShadowHost.widthAnchor.constraint(equalTo: mainOverlay.widthAnchor, multiplier: 0.92),
  239. jobListingsScrollView.widthAnchor.constraint(equalTo: mainOverlay.widthAnchor, multiplier: 0.92),
  240. jobListingsContainer.topAnchor.constraint(equalTo: jobListingsScrollView.contentView.topAnchor),
  241. jobListingsContainer.leadingAnchor.constraint(equalTo: jobListingsScrollView.contentView.leadingAnchor),
  242. jobListingsContainer.widthAnchor.constraint(equalTo: jobListingsScrollView.contentView.widthAnchor),
  243. greetingLabel.leadingAnchor.constraint(equalTo: mainOverlay.leadingAnchor, constant: 24),
  244. greetingLabel.trailingAnchor.constraint(equalTo: mainOverlay.trailingAnchor, constant: -24),
  245. subtitleLabel.leadingAnchor.constraint(equalTo: greetingLabel.leadingAnchor),
  246. subtitleLabel.trailingAnchor.constraint(equalTo: greetingLabel.trailingAnchor)
  247. ])
  248. }
  249. private func updateJobListingDescriptionWidths() {
  250. updateDescriptionColumnWidths(in: jobListingsStack, containerWidth: jobListingsContainer.bounds.width)
  251. updateDescriptionColumnWidths(in: savedJobsStack, containerWidth: savedJobsDocumentView.bounds.width)
  252. }
  253. private func updateDescriptionColumnWidths(in stack: NSStackView, containerWidth: CGFloat) {
  254. guard containerWidth > 1 else { return }
  255. // Matches `contentColumn` insets on the card (16 leading + 16 trailing). The description spans the full row below the buttons, so never subtract a “button strip” here — a too-narrow `preferredMaxLayoutWidth` inside a wider field makes wrapped `NSTextField` text lay out like a trailing-aligned band after resizes.
  256. let contentHorizontalInset: CGFloat = 32
  257. var didChange = false
  258. for card in stack.arrangedSubviews {
  259. guard let desc = card.viewWithTag(502) as? NSTextField else { continue }
  260. let cardWidth = card.bounds.width > 1 ? card.bounds.width : containerWidth
  261. let fallbackColumn = max(1, cardWidth - contentHorizontalInset)
  262. let columnWidth: CGFloat
  263. if desc.bounds.width > 1 {
  264. columnWidth = desc.bounds.width
  265. } else if let column = desc.superview, column.bounds.width > 1 {
  266. columnWidth = column.bounds.width
  267. } else {
  268. columnWidth = fallbackColumn
  269. }
  270. if abs(desc.preferredMaxLayoutWidth - columnWidth) > 0.5 {
  271. desc.preferredMaxLayoutWidth = columnWidth
  272. desc.invalidateIntrinsicContentSize()
  273. didChange = true
  274. }
  275. }
  276. if didChange {
  277. stack.needsLayout = true
  278. }
  279. }
  280. private func configureJobListings(_ jobs: [JobListing], noResultsForQuery: String?, updateLastResults: Bool = true) {
  281. if updateLastResults {
  282. lastSearchResults = jobs
  283. lastNoResultsQuery = noResultsForQuery
  284. }
  285. jobListingsStack.arrangedSubviews.forEach {
  286. jobListingsStack.removeArrangedSubview($0)
  287. $0.removeFromSuperview()
  288. }
  289. if jobs.isEmpty, let query = noResultsForQuery, !query.isEmpty {
  290. let empty = NSTextField(wrappingLabelWithString: "No jobs match “\(query)”. Try different keywords or browse the full list with an empty search.")
  291. empty.font = .systemFont(ofSize: 14, weight: .regular)
  292. empty.textColor = Theme.secondaryText
  293. empty.alignment = .center
  294. empty.maximumNumberOfLines = 0
  295. empty.translatesAutoresizingMaskIntoConstraints = false
  296. jobListingsStack.addArrangedSubview(empty)
  297. empty.widthAnchor.constraint(equalTo: jobListingsStack.widthAnchor).isActive = true
  298. return
  299. }
  300. for job in jobs {
  301. let card = makeJobListingCard(job, context: .homeSearchResults)
  302. jobListingsStack.addArrangedSubview(card)
  303. // Force every card to span the full row instead of hugging its intrinsic content width.
  304. card.widthAnchor.constraint(equalTo: jobListingsStack.widthAnchor).isActive = true
  305. }
  306. }
  307. private static func normalizedSavedJobs(_ jobs: [JobListing]) -> [JobListing] {
  308. var seen = Set<JobListing>()
  309. var out: [JobListing] = []
  310. for job in jobs where seen.insert(job).inserted {
  311. out.append(job)
  312. }
  313. return out
  314. }
  315. private func isJobSaved(_ job: JobListing) -> Bool {
  316. savedJobOrder.contains(job)
  317. }
  318. private func persistSavedJobs() {
  319. SavedJobsStore.save(savedJobOrder)
  320. }
  321. private func applySavedState(_ saved: Bool, for job: JobListing) {
  322. if saved {
  323. savedJobOrder.removeAll { $0 == job }
  324. savedJobOrder.insert(job, at: 0)
  325. } else {
  326. savedJobOrder.removeAll { $0 == job }
  327. }
  328. persistSavedJobs()
  329. }
  330. private func makeJobListingCard(_ job: JobListing, context: JobListingCardContext) -> NSView {
  331. let card = NSView()
  332. card.translatesAutoresizingMaskIntoConstraints = false
  333. card.wantsLayer = true
  334. card.layer?.backgroundColor = Theme.cardBackground.cgColor
  335. card.layer?.cornerRadius = 12
  336. card.layer?.borderWidth = 1
  337. card.layer?.borderColor = Theme.border.cgColor
  338. card.layer?.masksToBounds = true
  339. let titleField = NSTextField(labelWithString: job.title)
  340. titleField.font = .systemFont(ofSize: 16, weight: .semibold)
  341. titleField.textColor = Theme.primaryText
  342. titleField.maximumNumberOfLines = 2
  343. titleField.lineBreakMode = .byWordWrapping
  344. titleField.alignment = .left
  345. titleField.translatesAutoresizingMaskIntoConstraints = false
  346. let descriptionField = NSTextField(wrappingLabelWithString: job.description)
  347. descriptionField.font = .systemFont(ofSize: 13, weight: .regular)
  348. descriptionField.textColor = Theme.secondaryText
  349. descriptionField.maximumNumberOfLines = 0
  350. descriptionField.alignment = .left
  351. descriptionField.lineBreakMode = .byWordWrapping
  352. descriptionField.baseWritingDirection = .leftToRight
  353. descriptionField.attributedStringValue = Self.jobListingDescriptionAttributedString(job.description)
  354. if let cell = descriptionField.cell as? NSTextFieldCell {
  355. cell.alignment = .left
  356. cell.wraps = true
  357. }
  358. descriptionField.setContentHuggingPriority(.defaultLow, for: .horizontal)
  359. descriptionField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  360. descriptionField.tag = 502
  361. descriptionField.translatesAutoresizingMaskIntoConstraints = false
  362. let applyButton = JobPayloadButton(title: "Apply", target: self, action: #selector(didTapJobApply(_:)))
  363. applyButton.jobPayload = job
  364. applyButton.cardContext = context
  365. applyButton.isBordered = false
  366. applyButton.bezelStyle = .rounded
  367. applyButton.font = .systemFont(ofSize: 13, weight: .semibold)
  368. applyButton.wantsLayer = true
  369. applyButton.layer?.cornerRadius = 6
  370. applyButton.layer?.backgroundColor = Theme.brandBlue.cgColor
  371. applyButton.contentTintColor = Theme.proCTAText
  372. applyButton.focusRingType = .none
  373. applyButton.pointerCursor = true
  374. applyButton.hoverHandler = { [weak applyButton] hovering in
  375. applyButton?.layer?.backgroundColor = (hovering ? Theme.brandBlueHover : Theme.brandBlue).cgColor
  376. }
  377. applyButton.setContentHuggingPriority(.required, for: .horizontal)
  378. applyButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  379. let savedOn = isJobSaved(job)
  380. let savedButton = JobPayloadButton(title: savedOn ? "Saved" : "Save", target: self, action: #selector(didTapJobSaved(_:)))
  381. savedButton.jobPayload = job
  382. savedButton.cardContext = context
  383. savedButton.setButtonType(.toggle)
  384. savedButton.isBordered = false
  385. savedButton.bezelStyle = .rounded
  386. savedButton.font = .systemFont(ofSize: 13, weight: .semibold)
  387. savedButton.focusRingType = .none
  388. savedButton.state = savedOn ? .on : .off
  389. savedButton.pointerCursor = true
  390. savedButton.hoverHandler = { [weak self, weak savedButton] _ in
  391. guard let savedButton = savedButton else { return }
  392. self?.styleJobSavedButton(savedButton)
  393. }
  394. styleJobSavedButton(savedButton)
  395. savedButton.setContentHuggingPriority(.required, for: .horizontal)
  396. savedButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  397. let dismissButton = JobPayloadButton()
  398. dismissButton.jobPayload = job
  399. dismissButton.cardContext = context
  400. dismissButton.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Dismiss")
  401. dismissButton.imagePosition = .imageOnly
  402. dismissButton.imageScaling = .scaleProportionallyDown
  403. dismissButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .semibold)
  404. dismissButton.isBordered = false
  405. dismissButton.bezelStyle = .rounded
  406. dismissButton.contentTintColor = Theme.secondaryText
  407. dismissButton.target = self
  408. dismissButton.action = #selector(didTapJobDismiss(_:))
  409. dismissButton.toolTip = context == .savedJobsPage ? "Remove from saved" : "Dismiss"
  410. dismissButton.focusRingType = .none
  411. dismissButton.wantsLayer = true
  412. dismissButton.layer?.cornerRadius = 14
  413. dismissButton.layer?.backgroundColor = NSColor.clear.cgColor
  414. dismissButton.pointerCursor = true
  415. dismissButton.hoverHandler = { [weak dismissButton] hovering in
  416. dismissButton?.layer?.backgroundColor = (hovering ? Theme.neutralHoverFill : NSColor.clear).cgColor
  417. dismissButton?.contentTintColor = hovering ? Theme.primaryText : Theme.secondaryText
  418. }
  419. dismissButton.setContentHuggingPriority(.required, for: .horizontal)
  420. let buttonRow = NSStackView(views: [applyButton, savedButton, dismissButton])
  421. buttonRow.orientation = .horizontal
  422. buttonRow.spacing = 8
  423. buttonRow.alignment = .centerY
  424. buttonRow.translatesAutoresizingMaskIntoConstraints = false
  425. buttonRow.setContentHuggingPriority(.required, for: .horizontal)
  426. buttonRow.setContentCompressionResistancePriority(.required, for: .horizontal)
  427. // Title hugs the leading edge; a low–hugging-priority spacer absorbs remaining width so buttons stay trailing.
  428. titleField.setContentHuggingPriority(.defaultHigh, for: .horizontal)
  429. titleField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  430. let titleRowSpacer = NSView()
  431. titleRowSpacer.translatesAutoresizingMaskIntoConstraints = false
  432. titleRowSpacer.setContentHuggingPriority(NSLayoutConstraint.Priority(1), for: .horizontal)
  433. titleRowSpacer.setContentCompressionResistancePriority(NSLayoutConstraint.Priority(1), for: .horizontal)
  434. let titleAndActionsRow = NSStackView(views: [titleField, titleRowSpacer, buttonRow])
  435. titleAndActionsRow.orientation = .horizontal
  436. titleAndActionsRow.spacing = 0
  437. titleAndActionsRow.setCustomSpacing(14, after: titleRowSpacer)
  438. titleAndActionsRow.alignment = .centerY
  439. titleAndActionsRow.distribution = .fill
  440. titleAndActionsRow.userInterfaceLayoutDirection = .leftToRight
  441. titleAndActionsRow.translatesAutoresizingMaskIntoConstraints = false
  442. let contentColumn = NSStackView(views: [titleAndActionsRow, descriptionField])
  443. contentColumn.orientation = .vertical
  444. contentColumn.spacing = 6
  445. contentColumn.alignment = .width
  446. contentColumn.translatesAutoresizingMaskIntoConstraints = false
  447. card.addSubview(contentColumn)
  448. NSLayoutConstraint.activate([
  449. contentColumn.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 16),
  450. contentColumn.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -16),
  451. contentColumn.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
  452. contentColumn.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -14),
  453. applyButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 72),
  454. applyButton.heightAnchor.constraint(equalToConstant: 28),
  455. savedButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 72),
  456. savedButton.heightAnchor.constraint(equalToConstant: 28),
  457. dismissButton.widthAnchor.constraint(equalToConstant: 28),
  458. dismissButton.heightAnchor.constraint(equalToConstant: 28),
  459. descriptionField.widthAnchor.constraint(equalTo: contentColumn.widthAnchor)
  460. ])
  461. return card
  462. }
  463. private func styleJobSavedButton(_ button: NSButton) {
  464. button.wantsLayer = true
  465. button.layer?.cornerRadius = 6
  466. let on = button.state == .on
  467. let hovering = (button as? HoverableButton)?.isHovering ?? false
  468. if on {
  469. button.layer?.backgroundColor = (hovering ? Theme.selectionFillHover : Theme.selectionFill).cgColor
  470. button.layer?.borderWidth = 1
  471. button.layer?.borderColor = Theme.brandBlue.cgColor
  472. button.contentTintColor = Theme.brandBlue
  473. } else {
  474. button.layer?.backgroundColor = (hovering ? Theme.neutralHoverFill : Theme.cardBackground).cgColor
  475. button.layer?.borderWidth = 1
  476. button.layer?.borderColor = Theme.border.cgColor
  477. button.contentTintColor = Theme.primaryText
  478. }
  479. }
  480. @objc private func didTapJobApply(_ sender: NSButton) {
  481. guard let job = (sender as? JobPayloadButton)?.jobPayload else { return }
  482. let allowed = CharacterSet.urlQueryAllowed
  483. let q = job.title.addingPercentEncoding(withAllowedCharacters: allowed) ?? ""
  484. guard let url = URL(string: "https://www.indeed.com/jobs?q=\(q)") else { return }
  485. NSWorkspace.shared.open(url)
  486. }
  487. @objc private func didTapJobSaved(_ sender: NSButton) {
  488. guard let job = (sender as? JobPayloadButton)?.jobPayload else { return }
  489. let willSave = !isJobSaved(job)
  490. applySavedState(willSave, for: job)
  491. sender.state = willSave ? .on : .off
  492. sender.title = willSave ? "Saved" : "Save"
  493. styleJobSavedButton(sender)
  494. if isSavedJobsSidebarIndex(selectedSidebarIndex) {
  495. reloadSavedJobsListings()
  496. }
  497. }
  498. @objc private func didTapJobDismiss(_ sender: NSButton) {
  499. guard let button = sender as? JobPayloadButton, let job = button.jobPayload else { return }
  500. switch button.cardContext {
  501. case .homeSearchResults:
  502. lastSearchResults.removeAll { $0 == job }
  503. configureJobListings(lastSearchResults, noResultsForQuery: lastNoResultsQuery)
  504. case .savedJobsPage:
  505. applySavedState(false, for: job)
  506. reloadSavedJobsListings()
  507. if isHomeSidebarIndex(selectedSidebarIndex), !lastSearchResults.isEmpty {
  508. configureJobListings(lastSearchResults, noResultsForQuery: lastNoResultsQuery, updateLastResults: false)
  509. }
  510. }
  511. }
  512. private func configureSearchBar() {
  513. let pillCorner: CGFloat = 27
  514. let barHeight: CGFloat = 54
  515. searchBarShadowHost.translatesAutoresizingMaskIntoConstraints = false
  516. searchBarShadowHost.wantsLayer = true
  517. searchBarShadowHost.layer?.masksToBounds = false
  518. searchBarShadowHost.layer?.shadowColor = NSColor.black.withAlphaComponent(0.18).cgColor
  519. searchBarShadowHost.layer?.shadowOffset = CGSize(width: 0, height: 2)
  520. searchBarShadowHost.layer?.shadowRadius = 10
  521. searchBarShadowHost.layer?.shadowOpacity = 1
  522. searchBarShadowHost.setContentHuggingPriority(.defaultHigh, for: .vertical)
  523. searchCard.translatesAutoresizingMaskIntoConstraints = false
  524. searchCard.wantsLayer = true
  525. searchCard.layer?.backgroundColor = Theme.cardBackground.cgColor
  526. searchCard.layer?.cornerRadius = pillCorner
  527. searchCard.layer?.borderWidth = 1
  528. searchCard.layer?.borderColor = Theme.searchBarBorder.cgColor
  529. searchCard.layer?.masksToBounds = true
  530. searchBarShadowHost.addSubview(searchCard)
  531. func configureField(_ field: NSTextField, placeholder: String) {
  532. field.translatesAutoresizingMaskIntoConstraints = false
  533. field.isBordered = false
  534. field.drawsBackground = false
  535. field.focusRingType = .none
  536. field.font = .systemFont(ofSize: 14, weight: .regular)
  537. field.textColor = Theme.primaryText
  538. field.delegate = self
  539. field.placeholderAttributedString = NSAttributedString(
  540. string: placeholder,
  541. attributes: [
  542. .foregroundColor: Theme.secondaryText,
  543. .font: NSFont.systemFont(ofSize: 14, weight: .regular)
  544. ]
  545. )
  546. field.cell?.usesSingleLineMode = true
  547. field.cell?.wraps = false
  548. field.cell?.isScrollable = true
  549. field.target = self
  550. field.action = #selector(didSubmitSearch)
  551. }
  552. jobSearchIcon.translatesAutoresizingMaskIntoConstraints = false
  553. jobSearchIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 15, weight: .medium)
  554. jobSearchIcon.image = NSImage(systemSymbolName: "magnifyingglass", accessibilityDescription: "Job search")
  555. jobSearchIcon.contentTintColor = Theme.primaryText
  556. configureField(jobKeywordsField, placeholder: "Job title, keywords, or company")
  557. let ctaHeight: CGFloat = 42
  558. let ctaCorner = ctaHeight / 2
  559. findJobsCTAHost.translatesAutoresizingMaskIntoConstraints = false
  560. findJobsCTAHost.wantsLayer = true
  561. findJobsCTAHost.layer?.masksToBounds = false
  562. findJobsCTAHost.layer?.shadowColor = NSColor.black.cgColor
  563. findJobsCTAHost.layer?.shadowOpacity = 0.16
  564. findJobsCTAHost.layer?.shadowOffset = CGSize(width: 0, height: 2)
  565. findJobsCTAHost.layer?.shadowRadius = 6
  566. findJobsCTAChrome.translatesAutoresizingMaskIntoConstraints = false
  567. findJobsCTAChrome.wantsLayer = true
  568. findJobsCTAChrome.layer?.masksToBounds = true
  569. findJobsCTAChrome.layer?.cornerRadius = ctaCorner
  570. if #available(macOS 11.0, *) {
  571. findJobsCTAChrome.layer?.cornerCurve = .continuous
  572. }
  573. let gradient = CAGradientLayer()
  574. gradient.colors = [Theme.findJobsCTAHighlight.cgColor, Theme.brandBlue.cgColor]
  575. gradient.startPoint = CGPoint(x: 0.5, y: 1)
  576. gradient.endPoint = CGPoint(x: 0.5, y: 0)
  577. findJobsCTAChrome.layer?.addSublayer(gradient)
  578. findJobsCTAGradientLayer = gradient
  579. // Tracks hover over the full pill (the button only covers an inset area), so the gradient darkens whenever the mouse is anywhere over the CTA.
  580. findJobsCTAChrome.pointerCursor = true
  581. findJobsCTAChrome.hoverHandler = { [weak self] hovering in
  582. guard let layer = self?.findJobsCTAGradientLayer else { return }
  583. CATransaction.begin()
  584. CATransaction.setAnimationDuration(0.15)
  585. layer.colors = hovering
  586. ? [Theme.findJobsCTAHighlightHover.cgColor, Theme.brandBlueHover.cgColor]
  587. : [Theme.findJobsCTAHighlight.cgColor, Theme.brandBlue.cgColor]
  588. CATransaction.commit()
  589. }
  590. findJobsButton.translatesAutoresizingMaskIntoConstraints = false
  591. findJobsButton.title = ""
  592. findJobsButton.attributedTitle = NSAttributedString(
  593. string: "Find jobs",
  594. attributes: [
  595. .font: NSFont.systemFont(ofSize: 14, weight: .semibold),
  596. .foregroundColor: Theme.proCTAText,
  597. .kern: 0.35
  598. ]
  599. )
  600. findJobsButton.isBordered = false
  601. findJobsButton.bezelStyle = .rounded
  602. findJobsButton.wantsLayer = true
  603. findJobsButton.layer?.backgroundColor = NSColor.clear.cgColor
  604. findJobsButton.focusRingType = .none
  605. findJobsButton.target = self
  606. findJobsButton.action = #selector(didSubmitSearch)
  607. findJobsButton.setContentHuggingPriority(.required, for: .horizontal)
  608. findJobsButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  609. findJobsCTAHost.addSubview(findJobsCTAChrome)
  610. findJobsCTAHost.addSubview(findJobsButton)
  611. NSLayoutConstraint.activate([
  612. findJobsCTAChrome.leadingAnchor.constraint(equalTo: findJobsCTAHost.leadingAnchor),
  613. findJobsCTAChrome.trailingAnchor.constraint(equalTo: findJobsCTAHost.trailingAnchor),
  614. findJobsCTAChrome.topAnchor.constraint(equalTo: findJobsCTAHost.topAnchor),
  615. findJobsCTAChrome.bottomAnchor.constraint(equalTo: findJobsCTAHost.bottomAnchor),
  616. findJobsButton.leadingAnchor.constraint(equalTo: findJobsCTAHost.leadingAnchor, constant: 14),
  617. findJobsButton.trailingAnchor.constraint(equalTo: findJobsCTAHost.trailingAnchor, constant: -14),
  618. findJobsButton.topAnchor.constraint(equalTo: findJobsCTAHost.topAnchor),
  619. findJobsButton.bottomAnchor.constraint(equalTo: findJobsCTAHost.bottomAnchor)
  620. ])
  621. let keywordsStack = NSStackView(views: [jobSearchIcon, jobKeywordsField])
  622. keywordsStack.orientation = .horizontal
  623. keywordsStack.spacing = 10
  624. keywordsStack.alignment = .centerY
  625. keywordsStack.translatesAutoresizingMaskIntoConstraints = false
  626. keywordsStack.edgeInsets = NSEdgeInsets(top: 0, left: 18, bottom: 0, right: 10)
  627. keywordsStack.setContentHuggingPriority(.defaultLow, for: .horizontal)
  628. let row = NSStackView(views: [keywordsStack, findJobsCTAHost])
  629. row.orientation = .horizontal
  630. row.spacing = 0
  631. row.alignment = .centerY
  632. row.distribution = .fill
  633. row.translatesAutoresizingMaskIntoConstraints = false
  634. row.edgeInsets = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 7)
  635. searchCard.addSubview(row)
  636. NSLayoutConstraint.activate([
  637. searchCard.leadingAnchor.constraint(equalTo: searchBarShadowHost.leadingAnchor),
  638. searchCard.trailingAnchor.constraint(equalTo: searchBarShadowHost.trailingAnchor),
  639. searchCard.topAnchor.constraint(equalTo: searchBarShadowHost.topAnchor),
  640. searchCard.bottomAnchor.constraint(equalTo: searchBarShadowHost.bottomAnchor),
  641. searchBarShadowHost.heightAnchor.constraint(equalToConstant: barHeight),
  642. row.leadingAnchor.constraint(equalTo: searchCard.leadingAnchor),
  643. row.trailingAnchor.constraint(equalTo: searchCard.trailingAnchor),
  644. row.topAnchor.constraint(equalTo: searchCard.topAnchor),
  645. row.bottomAnchor.constraint(equalTo: searchCard.bottomAnchor),
  646. jobSearchIcon.widthAnchor.constraint(equalToConstant: 18),
  647. jobSearchIcon.heightAnchor.constraint(equalToConstant: 18),
  648. findJobsCTAHost.heightAnchor.constraint(equalToConstant: ctaHeight),
  649. findJobsCTAHost.widthAnchor.constraint(greaterThanOrEqualToConstant: 112)
  650. ])
  651. }
  652. private func updateFindJobsCTAShadowPath() {
  653. guard findJobsCTAHost.bounds.width > 0, findJobsCTAHost.bounds.height > 0 else { return }
  654. let r = findJobsCTAHost.bounds
  655. let radius = min(r.height / 2, r.width / 2)
  656. findJobsCTAHost.layer?.shadowPath = CGPath(
  657. roundedRect: r,
  658. cornerWidth: radius,
  659. cornerHeight: radius,
  660. transform: nil
  661. )
  662. }
  663. private func configureNonHomePlaceholder() {
  664. nonHomeHost.translatesAutoresizingMaskIntoConstraints = false
  665. nonHomeHost.wantsLayer = true
  666. nonHomeHost.layer?.backgroundColor = Theme.mainHostBackground.cgColor
  667. nonHomeHost.isHidden = true
  668. nonHomeGenericContainer.translatesAutoresizingMaskIntoConstraints = false
  669. savedJobsPageContainer.translatesAutoresizingMaskIntoConstraints = false
  670. nonHomeHost.addSubview(nonHomeGenericContainer)
  671. nonHomeHost.addSubview(savedJobsPageContainer)
  672. NSLayoutConstraint.activate([
  673. nonHomeGenericContainer.leadingAnchor.constraint(equalTo: nonHomeHost.leadingAnchor),
  674. nonHomeGenericContainer.trailingAnchor.constraint(equalTo: nonHomeHost.trailingAnchor),
  675. nonHomeGenericContainer.topAnchor.constraint(equalTo: nonHomeHost.topAnchor),
  676. nonHomeGenericContainer.bottomAnchor.constraint(equalTo: nonHomeHost.bottomAnchor),
  677. savedJobsPageContainer.leadingAnchor.constraint(equalTo: nonHomeHost.leadingAnchor),
  678. savedJobsPageContainer.trailingAnchor.constraint(equalTo: nonHomeHost.trailingAnchor),
  679. savedJobsPageContainer.topAnchor.constraint(equalTo: nonHomeHost.topAnchor),
  680. savedJobsPageContainer.bottomAnchor.constraint(equalTo: nonHomeHost.bottomAnchor)
  681. ])
  682. nonHomeTitleLabel.font = .systemFont(ofSize: 22, weight: .bold)
  683. nonHomeTitleLabel.textColor = Theme.primaryText
  684. nonHomeTitleLabel.alignment = .center
  685. nonHomeTitleLabel.maximumNumberOfLines = 1
  686. nonHomeSubtitleLabel.font = .systemFont(ofSize: 14, weight: .regular)
  687. nonHomeSubtitleLabel.textColor = Theme.secondaryText
  688. nonHomeSubtitleLabel.alignment = .center
  689. nonHomeSubtitleLabel.maximumNumberOfLines = 0
  690. nonHomeSubtitleLabel.stringValue = "This area is not available in the preview build. Use Home to search jobs."
  691. let genericStack = NSStackView(views: [nonHomeTitleLabel, nonHomeSubtitleLabel])
  692. genericStack.orientation = .vertical
  693. genericStack.spacing = 10
  694. genericStack.alignment = .centerX
  695. genericStack.translatesAutoresizingMaskIntoConstraints = false
  696. nonHomeGenericContainer.addSubview(genericStack)
  697. NSLayoutConstraint.activate([
  698. genericStack.centerXAnchor.constraint(equalTo: nonHomeGenericContainer.centerXAnchor),
  699. genericStack.centerYAnchor.constraint(equalTo: nonHomeGenericContainer.centerYAnchor),
  700. genericStack.leadingAnchor.constraint(greaterThanOrEqualTo: nonHomeGenericContainer.leadingAnchor, constant: 32),
  701. genericStack.trailingAnchor.constraint(lessThanOrEqualTo: nonHomeGenericContainer.trailingAnchor, constant: -32),
  702. nonHomeSubtitleLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 420)
  703. ])
  704. savedJobsPageTitleLabel.font = .systemFont(ofSize: 22, weight: .bold)
  705. savedJobsPageTitleLabel.textColor = Theme.primaryText
  706. savedJobsPageTitleLabel.alignment = .left
  707. savedJobsPageTitleLabel.maximumNumberOfLines = 1
  708. savedJobsPageSubtitleLabel.font = .systemFont(ofSize: 14, weight: .regular)
  709. savedJobsPageSubtitleLabel.textColor = Theme.secondaryText
  710. savedJobsPageSubtitleLabel.alignment = .left
  711. savedJobsPageSubtitleLabel.maximumNumberOfLines = 0
  712. savedJobsDocumentView.translatesAutoresizingMaskIntoConstraints = false
  713. savedJobsStack.orientation = .vertical
  714. savedJobsStack.spacing = 14
  715. savedJobsStack.alignment = .leading
  716. savedJobsStack.distribution = .fill
  717. savedJobsStack.translatesAutoresizingMaskIntoConstraints = false
  718. savedJobsStack.setContentHuggingPriority(.defaultHigh, for: .vertical)
  719. savedJobsStack.setHuggingPriority(.defaultLow, for: .horizontal)
  720. savedJobsDocumentView.addSubview(savedJobsStack)
  721. NSLayoutConstraint.activate([
  722. savedJobsStack.leadingAnchor.constraint(equalTo: savedJobsDocumentView.leadingAnchor),
  723. savedJobsStack.trailingAnchor.constraint(equalTo: savedJobsDocumentView.trailingAnchor),
  724. savedJobsStack.topAnchor.constraint(equalTo: savedJobsDocumentView.topAnchor),
  725. savedJobsStack.bottomAnchor.constraint(equalTo: savedJobsDocumentView.bottomAnchor)
  726. ])
  727. savedJobsScrollView.translatesAutoresizingMaskIntoConstraints = false
  728. savedJobsScrollView.hasVerticalScroller = true
  729. savedJobsScrollView.hasHorizontalScroller = false
  730. savedJobsScrollView.autohidesScrollers = true
  731. savedJobsScrollView.drawsBackground = false
  732. savedJobsScrollView.borderType = .noBorder
  733. savedJobsScrollView.documentView = savedJobsDocumentView
  734. savedJobsScrollView.setContentHuggingPriority(.defaultLow, for: .vertical)
  735. savedJobsScrollView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  736. let savedHeaderStack = NSStackView(views: [savedJobsPageTitleLabel, savedJobsPageSubtitleLabel])
  737. savedHeaderStack.orientation = .vertical
  738. savedHeaderStack.spacing = 6
  739. savedHeaderStack.alignment = .leading
  740. savedHeaderStack.translatesAutoresizingMaskIntoConstraints = false
  741. let savedOuterStack = NSStackView(views: [savedHeaderStack, savedJobsScrollView])
  742. savedOuterStack.orientation = .vertical
  743. savedOuterStack.spacing = 16
  744. // Leading alignment plus explicit column width keeps the title and subtitle on the same edge as the cards.
  745. savedOuterStack.alignment = .leading
  746. savedOuterStack.translatesAutoresizingMaskIntoConstraints = false
  747. savedJobsPageContainer.userInterfaceLayoutDirection = .leftToRight
  748. savedJobsPageContainer.addSubview(savedOuterStack)
  749. NSLayoutConstraint.activate([
  750. savedOuterStack.leadingAnchor.constraint(equalTo: savedJobsPageContainer.leadingAnchor, constant: 32),
  751. savedOuterStack.trailingAnchor.constraint(equalTo: savedJobsPageContainer.trailingAnchor, constant: -32),
  752. savedOuterStack.topAnchor.constraint(equalTo: savedJobsPageContainer.topAnchor, constant: 8),
  753. savedOuterStack.bottomAnchor.constraint(equalTo: savedJobsPageContainer.bottomAnchor),
  754. savedHeaderStack.widthAnchor.constraint(equalTo: savedOuterStack.widthAnchor),
  755. savedJobsScrollView.widthAnchor.constraint(equalTo: savedOuterStack.widthAnchor),
  756. savedJobsDocumentView.topAnchor.constraint(equalTo: savedJobsScrollView.contentView.topAnchor),
  757. savedJobsDocumentView.leadingAnchor.constraint(equalTo: savedJobsScrollView.contentView.leadingAnchor),
  758. savedJobsDocumentView.widthAnchor.constraint(equalTo: savedJobsScrollView.contentView.widthAnchor)
  759. ])
  760. }
  761. private func reloadSavedJobsListings() {
  762. savedJobsStack.arrangedSubviews.forEach {
  763. savedJobsStack.removeArrangedSubview($0)
  764. $0.removeFromSuperview()
  765. }
  766. if savedJobOrder.isEmpty {
  767. savedJobsPageSubtitleLabel.stringValue = "Save jobs from Home to see them here."
  768. let empty = NSTextField(wrappingLabelWithString: "No saved jobs yet. Search on Home, then tap Save on a listing.")
  769. empty.font = .systemFont(ofSize: 14, weight: .regular)
  770. empty.textColor = Theme.secondaryText
  771. empty.alignment = .left
  772. empty.maximumNumberOfLines = 0
  773. empty.translatesAutoresizingMaskIntoConstraints = false
  774. savedJobsStack.addArrangedSubview(empty)
  775. empty.widthAnchor.constraint(equalTo: savedJobsStack.widthAnchor).isActive = true
  776. return
  777. }
  778. savedJobsPageSubtitleLabel.stringValue = "\(savedJobOrder.count) saved \(savedJobOrder.count == 1 ? "position" : "positions")"
  779. for job in savedJobOrder {
  780. let card = makeJobListingCard(job, context: .savedJobsPage)
  781. savedJobsStack.addArrangedSubview(card)
  782. card.widthAnchor.constraint(equalTo: savedJobsStack.widthAnchor).isActive = true
  783. }
  784. }
  785. private func isSavedJobsSidebarIndex(_ index: Int) -> Bool {
  786. guard index >= 0, index < currentSidebarItems.count else { return false }
  787. return currentSidebarItems[index].title == "Saved Jobs"
  788. }
  789. private func isHomeSidebarIndex(_ index: Int) -> Bool {
  790. guard index >= 0, index < currentSidebarItems.count else { return false }
  791. return currentSidebarItems[index].title == "Home"
  792. }
  793. private func updateMainContentVisibility() {
  794. let home = isHomeSidebarIndex(selectedSidebarIndex)
  795. let savedJobs = isSavedJobsSidebarIndex(selectedSidebarIndex)
  796. mainOverlay.isHidden = !home
  797. nonHomeHost.isHidden = home
  798. nonHomeGenericContainer.isHidden = savedJobs
  799. savedJobsPageContainer.isHidden = !savedJobs
  800. if !home, selectedSidebarIndex < currentSidebarItems.count {
  801. if savedJobs {
  802. reloadSavedJobsListings()
  803. } else {
  804. nonHomeTitleLabel.stringValue = currentSidebarItems[selectedSidebarIndex].title
  805. }
  806. }
  807. }
  808. /// Removes result cards or the “no matches” message so a new search starts from a blank listing area.
  809. private func clearJobSearchResultsUI() {
  810. configureJobListings([], noResultsForQuery: nil)
  811. if let doc = jobListingsScrollView.documentView {
  812. doc.scroll(NSPoint(x: 0, y: 0))
  813. }
  814. }
  815. /// Restores the main job-search experience: cleared query and no listings until the user searches again.
  816. private func applyHomeState() {
  817. jobKeywordsField.stringValue = ""
  818. clearJobSearchResultsUI()
  819. window?.makeFirstResponder(nil)
  820. }
  821. private func updateSearchBarShadowPath() {
  822. guard searchBarShadowHost.bounds.width > 0, searchBarShadowHost.bounds.height > 0 else { return }
  823. let r = searchBarShadowHost.bounds
  824. let radius = min(r.height / 2, 27)
  825. searchBarShadowHost.layer?.shadowPath = CGPath(
  826. roundedRect: r,
  827. cornerWidth: radius,
  828. cornerHeight: radius,
  829. transform: nil
  830. )
  831. }
  832. @objc private func didSubmitSearch() {
  833. let query = jobKeywordsField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)
  834. let results = jobsMatchingSearch(query: query, in: catalogJobListings)
  835. let noResultsMessage: String? = (!results.isEmpty || query.isEmpty) ? nil : query
  836. configureJobListings(results, noResultsForQuery: noResultsMessage)
  837. window?.makeFirstResponder(nil)
  838. }
  839. /// Each whitespace-separated token must appear in the title or description (case-insensitive). Empty query returns the full catalog.
  840. private func jobsMatchingSearch(query: String, in jobs: [JobListing]) -> [JobListing] {
  841. let tokens = query
  842. .lowercased()
  843. .split(whereSeparator: { $0.isWhitespace })
  844. .map(String.init)
  845. .filter { !$0.isEmpty }
  846. guard !tokens.isEmpty else { return jobs }
  847. return jobs.filter { job in
  848. let haystack = "\(job.title) \(job.description)".lowercased()
  849. return tokens.allSatisfy { haystack.contains($0) }
  850. }
  851. }
  852. func controlTextDidBeginEditing(_ obj: Notification) {
  853. applySearchFieldInsertionPoint(obj.object)
  854. if (obj.object as? NSTextField) === jobKeywordsField {
  855. clearJobSearchResultsUI()
  856. }
  857. }
  858. func controlTextDidChange(_ obj: Notification) {
  859. applySearchFieldInsertionPoint(obj.object)
  860. }
  861. func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
  862. guard control === jobKeywordsField, commandSelector == #selector(NSResponder.insertNewline(_:)) else {
  863. return false
  864. }
  865. didSubmitSearch()
  866. return true
  867. }
  868. private func applySearchFieldInsertionPoint(_ object: Any?) {
  869. guard let field = object as? NSTextField,
  870. field === jobKeywordsField,
  871. let textView = field.window?.fieldEditor(true, for: field) as? NSTextView else { return }
  872. textView.insertionPointColor = Theme.primaryText
  873. }
  874. private func configureSidebar() {
  875. let items = currentSidebarItems
  876. sidebar.arrangedSubviews.forEach {
  877. sidebar.removeArrangedSubview($0)
  878. $0.removeFromSuperview()
  879. }
  880. let brand = NSTextField(labelWithString: "Indeed AI\nJob Finder")
  881. brand.font = .systemFont(ofSize: 18, weight: .bold)
  882. brand.textColor = Theme.brandBlue
  883. brand.alignment = .left
  884. sidebar.addArrangedSubview(brand)
  885. let titleToMenuSpacer = NSView()
  886. titleToMenuSpacer.translatesAutoresizingMaskIntoConstraints = false
  887. titleToMenuSpacer.heightAnchor.constraint(equalToConstant: 24).isActive = true
  888. sidebar.addArrangedSubview(titleToMenuSpacer)
  889. items.enumerated().forEach { index, item in
  890. let isSelected = index == selectedSidebarIndex
  891. let rowHost = SidebarNavRowView { [weak self] in
  892. self?.selectSidebarItem(at: index)
  893. }
  894. rowHost.translatesAutoresizingMaskIntoConstraints = false
  895. rowHost.wantsLayer = true
  896. rowHost.layer?.cornerRadius = 8
  897. rowHost.restingBackgroundColor = isSelected ? Theme.selectionFill : nil
  898. rowHost.hoverBackgroundColor = isSelected ? Theme.selectionFillHover : Theme.sidebarRowHoverFill
  899. rowHost.setAccessibilityLabel(item.title)
  900. rowHost.setAccessibilityRole(.button)
  901. rowHost.setAccessibilitySelected(isSelected)
  902. let row = NSStackView()
  903. row.orientation = .horizontal
  904. row.spacing = 8
  905. row.alignment = .centerY
  906. row.translatesAutoresizingMaskIntoConstraints = false
  907. let icon = NSImageView()
  908. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .medium)
  909. icon.image = NSImage(systemSymbolName: item.systemImage, accessibilityDescription: item.title)
  910. icon.contentTintColor = isSelected ? Theme.brandBlue : Theme.secondaryText
  911. let text = NSTextField(labelWithString: item.title)
  912. text.font = .systemFont(ofSize: 14, weight: .medium)
  913. text.textColor = isSelected ? Theme.brandBlue : Theme.secondaryText
  914. text.refusesFirstResponder = true
  915. row.addArrangedSubview(icon)
  916. row.addArrangedSubview(text)
  917. if let badge = item.badge {
  918. let badgeField = NSTextField(labelWithString: badge)
  919. badgeField.font = .systemFont(ofSize: 11, weight: .semibold)
  920. badgeField.textColor = Theme.primaryText
  921. badgeField.wantsLayer = true
  922. badgeField.layer?.backgroundColor = Theme.toggleBackground.cgColor
  923. badgeField.layer?.cornerRadius = 8
  924. badgeField.alignment = .center
  925. badgeField.maximumNumberOfLines = 1
  926. badgeField.lineBreakMode = .byClipping
  927. badgeField.refusesFirstResponder = true
  928. badgeField.translatesAutoresizingMaskIntoConstraints = false
  929. badgeField.widthAnchor.constraint(equalToConstant: 42).isActive = true
  930. row.addArrangedSubview(NSView())
  931. row.addArrangedSubview(badgeField)
  932. }
  933. rowHost.addSubview(row)
  934. NSLayoutConstraint.activate([
  935. row.leadingAnchor.constraint(equalTo: rowHost.leadingAnchor, constant: 10),
  936. row.trailingAnchor.constraint(equalTo: rowHost.trailingAnchor, constant: -10),
  937. row.topAnchor.constraint(equalTo: rowHost.topAnchor, constant: 8),
  938. row.bottomAnchor.constraint(equalTo: rowHost.bottomAnchor, constant: -8)
  939. ])
  940. rowHost.setContentHuggingPriority(.defaultLow, for: .horizontal)
  941. sidebar.addArrangedSubview(rowHost)
  942. let sidebarHorizontalInset = sidebar.edgeInsets.left + sidebar.edgeInsets.right
  943. rowHost.widthAnchor.constraint(equalTo: sidebar.widthAnchor, constant: -sidebarHorizontalInset).isActive = true
  944. }
  945. let sidebarBottomSpacer = NSView()
  946. sidebarBottomSpacer.translatesAutoresizingMaskIntoConstraints = false
  947. sidebarBottomSpacer.setContentHuggingPriority(.defaultLow, for: .vertical)
  948. sidebarBottomSpacer.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  949. sidebar.addArrangedSubview(sidebarBottomSpacer)
  950. let upgradeCard = NSView()
  951. upgradeCard.translatesAutoresizingMaskIntoConstraints = false
  952. upgradeCard.wantsLayer = true
  953. upgradeCard.layer?.backgroundColor = Theme.proCardFill.cgColor
  954. upgradeCard.layer?.cornerRadius = 14
  955. upgradeCard.layer?.borderWidth = 1
  956. upgradeCard.layer?.borderColor = Theme.proCardBorder.cgColor
  957. upgradeCard.layer?.masksToBounds = true
  958. let accentBar = NSView()
  959. accentBar.translatesAutoresizingMaskIntoConstraints = false
  960. accentBar.wantsLayer = true
  961. accentBar.layer?.backgroundColor = Theme.proAccent.cgColor
  962. let inner = NSStackView()
  963. inner.translatesAutoresizingMaskIntoConstraints = false
  964. inner.orientation = .vertical
  965. inner.spacing = 10
  966. inner.alignment = .centerX
  967. let proIcon = NSImageView()
  968. proIcon.translatesAutoresizingMaskIntoConstraints = false
  969. proIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .semibold)
  970. proIcon.image = NSImage(systemSymbolName: "sparkles", accessibilityDescription: nil)
  971. proIcon.contentTintColor = Theme.proAccent
  972. let proEyebrow = NSTextField(labelWithString: "Premium")
  973. proEyebrow.font = .systemFont(ofSize: 11, weight: .heavy)
  974. proEyebrow.textColor = Theme.proAccent
  975. proEyebrow.alignment = .center
  976. let eyebrowRow = NSStackView(views: [proIcon, proEyebrow])
  977. eyebrowRow.orientation = .horizontal
  978. eyebrowRow.spacing = 6
  979. eyebrowRow.alignment = .centerY
  980. let headline = NSTextField(labelWithString: "Upgrade to Pro")
  981. headline.font = .systemFont(ofSize: 16, weight: .bold)
  982. headline.textColor = Theme.primaryText
  983. headline.alignment = .center
  984. let upgradeDescription = NSTextField(wrappingLabelWithString: "Unlimited AI matches, smart alerts, and interview prep—all in one place.")
  985. upgradeDescription.font = .systemFont(ofSize: 12, weight: .regular)
  986. upgradeDescription.textColor = Theme.secondaryText
  987. upgradeDescription.alignment = .center
  988. // Sidebar content width is 190pt (218 − edge insets); card must stay within that band.
  989. let cardWidth: CGFloat = 186
  990. let innerContentWidth = cardWidth - 28
  991. upgradeDescription.preferredMaxLayoutWidth = innerContentWidth
  992. let upgradeButton = HoverableButton(title: "Upgrade to Pro", target: self, action: #selector(didTapUpgradeToPro))
  993. upgradeButton.isBordered = false
  994. upgradeButton.bezelStyle = .rounded
  995. upgradeButton.font = .systemFont(ofSize: 13, weight: .bold)
  996. upgradeButton.contentTintColor = Theme.proCTAText
  997. upgradeButton.alignment = .center
  998. upgradeButton.wantsLayer = true
  999. upgradeButton.layer?.backgroundColor = Theme.proCTABackground.cgColor
  1000. upgradeButton.layer?.cornerRadius = 20
  1001. upgradeButton.translatesAutoresizingMaskIntoConstraints = false
  1002. upgradeButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
  1003. upgradeButton.pointerCursor = true
  1004. upgradeButton.hoverHandler = { [weak upgradeButton] hovering in
  1005. upgradeButton?.layer?.backgroundColor = (hovering ? Theme.brandBlueHover : Theme.proCTABackground).cgColor
  1006. }
  1007. inner.addArrangedSubview(eyebrowRow)
  1008. inner.addArrangedSubview(headline)
  1009. inner.addArrangedSubview(upgradeDescription)
  1010. inner.addArrangedSubview(upgradeButton)
  1011. upgradeCard.addSubview(accentBar)
  1012. upgradeCard.addSubview(inner)
  1013. NSLayoutConstraint.activate([
  1014. upgradeCard.widthAnchor.constraint(equalToConstant: cardWidth),
  1015. accentBar.topAnchor.constraint(equalTo: upgradeCard.topAnchor),
  1016. accentBar.leadingAnchor.constraint(equalTo: upgradeCard.leadingAnchor),
  1017. accentBar.trailingAnchor.constraint(equalTo: upgradeCard.trailingAnchor),
  1018. accentBar.heightAnchor.constraint(equalToConstant: 2),
  1019. inner.leadingAnchor.constraint(equalTo: upgradeCard.leadingAnchor, constant: 14),
  1020. inner.trailingAnchor.constraint(equalTo: upgradeCard.trailingAnchor, constant: -14),
  1021. inner.topAnchor.constraint(equalTo: accentBar.bottomAnchor, constant: 12),
  1022. inner.bottomAnchor.constraint(equalTo: upgradeCard.bottomAnchor, constant: -14),
  1023. upgradeButton.widthAnchor.constraint(equalTo: inner.widthAnchor)
  1024. ])
  1025. sidebar.addArrangedSubview(upgradeCard)
  1026. }
  1027. @objc private func didTapUpgradeToPro() {
  1028. guard let url = URL(string: "https://www.indeed.com") else { return }
  1029. NSWorkspace.shared.open(url)
  1030. }
  1031. private func selectSidebarItem(at index: Int) {
  1032. guard index >= 0, index < currentSidebarItems.count else { return }
  1033. let selectingHome = isHomeSidebarIndex(index)
  1034. if index == selectedSidebarIndex {
  1035. if selectingHome {
  1036. applyHomeState()
  1037. }
  1038. return
  1039. }
  1040. selectedSidebarIndex = index
  1041. configureSidebar()
  1042. updateMainContentVisibility()
  1043. if selectingHome {
  1044. applyHomeState()
  1045. }
  1046. }
  1047. }
  1048. /// `NSButton` that carries a `JobListing` for card actions (`representedObject` is unavailable on `NSButton` in this target).
  1049. private final class JobPayloadButton: HoverableButton {
  1050. var jobPayload: JobListing?
  1051. var cardContext: JobListingCardContext = .homeSearchResults
  1052. }
  1053. /// `NSButton` with a tracking area that reports hover transitions and (optionally) swaps in a pointing-hand cursor while hovered.
  1054. private class HoverableButton: NSButton {
  1055. var hoverHandler: ((Bool) -> Void)?
  1056. var pointerCursor: Bool = false
  1057. private(set) var isHovering: Bool = false
  1058. private var trackingArea: NSTrackingArea?
  1059. private var didPushCursor: Bool = false
  1060. override func updateTrackingAreas() {
  1061. super.updateTrackingAreas()
  1062. if let area = trackingArea { removeTrackingArea(area) }
  1063. let area = NSTrackingArea(
  1064. rect: bounds,
  1065. options: [.activeInKeyWindow, .mouseEnteredAndExited, .inVisibleRect],
  1066. owner: self,
  1067. userInfo: nil
  1068. )
  1069. addTrackingArea(area)
  1070. trackingArea = area
  1071. }
  1072. override func mouseEntered(with event: NSEvent) {
  1073. super.mouseEntered(with: event)
  1074. isHovering = true
  1075. hoverHandler?(true)
  1076. if pointerCursor, !didPushCursor {
  1077. NSCursor.pointingHand.push()
  1078. didPushCursor = true
  1079. }
  1080. }
  1081. override func mouseExited(with event: NSEvent) {
  1082. super.mouseExited(with: event)
  1083. isHovering = false
  1084. hoverHandler?(false)
  1085. if didPushCursor {
  1086. NSCursor.pop()
  1087. didPushCursor = false
  1088. }
  1089. }
  1090. override func viewWillMove(toWindow newWindow: NSWindow?) {
  1091. super.viewWillMove(toWindow: newWindow)
  1092. // Guard against an unbalanced cursor stack if the button is removed mid-hover (e.g. job card replaced after a search).
  1093. if newWindow == nil, didPushCursor {
  1094. NSCursor.pop()
  1095. didPushCursor = false
  1096. isHovering = false
  1097. }
  1098. }
  1099. }
  1100. /// `NSView` companion to `HoverableButton`: emits hover transitions and can manage a pointing-hand cursor. Used to track hover over composite controls like the gradient "Find jobs" pill.
  1101. private class HoverableView: NSView {
  1102. var hoverHandler: ((Bool) -> Void)?
  1103. var pointerCursor: Bool = false
  1104. private(set) var isHovering: Bool = false
  1105. private var trackingArea: NSTrackingArea?
  1106. private var didPushCursor: Bool = false
  1107. override func updateTrackingAreas() {
  1108. super.updateTrackingAreas()
  1109. if let area = trackingArea { removeTrackingArea(area) }
  1110. let area = NSTrackingArea(
  1111. rect: bounds,
  1112. options: [.activeInKeyWindow, .mouseEnteredAndExited, .inVisibleRect],
  1113. owner: self,
  1114. userInfo: nil
  1115. )
  1116. addTrackingArea(area)
  1117. trackingArea = area
  1118. }
  1119. override func mouseEntered(with event: NSEvent) {
  1120. super.mouseEntered(with: event)
  1121. isHovering = true
  1122. hoverHandler?(true)
  1123. if pointerCursor, !didPushCursor {
  1124. NSCursor.pointingHand.push()
  1125. didPushCursor = true
  1126. }
  1127. }
  1128. override func mouseExited(with event: NSEvent) {
  1129. super.mouseExited(with: event)
  1130. isHovering = false
  1131. hoverHandler?(false)
  1132. if didPushCursor {
  1133. NSCursor.pop()
  1134. didPushCursor = false
  1135. }
  1136. }
  1137. override func viewWillMove(toWindow newWindow: NSWindow?) {
  1138. super.viewWillMove(toWindow: newWindow)
  1139. if newWindow == nil, didPushCursor {
  1140. NSCursor.pop()
  1141. didPushCursor = false
  1142. isHovering = false
  1143. }
  1144. }
  1145. }
  1146. /// Document view for the job list `NSScrollView`; flipped coordinates keep short result sets aligned to the top of the clip (avoids a large empty band above the cards on macOS).
  1147. private final class JobListingsDocumentView: NSView {
  1148. override var isFlipped: Bool { true }
  1149. }
  1150. /// Captures clicks for the full sidebar pill so icon, label, and padding behave as one tab. Manages its own hover background so non-selected rows highlight subtly on hover without disturbing the selected-row fill.
  1151. private final class SidebarNavRowView: NSView {
  1152. private let onSelect: () -> Void
  1153. var restingBackgroundColor: NSColor? {
  1154. didSet { applyBackground() }
  1155. }
  1156. var hoverBackgroundColor: NSColor?
  1157. private var isHovering: Bool = false
  1158. private var didPushCursor: Bool = false
  1159. init(onSelect: @escaping () -> Void) {
  1160. self.onSelect = onSelect
  1161. super.init(frame: .zero)
  1162. }
  1163. @available(*, unavailable)
  1164. required init?(coder: NSCoder) {
  1165. fatalError("init(coder:) has not been implemented")
  1166. }
  1167. override func hitTest(_ point: NSPoint) -> NSView? {
  1168. guard let superview else { return super.hitTest(point) }
  1169. let local = convert(point, from: superview)
  1170. return bounds.contains(local) ? self : nil
  1171. }
  1172. override func mouseDown(with event: NSEvent) {
  1173. onSelect()
  1174. }
  1175. override func updateTrackingAreas() {
  1176. super.updateTrackingAreas()
  1177. trackingAreas.forEach { removeTrackingArea($0) }
  1178. addTrackingArea(NSTrackingArea(
  1179. rect: bounds,
  1180. options: [.activeInKeyWindow, .mouseEnteredAndExited, .inVisibleRect],
  1181. owner: self,
  1182. userInfo: nil
  1183. ))
  1184. }
  1185. override func mouseEntered(with event: NSEvent) {
  1186. super.mouseEntered(with: event)
  1187. isHovering = true
  1188. applyBackground()
  1189. if !didPushCursor {
  1190. NSCursor.pointingHand.push()
  1191. didPushCursor = true
  1192. }
  1193. }
  1194. override func mouseExited(with event: NSEvent) {
  1195. super.mouseExited(with: event)
  1196. isHovering = false
  1197. applyBackground()
  1198. if didPushCursor {
  1199. NSCursor.pop()
  1200. didPushCursor = false
  1201. }
  1202. }
  1203. override func viewWillMove(toWindow newWindow: NSWindow?) {
  1204. super.viewWillMove(toWindow: newWindow)
  1205. if newWindow == nil, didPushCursor {
  1206. NSCursor.pop()
  1207. didPushCursor = false
  1208. isHovering = false
  1209. }
  1210. }
  1211. private func applyBackground() {
  1212. let color = isHovering ? (hoverBackgroundColor ?? restingBackgroundColor) : restingBackgroundColor
  1213. layer?.backgroundColor = color?.cgColor
  1214. }
  1215. }