Sin descripción

DashboardView.swift 91KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982
  1. //
  2. // DashboardView.swift
  3. // App for Indeed
  4. //
  5. import Cocoa
  6. import QuartzCore
  7. import Security
  8. private enum JobListingCardContext {
  9. case homeSearchResults
  10. case savedJobsPage
  11. }
  12. final class DashboardView: NSView, NSTextFieldDelegate {
  13. /// Indeed.com-inspired neutrals and brand blue (white surfaces, `#2557a7` accent, `#2d2d2d` / `#767676` text, `#d4d2d0` borders).
  14. private enum Theme {
  15. static let brandBlue = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 1)
  16. static let pageBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  17. static let chromeBackground = NSColor(srgbRed: 247 / 255, green: 247 / 255, blue: 247 / 255, alpha: 1)
  18. static let sidebarBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  19. static let mainHostBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  20. /// Subtitle on the welcome hero: readable blue-gray aligned with brand.
  21. static let welcomeSubtitleText = NSColor(srgbRed: 52 / 255, green: 92 / 255, blue: 142 / 255, alpha: 1)
  22. static let selectionFill = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 0.12)
  23. static let cardBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  24. static let toggleBackground = NSColor(srgbRed: 232 / 255, green: 232 / 255, blue: 232 / 255, alpha: 1)
  25. static let primaryText = NSColor(srgbRed: 45 / 255, green: 45 / 255, blue: 45 / 255, alpha: 1)
  26. static let secondaryText = NSColor(srgbRed: 118 / 255, green: 118 / 255, blue: 118 / 255, alpha: 1)
  27. static let tertiaryText = NSColor(srgbRed: 118 / 255, green: 118 / 255, blue: 118 / 255, alpha: 1)
  28. static let border = NSColor(srgbRed: 212 / 255, green: 210 / 255, blue: 208 / 255, alpha: 1)
  29. /// Job search bar outer stroke (charcoal).
  30. static let searchBarBorder = NSColor(srgbRed: 58 / 255, green: 58 / 255, blue: 58 / 255, alpha: 1)
  31. /// Search bar border on hover (brand-tinted, matches focus affordance elsewhere).
  32. static let searchBarBorderHover = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 0.45)
  33. static let proCardFill = NSColor(srgbRed: 239 / 255, green: 244 / 255, blue: 252 / 255, alpha: 1)
  34. static let proCardBorder = NSColor(srgbRed: 212 / 255, green: 210 / 255, blue: 208 / 255, alpha: 1)
  35. static let proAccent = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 1)
  36. static let proCTABackground = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 1)
  37. static let proCTAText = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  38. /// Slightly lighter blue for the top of the search-bar “Find jobs” pill (reads less flat than a solid fill).
  39. static let findJobsCTAHighlight = NSColor(srgbRed: 54 / 255, green: 110 / 255, blue: 198 / 255, alpha: 1)
  40. /// Hover states: darker brand blue, deeper gradient top, stronger tints, and subtle neutral fills used across CTAs, toggles, and the sidebar.
  41. static let brandBlueHover = NSColor(srgbRed: 28 / 255, green: 70 / 255, blue: 140 / 255, alpha: 1)
  42. static let findJobsCTAHighlightHover = NSColor(srgbRed: 44 / 255, green: 94 / 255, blue: 178 / 255, alpha: 1)
  43. static let selectionFillHover = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 0.2)
  44. static let neutralHoverFill = NSColor(srgbRed: 240 / 255, green: 240 / 255, blue: 240 / 255, alpha: 1)
  45. static let sidebarRowHoverFill = NSColor(srgbRed: 0, green: 0, blue: 0, alpha: 0.04)
  46. static let settingsPageBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  47. static let settingsGroupBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  48. static let settingsIconBackground = NSColor(srgbRed: 239 / 255, green: 244 / 255, blue: 252 / 255, alpha: 1)
  49. static let settingsDivider = NSColor(srgbRed: 228 / 255, green: 228 / 255, blue: 228 / 255, alpha: 1)
  50. }
  51. /// Multiline `NSTextField` often ignores `alignment` for wrapped runs; explicit paragraph alignment matches the title.
  52. private static func jobListingDescriptionAttributedString(_ plain: String) -> NSAttributedString {
  53. let paragraph = NSMutableParagraphStyle()
  54. paragraph.alignment = .left
  55. paragraph.lineBreakMode = .byWordWrapping
  56. paragraph.baseWritingDirection = .leftToRight
  57. let font = NSFont.systemFont(ofSize: 13, weight: .regular)
  58. return NSAttributedString(string: plain, attributes: [
  59. .font: font,
  60. .foregroundColor: Theme.secondaryText,
  61. .paragraphStyle: paragraph
  62. ])
  63. }
  64. private let contentStack = NSStackView()
  65. private let chromeContainer = NSView()
  66. private let sidebar = NSStackView()
  67. private let mainHost = NSView()
  68. private let mainOverlay = NSStackView()
  69. private let greetingLabel = NSTextField(labelWithString: "")
  70. private let subtitleLabel = NSTextField(labelWithString: "")
  71. private let searchBarShadowHost = NSView()
  72. private let searchCard = HoverableView()
  73. private let jobSearchIcon = NSImageView()
  74. private let jobKeywordsField = NSTextField()
  75. private let findJobsButton = HoverableButton()
  76. private let findJobsCTAHost = NSView()
  77. private let findJobsCTAChrome = HoverableView()
  78. private var findJobsCTAGradientLayer: CAGradientLayer?
  79. private let chatStatusStack = NSStackView()
  80. private let chatStatusIcon = NSImageView()
  81. private let chatStatusLabel = NSTextField(labelWithString: "Opening the vault...")
  82. private let chatScrollView = NSScrollView()
  83. private let chatDocumentView = JobListingsDocumentView()
  84. private let chatStack = NSStackView()
  85. private let jobListingsScrollView = NSScrollView()
  86. /// Flipped so short result lists stay visually under the search bar instead of leaving a gap above the cards.
  87. private let jobListingsContainer = JobListingsDocumentView()
  88. private let jobListingsStack = NSStackView()
  89. /// Shown when a sidebar item other than Home is selected.
  90. private let nonHomeHost = NSView()
  91. private let nonHomeGenericContainer = NSView()
  92. private let nonHomeTitleLabel = NSTextField(labelWithString: "")
  93. private let nonHomeSubtitleLabel = NSTextField(wrappingLabelWithString: "")
  94. private let savedJobsPageContainer = NSView()
  95. private let savedJobsPageTitleLabel = NSTextField(labelWithString: "Saved Jobs")
  96. private let savedJobsPageSubtitleLabel = NSTextField(wrappingLabelWithString: "")
  97. private let savedJobsScrollView = NSScrollView()
  98. private let savedJobsDocumentView = JobListingsDocumentView()
  99. private let savedJobsStack = NSStackView()
  100. private let settingsPageContainer = NSView()
  101. private let themeControl = NSSegmentedControl(labels: ["System", "Light", "Dark"], trackingMode: .selectOne, target: nil, action: nil)
  102. private var currentSidebarItems: [SidebarItem] = []
  103. private var selectedSidebarIndex: Int = 0
  104. /// Last successful search result set (used when removing a card with the dismiss control).
  105. private var lastSearchResults: [JobListing] = []
  106. private var lastNoResultsQuery: String?
  107. /// Most recently saved jobs appear first; persisted across launches.
  108. private var savedJobOrder: [JobListing] = []
  109. private var chatMessages: [ChatMessage] = []
  110. private var isAwaitingResponse = false
  111. private let jobSearchService = OpenAIJobSearchService()
  112. override init(frame frameRect: NSRect) {
  113. super.init(frame: frameRect)
  114. setupLayout()
  115. }
  116. required init?(coder: NSCoder) {
  117. super.init(coder: coder)
  118. setupLayout()
  119. }
  120. override func layout() {
  121. super.layout()
  122. updateSearchBarShadowPath()
  123. findJobsCTAGradientLayer?.frame = findJobsCTAChrome.bounds
  124. updateFindJobsCTAShadowPath()
  125. updateJobListingDescriptionWidths()
  126. }
  127. func render(_ data: DashboardData) {
  128. greetingLabel.stringValue = "Welcome"
  129. subtitleLabel.stringValue = data.subtitle
  130. currentSidebarItems = data.sidebarItems
  131. if selectedSidebarIndex >= currentSidebarItems.count {
  132. selectedSidebarIndex = max(0, currentSidebarItems.count - 1)
  133. }
  134. configureSidebar()
  135. savedJobOrder = Self.normalizedSavedJobs(SavedJobsStore.load())
  136. configureJobListings([], noResultsForQuery: nil)
  137. resetChatState()
  138. updateMainContentVisibility()
  139. }
  140. private func setupLayout() {
  141. wantsLayer = true
  142. layer?.backgroundColor = Theme.pageBackground.cgColor
  143. contentStack.orientation = .horizontal
  144. contentStack.spacing = 10
  145. contentStack.distribution = .fill
  146. contentStack.translatesAutoresizingMaskIntoConstraints = false
  147. contentStack.alignment = .height
  148. // Tighter chrome insets so panels sit closer to the window edges (especially leading / top under the title bar).
  149. contentStack.edgeInsets = NSEdgeInsets(top: 10, left: 12, bottom: 20, right: 20)
  150. chromeContainer.translatesAutoresizingMaskIntoConstraints = false
  151. chromeContainer.wantsLayer = true
  152. chromeContainer.layer?.backgroundColor = Theme.chromeBackground.cgColor
  153. chromeContainer.layer?.cornerRadius = 0
  154. addSubview(chromeContainer)
  155. chromeContainer.addSubview(contentStack)
  156. sidebar.orientation = .vertical
  157. sidebar.spacing = 10
  158. sidebar.distribution = .fill
  159. sidebar.alignment = .leading
  160. sidebar.wantsLayer = true
  161. sidebar.layer?.backgroundColor = Theme.sidebarBackground.cgColor
  162. sidebar.layer?.cornerRadius = 16
  163. sidebar.edgeInsets = NSEdgeInsets(top: 16, left: 12, bottom: 16, right: 12)
  164. sidebar.translatesAutoresizingMaskIntoConstraints = false
  165. mainHost.translatesAutoresizingMaskIntoConstraints = false
  166. mainHost.wantsLayer = true
  167. mainHost.layer?.backgroundColor = Theme.mainHostBackground.cgColor
  168. mainHost.layer?.cornerRadius = 16
  169. mainHost.layer?.masksToBounds = true
  170. sidebar.setContentHuggingPriority(.required, for: .horizontal)
  171. mainHost.setContentHuggingPriority(.defaultLow, for: .horizontal)
  172. mainHost.addSubview(mainOverlay)
  173. configureNonHomePlaceholder()
  174. mainHost.addSubview(nonHomeHost)
  175. mainOverlay.orientation = .vertical
  176. mainOverlay.spacing = 0
  177. mainOverlay.alignment = .centerX
  178. mainOverlay.distribution = .fill
  179. mainOverlay.translatesAutoresizingMaskIntoConstraints = false
  180. mainOverlay.setContentHuggingPriority(.defaultLow, for: .vertical)
  181. greetingLabel.font = .systemFont(ofSize: 32, weight: .bold)
  182. greetingLabel.textColor = Theme.brandBlue
  183. greetingLabel.alignment = .center
  184. greetingLabel.maximumNumberOfLines = 1
  185. subtitleLabel.font = .systemFont(ofSize: 15, weight: .regular)
  186. subtitleLabel.textColor = Theme.welcomeSubtitleText
  187. subtitleLabel.alignment = .center
  188. subtitleLabel.maximumNumberOfLines = 2
  189. let topInset = NSView()
  190. topInset.translatesAutoresizingMaskIntoConstraints = false
  191. topInset.heightAnchor.constraint(equalToConstant: 18).isActive = true
  192. configureSearchBar()
  193. configureChatViews()
  194. let titleBlock = NSStackView(views: [greetingLabel, subtitleLabel])
  195. titleBlock.orientation = .vertical
  196. titleBlock.spacing = 10
  197. titleBlock.alignment = .centerX
  198. let midSpacer = NSView()
  199. midSpacer.translatesAutoresizingMaskIntoConstraints = false
  200. midSpacer.heightAnchor.constraint(equalToConstant: 20).isActive = true
  201. let listingsTopSpacer = NSView()
  202. listingsTopSpacer.translatesAutoresizingMaskIntoConstraints = false
  203. listingsTopSpacer.heightAnchor.constraint(equalToConstant: 12).isActive = true
  204. jobListingsContainer.translatesAutoresizingMaskIntoConstraints = false
  205. jobListingsStack.orientation = .vertical
  206. jobListingsStack.spacing = 14
  207. // `.leading` keeps cards left-anchored; explicit width constraints below stretch each card across the full row.
  208. jobListingsStack.alignment = .leading
  209. jobListingsStack.distribution = .fill
  210. jobListingsStack.translatesAutoresizingMaskIntoConstraints = false
  211. jobListingsStack.setContentHuggingPriority(.defaultHigh, for: .vertical)
  212. jobListingsStack.setHuggingPriority(.defaultLow, for: .horizontal)
  213. jobListingsContainer.addSubview(jobListingsStack)
  214. NSLayoutConstraint.activate([
  215. jobListingsStack.leadingAnchor.constraint(equalTo: jobListingsContainer.leadingAnchor),
  216. jobListingsStack.trailingAnchor.constraint(equalTo: jobListingsContainer.trailingAnchor),
  217. jobListingsStack.topAnchor.constraint(equalTo: jobListingsContainer.topAnchor),
  218. jobListingsStack.bottomAnchor.constraint(equalTo: jobListingsContainer.bottomAnchor)
  219. ])
  220. jobListingsScrollView.translatesAutoresizingMaskIntoConstraints = false
  221. jobListingsScrollView.hasVerticalScroller = true
  222. jobListingsScrollView.hasHorizontalScroller = false
  223. jobListingsScrollView.autohidesScrollers = true
  224. jobListingsScrollView.drawsBackground = false
  225. jobListingsScrollView.borderType = .noBorder
  226. jobListingsScrollView.documentView = jobListingsContainer
  227. jobListingsScrollView.setContentHuggingPriority(.defaultLow, for: .vertical)
  228. jobListingsScrollView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  229. mainOverlay.addArrangedSubview(topInset)
  230. mainOverlay.addArrangedSubview(titleBlock)
  231. mainOverlay.addArrangedSubview(midSpacer)
  232. mainOverlay.addArrangedSubview(chatStatusStack)
  233. mainOverlay.addArrangedSubview(listingsTopSpacer)
  234. mainOverlay.addArrangedSubview(chatScrollView)
  235. mainOverlay.addArrangedSubview(searchBarShadowHost)
  236. contentStack.addArrangedSubview(sidebar)
  237. contentStack.addArrangedSubview(mainHost)
  238. NSLayoutConstraint.activate([
  239. chromeContainer.leadingAnchor.constraint(equalTo: leadingAnchor),
  240. chromeContainer.trailingAnchor.constraint(equalTo: trailingAnchor),
  241. chromeContainer.topAnchor.constraint(equalTo: topAnchor),
  242. chromeContainer.bottomAnchor.constraint(equalTo: bottomAnchor),
  243. contentStack.leadingAnchor.constraint(equalTo: chromeContainer.leadingAnchor),
  244. contentStack.trailingAnchor.constraint(equalTo: chromeContainer.trailingAnchor),
  245. contentStack.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
  246. contentStack.bottomAnchor.constraint(equalTo: chromeContainer.bottomAnchor),
  247. sidebar.widthAnchor.constraint(equalToConstant: 218),
  248. mainHost.widthAnchor.constraint(greaterThanOrEqualToConstant: 720),
  249. mainOverlay.leadingAnchor.constraint(equalTo: mainHost.leadingAnchor),
  250. mainOverlay.trailingAnchor.constraint(equalTo: mainHost.trailingAnchor),
  251. mainOverlay.topAnchor.constraint(equalTo: mainHost.topAnchor),
  252. mainOverlay.bottomAnchor.constraint(equalTo: mainHost.bottomAnchor, constant: -24),
  253. nonHomeHost.leadingAnchor.constraint(equalTo: mainHost.leadingAnchor),
  254. nonHomeHost.trailingAnchor.constraint(equalTo: mainHost.trailingAnchor),
  255. nonHomeHost.topAnchor.constraint(equalTo: mainHost.topAnchor),
  256. nonHomeHost.bottomAnchor.constraint(equalTo: mainHost.bottomAnchor, constant: -24),
  257. searchBarShadowHost.widthAnchor.constraint(equalTo: mainOverlay.widthAnchor, multiplier: 0.92),
  258. chatStatusStack.widthAnchor.constraint(equalTo: mainOverlay.widthAnchor, multiplier: 0.92),
  259. chatScrollView.widthAnchor.constraint(equalTo: mainOverlay.widthAnchor, multiplier: 0.92),
  260. jobListingsContainer.topAnchor.constraint(equalTo: jobListingsScrollView.contentView.topAnchor),
  261. jobListingsContainer.leadingAnchor.constraint(equalTo: jobListingsScrollView.contentView.leadingAnchor),
  262. jobListingsContainer.widthAnchor.constraint(equalTo: jobListingsScrollView.contentView.widthAnchor),
  263. greetingLabel.leadingAnchor.constraint(equalTo: mainOverlay.leadingAnchor, constant: 16),
  264. greetingLabel.trailingAnchor.constraint(equalTo: mainOverlay.trailingAnchor, constant: -16),
  265. subtitleLabel.leadingAnchor.constraint(equalTo: greetingLabel.leadingAnchor),
  266. subtitleLabel.trailingAnchor.constraint(equalTo: greetingLabel.trailingAnchor)
  267. ])
  268. }
  269. private func configureChatViews() {
  270. chatStatusStack.orientation = .vertical
  271. chatStatusStack.spacing = 6
  272. chatStatusStack.alignment = .centerX
  273. chatStatusStack.translatesAutoresizingMaskIntoConstraints = false
  274. chatStatusIcon.translatesAutoresizingMaskIntoConstraints = false
  275. chatStatusIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 36, weight: .regular)
  276. chatStatusIcon.image = NSImage(systemSymbolName: "sparkles", accessibilityDescription: "Assistant status")
  277. chatStatusIcon.contentTintColor = Theme.brandBlue
  278. chatStatusLabel.font = .systemFont(ofSize: 20, weight: .semibold)
  279. chatStatusLabel.textColor = Theme.primaryText
  280. chatStatusLabel.alignment = .center
  281. chatStatusLabel.maximumNumberOfLines = 1
  282. chatStatusStack.addArrangedSubview(chatStatusIcon)
  283. chatStatusStack.addArrangedSubview(chatStatusLabel)
  284. chatDocumentView.translatesAutoresizingMaskIntoConstraints = false
  285. chatStack.orientation = .vertical
  286. chatStack.spacing = 10
  287. chatStack.alignment = .width
  288. chatStack.distribution = .fill
  289. chatStack.translatesAutoresizingMaskIntoConstraints = false
  290. chatDocumentView.addSubview(chatStack)
  291. NSLayoutConstraint.activate([
  292. chatStack.leadingAnchor.constraint(equalTo: chatDocumentView.leadingAnchor),
  293. chatStack.trailingAnchor.constraint(equalTo: chatDocumentView.trailingAnchor),
  294. chatStack.topAnchor.constraint(equalTo: chatDocumentView.topAnchor, constant: 4),
  295. chatStack.bottomAnchor.constraint(equalTo: chatDocumentView.bottomAnchor, constant: -4)
  296. ])
  297. chatScrollView.translatesAutoresizingMaskIntoConstraints = false
  298. chatScrollView.hasVerticalScroller = true
  299. chatScrollView.hasHorizontalScroller = false
  300. chatScrollView.autohidesScrollers = true
  301. chatScrollView.drawsBackground = false
  302. chatScrollView.borderType = .noBorder
  303. chatScrollView.documentView = chatDocumentView
  304. chatScrollView.setContentHuggingPriority(.defaultLow, for: .vertical)
  305. chatScrollView.heightAnchor.constraint(greaterThanOrEqualToConstant: 260).isActive = true
  306. }
  307. private func updateJobListingDescriptionWidths() {
  308. updateDescriptionColumnWidths(in: jobListingsStack, containerWidth: jobListingsContainer.bounds.width)
  309. updateDescriptionColumnWidths(in: savedJobsStack, containerWidth: savedJobsDocumentView.bounds.width)
  310. }
  311. private func updateDescriptionColumnWidths(in stack: NSStackView, containerWidth: CGFloat) {
  312. guard containerWidth > 1 else { return }
  313. // 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.
  314. let contentHorizontalInset: CGFloat = 32
  315. var didChange = false
  316. for card in stack.arrangedSubviews {
  317. guard let desc = card.viewWithTag(502) as? NSTextField else { continue }
  318. let cardWidth = card.bounds.width > 1 ? card.bounds.width : containerWidth
  319. let fallbackColumn = max(1, cardWidth - contentHorizontalInset)
  320. let columnWidth: CGFloat
  321. if desc.bounds.width > 1 {
  322. columnWidth = desc.bounds.width
  323. } else if let column = desc.superview, column.bounds.width > 1 {
  324. columnWidth = column.bounds.width
  325. } else {
  326. columnWidth = fallbackColumn
  327. }
  328. if abs(desc.preferredMaxLayoutWidth - columnWidth) > 0.5 {
  329. desc.preferredMaxLayoutWidth = columnWidth
  330. desc.invalidateIntrinsicContentSize()
  331. didChange = true
  332. }
  333. }
  334. if didChange {
  335. stack.needsLayout = true
  336. }
  337. }
  338. private func configureJobListings(_ jobs: [JobListing], noResultsForQuery: String?, updateLastResults: Bool = true) {
  339. if updateLastResults {
  340. lastSearchResults = jobs
  341. lastNoResultsQuery = noResultsForQuery
  342. }
  343. jobListingsStack.arrangedSubviews.forEach {
  344. jobListingsStack.removeArrangedSubview($0)
  345. $0.removeFromSuperview()
  346. }
  347. if jobs.isEmpty, let query = noResultsForQuery, !query.isEmpty {
  348. let empty = NSTextField(wrappingLabelWithString: "No jobs match “\(query)”. Try different keywords or browse the full list with an empty search.")
  349. empty.font = .systemFont(ofSize: 14, weight: .regular)
  350. empty.textColor = Theme.secondaryText
  351. empty.alignment = .center
  352. empty.maximumNumberOfLines = 0
  353. empty.translatesAutoresizingMaskIntoConstraints = false
  354. jobListingsStack.addArrangedSubview(empty)
  355. empty.widthAnchor.constraint(equalTo: jobListingsStack.widthAnchor).isActive = true
  356. return
  357. }
  358. for job in jobs {
  359. let card = makeJobListingCard(job, context: .homeSearchResults)
  360. jobListingsStack.addArrangedSubview(card)
  361. // Force every card to span the full row instead of hugging its intrinsic content width.
  362. card.widthAnchor.constraint(equalTo: jobListingsStack.widthAnchor).isActive = true
  363. }
  364. }
  365. private static func normalizedSavedJobs(_ jobs: [JobListing]) -> [JobListing] {
  366. var seen = Set<JobListing>()
  367. var out: [JobListing] = []
  368. for job in jobs where seen.insert(job).inserted {
  369. out.append(job)
  370. }
  371. return out
  372. }
  373. private func isJobSaved(_ job: JobListing) -> Bool {
  374. savedJobOrder.contains(job)
  375. }
  376. private func persistSavedJobs() {
  377. SavedJobsStore.save(savedJobOrder)
  378. }
  379. private func applySavedState(_ saved: Bool, for job: JobListing) {
  380. if saved {
  381. savedJobOrder.removeAll { $0 == job }
  382. savedJobOrder.insert(job, at: 0)
  383. } else {
  384. savedJobOrder.removeAll { $0 == job }
  385. }
  386. persistSavedJobs()
  387. }
  388. private func makeJobListingCard(_ job: JobListing, context: JobListingCardContext) -> NSView {
  389. let card = NSView()
  390. card.translatesAutoresizingMaskIntoConstraints = false
  391. card.wantsLayer = true
  392. card.layer?.backgroundColor = Theme.cardBackground.cgColor
  393. card.layer?.cornerRadius = 12
  394. card.layer?.borderWidth = 1
  395. card.layer?.borderColor = Theme.border.cgColor
  396. card.layer?.masksToBounds = true
  397. let titleField = NSTextField(labelWithString: job.title)
  398. titleField.font = .systemFont(ofSize: 16, weight: .semibold)
  399. titleField.textColor = Theme.primaryText
  400. titleField.maximumNumberOfLines = 2
  401. titleField.lineBreakMode = .byWordWrapping
  402. titleField.alignment = .left
  403. titleField.translatesAutoresizingMaskIntoConstraints = false
  404. let descriptionField = NSTextField(wrappingLabelWithString: job.description)
  405. descriptionField.font = .systemFont(ofSize: 13, weight: .regular)
  406. descriptionField.textColor = Theme.secondaryText
  407. descriptionField.maximumNumberOfLines = 0
  408. descriptionField.alignment = .left
  409. descriptionField.lineBreakMode = .byWordWrapping
  410. descriptionField.baseWritingDirection = .leftToRight
  411. descriptionField.attributedStringValue = Self.jobListingDescriptionAttributedString(job.description)
  412. if let cell = descriptionField.cell as? NSTextFieldCell {
  413. cell.alignment = .left
  414. cell.wraps = true
  415. }
  416. descriptionField.setContentHuggingPriority(.defaultLow, for: .horizontal)
  417. descriptionField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  418. descriptionField.tag = 502
  419. descriptionField.translatesAutoresizingMaskIntoConstraints = false
  420. let applyButton = JobPayloadButton(title: "Apply", target: self, action: #selector(didTapJobApply(_:)))
  421. applyButton.jobPayload = job
  422. applyButton.cardContext = context
  423. applyButton.isBordered = false
  424. applyButton.bezelStyle = .rounded
  425. applyButton.font = .systemFont(ofSize: 13, weight: .semibold)
  426. applyButton.wantsLayer = true
  427. applyButton.layer?.cornerRadius = 6
  428. applyButton.layer?.backgroundColor = Theme.brandBlue.cgColor
  429. applyButton.contentTintColor = Theme.proCTAText
  430. applyButton.focusRingType = .none
  431. applyButton.pointerCursor = true
  432. applyButton.hoverHandler = { [weak applyButton] hovering in
  433. applyButton?.layer?.backgroundColor = (hovering ? Theme.brandBlueHover : Theme.brandBlue).cgColor
  434. }
  435. applyButton.setContentHuggingPriority(.required, for: .horizontal)
  436. applyButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  437. let savedOn = isJobSaved(job)
  438. let savedButton = JobPayloadButton(title: savedOn ? "Saved" : "Save", target: self, action: #selector(didTapJobSaved(_:)))
  439. savedButton.jobPayload = job
  440. savedButton.cardContext = context
  441. savedButton.setButtonType(.toggle)
  442. savedButton.isBordered = false
  443. savedButton.bezelStyle = .rounded
  444. savedButton.font = .systemFont(ofSize: 13, weight: .semibold)
  445. savedButton.focusRingType = .none
  446. savedButton.state = savedOn ? .on : .off
  447. savedButton.pointerCursor = true
  448. savedButton.hoverHandler = { [weak self, weak savedButton] _ in
  449. guard let savedButton = savedButton else { return }
  450. self?.styleJobSavedButton(savedButton)
  451. }
  452. styleJobSavedButton(savedButton)
  453. savedButton.setContentHuggingPriority(.required, for: .horizontal)
  454. savedButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  455. let dismissButton = JobPayloadButton()
  456. dismissButton.jobPayload = job
  457. dismissButton.cardContext = context
  458. dismissButton.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Dismiss")
  459. dismissButton.imagePosition = .imageOnly
  460. dismissButton.imageScaling = .scaleProportionallyDown
  461. dismissButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .semibold)
  462. dismissButton.isBordered = false
  463. dismissButton.bezelStyle = .rounded
  464. dismissButton.contentTintColor = Theme.secondaryText
  465. dismissButton.target = self
  466. dismissButton.action = #selector(didTapJobDismiss(_:))
  467. dismissButton.toolTip = context == .savedJobsPage ? "Remove from saved" : "Dismiss"
  468. dismissButton.focusRingType = .none
  469. dismissButton.wantsLayer = true
  470. dismissButton.layer?.cornerRadius = 14
  471. dismissButton.layer?.backgroundColor = NSColor.clear.cgColor
  472. dismissButton.pointerCursor = true
  473. dismissButton.hoverHandler = { [weak dismissButton] hovering in
  474. dismissButton?.layer?.backgroundColor = (hovering ? Theme.neutralHoverFill : NSColor.clear).cgColor
  475. dismissButton?.contentTintColor = hovering ? Theme.primaryText : Theme.secondaryText
  476. }
  477. dismissButton.setContentHuggingPriority(.required, for: .horizontal)
  478. let buttonRow = NSStackView(views: [applyButton, savedButton, dismissButton])
  479. buttonRow.orientation = .horizontal
  480. buttonRow.spacing = 8
  481. buttonRow.alignment = .centerY
  482. buttonRow.translatesAutoresizingMaskIntoConstraints = false
  483. buttonRow.setContentHuggingPriority(.required, for: .horizontal)
  484. buttonRow.setContentCompressionResistancePriority(.required, for: .horizontal)
  485. // Title hugs the leading edge; a low–hugging-priority spacer absorbs remaining width so buttons stay trailing.
  486. titleField.setContentHuggingPriority(.defaultHigh, for: .horizontal)
  487. titleField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  488. let titleRowSpacer = NSView()
  489. titleRowSpacer.translatesAutoresizingMaskIntoConstraints = false
  490. titleRowSpacer.setContentHuggingPriority(NSLayoutConstraint.Priority(1), for: .horizontal)
  491. titleRowSpacer.setContentCompressionResistancePriority(NSLayoutConstraint.Priority(1), for: .horizontal)
  492. let titleAndActionsRow = NSStackView(views: [titleField, titleRowSpacer, buttonRow])
  493. titleAndActionsRow.orientation = .horizontal
  494. titleAndActionsRow.spacing = 0
  495. titleAndActionsRow.setCustomSpacing(14, after: titleRowSpacer)
  496. titleAndActionsRow.alignment = .centerY
  497. titleAndActionsRow.distribution = .fill
  498. titleAndActionsRow.userInterfaceLayoutDirection = .leftToRight
  499. titleAndActionsRow.translatesAutoresizingMaskIntoConstraints = false
  500. let contentColumn = NSStackView(views: [titleAndActionsRow, descriptionField])
  501. contentColumn.orientation = .vertical
  502. contentColumn.spacing = 6
  503. contentColumn.alignment = .width
  504. contentColumn.translatesAutoresizingMaskIntoConstraints = false
  505. card.addSubview(contentColumn)
  506. NSLayoutConstraint.activate([
  507. contentColumn.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 16),
  508. contentColumn.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -16),
  509. contentColumn.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
  510. contentColumn.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -14),
  511. applyButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 72),
  512. applyButton.heightAnchor.constraint(equalToConstant: 28),
  513. savedButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 72),
  514. savedButton.heightAnchor.constraint(equalToConstant: 28),
  515. dismissButton.widthAnchor.constraint(equalToConstant: 28),
  516. dismissButton.heightAnchor.constraint(equalToConstant: 28),
  517. descriptionField.widthAnchor.constraint(equalTo: contentColumn.widthAnchor)
  518. ])
  519. return card
  520. }
  521. private func styleJobSavedButton(_ button: NSButton) {
  522. button.wantsLayer = true
  523. button.layer?.cornerRadius = 6
  524. let on = button.state == .on
  525. let hovering = (button as? HoverableButton)?.isHovering ?? false
  526. if on {
  527. button.layer?.backgroundColor = (hovering ? Theme.selectionFillHover : Theme.selectionFill).cgColor
  528. button.layer?.borderWidth = 1
  529. button.layer?.borderColor = Theme.brandBlue.cgColor
  530. button.contentTintColor = Theme.brandBlue
  531. } else {
  532. button.layer?.backgroundColor = (hovering ? Theme.neutralHoverFill : Theme.cardBackground).cgColor
  533. button.layer?.borderWidth = 1
  534. button.layer?.borderColor = Theme.border.cgColor
  535. button.contentTintColor = Theme.primaryText
  536. }
  537. }
  538. @objc private func didTapJobApply(_ sender: NSButton) {
  539. guard let job = (sender as? JobPayloadButton)?.jobPayload else { return }
  540. if let rawURL = job.url, let url = URL(string: rawURL), !rawURL.isEmpty {
  541. NSWorkspace.shared.open(url)
  542. return
  543. }
  544. let allowed = CharacterSet.urlQueryAllowed
  545. let q = job.title.addingPercentEncoding(withAllowedCharacters: allowed) ?? ""
  546. guard let url = URL(string: "https://www.indeed.com/jobs?q=\(q)") else { return }
  547. NSWorkspace.shared.open(url)
  548. }
  549. @objc private func didTapJobSaved(_ sender: NSButton) {
  550. guard let job = (sender as? JobPayloadButton)?.jobPayload else { return }
  551. let willSave = !isJobSaved(job)
  552. applySavedState(willSave, for: job)
  553. sender.state = willSave ? .on : .off
  554. sender.title = willSave ? "Saved" : "Save"
  555. styleJobSavedButton(sender)
  556. if isSavedJobsSidebarIndex(selectedSidebarIndex) {
  557. reloadSavedJobsListings()
  558. }
  559. }
  560. @objc private func didTapJobDismiss(_ sender: NSButton) {
  561. guard let button = sender as? JobPayloadButton, let job = button.jobPayload else { return }
  562. switch button.cardContext {
  563. case .homeSearchResults:
  564. lastSearchResults.removeAll { $0 == job }
  565. configureJobListings(lastSearchResults, noResultsForQuery: lastNoResultsQuery)
  566. case .savedJobsPage:
  567. applySavedState(false, for: job)
  568. reloadSavedJobsListings()
  569. if isHomeSidebarIndex(selectedSidebarIndex), !lastSearchResults.isEmpty {
  570. configureJobListings(lastSearchResults, noResultsForQuery: lastNoResultsQuery, updateLastResults: false)
  571. }
  572. }
  573. }
  574. private func configureSearchBar() {
  575. let pillCorner: CGFloat = 27
  576. let barHeight: CGFloat = 54
  577. searchBarShadowHost.translatesAutoresizingMaskIntoConstraints = false
  578. searchBarShadowHost.wantsLayer = true
  579. searchBarShadowHost.layer?.masksToBounds = false
  580. searchBarShadowHost.layer?.shadowColor = NSColor.black.withAlphaComponent(0.18).cgColor
  581. searchBarShadowHost.layer?.shadowOffset = CGSize(width: 0, height: 2)
  582. searchBarShadowHost.layer?.shadowRadius = 10
  583. searchBarShadowHost.layer?.shadowOpacity = 1
  584. searchBarShadowHost.setContentHuggingPriority(.defaultHigh, for: .vertical)
  585. searchCard.translatesAutoresizingMaskIntoConstraints = false
  586. searchCard.wantsLayer = true
  587. searchCard.layer?.backgroundColor = Theme.cardBackground.cgColor
  588. searchCard.layer?.cornerRadius = pillCorner
  589. searchCard.layer?.borderWidth = 1
  590. searchCard.layer?.borderColor = Theme.searchBarBorder.cgColor
  591. searchCard.layer?.masksToBounds = true
  592. searchCard.hoverHandler = { [weak self] hovering in
  593. guard let self else { return }
  594. CATransaction.begin()
  595. CATransaction.setAnimationDuration(0.15)
  596. self.searchCard.layer?.backgroundColor = (hovering ? Theme.neutralHoverFill : Theme.cardBackground).cgColor
  597. self.searchCard.layer?.borderColor = (hovering ? Theme.searchBarBorderHover : Theme.searchBarBorder).cgColor
  598. self.searchBarShadowHost.layer?.shadowColor = NSColor.black.withAlphaComponent(hovering ? 0.24 : 0.18).cgColor
  599. self.searchBarShadowHost.layer?.shadowRadius = hovering ? 12 : 10
  600. CATransaction.commit()
  601. }
  602. searchBarShadowHost.addSubview(searchCard)
  603. func configureField(_ field: NSTextField, placeholder: String) {
  604. field.translatesAutoresizingMaskIntoConstraints = false
  605. field.isBordered = false
  606. field.drawsBackground = false
  607. field.focusRingType = .none
  608. field.font = .systemFont(ofSize: 14, weight: .regular)
  609. field.textColor = Theme.primaryText
  610. field.delegate = self
  611. field.placeholderAttributedString = NSAttributedString(
  612. string: placeholder,
  613. attributes: [
  614. .foregroundColor: Theme.secondaryText,
  615. .font: NSFont.systemFont(ofSize: 14, weight: .regular)
  616. ]
  617. )
  618. field.cell?.usesSingleLineMode = true
  619. field.cell?.wraps = false
  620. field.cell?.isScrollable = true
  621. field.target = self
  622. field.action = #selector(didSubmitSearch)
  623. }
  624. jobSearchIcon.translatesAutoresizingMaskIntoConstraints = false
  625. jobSearchIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 15, weight: .medium)
  626. jobSearchIcon.image = NSImage(systemSymbolName: "magnifyingglass", accessibilityDescription: "Job search")
  627. jobSearchIcon.contentTintColor = Theme.primaryText
  628. configureField(jobKeywordsField, placeholder: "Ask for roles, skills, salary, or job descriptions...")
  629. let ctaHeight: CGFloat = 42
  630. let ctaCorner = ctaHeight / 2
  631. findJobsCTAHost.translatesAutoresizingMaskIntoConstraints = false
  632. findJobsCTAHost.wantsLayer = true
  633. findJobsCTAHost.layer?.masksToBounds = false
  634. findJobsCTAHost.layer?.shadowColor = NSColor.black.cgColor
  635. findJobsCTAHost.layer?.shadowOpacity = 0.16
  636. findJobsCTAHost.layer?.shadowOffset = CGSize(width: 0, height: 2)
  637. findJobsCTAHost.layer?.shadowRadius = 6
  638. findJobsCTAChrome.translatesAutoresizingMaskIntoConstraints = false
  639. findJobsCTAChrome.wantsLayer = true
  640. findJobsCTAChrome.layer?.masksToBounds = true
  641. findJobsCTAChrome.layer?.cornerRadius = ctaCorner
  642. if #available(macOS 11.0, *) {
  643. findJobsCTAChrome.layer?.cornerCurve = .continuous
  644. }
  645. let gradient = CAGradientLayer()
  646. gradient.colors = [Theme.findJobsCTAHighlight.cgColor, Theme.brandBlue.cgColor]
  647. gradient.startPoint = CGPoint(x: 0.5, y: 1)
  648. gradient.endPoint = CGPoint(x: 0.5, y: 0)
  649. findJobsCTAChrome.layer?.addSublayer(gradient)
  650. findJobsCTAGradientLayer = gradient
  651. // 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.
  652. findJobsCTAChrome.pointerCursor = true
  653. findJobsCTAChrome.hoverHandler = { [weak self] hovering in
  654. guard let layer = self?.findJobsCTAGradientLayer else { return }
  655. CATransaction.begin()
  656. CATransaction.setAnimationDuration(0.15)
  657. layer.colors = hovering
  658. ? [Theme.findJobsCTAHighlightHover.cgColor, Theme.brandBlueHover.cgColor]
  659. : [Theme.findJobsCTAHighlight.cgColor, Theme.brandBlue.cgColor]
  660. CATransaction.commit()
  661. }
  662. findJobsButton.translatesAutoresizingMaskIntoConstraints = false
  663. findJobsButton.title = ""
  664. findJobsButton.attributedTitle = NSAttributedString(
  665. string: "Send",
  666. attributes: [
  667. .font: NSFont.systemFont(ofSize: 14, weight: .semibold),
  668. .foregroundColor: Theme.proCTAText,
  669. .kern: 0.35
  670. ]
  671. )
  672. findJobsButton.isBordered = false
  673. findJobsButton.bezelStyle = .rounded
  674. findJobsButton.wantsLayer = true
  675. findJobsButton.layer?.backgroundColor = NSColor.clear.cgColor
  676. findJobsButton.focusRingType = .none
  677. findJobsButton.target = self
  678. findJobsButton.action = #selector(didSubmitSearch)
  679. findJobsButton.setContentHuggingPriority(.required, for: .horizontal)
  680. findJobsButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  681. findJobsCTAHost.addSubview(findJobsCTAChrome)
  682. findJobsCTAHost.addSubview(findJobsButton)
  683. NSLayoutConstraint.activate([
  684. findJobsCTAChrome.leadingAnchor.constraint(equalTo: findJobsCTAHost.leadingAnchor),
  685. findJobsCTAChrome.trailingAnchor.constraint(equalTo: findJobsCTAHost.trailingAnchor),
  686. findJobsCTAChrome.topAnchor.constraint(equalTo: findJobsCTAHost.topAnchor),
  687. findJobsCTAChrome.bottomAnchor.constraint(equalTo: findJobsCTAHost.bottomAnchor),
  688. findJobsButton.leadingAnchor.constraint(equalTo: findJobsCTAHost.leadingAnchor, constant: 14),
  689. findJobsButton.trailingAnchor.constraint(equalTo: findJobsCTAHost.trailingAnchor, constant: -14),
  690. findJobsButton.topAnchor.constraint(equalTo: findJobsCTAHost.topAnchor),
  691. findJobsButton.bottomAnchor.constraint(equalTo: findJobsCTAHost.bottomAnchor)
  692. ])
  693. let keywordsStack = NSStackView(views: [jobSearchIcon, jobKeywordsField])
  694. keywordsStack.orientation = .horizontal
  695. keywordsStack.spacing = 10
  696. keywordsStack.alignment = .centerY
  697. keywordsStack.translatesAutoresizingMaskIntoConstraints = false
  698. keywordsStack.edgeInsets = NSEdgeInsets(top: 0, left: 18, bottom: 0, right: 10)
  699. keywordsStack.setContentHuggingPriority(.defaultLow, for: .horizontal)
  700. let row = NSStackView(views: [keywordsStack, findJobsCTAHost])
  701. row.orientation = .horizontal
  702. row.spacing = 0
  703. row.alignment = .centerY
  704. row.distribution = .fill
  705. row.translatesAutoresizingMaskIntoConstraints = false
  706. row.edgeInsets = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 7)
  707. searchCard.addSubview(row)
  708. NSLayoutConstraint.activate([
  709. searchCard.leadingAnchor.constraint(equalTo: searchBarShadowHost.leadingAnchor),
  710. searchCard.trailingAnchor.constraint(equalTo: searchBarShadowHost.trailingAnchor),
  711. searchCard.topAnchor.constraint(equalTo: searchBarShadowHost.topAnchor),
  712. searchCard.bottomAnchor.constraint(equalTo: searchBarShadowHost.bottomAnchor),
  713. searchBarShadowHost.heightAnchor.constraint(equalToConstant: barHeight),
  714. row.leadingAnchor.constraint(equalTo: searchCard.leadingAnchor),
  715. row.trailingAnchor.constraint(equalTo: searchCard.trailingAnchor),
  716. row.topAnchor.constraint(equalTo: searchCard.topAnchor),
  717. row.bottomAnchor.constraint(equalTo: searchCard.bottomAnchor),
  718. jobSearchIcon.widthAnchor.constraint(equalToConstant: 18),
  719. jobSearchIcon.heightAnchor.constraint(equalToConstant: 18),
  720. findJobsCTAHost.heightAnchor.constraint(equalToConstant: ctaHeight),
  721. findJobsCTAHost.widthAnchor.constraint(greaterThanOrEqualToConstant: 112)
  722. ])
  723. searchCard.hoverHandler = nil
  724. }
  725. private func updateFindJobsCTAShadowPath() {
  726. guard findJobsCTAHost.bounds.width > 0, findJobsCTAHost.bounds.height > 0 else { return }
  727. let r = findJobsCTAHost.bounds
  728. let radius = min(r.height / 2, r.width / 2)
  729. findJobsCTAHost.layer?.shadowPath = CGPath(
  730. roundedRect: r,
  731. cornerWidth: radius,
  732. cornerHeight: radius,
  733. transform: nil
  734. )
  735. }
  736. private func configureNonHomePlaceholder() {
  737. nonHomeHost.translatesAutoresizingMaskIntoConstraints = false
  738. nonHomeHost.wantsLayer = true
  739. nonHomeHost.layer?.backgroundColor = Theme.mainHostBackground.cgColor
  740. nonHomeHost.isHidden = true
  741. nonHomeGenericContainer.translatesAutoresizingMaskIntoConstraints = false
  742. savedJobsPageContainer.translatesAutoresizingMaskIntoConstraints = false
  743. settingsPageContainer.translatesAutoresizingMaskIntoConstraints = false
  744. nonHomeHost.addSubview(nonHomeGenericContainer)
  745. nonHomeHost.addSubview(savedJobsPageContainer)
  746. nonHomeHost.addSubview(settingsPageContainer)
  747. NSLayoutConstraint.activate([
  748. nonHomeGenericContainer.leadingAnchor.constraint(equalTo: nonHomeHost.leadingAnchor),
  749. nonHomeGenericContainer.trailingAnchor.constraint(equalTo: nonHomeHost.trailingAnchor),
  750. nonHomeGenericContainer.topAnchor.constraint(equalTo: nonHomeHost.topAnchor),
  751. nonHomeGenericContainer.bottomAnchor.constraint(equalTo: nonHomeHost.bottomAnchor),
  752. savedJobsPageContainer.leadingAnchor.constraint(equalTo: nonHomeHost.leadingAnchor),
  753. savedJobsPageContainer.trailingAnchor.constraint(equalTo: nonHomeHost.trailingAnchor),
  754. savedJobsPageContainer.topAnchor.constraint(equalTo: nonHomeHost.topAnchor),
  755. savedJobsPageContainer.bottomAnchor.constraint(equalTo: nonHomeHost.bottomAnchor),
  756. settingsPageContainer.leadingAnchor.constraint(equalTo: nonHomeHost.leadingAnchor),
  757. settingsPageContainer.trailingAnchor.constraint(equalTo: nonHomeHost.trailingAnchor),
  758. settingsPageContainer.topAnchor.constraint(equalTo: nonHomeHost.topAnchor),
  759. settingsPageContainer.bottomAnchor.constraint(equalTo: nonHomeHost.bottomAnchor)
  760. ])
  761. nonHomeTitleLabel.font = .systemFont(ofSize: 22, weight: .bold)
  762. nonHomeTitleLabel.textColor = Theme.primaryText
  763. nonHomeTitleLabel.alignment = .center
  764. nonHomeTitleLabel.maximumNumberOfLines = 1
  765. nonHomeSubtitleLabel.font = .systemFont(ofSize: 14, weight: .regular)
  766. nonHomeSubtitleLabel.textColor = Theme.secondaryText
  767. nonHomeSubtitleLabel.alignment = .center
  768. nonHomeSubtitleLabel.maximumNumberOfLines = 0
  769. nonHomeSubtitleLabel.stringValue = "This area is not available in the preview build. Use Home to search jobs."
  770. let genericStack = NSStackView(views: [nonHomeTitleLabel, nonHomeSubtitleLabel])
  771. genericStack.orientation = .vertical
  772. genericStack.spacing = 10
  773. genericStack.alignment = .centerX
  774. genericStack.translatesAutoresizingMaskIntoConstraints = false
  775. nonHomeGenericContainer.addSubview(genericStack)
  776. NSLayoutConstraint.activate([
  777. genericStack.centerXAnchor.constraint(equalTo: nonHomeGenericContainer.centerXAnchor),
  778. genericStack.centerYAnchor.constraint(equalTo: nonHomeGenericContainer.centerYAnchor),
  779. genericStack.leadingAnchor.constraint(greaterThanOrEqualTo: nonHomeGenericContainer.leadingAnchor, constant: 32),
  780. genericStack.trailingAnchor.constraint(lessThanOrEqualTo: nonHomeGenericContainer.trailingAnchor, constant: -32),
  781. nonHomeSubtitleLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 420)
  782. ])
  783. savedJobsPageTitleLabel.font = .systemFont(ofSize: 22, weight: .bold)
  784. savedJobsPageTitleLabel.textColor = Theme.primaryText
  785. savedJobsPageTitleLabel.alignment = .left
  786. savedJobsPageTitleLabel.maximumNumberOfLines = 1
  787. savedJobsPageSubtitleLabel.font = .systemFont(ofSize: 14, weight: .regular)
  788. savedJobsPageSubtitleLabel.textColor = Theme.secondaryText
  789. savedJobsPageSubtitleLabel.alignment = .left
  790. savedJobsPageSubtitleLabel.maximumNumberOfLines = 0
  791. savedJobsDocumentView.translatesAutoresizingMaskIntoConstraints = false
  792. savedJobsStack.orientation = .vertical
  793. savedJobsStack.spacing = 14
  794. savedJobsStack.alignment = .leading
  795. savedJobsStack.distribution = .fill
  796. savedJobsStack.translatesAutoresizingMaskIntoConstraints = false
  797. savedJobsStack.setContentHuggingPriority(.defaultHigh, for: .vertical)
  798. savedJobsStack.setHuggingPriority(.defaultLow, for: .horizontal)
  799. savedJobsDocumentView.addSubview(savedJobsStack)
  800. NSLayoutConstraint.activate([
  801. savedJobsStack.leadingAnchor.constraint(equalTo: savedJobsDocumentView.leadingAnchor),
  802. savedJobsStack.trailingAnchor.constraint(equalTo: savedJobsDocumentView.trailingAnchor),
  803. savedJobsStack.topAnchor.constraint(equalTo: savedJobsDocumentView.topAnchor),
  804. savedJobsStack.bottomAnchor.constraint(equalTo: savedJobsDocumentView.bottomAnchor)
  805. ])
  806. savedJobsScrollView.translatesAutoresizingMaskIntoConstraints = false
  807. savedJobsScrollView.hasVerticalScroller = true
  808. savedJobsScrollView.hasHorizontalScroller = false
  809. savedJobsScrollView.autohidesScrollers = true
  810. savedJobsScrollView.drawsBackground = false
  811. savedJobsScrollView.borderType = .noBorder
  812. savedJobsScrollView.documentView = savedJobsDocumentView
  813. savedJobsScrollView.setContentHuggingPriority(.defaultLow, for: .vertical)
  814. savedJobsScrollView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  815. let savedHeaderStack = NSStackView(views: [savedJobsPageTitleLabel, savedJobsPageSubtitleLabel])
  816. savedHeaderStack.orientation = .vertical
  817. savedHeaderStack.spacing = 6
  818. savedHeaderStack.alignment = .leading
  819. savedHeaderStack.translatesAutoresizingMaskIntoConstraints = false
  820. let savedOuterStack = NSStackView(views: [savedHeaderStack, savedJobsScrollView])
  821. savedOuterStack.orientation = .vertical
  822. savedOuterStack.spacing = 16
  823. // Leading alignment plus explicit column width keeps the title and subtitle on the same edge as the cards.
  824. savedOuterStack.alignment = .leading
  825. savedOuterStack.translatesAutoresizingMaskIntoConstraints = false
  826. savedJobsPageContainer.userInterfaceLayoutDirection = .leftToRight
  827. savedJobsPageContainer.addSubview(savedOuterStack)
  828. NSLayoutConstraint.activate([
  829. savedOuterStack.leadingAnchor.constraint(equalTo: savedJobsPageContainer.leadingAnchor, constant: 32),
  830. savedOuterStack.trailingAnchor.constraint(equalTo: savedJobsPageContainer.trailingAnchor, constant: -32),
  831. savedOuterStack.topAnchor.constraint(equalTo: savedJobsPageContainer.topAnchor, constant: 8),
  832. savedOuterStack.bottomAnchor.constraint(equalTo: savedJobsPageContainer.bottomAnchor),
  833. savedHeaderStack.widthAnchor.constraint(equalTo: savedOuterStack.widthAnchor),
  834. savedJobsScrollView.widthAnchor.constraint(equalTo: savedOuterStack.widthAnchor),
  835. savedJobsDocumentView.topAnchor.constraint(equalTo: savedJobsScrollView.contentView.topAnchor),
  836. savedJobsDocumentView.leadingAnchor.constraint(equalTo: savedJobsScrollView.contentView.leadingAnchor),
  837. savedJobsDocumentView.widthAnchor.constraint(equalTo: savedJobsScrollView.contentView.widthAnchor)
  838. ])
  839. configureSettingsPage()
  840. }
  841. private func configureSettingsPage() {
  842. settingsPageContainer.wantsLayer = true
  843. settingsPageContainer.layer?.backgroundColor = Theme.settingsPageBackground.cgColor
  844. settingsPageContainer.isHidden = true
  845. let contentStack = NSStackView()
  846. contentStack.orientation = .vertical
  847. contentStack.spacing = 26
  848. contentStack.alignment = .leading
  849. contentStack.translatesAutoresizingMaskIntoConstraints = false
  850. let settingsSection = makeSettingsSection(rows: [
  851. makeSettingsRow(title: "Share App", systemImage: "square.and.arrow.up", accessory: nil),
  852. makeSettingsRow(title: "Theme", systemImage: "circle.lefthalf.filled", accessory: makeThemeControl()),
  853. makeSettingsRow(title: "More Apps", systemImage: "square.grid.2x2", accessory: nil)
  854. ])
  855. let aboutTitle = NSTextField(labelWithString: "About")
  856. aboutTitle.font = .systemFont(ofSize: 12, weight: .semibold)
  857. aboutTitle.textColor = Theme.secondaryText
  858. aboutTitle.alignment = .left
  859. let aboutSection = makeSettingsSection(rows: [
  860. makeSettingsRow(title: "Support", systemImage: "questionmark.circle", accessory: nil),
  861. makeSettingsRow(title: "Terms of Use", systemImage: "doc.text", accessory: nil),
  862. makeSettingsRow(title: "Privacy Policy", systemImage: "shield", accessory: nil)
  863. ])
  864. let aboutStack = NSStackView(views: [aboutTitle, aboutSection])
  865. aboutStack.orientation = .vertical
  866. aboutStack.spacing = 14
  867. aboutStack.alignment = .leading
  868. aboutStack.translatesAutoresizingMaskIntoConstraints = false
  869. contentStack.addArrangedSubview(settingsSection)
  870. contentStack.addArrangedSubview(aboutStack)
  871. settingsPageContainer.addSubview(contentStack)
  872. NSLayoutConstraint.activate([
  873. contentStack.leadingAnchor.constraint(equalTo: settingsPageContainer.leadingAnchor, constant: 42),
  874. contentStack.trailingAnchor.constraint(lessThanOrEqualTo: settingsPageContainer.trailingAnchor, constant: -42),
  875. contentStack.topAnchor.constraint(equalTo: settingsPageContainer.topAnchor, constant: 48),
  876. settingsSection.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  877. aboutStack.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  878. aboutSection.widthAnchor.constraint(equalTo: aboutStack.widthAnchor),
  879. contentStack.widthAnchor.constraint(equalTo: settingsPageContainer.widthAnchor, constant: -84)
  880. ])
  881. }
  882. private func makeThemeControl() -> NSSegmentedControl {
  883. themeControl.target = self
  884. themeControl.action = #selector(didChangeThemeSelection(_:))
  885. themeControl.selectedSegment = 0
  886. themeControl.segmentStyle = .rounded
  887. themeControl.controlSize = .large
  888. themeControl.font = .systemFont(ofSize: 13, weight: .semibold)
  889. themeControl.translatesAutoresizingMaskIntoConstraints = false
  890. themeControl.widthAnchor.constraint(equalToConstant: 204).isActive = true
  891. themeControl.heightAnchor.constraint(equalToConstant: 30).isActive = true
  892. return themeControl
  893. }
  894. private func makeSettingsSection(rows: [NSView]) -> NSView {
  895. let section = NSStackView()
  896. section.orientation = .vertical
  897. section.spacing = 0
  898. section.alignment = .leading
  899. section.translatesAutoresizingMaskIntoConstraints = false
  900. section.wantsLayer = true
  901. section.layer?.backgroundColor = Theme.settingsGroupBackground.cgColor
  902. section.layer?.cornerRadius = 14
  903. section.layer?.borderWidth = 1
  904. section.layer?.borderColor = Theme.border.cgColor
  905. section.layer?.masksToBounds = true
  906. for (index, row) in rows.enumerated() {
  907. section.addArrangedSubview(row)
  908. row.widthAnchor.constraint(equalTo: section.widthAnchor).isActive = true
  909. if index < rows.count - 1 {
  910. let divider = NSView()
  911. divider.translatesAutoresizingMaskIntoConstraints = false
  912. divider.wantsLayer = true
  913. divider.layer?.backgroundColor = Theme.settingsDivider.cgColor
  914. section.addArrangedSubview(divider)
  915. NSLayoutConstraint.activate([
  916. divider.heightAnchor.constraint(equalToConstant: 1),
  917. divider.leadingAnchor.constraint(equalTo: section.leadingAnchor),
  918. divider.trailingAnchor.constraint(equalTo: section.trailingAnchor)
  919. ])
  920. }
  921. }
  922. return section
  923. }
  924. private func makeSettingsRow(title: String, systemImage: String, accessory: NSView?) -> NSView {
  925. let row = NSView()
  926. row.translatesAutoresizingMaskIntoConstraints = false
  927. row.wantsLayer = true
  928. let iconTile = NSView()
  929. iconTile.translatesAutoresizingMaskIntoConstraints = false
  930. iconTile.wantsLayer = true
  931. iconTile.layer?.backgroundColor = Theme.settingsIconBackground.cgColor
  932. iconTile.layer?.cornerRadius = 9
  933. let icon = NSImageView()
  934. icon.translatesAutoresizingMaskIntoConstraints = false
  935. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .medium)
  936. icon.image = NSImage(systemSymbolName: systemImage, accessibilityDescription: title)
  937. icon.contentTintColor = Theme.brandBlue
  938. let titleLabel = NSTextField(labelWithString: title)
  939. titleLabel.font = .systemFont(ofSize: 14, weight: .medium)
  940. titleLabel.textColor = Theme.secondaryText
  941. titleLabel.alignment = .left
  942. let rowStack = NSStackView()
  943. rowStack.orientation = .horizontal
  944. rowStack.spacing = 16
  945. rowStack.alignment = .centerY
  946. rowStack.translatesAutoresizingMaskIntoConstraints = false
  947. let spacer = NSView()
  948. spacer.translatesAutoresizingMaskIntoConstraints = false
  949. spacer.setContentHuggingPriority(NSLayoutConstraint.Priority(1), for: .horizontal)
  950. iconTile.addSubview(icon)
  951. rowStack.addArrangedSubview(iconTile)
  952. rowStack.addArrangedSubview(titleLabel)
  953. rowStack.addArrangedSubview(spacer)
  954. if let accessory {
  955. rowStack.addArrangedSubview(accessory)
  956. }
  957. row.addSubview(rowStack)
  958. NSLayoutConstraint.activate([
  959. row.heightAnchor.constraint(equalToConstant: 68),
  960. iconTile.widthAnchor.constraint(equalToConstant: 38),
  961. iconTile.heightAnchor.constraint(equalToConstant: 38),
  962. icon.centerXAnchor.constraint(equalTo: iconTile.centerXAnchor),
  963. icon.centerYAnchor.constraint(equalTo: iconTile.centerYAnchor),
  964. icon.widthAnchor.constraint(equalToConstant: 20),
  965. icon.heightAnchor.constraint(equalToConstant: 20),
  966. rowStack.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 16),
  967. rowStack.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -16),
  968. rowStack.topAnchor.constraint(equalTo: row.topAnchor),
  969. rowStack.bottomAnchor.constraint(equalTo: row.bottomAnchor)
  970. ])
  971. return row
  972. }
  973. private func reloadSavedJobsListings() {
  974. savedJobsStack.arrangedSubviews.forEach {
  975. savedJobsStack.removeArrangedSubview($0)
  976. $0.removeFromSuperview()
  977. }
  978. if savedJobOrder.isEmpty {
  979. savedJobsPageSubtitleLabel.stringValue = "Save jobs from Home to see them here."
  980. let empty = NSTextField(wrappingLabelWithString: "No saved jobs yet. Search on Home, then tap Save on a listing.")
  981. empty.font = .systemFont(ofSize: 14, weight: .regular)
  982. empty.textColor = Theme.secondaryText
  983. empty.alignment = .left
  984. empty.maximumNumberOfLines = 0
  985. empty.translatesAutoresizingMaskIntoConstraints = false
  986. savedJobsStack.addArrangedSubview(empty)
  987. empty.widthAnchor.constraint(equalTo: savedJobsStack.widthAnchor).isActive = true
  988. return
  989. }
  990. savedJobsPageSubtitleLabel.stringValue = "\(savedJobOrder.count) saved \(savedJobOrder.count == 1 ? "position" : "positions")"
  991. for job in savedJobOrder {
  992. let card = makeJobListingCard(job, context: .savedJobsPage)
  993. savedJobsStack.addArrangedSubview(card)
  994. card.widthAnchor.constraint(equalTo: savedJobsStack.widthAnchor).isActive = true
  995. }
  996. }
  997. private func isSavedJobsSidebarIndex(_ index: Int) -> Bool {
  998. guard index >= 0, index < currentSidebarItems.count else { return false }
  999. return currentSidebarItems[index].title == "Saved Jobs"
  1000. }
  1001. private func isHomeSidebarIndex(_ index: Int) -> Bool {
  1002. guard index >= 0, index < currentSidebarItems.count else { return false }
  1003. return currentSidebarItems[index].title == "Home"
  1004. }
  1005. private func isSettingsSidebarIndex(_ index: Int) -> Bool {
  1006. guard index >= 0, index < currentSidebarItems.count else { return false }
  1007. return currentSidebarItems[index].title == "Settings"
  1008. }
  1009. private func updateMainContentVisibility() {
  1010. let home = isHomeSidebarIndex(selectedSidebarIndex)
  1011. let savedJobs = isSavedJobsSidebarIndex(selectedSidebarIndex)
  1012. let settings = isSettingsSidebarIndex(selectedSidebarIndex)
  1013. mainOverlay.isHidden = !home
  1014. nonHomeHost.isHidden = home
  1015. nonHomeGenericContainer.isHidden = savedJobs || settings
  1016. savedJobsPageContainer.isHidden = !savedJobs
  1017. settingsPageContainer.isHidden = !settings
  1018. if !home, selectedSidebarIndex < currentSidebarItems.count {
  1019. if savedJobs {
  1020. reloadSavedJobsListings()
  1021. } else if settings {
  1022. window?.makeFirstResponder(nil)
  1023. } else {
  1024. nonHomeTitleLabel.stringValue = currentSidebarItems[selectedSidebarIndex].title
  1025. }
  1026. }
  1027. }
  1028. /// Removes result cards or the “no matches” message so a new search starts from a blank listing area.
  1029. private func clearJobSearchResultsUI() {
  1030. configureJobListings([], noResultsForQuery: nil)
  1031. if let doc = jobListingsScrollView.documentView {
  1032. doc.scroll(NSPoint(x: 0, y: 0))
  1033. }
  1034. }
  1035. /// Restores the main job-search experience: cleared query and no listings until the user searches again.
  1036. private func applyHomeState() {
  1037. jobKeywordsField.stringValue = ""
  1038. resetChatState()
  1039. window?.makeFirstResponder(nil)
  1040. }
  1041. private func updateSearchBarShadowPath() {
  1042. guard searchBarShadowHost.bounds.width > 0, searchBarShadowHost.bounds.height > 0 else { return }
  1043. let r = searchBarShadowHost.bounds
  1044. let radius = min(r.height / 2, 27)
  1045. searchBarShadowHost.layer?.shadowPath = CGPath(
  1046. roundedRect: r,
  1047. cornerWidth: radius,
  1048. cornerHeight: radius,
  1049. transform: nil
  1050. )
  1051. }
  1052. @objc private func didSubmitSearch() {
  1053. let prompt = jobKeywordsField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)
  1054. guard !prompt.isEmpty, !isAwaitingResponse else { return }
  1055. clearJobSearchResultsUI()
  1056. appendChatBubble(text: prompt, isUser: true)
  1057. chatMessages.append(ChatMessage(role: "user", content: prompt))
  1058. jobKeywordsField.stringValue = ""
  1059. isAwaitingResponse = true
  1060. chatStatusLabel.stringValue = "Thinking..."
  1061. setInputEnabled(false)
  1062. jobSearchService.searchJobs(query: prompt) { [weak self] result in
  1063. DispatchQueue.main.async {
  1064. guard let self else { return }
  1065. self.isAwaitingResponse = false
  1066. self.setInputEnabled(true)
  1067. switch result {
  1068. case .success(let output):
  1069. let normalizedJobs = self.normalizedJobs(output.jobs)
  1070. self.configureJobListings(normalizedJobs, noResultsForQuery: prompt)
  1071. let reply = self.makeAssistantSearchReply(query: prompt, jobs: normalizedJobs, jsonResult: output.rawJSON)
  1072. self.chatMessages.append(ChatMessage(role: "assistant", content: reply))
  1073. self.appendChatBubble(text: reply, isUser: false)
  1074. self.chatStatusLabel.stringValue = "Ask for another job, company, or skill match"
  1075. case .failure(let error):
  1076. self.appendChatBubble(text: error.localizedDescription, isUser: false)
  1077. self.chatStatusLabel.stringValue = "Could not reach API. Try again."
  1078. self.configureJobListings([], noResultsForQuery: prompt)
  1079. }
  1080. }
  1081. }
  1082. window?.makeFirstResponder(nil)
  1083. }
  1084. private func normalizedJobs(_ jobs: [JobListing]) -> [JobListing] {
  1085. let trimmed = jobs.map {
  1086. JobListing(
  1087. title: $0.title.trimmingCharacters(in: .whitespacesAndNewlines),
  1088. description: $0.description.trimmingCharacters(in: .whitespacesAndNewlines),
  1089. url: $0.url?.trimmingCharacters(in: .whitespacesAndNewlines)
  1090. )
  1091. }
  1092. return trimmed.filter { !$0.title.isEmpty && !$0.description.isEmpty }
  1093. }
  1094. private func makeAssistantSearchReply(query: String, jobs: [JobListing], jsonResult: String) -> String {
  1095. if jobs.isEmpty {
  1096. return """
  1097. No jobs were found for "\(query)".
  1098. JSON result:
  1099. \(jsonResult)
  1100. """
  1101. }
  1102. let rows = jobs.prefix(8).enumerated().map { index, job in
  1103. let fallback = "https://www.indeed.com/jobs?q=\(job.title.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")"
  1104. let link = (job.url?.isEmpty == false) ? job.url! : fallback
  1105. let compactDescription = compactSingleLine(job.description, maxCharacters: 110)
  1106. return "\(index + 1)) \(job.title) | \(compactDescription) | \(link)"
  1107. }
  1108. return """
  1109. Found \(jobs.count) job result(s) for "\(query)".
  1110. Row-wise results:
  1111. \(rows.joined(separator: "\n"))
  1112. JSON result:
  1113. \(jsonResult)
  1114. """
  1115. }
  1116. private func compactSingleLine(_ text: String, maxCharacters: Int) -> String {
  1117. let single = text
  1118. .replacingOccurrences(of: "\n", with: " ")
  1119. .replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
  1120. .trimmingCharacters(in: .whitespacesAndNewlines)
  1121. guard single.count > maxCharacters, maxCharacters > 1 else { return single }
  1122. let end = single.index(single.startIndex, offsetBy: maxCharacters - 1)
  1123. return String(single[..<end]) + "…"
  1124. }
  1125. func controlTextDidBeginEditing(_ obj: Notification) {
  1126. applySearchFieldInsertionPoint(obj.object)
  1127. if (obj.object as? NSTextField) === jobKeywordsField {
  1128. chatStatusLabel.stringValue = "Opening the vault..."
  1129. }
  1130. }
  1131. func controlTextDidChange(_ obj: Notification) {
  1132. applySearchFieldInsertionPoint(obj.object)
  1133. }
  1134. func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
  1135. guard control === jobKeywordsField, commandSelector == #selector(NSResponder.insertNewline(_:)) else {
  1136. return false
  1137. }
  1138. didSubmitSearch()
  1139. return true
  1140. }
  1141. private func applySearchFieldInsertionPoint(_ object: Any?) {
  1142. guard let field = object as? NSTextField,
  1143. field === jobKeywordsField,
  1144. let textView = field.window?.fieldEditor(true, for: field) as? NSTextView else { return }
  1145. textView.insertionPointColor = Theme.primaryText
  1146. }
  1147. private func resetChatState() {
  1148. chatMessages.removeAll()
  1149. chatStack.arrangedSubviews.forEach {
  1150. chatStack.removeArrangedSubview($0)
  1151. $0.removeFromSuperview()
  1152. }
  1153. let welcome = "Tell me what role you want and I will return job descriptions, key skills, and a quick fit summary."
  1154. chatMessages.append(ChatMessage(role: "assistant", content: welcome))
  1155. appendChatBubble(text: welcome, isUser: false)
  1156. chatStatusLabel.stringValue = "Opening the vault..."
  1157. }
  1158. private func appendChatBubble(text: String, isUser: Bool) {
  1159. let host = NSView()
  1160. host.translatesAutoresizingMaskIntoConstraints = false
  1161. let bubble = NSTextField(wrappingLabelWithString: text)
  1162. bubble.font = .systemFont(ofSize: 13, weight: .regular)
  1163. bubble.maximumNumberOfLines = 0
  1164. bubble.lineBreakMode = .byWordWrapping
  1165. bubble.alignment = .left
  1166. bubble.textColor = isUser ? .white : Theme.primaryText
  1167. bubble.wantsLayer = true
  1168. bubble.layer?.cornerRadius = 12
  1169. bubble.layer?.masksToBounds = true
  1170. bubble.layer?.backgroundColor = (isUser ? Theme.brandBlue : Theme.chromeBackground).cgColor
  1171. bubble.translatesAutoresizingMaskIntoConstraints = false
  1172. host.addSubview(bubble)
  1173. chatStack.addArrangedSubview(host)
  1174. host.widthAnchor.constraint(equalTo: chatStack.widthAnchor).isActive = true
  1175. let leading = bubble.leadingAnchor.constraint(equalTo: host.leadingAnchor, constant: 8)
  1176. let trailing = bubble.trailingAnchor.constraint(equalTo: host.trailingAnchor, constant: -8)
  1177. let maxWidth = bubble.widthAnchor.constraint(lessThanOrEqualTo: host.widthAnchor, multiplier: 0.78)
  1178. maxWidth.priority = .required
  1179. NSLayoutConstraint.activate([
  1180. bubble.topAnchor.constraint(equalTo: host.topAnchor),
  1181. bubble.bottomAnchor.constraint(equalTo: host.bottomAnchor),
  1182. bubble.heightAnchor.constraint(greaterThanOrEqualToConstant: 34),
  1183. maxWidth,
  1184. isUser ? leading.withPriority(.defaultLow) : leading.withPriority(.required),
  1185. isUser ? trailing.withPriority(.required) : trailing.withPriority(.defaultLow)
  1186. ])
  1187. DispatchQueue.main.async {
  1188. let maxY = max(0, self.chatDocumentView.bounds.height - self.chatScrollView.contentView.bounds.height)
  1189. self.chatScrollView.contentView.scroll(to: NSPoint(x: 0, y: maxY))
  1190. self.chatScrollView.reflectScrolledClipView(self.chatScrollView.contentView)
  1191. }
  1192. }
  1193. private func setInputEnabled(_ enabled: Bool) {
  1194. jobKeywordsField.isEnabled = enabled
  1195. findJobsButton.isEnabled = enabled
  1196. findJobsButton.alphaValue = enabled ? 1 : 0.65
  1197. }
  1198. private func configureSidebar() {
  1199. let items = currentSidebarItems
  1200. sidebar.arrangedSubviews.forEach {
  1201. sidebar.removeArrangedSubview($0)
  1202. $0.removeFromSuperview()
  1203. }
  1204. let brand = NSTextField(labelWithString: "Indeed AI\nJob Finder")
  1205. brand.font = .systemFont(ofSize: 18, weight: .bold)
  1206. brand.textColor = Theme.brandBlue
  1207. brand.alignment = .left
  1208. brand.maximumNumberOfLines = 2
  1209. // Tight multiline height in the sidebar stack (zero width makes intrinsic height unreliable).
  1210. brand.preferredMaxLayoutWidth = 194
  1211. sidebar.addArrangedSubview(brand)
  1212. sidebar.setCustomSpacing(10, after: brand)
  1213. items.enumerated().forEach { index, item in
  1214. let isSelected = index == selectedSidebarIndex
  1215. let rowHost = SidebarNavRowView { [weak self] in
  1216. self?.selectSidebarItem(at: index)
  1217. }
  1218. rowHost.translatesAutoresizingMaskIntoConstraints = false
  1219. rowHost.wantsLayer = true
  1220. rowHost.layer?.cornerRadius = 8
  1221. rowHost.restingBackgroundColor = isSelected ? Theme.selectionFill : nil
  1222. rowHost.hoverBackgroundColor = isSelected ? Theme.selectionFillHover : Theme.sidebarRowHoverFill
  1223. rowHost.setAccessibilityLabel(item.title)
  1224. rowHost.setAccessibilityRole(.button)
  1225. rowHost.setAccessibilitySelected(isSelected)
  1226. let row = NSStackView()
  1227. row.orientation = .horizontal
  1228. row.spacing = 8
  1229. row.alignment = .centerY
  1230. row.translatesAutoresizingMaskIntoConstraints = false
  1231. let icon = NSImageView()
  1232. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .medium)
  1233. icon.image = NSImage(systemSymbolName: item.systemImage, accessibilityDescription: item.title)
  1234. icon.contentTintColor = isSelected ? Theme.brandBlue : Theme.secondaryText
  1235. let text = NSTextField(labelWithString: item.title)
  1236. text.font = .systemFont(ofSize: 14, weight: .medium)
  1237. text.textColor = isSelected ? Theme.brandBlue : Theme.secondaryText
  1238. text.refusesFirstResponder = true
  1239. row.addArrangedSubview(icon)
  1240. row.addArrangedSubview(text)
  1241. if let badge = item.badge {
  1242. let badgeField = NSTextField(labelWithString: badge)
  1243. badgeField.font = .systemFont(ofSize: 11, weight: .semibold)
  1244. badgeField.textColor = Theme.primaryText
  1245. badgeField.wantsLayer = true
  1246. badgeField.layer?.backgroundColor = Theme.toggleBackground.cgColor
  1247. badgeField.layer?.cornerRadius = 8
  1248. badgeField.alignment = .center
  1249. badgeField.maximumNumberOfLines = 1
  1250. badgeField.lineBreakMode = .byClipping
  1251. badgeField.refusesFirstResponder = true
  1252. badgeField.translatesAutoresizingMaskIntoConstraints = false
  1253. badgeField.widthAnchor.constraint(equalToConstant: 42).isActive = true
  1254. row.addArrangedSubview(NSView())
  1255. row.addArrangedSubview(badgeField)
  1256. }
  1257. rowHost.addSubview(row)
  1258. NSLayoutConstraint.activate([
  1259. row.leadingAnchor.constraint(equalTo: rowHost.leadingAnchor, constant: 10),
  1260. row.trailingAnchor.constraint(equalTo: rowHost.trailingAnchor, constant: -10),
  1261. row.topAnchor.constraint(equalTo: rowHost.topAnchor, constant: 8),
  1262. row.bottomAnchor.constraint(equalTo: rowHost.bottomAnchor, constant: -8)
  1263. ])
  1264. rowHost.setContentHuggingPriority(.defaultLow, for: .horizontal)
  1265. sidebar.addArrangedSubview(rowHost)
  1266. let sidebarHorizontalInset = sidebar.edgeInsets.left + sidebar.edgeInsets.right
  1267. rowHost.widthAnchor.constraint(equalTo: sidebar.widthAnchor, constant: -sidebarHorizontalInset).isActive = true
  1268. }
  1269. let sidebarBottomSpacer = NSView()
  1270. sidebarBottomSpacer.translatesAutoresizingMaskIntoConstraints = false
  1271. sidebarBottomSpacer.setContentHuggingPriority(.defaultLow, for: .vertical)
  1272. sidebarBottomSpacer.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  1273. sidebar.addArrangedSubview(sidebarBottomSpacer)
  1274. let upgradeCard = NSView()
  1275. upgradeCard.translatesAutoresizingMaskIntoConstraints = false
  1276. upgradeCard.wantsLayer = true
  1277. upgradeCard.layer?.backgroundColor = Theme.proCardFill.cgColor
  1278. upgradeCard.layer?.cornerRadius = 14
  1279. upgradeCard.layer?.borderWidth = 1
  1280. upgradeCard.layer?.borderColor = Theme.proCardBorder.cgColor
  1281. upgradeCard.layer?.masksToBounds = true
  1282. let accentBar = NSView()
  1283. accentBar.translatesAutoresizingMaskIntoConstraints = false
  1284. accentBar.wantsLayer = true
  1285. accentBar.layer?.backgroundColor = Theme.proAccent.cgColor
  1286. let inner = NSStackView()
  1287. inner.translatesAutoresizingMaskIntoConstraints = false
  1288. inner.orientation = .vertical
  1289. inner.spacing = 10
  1290. inner.alignment = .centerX
  1291. let proIcon = NSImageView()
  1292. proIcon.translatesAutoresizingMaskIntoConstraints = false
  1293. proIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .semibold)
  1294. proIcon.image = NSImage(systemSymbolName: "sparkles", accessibilityDescription: nil)
  1295. proIcon.contentTintColor = Theme.proAccent
  1296. let proEyebrow = NSTextField(labelWithString: "Premium")
  1297. proEyebrow.font = .systemFont(ofSize: 11, weight: .heavy)
  1298. proEyebrow.textColor = Theme.proAccent
  1299. proEyebrow.alignment = .center
  1300. let eyebrowRow = NSStackView(views: [proIcon, proEyebrow])
  1301. eyebrowRow.orientation = .horizontal
  1302. eyebrowRow.spacing = 6
  1303. eyebrowRow.alignment = .centerY
  1304. let headline = NSTextField(labelWithString: "Upgrade to Pro")
  1305. headline.font = .systemFont(ofSize: 16, weight: .bold)
  1306. headline.textColor = Theme.primaryText
  1307. headline.alignment = .center
  1308. let upgradeDescription = NSTextField(wrappingLabelWithString: "Unlimited AI matches, smart alerts, and interview prep—all in one place.")
  1309. upgradeDescription.font = .systemFont(ofSize: 12, weight: .regular)
  1310. upgradeDescription.textColor = Theme.secondaryText
  1311. upgradeDescription.alignment = .center
  1312. // Sidebar content width is the fixed sidebar width minus horizontal edge insets; card must stay within that band.
  1313. let cardWidth: CGFloat = 186
  1314. let innerContentWidth = cardWidth - 28
  1315. upgradeDescription.preferredMaxLayoutWidth = innerContentWidth
  1316. let upgradeButton = HoverableButton(title: "Upgrade to Pro", target: self, action: #selector(didTapUpgradeToPro))
  1317. upgradeButton.isBordered = false
  1318. upgradeButton.bezelStyle = .rounded
  1319. upgradeButton.font = .systemFont(ofSize: 13, weight: .bold)
  1320. upgradeButton.contentTintColor = Theme.proCTAText
  1321. upgradeButton.alignment = .center
  1322. upgradeButton.wantsLayer = true
  1323. upgradeButton.layer?.backgroundColor = Theme.proCTABackground.cgColor
  1324. upgradeButton.layer?.cornerRadius = 20
  1325. upgradeButton.translatesAutoresizingMaskIntoConstraints = false
  1326. upgradeButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
  1327. upgradeButton.pointerCursor = true
  1328. upgradeButton.hoverHandler = { [weak upgradeButton] hovering in
  1329. upgradeButton?.layer?.backgroundColor = (hovering ? Theme.brandBlueHover : Theme.proCTABackground).cgColor
  1330. }
  1331. inner.addArrangedSubview(eyebrowRow)
  1332. inner.addArrangedSubview(headline)
  1333. inner.addArrangedSubview(upgradeDescription)
  1334. inner.addArrangedSubview(upgradeButton)
  1335. upgradeCard.addSubview(accentBar)
  1336. upgradeCard.addSubview(inner)
  1337. NSLayoutConstraint.activate([
  1338. upgradeCard.widthAnchor.constraint(equalToConstant: cardWidth),
  1339. accentBar.topAnchor.constraint(equalTo: upgradeCard.topAnchor),
  1340. accentBar.leadingAnchor.constraint(equalTo: upgradeCard.leadingAnchor),
  1341. accentBar.trailingAnchor.constraint(equalTo: upgradeCard.trailingAnchor),
  1342. accentBar.heightAnchor.constraint(equalToConstant: 2),
  1343. inner.leadingAnchor.constraint(equalTo: upgradeCard.leadingAnchor, constant: 14),
  1344. inner.trailingAnchor.constraint(equalTo: upgradeCard.trailingAnchor, constant: -14),
  1345. inner.topAnchor.constraint(equalTo: accentBar.bottomAnchor, constant: 12),
  1346. inner.bottomAnchor.constraint(equalTo: upgradeCard.bottomAnchor, constant: -14),
  1347. upgradeButton.widthAnchor.constraint(equalTo: inner.widthAnchor)
  1348. ])
  1349. sidebar.addArrangedSubview(upgradeCard)
  1350. }
  1351. @objc private func didTapUpgradeToPro() {
  1352. guard let url = URL(string: "https://www.indeed.com") else { return }
  1353. NSWorkspace.shared.open(url)
  1354. }
  1355. @objc private func didChangeThemeSelection(_ sender: NSSegmentedControl) {
  1356. switch sender.selectedSegment {
  1357. case 1:
  1358. NSApp.appearance = NSAppearance(named: .aqua)
  1359. case 2:
  1360. NSApp.appearance = NSAppearance(named: .darkAqua)
  1361. default:
  1362. NSApp.appearance = nil
  1363. }
  1364. }
  1365. private func selectSidebarItem(at index: Int) {
  1366. guard index >= 0, index < currentSidebarItems.count else { return }
  1367. let selectingHome = isHomeSidebarIndex(index)
  1368. if index == selectedSidebarIndex {
  1369. if selectingHome {
  1370. applyHomeState()
  1371. }
  1372. return
  1373. }
  1374. selectedSidebarIndex = index
  1375. configureSidebar()
  1376. updateMainContentVisibility()
  1377. if selectingHome {
  1378. applyHomeState()
  1379. }
  1380. }
  1381. }
  1382. private struct ChatMessage: Codable {
  1383. let role: String
  1384. let content: String
  1385. }
  1386. private final class OpenAIJobSearchService {
  1387. private let endpoint = URL(string: "https://api.openai.com/v1/responses")!
  1388. private let session = URLSession(configuration: .ephemeral)
  1389. func searchJobs(query: String, completion: @escaping (Result<JobSearchOutput, Error>) -> Void) {
  1390. let apiKey = OpenAIConfiguration.apiKey
  1391. guard OpenAIConfiguration.hasAPIKey else {
  1392. completion(.failure(NSError(
  1393. domain: "OpenAIJobSearchService",
  1394. code: 1,
  1395. userInfo: [NSLocalizedDescriptionKey: "Missing API key. Set it in OpenAIConfiguration.swift."]
  1396. )))
  1397. return
  1398. }
  1399. var request = URLRequest(url: endpoint)
  1400. request.httpMethod = "POST"
  1401. request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  1402. request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
  1403. request.timeoutInterval = 45
  1404. let instructions = """
  1405. Search the web for currently available jobs related to this role query: "\(query)".
  1406. Return ONLY strict JSON that matches this schema:
  1407. {
  1408. "jobs": [
  1409. {
  1410. "title": "string",
  1411. "description": "string",
  1412. "url": "https://..."
  1413. }
  1414. ]
  1415. }
  1416. Keep descriptions concise (1 sentence), include real apply/listing URLs when available, and return up to 8 jobs.
  1417. """
  1418. let payload = OpenAIResponsesRequest(
  1419. model: "gpt-4o-mini",
  1420. input: instructions,
  1421. tools: [OpenAIResponsesTool(type: "web_search_preview")]
  1422. )
  1423. do {
  1424. request.httpBody = try JSONEncoder().encode(payload)
  1425. } catch {
  1426. completion(.failure(error))
  1427. return
  1428. }
  1429. session.dataTask(with: request) { data, response, error in
  1430. if let error {
  1431. completion(.failure(error))
  1432. return
  1433. }
  1434. guard let data else {
  1435. completion(.failure(NSError(
  1436. domain: "OpenAIJobSearchService",
  1437. code: 2,
  1438. userInfo: [NSLocalizedDescriptionKey: "API returned an empty response."]
  1439. )))
  1440. return
  1441. }
  1442. if let http = response as? HTTPURLResponse, !(200...299).contains(http.statusCode) {
  1443. if let apiError = try? JSONDecoder().decode(OpenAIAPIErrorResponse.self, from: data) {
  1444. completion(.failure(NSError(
  1445. domain: "OpenAIJobSearchService",
  1446. code: http.statusCode,
  1447. userInfo: [NSLocalizedDescriptionKey: apiError.error.message]
  1448. )))
  1449. } else {
  1450. completion(.failure(NSError(
  1451. domain: "OpenAIJobSearchService",
  1452. code: http.statusCode,
  1453. userInfo: [NSLocalizedDescriptionKey: "Job search request failed with status \(http.statusCode)."]
  1454. )))
  1455. }
  1456. return
  1457. }
  1458. do {
  1459. let decoded = try JSONDecoder().decode(OpenAIResponsesResponse.self, from: data)
  1460. let text = decoded.bestText.trimmingCharacters(in: .whitespacesAndNewlines)
  1461. guard !text.isEmpty else {
  1462. throw NSError(
  1463. domain: "OpenAIJobSearchService",
  1464. code: 4,
  1465. userInfo: [NSLocalizedDescriptionKey: "The API returned an empty text payload."]
  1466. )
  1467. }
  1468. let cleanedText = Self.extractJSONObject(from: text)
  1469. let jsonData = Data(cleanedText.utf8)
  1470. let jobsPayload = try JSONDecoder().decode(JobSearchResultsPayload.self, from: jsonData)
  1471. completion(.success(JobSearchOutput(jobs: jobsPayload.jobs, rawJSON: cleanedText)))
  1472. } catch {
  1473. let rawBody = String(data: data, encoding: .utf8) ?? "<non-utf8 response>"
  1474. let message = "The API response could not be parsed as job JSON. Raw response: \(rawBody.prefix(600))"
  1475. completion(.failure(NSError(
  1476. domain: "OpenAIJobSearchService",
  1477. code: 5,
  1478. userInfo: [NSLocalizedDescriptionKey: message]
  1479. )))
  1480. }
  1481. }.resume()
  1482. }
  1483. private static func extractJSONObject(from text: String) -> String {
  1484. if let range = text.range(of: "\\{[\\s\\S]*\\}", options: .regularExpression) {
  1485. return String(text[range])
  1486. }
  1487. return text
  1488. }
  1489. }
  1490. private struct OpenAIResponsesRequest: Codable {
  1491. let model: String
  1492. let input: String
  1493. let tools: [OpenAIResponsesTool]
  1494. }
  1495. private struct OpenAIResponsesTool: Codable {
  1496. let type: String
  1497. }
  1498. private struct OpenAIResponsesResponse: Codable {
  1499. let outputText: String?
  1500. let output: [OpenAIOutputItem]?
  1501. enum CodingKeys: String, CodingKey {
  1502. case outputText = "output_text"
  1503. case output
  1504. }
  1505. var bestText: String {
  1506. if let outputText, !outputText.isEmpty {
  1507. return outputText
  1508. }
  1509. let collected = (output ?? [])
  1510. .flatMap { $0.content ?? [] }
  1511. .compactMap { chunk in
  1512. switch chunk {
  1513. case .outputText(let value):
  1514. return value.text
  1515. case .inputText:
  1516. return nil
  1517. }
  1518. }
  1519. .joined(separator: "\n")
  1520. return collected
  1521. }
  1522. }
  1523. private struct OpenAIOutputItem: Codable {
  1524. let content: [OpenAIOutputContent]?
  1525. }
  1526. private enum OpenAIOutputContent: Codable {
  1527. case outputText(OpenAITextChunk)
  1528. case inputText(OpenAITextChunk)
  1529. enum CodingKeys: String, CodingKey {
  1530. case type
  1531. case text
  1532. }
  1533. init(from decoder: Decoder) throws {
  1534. let container = try decoder.container(keyedBy: CodingKeys.self)
  1535. let type = try container.decode(String.self, forKey: .type)
  1536. let text = try container.decode(String.self, forKey: .text)
  1537. let payload = OpenAITextChunk(text: text)
  1538. if type == "output_text" {
  1539. self = .outputText(payload)
  1540. } else {
  1541. self = .inputText(payload)
  1542. }
  1543. }
  1544. func encode(to encoder: Encoder) throws {
  1545. var container = encoder.container(keyedBy: CodingKeys.self)
  1546. switch self {
  1547. case .outputText(let chunk):
  1548. try container.encode("output_text", forKey: .type)
  1549. try container.encode(chunk.text, forKey: .text)
  1550. case .inputText(let chunk):
  1551. try container.encode("input_text", forKey: .type)
  1552. try container.encode(chunk.text, forKey: .text)
  1553. }
  1554. }
  1555. }
  1556. private struct OpenAITextChunk: Codable {
  1557. let text: String
  1558. }
  1559. private struct JobSearchResultsPayload: Codable {
  1560. let jobs: [JobListing]
  1561. }
  1562. private struct JobSearchOutput {
  1563. let jobs: [JobListing]
  1564. let rawJSON: String
  1565. }
  1566. private struct OpenAIAPIErrorResponse: Codable {
  1567. let error: APIError
  1568. struct APIError: Codable {
  1569. let message: String
  1570. }
  1571. }
  1572. private extension NSLayoutConstraint {
  1573. func withPriority(_ priority: NSLayoutConstraint.Priority) -> NSLayoutConstraint {
  1574. self.priority = priority
  1575. return self
  1576. }
  1577. }
  1578. /// `NSButton` that carries a `JobListing` for card actions (`representedObject` is unavailable on `NSButton` in this target).
  1579. private final class JobPayloadButton: HoverableButton {
  1580. var jobPayload: JobListing?
  1581. var cardContext: JobListingCardContext = .homeSearchResults
  1582. }
  1583. /// `NSButton` with a tracking area that reports hover transitions and (optionally) swaps in a pointing-hand cursor while hovered.
  1584. private class HoverableButton: NSButton {
  1585. var hoverHandler: ((Bool) -> Void)?
  1586. var pointerCursor: Bool = false
  1587. private(set) var isHovering: Bool = false
  1588. private var trackingArea: NSTrackingArea?
  1589. private var didPushCursor: Bool = false
  1590. override func updateTrackingAreas() {
  1591. super.updateTrackingAreas()
  1592. if let area = trackingArea { removeTrackingArea(area) }
  1593. let area = NSTrackingArea(
  1594. rect: bounds,
  1595. options: [.activeInKeyWindow, .mouseEnteredAndExited, .inVisibleRect],
  1596. owner: self,
  1597. userInfo: nil
  1598. )
  1599. addTrackingArea(area)
  1600. trackingArea = area
  1601. }
  1602. override func mouseEntered(with event: NSEvent) {
  1603. super.mouseEntered(with: event)
  1604. isHovering = true
  1605. hoverHandler?(true)
  1606. if pointerCursor, !didPushCursor {
  1607. NSCursor.pointingHand.push()
  1608. didPushCursor = true
  1609. }
  1610. }
  1611. override func mouseExited(with event: NSEvent) {
  1612. super.mouseExited(with: event)
  1613. isHovering = false
  1614. hoverHandler?(false)
  1615. if didPushCursor {
  1616. NSCursor.pop()
  1617. didPushCursor = false
  1618. }
  1619. }
  1620. override func viewWillMove(toWindow newWindow: NSWindow?) {
  1621. super.viewWillMove(toWindow: newWindow)
  1622. // Guard against an unbalanced cursor stack if the button is removed mid-hover (e.g. job card replaced after a search).
  1623. if newWindow == nil, didPushCursor {
  1624. NSCursor.pop()
  1625. didPushCursor = false
  1626. isHovering = false
  1627. }
  1628. }
  1629. }
  1630. /// `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.
  1631. private class HoverableView: NSView {
  1632. var hoverHandler: ((Bool) -> Void)?
  1633. var pointerCursor: Bool = false
  1634. private(set) var isHovering: Bool = false
  1635. private var trackingArea: NSTrackingArea?
  1636. private var didPushCursor: Bool = false
  1637. override func updateTrackingAreas() {
  1638. super.updateTrackingAreas()
  1639. if let area = trackingArea { removeTrackingArea(area) }
  1640. let area = NSTrackingArea(
  1641. rect: bounds,
  1642. options: [.activeInKeyWindow, .mouseEnteredAndExited, .inVisibleRect],
  1643. owner: self,
  1644. userInfo: nil
  1645. )
  1646. addTrackingArea(area)
  1647. trackingArea = area
  1648. }
  1649. override func mouseEntered(with event: NSEvent) {
  1650. super.mouseEntered(with: event)
  1651. isHovering = true
  1652. hoverHandler?(true)
  1653. if pointerCursor, !didPushCursor {
  1654. NSCursor.pointingHand.push()
  1655. didPushCursor = true
  1656. }
  1657. }
  1658. override func mouseExited(with event: NSEvent) {
  1659. super.mouseExited(with: event)
  1660. isHovering = false
  1661. hoverHandler?(false)
  1662. if didPushCursor {
  1663. NSCursor.pop()
  1664. didPushCursor = false
  1665. }
  1666. }
  1667. override func viewWillMove(toWindow newWindow: NSWindow?) {
  1668. super.viewWillMove(toWindow: newWindow)
  1669. if newWindow == nil, didPushCursor {
  1670. NSCursor.pop()
  1671. didPushCursor = false
  1672. isHovering = false
  1673. }
  1674. }
  1675. }
  1676. /// 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).
  1677. private final class JobListingsDocumentView: NSView {
  1678. override var isFlipped: Bool { true }
  1679. }
  1680. /// 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.
  1681. private final class SidebarNavRowView: NSView {
  1682. private let onSelect: () -> Void
  1683. var restingBackgroundColor: NSColor? {
  1684. didSet { applyBackground() }
  1685. }
  1686. var hoverBackgroundColor: NSColor?
  1687. private var isHovering: Bool = false
  1688. private var didPushCursor: Bool = false
  1689. init(onSelect: @escaping () -> Void) {
  1690. self.onSelect = onSelect
  1691. super.init(frame: .zero)
  1692. }
  1693. @available(*, unavailable)
  1694. required init?(coder: NSCoder) {
  1695. fatalError("init(coder:) has not been implemented")
  1696. }
  1697. override func hitTest(_ point: NSPoint) -> NSView? {
  1698. guard let superview else { return super.hitTest(point) }
  1699. let local = convert(point, from: superview)
  1700. return bounds.contains(local) ? self : nil
  1701. }
  1702. override func mouseDown(with event: NSEvent) {
  1703. onSelect()
  1704. }
  1705. override func updateTrackingAreas() {
  1706. super.updateTrackingAreas()
  1707. trackingAreas.forEach { removeTrackingArea($0) }
  1708. addTrackingArea(NSTrackingArea(
  1709. rect: bounds,
  1710. options: [.activeInKeyWindow, .mouseEnteredAndExited, .inVisibleRect],
  1711. owner: self,
  1712. userInfo: nil
  1713. ))
  1714. }
  1715. override func mouseEntered(with event: NSEvent) {
  1716. super.mouseEntered(with: event)
  1717. isHovering = true
  1718. applyBackground()
  1719. if !didPushCursor {
  1720. NSCursor.pointingHand.push()
  1721. didPushCursor = true
  1722. }
  1723. }
  1724. override func mouseExited(with event: NSEvent) {
  1725. super.mouseExited(with: event)
  1726. isHovering = false
  1727. applyBackground()
  1728. if didPushCursor {
  1729. NSCursor.pop()
  1730. didPushCursor = false
  1731. }
  1732. }
  1733. override func viewWillMove(toWindow newWindow: NSWindow?) {
  1734. super.viewWillMove(toWindow: newWindow)
  1735. if newWindow == nil, didPushCursor {
  1736. NSCursor.pop()
  1737. didPushCursor = false
  1738. isHovering = false
  1739. }
  1740. }
  1741. private func applyBackground() {
  1742. let color = isHovering ? (hoverBackgroundColor ?? restingBackgroundColor) : restingBackgroundColor
  1743. layer?.backgroundColor = color?.cgColor
  1744. }
  1745. }