Sin descripción

DashboardView.swift 133KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871
  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: dark neutral gray to match the reference layout.
  21. static let welcomeSubtitleText = NSColor(srgbRed: 64 / 255, green: 64 / 255, blue: 64 / 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. /// Home status strip and soft accents (light blue panel in the reference UI).
  30. static let statusBannerBackground = NSColor(srgbRed: 232 / 255, green: 242 / 255, blue: 252 / 255, alpha: 1)
  31. static let featureIconWell = NSColor(srgbRed: 220 / 255, green: 235 / 255, blue: 252 / 255, alpha: 1)
  32. /// Job search bar outer stroke (soft blue-gray, pill field in the reference UI).
  33. static let searchBarBorder = NSColor(srgbRed: 180 / 255, green: 200 / 255, blue: 228 / 255, alpha: 1)
  34. /// Search bar border on hover (brand-tinted, matches focus affordance elsewhere).
  35. static let searchBarBorderHover = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 0.55)
  36. static let proCardFill = NSColor(srgbRed: 239 / 255, green: 244 / 255, blue: 252 / 255, alpha: 1)
  37. static let proCardBorder = NSColor(srgbRed: 212 / 255, green: 210 / 255, blue: 208 / 255, alpha: 1)
  38. static let proAccent = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 1)
  39. static let proCTABackground = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 1)
  40. static let proCTAText = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  41. /// Slightly lighter blue for the top of the search-bar “Find jobs” pill (reads less flat than a solid fill).
  42. static let findJobsCTAHighlight = NSColor(srgbRed: 54 / 255, green: 110 / 255, blue: 198 / 255, alpha: 1)
  43. /// Hover states: darker brand blue, deeper gradient top, stronger tints, and subtle neutral fills used across CTAs, toggles, and the sidebar.
  44. static let brandBlueHover = NSColor(srgbRed: 28 / 255, green: 70 / 255, blue: 140 / 255, alpha: 1)
  45. static let findJobsCTAHighlightHover = NSColor(srgbRed: 44 / 255, green: 94 / 255, blue: 178 / 255, alpha: 1)
  46. static let selectionFillHover = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 0.2)
  47. static let neutralHoverFill = NSColor(srgbRed: 240 / 255, green: 240 / 255, blue: 240 / 255, alpha: 1)
  48. static let sidebarRowHoverFill = NSColor(srgbRed: 0, green: 0, blue: 0, alpha: 0.04)
  49. static let settingsPageBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  50. static let settingsGroupBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  51. static let settingsIconBackground = NSColor(srgbRed: 239 / 255, green: 244 / 255, blue: 252 / 255, alpha: 1)
  52. static let settingsDivider = NSColor(srgbRed: 228 / 255, green: 228 / 255, blue: 228 / 255, alpha: 1)
  53. }
  54. /// Multiline `NSTextField` often ignores `alignment` for wrapped runs; explicit paragraph alignment matches the title.
  55. private static func jobListingDescriptionAttributedString(_ plain: String) -> NSAttributedString {
  56. let paragraph = NSMutableParagraphStyle()
  57. paragraph.alignment = .left
  58. paragraph.lineBreakMode = .byWordWrapping
  59. paragraph.baseWritingDirection = .leftToRight
  60. let font = NSFont.systemFont(ofSize: 13, weight: .regular)
  61. return NSAttributedString(string: plain, attributes: [
  62. .font: font,
  63. .foregroundColor: Theme.secondaryText,
  64. .paragraphStyle: paragraph
  65. ])
  66. }
  67. private let contentStack = NSStackView()
  68. private let chromeContainer = NSView()
  69. private let sidebar = NSStackView()
  70. private let mainHost = NSView()
  71. private let mainOverlay = NSStackView()
  72. private let greetingLabel = NSTextField(labelWithString: "")
  73. private let subtitleLabel = NSTextField(labelWithString: "")
  74. private let searchBarShadowHost = NSView()
  75. private let searchCard = HoverableView()
  76. private let jobSearchIcon = NSImageView()
  77. private let jobKeywordsField = NSTextField()
  78. private let findJobsButton = HoverableButton()
  79. private let findJobsCTAHost = NSView()
  80. private let findJobsCTAChrome = HoverableView()
  81. private var findJobsCTAGradientLayer: CAGradientLayer?
  82. private let statusBannerContainer = NSView()
  83. private let statusBannerInner = NSView()
  84. private let statusBannerRow = NSStackView()
  85. private let chatStatusSymbolContainer = NSView()
  86. private let chatStatusIcon = NSImageView()
  87. private let chatStatusLoadingIndicator = NSProgressIndicator()
  88. private let chatStatusLabel = NSTextField(wrappingLabelWithString: "Opening the vault...")
  89. private let statusBrandTrailing = NSStackView()
  90. private let statusBrandStarIcon = NSImageView()
  91. private let statusBrandLabel = NSTextField(labelWithString: "AI Job Finder")
  92. private let welcomeSparkleIcon = NSImageView()
  93. private let featureCardsRow = NSStackView()
  94. private let chatScrollView = NSScrollView()
  95. private let chatDocumentView = JobListingsDocumentView()
  96. private let chatStack = NSStackView()
  97. /// Shown when a sidebar item other than Home is selected.
  98. private let nonHomeHost = NSView()
  99. private let nonHomeGenericContainer = NSView()
  100. private let nonHomeTitleLabel = NSTextField(labelWithString: "")
  101. private let nonHomeSubtitleLabel = NSTextField(wrappingLabelWithString: "")
  102. private let savedJobsPageContainer = NSView()
  103. private let savedJobsPageTitleLabel = NSTextField(labelWithString: "Saved Jobs")
  104. private let savedJobsPageSubtitleLabel = NSTextField(wrappingLabelWithString: "")
  105. private let savedJobsScrollView = NSScrollView()
  106. private let savedJobsDocumentView = JobListingsDocumentView()
  107. private let savedJobsStack = NSStackView()
  108. private let settingsPageContainer = NSView()
  109. private let themeControl = NSSegmentedControl(labels: ["System", "Light", "Dark"], trackingMode: .selectOne, target: nil, action: nil)
  110. private var currentSidebarItems: [SidebarItem] = []
  111. private var selectedSidebarIndex: Int = 0
  112. /// All jobs that have been shown in the current chat session, oldest first. Used to deduplicate continuation searches so "show more" doesn't re-display the same listings.
  113. private var lastSearchResults: [JobListing] = []
  114. /// "Show more jobs" row under the latest assistant message that listed jobs; removed when a newer listing block replaces it.
  115. private var trailingLoadMoreJobsRow: NSView?
  116. private weak var trailingLoadMoreJobsButton: HoverableButton?
  117. /// Most recently saved jobs appear first; persisted across launches.
  118. private var savedJobOrder: [JobListing] = []
  119. private var chatMessages: [ChatMessage] = []
  120. private var isAwaitingResponse = false
  121. private let jobSearchService = OpenAIJobSearchService()
  122. /// Upper bound sent to the model per request (was fixed at 8 in the prompt). Clamped when calling the API.
  123. private static let jobsPerSearchDefault = 15
  124. private static let jobsPerSearchMin = 1
  125. private static let jobsPerSearchMaxCap = 25
  126. private static func clampedJobsPerRequest(_ requested: Int = jobsPerSearchDefault) -> Int {
  127. min(jobsPerSearchMaxCap, max(jobsPerSearchMin, requested))
  128. }
  129. private static let chatStatusSparklePulseKey = "chatStatusSparklePulse"
  130. private static let welcomeSubtitleBreathKey = "welcomeSubtitleBreath"
  131. override init(frame frameRect: NSRect) {
  132. super.init(frame: frameRect)
  133. setupLayout()
  134. }
  135. required init?(coder: NSCoder) {
  136. super.init(coder: coder)
  137. setupLayout()
  138. }
  139. override func layout() {
  140. super.layout()
  141. updateSearchBarShadowPath()
  142. findJobsCTAGradientLayer?.frame = findJobsCTAChrome.bounds
  143. updateFindJobsCTAShadowPath()
  144. updateJobListingDescriptionWidths()
  145. updateChatBubbleWidths()
  146. updateStatusBannerLabelWidth()
  147. }
  148. func render(_ data: DashboardData) {
  149. greetingLabel.stringValue = "Welcome"
  150. subtitleLabel.stringValue = data.subtitle
  151. currentSidebarItems = data.sidebarItems
  152. if selectedSidebarIndex >= currentSidebarItems.count {
  153. selectedSidebarIndex = max(0, currentSidebarItems.count - 1)
  154. }
  155. configureSidebar()
  156. savedJobOrder = Self.normalizedSavedJobs(SavedJobsStore.load())
  157. resetChatState()
  158. updateMainContentVisibility()
  159. }
  160. private func setupLayout() {
  161. wantsLayer = true
  162. layer?.backgroundColor = Theme.pageBackground.cgColor
  163. contentStack.orientation = .horizontal
  164. contentStack.spacing = 10
  165. contentStack.distribution = .fill
  166. contentStack.translatesAutoresizingMaskIntoConstraints = false
  167. contentStack.alignment = .height
  168. // Tighter chrome insets so panels sit closer to the window edges (especially leading / top under the title bar).
  169. contentStack.edgeInsets = NSEdgeInsets(top: 10, left: 12, bottom: 20, right: 20)
  170. chromeContainer.translatesAutoresizingMaskIntoConstraints = false
  171. chromeContainer.wantsLayer = true
  172. chromeContainer.layer?.backgroundColor = Theme.chromeBackground.cgColor
  173. chromeContainer.layer?.cornerRadius = 0
  174. addSubview(chromeContainer)
  175. chromeContainer.addSubview(contentStack)
  176. sidebar.orientation = .vertical
  177. sidebar.spacing = 10
  178. sidebar.distribution = .fill
  179. sidebar.alignment = .leading
  180. sidebar.wantsLayer = true
  181. sidebar.layer?.backgroundColor = Theme.sidebarBackground.cgColor
  182. sidebar.layer?.cornerRadius = 16
  183. sidebar.edgeInsets = NSEdgeInsets(top: 16, left: 12, bottom: 16, right: 12)
  184. sidebar.translatesAutoresizingMaskIntoConstraints = false
  185. mainHost.translatesAutoresizingMaskIntoConstraints = false
  186. mainHost.wantsLayer = true
  187. mainHost.layer?.backgroundColor = Theme.mainHostBackground.cgColor
  188. mainHost.layer?.cornerRadius = 16
  189. mainHost.layer?.masksToBounds = true
  190. sidebar.setContentHuggingPriority(.required, for: .horizontal)
  191. mainHost.setContentHuggingPriority(.defaultLow, for: .horizontal)
  192. mainHost.addSubview(mainOverlay)
  193. configureNonHomePlaceholder()
  194. mainHost.addSubview(nonHomeHost)
  195. mainOverlay.orientation = .vertical
  196. mainOverlay.spacing = 0
  197. mainOverlay.alignment = .centerX
  198. mainOverlay.distribution = .fill
  199. mainOverlay.translatesAutoresizingMaskIntoConstraints = false
  200. mainOverlay.setContentHuggingPriority(.defaultLow, for: .vertical)
  201. greetingLabel.font = .systemFont(ofSize: 32, weight: .bold)
  202. greetingLabel.textColor = Theme.brandBlue
  203. greetingLabel.alignment = .center
  204. greetingLabel.maximumNumberOfLines = 1
  205. subtitleLabel.font = .systemFont(ofSize: 15, weight: .regular)
  206. subtitleLabel.textColor = Theme.welcomeSubtitleText
  207. subtitleLabel.alignment = .center
  208. subtitleLabel.maximumNumberOfLines = 2
  209. subtitleLabel.wantsLayer = true
  210. let topInset = NSView()
  211. topInset.translatesAutoresizingMaskIntoConstraints = false
  212. topInset.heightAnchor.constraint(equalToConstant: 18).isActive = true
  213. configureSearchBar()
  214. configureChatViews()
  215. welcomeSparkleIcon.translatesAutoresizingMaskIntoConstraints = false
  216. welcomeSparkleIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 16, weight: .semibold)
  217. welcomeSparkleIcon.image = NSImage(systemSymbolName: "sparkles", accessibilityDescription: nil)
  218. welcomeSparkleIcon.contentTintColor = Theme.brandBlue
  219. let titleBlock = NSStackView(views: [greetingLabel, subtitleLabel, welcomeSparkleIcon])
  220. titleBlock.orientation = .vertical
  221. titleBlock.spacing = 10
  222. titleBlock.alignment = .centerX
  223. configureFeatureShortcutCards()
  224. let midSpacer = NSView()
  225. midSpacer.translatesAutoresizingMaskIntoConstraints = false
  226. midSpacer.heightAnchor.constraint(equalToConstant: 12).isActive = true
  227. let chatTopSpacer = NSView()
  228. chatTopSpacer.translatesAutoresizingMaskIntoConstraints = false
  229. chatTopSpacer.heightAnchor.constraint(equalToConstant: 14).isActive = true
  230. let chatBottomSpacer = NSView()
  231. chatBottomSpacer.translatesAutoresizingMaskIntoConstraints = false
  232. chatBottomSpacer.heightAnchor.constraint(equalToConstant: 14).isActive = true
  233. mainOverlay.addArrangedSubview(topInset)
  234. mainOverlay.addArrangedSubview(titleBlock)
  235. mainOverlay.addArrangedSubview(featureCardsRow)
  236. mainOverlay.addArrangedSubview(midSpacer)
  237. mainOverlay.addArrangedSubview(statusBannerContainer)
  238. mainOverlay.addArrangedSubview(chatTopSpacer)
  239. mainOverlay.addArrangedSubview(chatScrollView)
  240. mainOverlay.addArrangedSubview(chatBottomSpacer)
  241. mainOverlay.addArrangedSubview(searchBarShadowHost)
  242. contentStack.addArrangedSubview(sidebar)
  243. contentStack.addArrangedSubview(mainHost)
  244. NSLayoutConstraint.activate([
  245. chromeContainer.leadingAnchor.constraint(equalTo: leadingAnchor),
  246. chromeContainer.trailingAnchor.constraint(equalTo: trailingAnchor),
  247. chromeContainer.topAnchor.constraint(equalTo: topAnchor),
  248. chromeContainer.bottomAnchor.constraint(equalTo: bottomAnchor),
  249. contentStack.leadingAnchor.constraint(equalTo: chromeContainer.leadingAnchor),
  250. contentStack.trailingAnchor.constraint(equalTo: chromeContainer.trailingAnchor),
  251. contentStack.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
  252. contentStack.bottomAnchor.constraint(equalTo: chromeContainer.bottomAnchor),
  253. sidebar.widthAnchor.constraint(equalToConstant: 218),
  254. mainHost.widthAnchor.constraint(greaterThanOrEqualToConstant: 720),
  255. mainOverlay.leadingAnchor.constraint(equalTo: mainHost.leadingAnchor),
  256. mainOverlay.trailingAnchor.constraint(equalTo: mainHost.trailingAnchor),
  257. mainOverlay.topAnchor.constraint(equalTo: mainHost.topAnchor),
  258. mainOverlay.bottomAnchor.constraint(equalTo: mainHost.bottomAnchor, constant: -24),
  259. nonHomeHost.leadingAnchor.constraint(equalTo: mainHost.leadingAnchor),
  260. nonHomeHost.trailingAnchor.constraint(equalTo: mainHost.trailingAnchor),
  261. nonHomeHost.topAnchor.constraint(equalTo: mainHost.topAnchor),
  262. nonHomeHost.bottomAnchor.constraint(equalTo: mainHost.bottomAnchor, constant: -24),
  263. searchBarShadowHost.widthAnchor.constraint(equalTo: mainOverlay.widthAnchor, multiplier: 0.92),
  264. statusBannerContainer.widthAnchor.constraint(equalTo: mainOverlay.widthAnchor, multiplier: 0.92),
  265. featureCardsRow.widthAnchor.constraint(equalTo: mainOverlay.widthAnchor, multiplier: 0.92),
  266. chatScrollView.widthAnchor.constraint(equalTo: mainOverlay.widthAnchor, multiplier: 0.92),
  267. greetingLabel.leadingAnchor.constraint(equalTo: mainOverlay.leadingAnchor, constant: 16),
  268. greetingLabel.trailingAnchor.constraint(equalTo: mainOverlay.trailingAnchor, constant: -16),
  269. subtitleLabel.leadingAnchor.constraint(equalTo: greetingLabel.leadingAnchor),
  270. subtitleLabel.trailingAnchor.constraint(equalTo: greetingLabel.trailingAnchor)
  271. ])
  272. }
  273. private func configureFeatureShortcutCards() {
  274. featureCardsRow.orientation = .horizontal
  275. featureCardsRow.spacing = 12
  276. featureCardsRow.distribution = .fillEqually
  277. featureCardsRow.alignment = .top
  278. featureCardsRow.translatesAutoresizingMaskIntoConstraints = false
  279. let specs: [(symbol: String, title: String, subtitle: String, action: Selector)] = [
  280. ("briefcase.fill", "Role", "Explore similar or better job roles", #selector(didTapFeatureRole)),
  281. ("building.2.fill", "Company", "Find opportunities at other companies", #selector(didTapFeatureCompany)),
  282. ("chevron.left.forwardslash.chevron.right", "Skill", "Match jobs that fit your skills", #selector(didTapFeatureSkill))
  283. ]
  284. for spec in specs {
  285. let card = FeatureShortcutCardView(
  286. symbolName: spec.symbol,
  287. title: spec.title,
  288. subtitle: spec.subtitle,
  289. target: self,
  290. action: spec.action
  291. )
  292. featureCardsRow.addArrangedSubview(card)
  293. }
  294. }
  295. private func configureChatViews() {
  296. statusBannerContainer.translatesAutoresizingMaskIntoConstraints = false
  297. statusBannerContainer.setContentHuggingPriority(.defaultHigh, for: .vertical)
  298. statusBannerInner.translatesAutoresizingMaskIntoConstraints = false
  299. statusBannerInner.wantsLayer = true
  300. statusBannerInner.layer?.backgroundColor = Theme.statusBannerBackground.cgColor
  301. statusBannerInner.layer?.cornerRadius = 14
  302. if #available(macOS 11.0, *) {
  303. statusBannerInner.layer?.cornerCurve = .continuous
  304. }
  305. statusBannerInner.layer?.masksToBounds = true
  306. statusBannerContainer.addSubview(statusBannerInner)
  307. statusBannerRow.orientation = .horizontal
  308. statusBannerRow.spacing = 12
  309. statusBannerRow.alignment = .top
  310. statusBannerRow.translatesAutoresizingMaskIntoConstraints = false
  311. chatStatusSymbolContainer.translatesAutoresizingMaskIntoConstraints = false
  312. chatStatusSymbolContainer.wantsLayer = true
  313. chatStatusSymbolContainer.layer?.backgroundColor = Theme.brandBlue.cgColor
  314. chatStatusSymbolContainer.layer?.cornerRadius = 20
  315. chatStatusIcon.translatesAutoresizingMaskIntoConstraints = false
  316. chatStatusIcon.wantsLayer = true
  317. chatStatusIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 15, weight: .semibold)
  318. chatStatusIcon.image = NSImage(systemSymbolName: "sparkles", accessibilityDescription: "Assistant status")
  319. chatStatusIcon.contentTintColor = .white
  320. chatStatusLoadingIndicator.translatesAutoresizingMaskIntoConstraints = false
  321. chatStatusLoadingIndicator.style = .spinning
  322. chatStatusLoadingIndicator.isIndeterminate = true
  323. chatStatusLoadingIndicator.isDisplayedWhenStopped = false
  324. chatStatusLoadingIndicator.controlSize = .regular
  325. chatStatusLoadingIndicator.isHidden = true
  326. chatStatusLoadingIndicator.setAccessibilityRole(.progressIndicator)
  327. chatStatusLoadingIndicator.setAccessibilityLabel("Searching for jobs")
  328. chatStatusSymbolContainer.addSubview(chatStatusIcon)
  329. chatStatusSymbolContainer.addSubview(chatStatusLoadingIndicator)
  330. NSLayoutConstraint.activate([
  331. chatStatusSymbolContainer.widthAnchor.constraint(equalToConstant: 40),
  332. chatStatusSymbolContainer.heightAnchor.constraint(equalToConstant: 40),
  333. chatStatusIcon.centerXAnchor.constraint(equalTo: chatStatusSymbolContainer.centerXAnchor),
  334. chatStatusIcon.centerYAnchor.constraint(equalTo: chatStatusSymbolContainer.centerYAnchor),
  335. chatStatusLoadingIndicator.centerXAnchor.constraint(equalTo: chatStatusSymbolContainer.centerXAnchor),
  336. chatStatusLoadingIndicator.centerYAnchor.constraint(equalTo: chatStatusSymbolContainer.centerYAnchor),
  337. chatStatusLoadingIndicator.widthAnchor.constraint(equalToConstant: 26),
  338. chatStatusLoadingIndicator.heightAnchor.constraint(equalToConstant: 26)
  339. ])
  340. chatStatusLabel.font = .systemFont(ofSize: 13, weight: .regular)
  341. chatStatusLabel.textColor = Theme.primaryText
  342. chatStatusLabel.alignment = .left
  343. chatStatusLabel.maximumNumberOfLines = 0
  344. chatStatusLabel.lineBreakMode = .byWordWrapping
  345. chatStatusLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
  346. chatStatusLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  347. chatStatusLabel.translatesAutoresizingMaskIntoConstraints = false
  348. statusBrandStarIcon.translatesAutoresizingMaskIntoConstraints = false
  349. statusBrandStarIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
  350. statusBrandStarIcon.image = NSImage(systemSymbolName: "sparkle", accessibilityDescription: nil)
  351. statusBrandStarIcon.contentTintColor = Theme.brandBlue
  352. statusBrandLabel.font = .systemFont(ofSize: 12, weight: .semibold)
  353. statusBrandLabel.textColor = Theme.brandBlue
  354. statusBrandLabel.alignment = .right
  355. statusBrandLabel.maximumNumberOfLines = 1
  356. statusBrandTrailing.orientation = .horizontal
  357. statusBrandTrailing.spacing = 5
  358. statusBrandTrailing.alignment = .centerY
  359. statusBrandTrailing.translatesAutoresizingMaskIntoConstraints = false
  360. statusBrandTrailing.addArrangedSubview(statusBrandStarIcon)
  361. statusBrandTrailing.addArrangedSubview(statusBrandLabel)
  362. statusBrandTrailing.setContentHuggingPriority(.required, for: .horizontal)
  363. statusBrandTrailing.setContentCompressionResistancePriority(.required, for: .horizontal)
  364. statusBannerRow.addArrangedSubview(chatStatusSymbolContainer)
  365. statusBannerRow.addArrangedSubview(chatStatusLabel)
  366. statusBannerInner.addSubview(statusBannerRow)
  367. statusBannerContainer.addSubview(statusBannerInner)
  368. statusBannerContainer.addSubview(statusBrandTrailing)
  369. statusBannerInner.setContentHuggingPriority(.defaultHigh, for: .horizontal)
  370. statusBannerInner.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  371. NSLayoutConstraint.activate([
  372. statusBannerInner.leadingAnchor.constraint(equalTo: statusBannerContainer.leadingAnchor),
  373. statusBannerInner.topAnchor.constraint(equalTo: statusBannerContainer.topAnchor),
  374. statusBannerInner.bottomAnchor.constraint(equalTo: statusBannerContainer.bottomAnchor),
  375. statusBannerInner.trailingAnchor.constraint(lessThanOrEqualTo: statusBrandTrailing.leadingAnchor, constant: -16),
  376. statusBrandTrailing.trailingAnchor.constraint(equalTo: statusBannerContainer.trailingAnchor),
  377. statusBrandTrailing.centerYAnchor.constraint(equalTo: statusBannerContainer.centerYAnchor),
  378. statusBannerRow.leadingAnchor.constraint(equalTo: statusBannerInner.leadingAnchor, constant: 14),
  379. statusBannerRow.trailingAnchor.constraint(equalTo: statusBannerInner.trailingAnchor, constant: -16),
  380. statusBannerRow.topAnchor.constraint(equalTo: statusBannerInner.topAnchor, constant: 10),
  381. statusBannerRow.bottomAnchor.constraint(equalTo: statusBannerInner.bottomAnchor, constant: -10),
  382. statusBannerContainer.heightAnchor.constraint(greaterThanOrEqualToConstant: 52)
  383. ])
  384. syncChatStatusLoadingIndicator(forStatusText: chatStatusLabel.stringValue)
  385. syncChatStatusBannerVisuals(forStatusText: chatStatusLabel.stringValue)
  386. chatDocumentView.translatesAutoresizingMaskIntoConstraints = false
  387. chatStack.orientation = .vertical
  388. chatStack.spacing = 18
  389. chatStack.alignment = .width
  390. chatStack.distribution = .fill
  391. chatStack.translatesAutoresizingMaskIntoConstraints = false
  392. chatDocumentView.addSubview(chatStack)
  393. NSLayoutConstraint.activate([
  394. chatStack.leadingAnchor.constraint(equalTo: chatDocumentView.leadingAnchor, constant: 4),
  395. chatStack.trailingAnchor.constraint(equalTo: chatDocumentView.trailingAnchor, constant: -4),
  396. chatStack.topAnchor.constraint(equalTo: chatDocumentView.topAnchor, constant: 8),
  397. chatStack.bottomAnchor.constraint(equalTo: chatDocumentView.bottomAnchor, constant: -8)
  398. ])
  399. chatScrollView.translatesAutoresizingMaskIntoConstraints = false
  400. chatScrollView.hasVerticalScroller = true
  401. chatScrollView.hasHorizontalScroller = false
  402. // Legacy reserves a dedicated track to the right of the clip view so the thumb never sits on top of cards/buttons.
  403. chatScrollView.scrollerStyle = .legacy
  404. chatScrollView.autohidesScrollers = true
  405. chatScrollView.drawsBackground = false
  406. chatScrollView.borderType = .noBorder
  407. chatScrollView.documentView = chatDocumentView
  408. chatScrollView.setContentHuggingPriority(.defaultLow, for: .vertical)
  409. chatScrollView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  410. chatScrollView.heightAnchor.constraint(greaterThanOrEqualToConstant: 320).isActive = true
  411. // Match Saved Jobs: pin document width to the clip view so cards and bubbles track window width instead of sticking to a narrow intrinsic width.
  412. NSLayoutConstraint.activate([
  413. chatDocumentView.topAnchor.constraint(equalTo: chatScrollView.contentView.topAnchor),
  414. chatDocumentView.leadingAnchor.constraint(equalTo: chatScrollView.contentView.leadingAnchor),
  415. chatDocumentView.widthAnchor.constraint(equalTo: chatScrollView.contentView.widthAnchor)
  416. ])
  417. }
  418. private func setChatStatusLabel(_ text: String) {
  419. chatStatusLabel.stringValue = text
  420. syncChatStatusLoadingIndicator(forStatusText: text)
  421. syncChatStatusBannerVisuals(forStatusText: text)
  422. syncChatStatusSparkleAnimation()
  423. updateStatusBannerLabelWidth()
  424. }
  425. private func updateStatusBannerLabelWidth() {
  426. guard statusBannerContainer.bounds.width > 1 else { return }
  427. let trailingWidth = max(96, statusBrandTrailing.fittingSize.width)
  428. let chrome: CGFloat = 14 + 40 + 12 + 16 + 16 + trailingWidth
  429. let target = max(80, statusBannerContainer.bounds.width - chrome)
  430. if abs(chatStatusLabel.preferredMaxLayoutWidth - target) > 0.5 {
  431. chatStatusLabel.preferredMaxLayoutWidth = target
  432. chatStatusLabel.invalidateIntrinsicContentSize()
  433. }
  434. }
  435. /// Leading status glyph: sparkles for prompts, magnifying glass for search-result summaries and errors.
  436. private func syncChatStatusBannerVisuals(forStatusText text: String) {
  437. if text == "Thinking..." { return }
  438. let lower = text.lowercased()
  439. let useMagnifyingGlass =
  440. text.hasPrefix("Found ")
  441. || text.hasPrefix("Here are")
  442. || text.hasPrefix("No jobs")
  443. || text.contains("couldn't find")
  444. || lower.contains("try again")
  445. || lower.contains("could not reach")
  446. || lower.contains("search did not finish")
  447. let config = NSImage.SymbolConfiguration(pointSize: 15, weight: .semibold)
  448. chatStatusIcon.symbolConfiguration = config
  449. if useMagnifyingGlass {
  450. chatStatusIcon.image = NSImage(systemSymbolName: "magnifyingglass", accessibilityDescription: "Search status")
  451. } else {
  452. chatStatusIcon.image = NSImage(systemSymbolName: "sparkles", accessibilityDescription: "Assistant status")
  453. }
  454. chatStatusIcon.contentTintColor = .white
  455. chatStatusSymbolContainer.layer?.backgroundColor = Theme.brandBlue.cgColor
  456. }
  457. private func syncChatStatusLoadingIndicator(forStatusText text: String) {
  458. let loading = (text == "Thinking...")
  459. if loading {
  460. chatStatusIcon.isHidden = true
  461. chatStatusLoadingIndicator.isHidden = false
  462. chatStatusLoadingIndicator.startAnimation(nil)
  463. chatStatusSymbolContainer.layer?.backgroundColor = Theme.featureIconWell.cgColor
  464. } else {
  465. chatStatusLoadingIndicator.stopAnimation(nil)
  466. chatStatusIcon.isHidden = false
  467. chatStatusLoadingIndicator.isHidden = true
  468. chatStatusSymbolContainer.layer?.backgroundColor = Theme.brandBlue.cgColor
  469. }
  470. }
  471. private func isWelcomeHeroVisible() -> Bool {
  472. !mainOverlay.isHidden
  473. }
  474. private var prefersReducedMotion: Bool {
  475. NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
  476. }
  477. private func shouldAnimateChatStatusSparkles(for statusText: String) -> Bool {
  478. statusText == "Ask me to find jobs"
  479. || statusText == "Opening the vault..."
  480. }
  481. private func syncChatStatusSparkleAnimation() {
  482. guard !prefersReducedMotion else {
  483. stopChatStatusSparkleAnimation()
  484. return
  485. }
  486. guard isWelcomeHeroVisible(), shouldAnimateChatStatusSparkles(for: chatStatusLabel.stringValue) else {
  487. stopChatStatusSparkleAnimation()
  488. return
  489. }
  490. guard let layer = chatStatusIcon.layer, layer.animation(forKey: Self.chatStatusSparklePulseKey) == nil else { return }
  491. let scale = CABasicAnimation(keyPath: "transform.scale")
  492. scale.fromValue = 1.0
  493. scale.toValue = 1.1
  494. scale.duration = 1.25
  495. scale.autoreverses = true
  496. scale.repeatCount = .greatestFiniteMagnitude
  497. scale.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  498. layer.add(scale, forKey: Self.chatStatusSparklePulseKey)
  499. }
  500. private func stopChatStatusSparkleAnimation() {
  501. chatStatusIcon.layer?.removeAnimation(forKey: Self.chatStatusSparklePulseKey)
  502. chatStatusIcon.layer?.transform = CATransform3DIdentity
  503. }
  504. private func syncWelcomeSubtitleBreathingAnimation() {
  505. guard !prefersReducedMotion else {
  506. stopWelcomeSubtitleBreathingAnimation()
  507. return
  508. }
  509. guard isWelcomeHeroVisible(), !subtitleLabel.stringValue.isEmpty else {
  510. stopWelcomeSubtitleBreathingAnimation()
  511. return
  512. }
  513. guard let layer = subtitleLabel.layer, layer.animation(forKey: Self.welcomeSubtitleBreathKey) == nil else { return }
  514. let pulse = CABasicAnimation(keyPath: "opacity")
  515. pulse.fromValue = 1.0
  516. pulse.toValue = 0.86
  517. pulse.duration = 2.4
  518. pulse.autoreverses = true
  519. pulse.repeatCount = .greatestFiniteMagnitude
  520. pulse.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  521. layer.add(pulse, forKey: Self.welcomeSubtitleBreathKey)
  522. }
  523. private func stopWelcomeSubtitleBreathingAnimation() {
  524. subtitleLabel.layer?.removeAnimation(forKey: Self.welcomeSubtitleBreathKey)
  525. subtitleLabel.layer?.opacity = 1
  526. }
  527. private func updateJobListingDescriptionWidths() {
  528. updateDescriptionColumnWidths(in: savedJobsStack, containerWidth: savedJobsDocumentView.bounds.width)
  529. walkChatJobStacks { stack in
  530. updateDescriptionColumnWidths(in: stack, containerWidth: stack.bounds.width)
  531. }
  532. }
  533. private func walkChatJobStacks(_ visitor: (ChatJobsStackView) -> Void) {
  534. func walk(_ view: NSView) {
  535. if let stack = view as? ChatJobsStackView {
  536. visitor(stack)
  537. }
  538. for sub in view.subviews { walk(sub) }
  539. }
  540. walk(chatStack)
  541. }
  542. /// Chat bubble text fields are wrapping labels whose `preferredMaxLayoutWidth` needs to track the available row width so long strings reflow correctly when the window resizes.
  543. private func updateChatBubbleWidths() {
  544. func walk(_ view: NSView) {
  545. if let label = view as? ChatBubbleLabel,
  546. let bubble = label.superview, bubble.bounds.width > 1 {
  547. let target = max(40, bubble.bounds.width - 28)
  548. if abs(label.preferredMaxLayoutWidth - target) > 0.5 {
  549. label.preferredMaxLayoutWidth = target
  550. label.invalidateIntrinsicContentSize()
  551. }
  552. }
  553. for sub in view.subviews { walk(sub) }
  554. }
  555. walk(chatStack)
  556. }
  557. private func updateDescriptionColumnWidths(in stack: NSStackView, containerWidth: CGFloat) {
  558. guard containerWidth > 1 else { return }
  559. // 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.
  560. let contentHorizontalInset: CGFloat = 32
  561. var didChange = false
  562. for card in stack.arrangedSubviews {
  563. guard let desc = card.viewWithTag(502) as? NSTextField else { continue }
  564. let cardWidth = card.bounds.width > 1 ? card.bounds.width : containerWidth
  565. let fallbackColumn = max(1, cardWidth - contentHorizontalInset)
  566. let columnWidth: CGFloat
  567. if desc.bounds.width > 1 {
  568. columnWidth = desc.bounds.width
  569. } else if let column = desc.superview, column.bounds.width > 1 {
  570. columnWidth = column.bounds.width
  571. } else {
  572. columnWidth = fallbackColumn
  573. }
  574. if abs(desc.preferredMaxLayoutWidth - columnWidth) > 0.5 {
  575. desc.preferredMaxLayoutWidth = columnWidth
  576. desc.invalidateIntrinsicContentSize()
  577. didChange = true
  578. }
  579. }
  580. if didChange {
  581. stack.needsLayout = true
  582. }
  583. }
  584. private static func normalizedSavedJobs(_ jobs: [JobListing]) -> [JobListing] {
  585. var seen = Set<JobListing>()
  586. var out: [JobListing] = []
  587. for job in jobs where seen.insert(job).inserted {
  588. out.append(job)
  589. }
  590. return out
  591. }
  592. private func isJobSaved(_ job: JobListing) -> Bool {
  593. savedJobOrder.contains(job)
  594. }
  595. private func persistSavedJobs() {
  596. SavedJobsStore.save(savedJobOrder)
  597. }
  598. private func applySavedState(_ saved: Bool, for job: JobListing) {
  599. if saved {
  600. savedJobOrder.removeAll { $0 == job }
  601. savedJobOrder.insert(job, at: 0)
  602. } else {
  603. savedJobOrder.removeAll { $0 == job }
  604. }
  605. persistSavedJobs()
  606. }
  607. private func jobListingHostSubtitle(_ job: JobListing) -> String {
  608. guard let raw = job.url, let url = URL(string: raw), let host = url.host?.lowercased() else {
  609. return "Indeed"
  610. }
  611. if host.hasPrefix("www.") {
  612. return String(host.dropFirst(4))
  613. }
  614. return host
  615. }
  616. private func jobListingCategorySymbol(for job: JobListing) -> String {
  617. let blob = (job.title + " " + job.description).lowercased()
  618. if blob.contains("machine learning") || blob.contains("deep learning") || blob.contains(" ml ") {
  619. return "brain.head.profile"
  620. }
  621. if blob.contains("audio") || blob.contains(" sound ") || blob.contains("dsp") {
  622. return "waveform"
  623. }
  624. if blob.contains("ios") || blob.contains("swift") || blob.contains("mobile") {
  625. return "iphone"
  626. }
  627. if blob.contains("design") || blob.contains(" ux") || blob.contains("figma") {
  628. return "paintpalette.fill"
  629. }
  630. if blob.contains("data ") || blob.contains("analytics") {
  631. return "chart.bar.fill"
  632. }
  633. if blob.contains("ai") || blob.contains("llm") || blob.contains("nlp") {
  634. return "cpu"
  635. }
  636. return "briefcase.fill"
  637. }
  638. private func makeJobListingCard(_ job: JobListing, context: JobListingCardContext) -> NSView {
  639. let card = NSView()
  640. card.translatesAutoresizingMaskIntoConstraints = false
  641. card.wantsLayer = true
  642. card.layer?.backgroundColor = Theme.cardBackground.cgColor
  643. card.layer?.cornerRadius = 14
  644. card.layer?.borderWidth = 1
  645. card.layer?.borderColor = Theme.border.cgColor
  646. card.layer?.masksToBounds = true
  647. let iconBox = NSView()
  648. iconBox.translatesAutoresizingMaskIntoConstraints = false
  649. iconBox.wantsLayer = true
  650. iconBox.layer?.backgroundColor = Theme.brandBlue.cgColor
  651. iconBox.layer?.cornerRadius = 12
  652. if #available(macOS 11.0, *) {
  653. iconBox.layer?.cornerCurve = .continuous
  654. }
  655. let categoryIcon = NSImageView()
  656. categoryIcon.translatesAutoresizingMaskIntoConstraints = false
  657. categoryIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 22, weight: .medium)
  658. categoryIcon.image = NSImage(systemSymbolName: jobListingCategorySymbol(for: job), accessibilityDescription: nil)
  659. categoryIcon.contentTintColor = .white
  660. iconBox.addSubview(categoryIcon)
  661. let titleField = NSTextField(labelWithString: job.title)
  662. titleField.font = .systemFont(ofSize: 16, weight: .semibold)
  663. titleField.textColor = Theme.brandBlue
  664. titleField.maximumNumberOfLines = 2
  665. titleField.lineBreakMode = .byWordWrapping
  666. titleField.alignment = .left
  667. titleField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  668. titleField.translatesAutoresizingMaskIntoConstraints = false
  669. let buildingIcon = NSImageView()
  670. buildingIcon.translatesAutoresizingMaskIntoConstraints = false
  671. buildingIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 12, weight: .medium)
  672. buildingIcon.image = NSImage(systemSymbolName: "building.2.fill", accessibilityDescription: nil)
  673. buildingIcon.contentTintColor = Theme.welcomeSubtitleText
  674. let companyLabel = NSTextField(labelWithString: jobListingHostSubtitle(job))
  675. companyLabel.font = .systemFont(ofSize: 12, weight: .medium)
  676. companyLabel.textColor = Theme.welcomeSubtitleText
  677. companyLabel.maximumNumberOfLines = 1
  678. companyLabel.lineBreakMode = .byTruncatingTail
  679. companyLabel.translatesAutoresizingMaskIntoConstraints = false
  680. let companyRow = NSStackView(views: [buildingIcon, companyLabel])
  681. companyRow.orientation = .horizontal
  682. companyRow.spacing = 5
  683. companyRow.alignment = .centerY
  684. companyRow.translatesAutoresizingMaskIntoConstraints = false
  685. let descriptionField = NSTextField(wrappingLabelWithString: job.description)
  686. descriptionField.font = .systemFont(ofSize: 13, weight: .regular)
  687. descriptionField.textColor = Theme.secondaryText
  688. descriptionField.maximumNumberOfLines = 2
  689. descriptionField.lineBreakMode = .byWordWrapping
  690. descriptionField.alignment = .left
  691. descriptionField.baseWritingDirection = .leftToRight
  692. descriptionField.attributedStringValue = Self.jobListingDescriptionAttributedString(job.description)
  693. if let cell = descriptionField.cell as? NSTextFieldCell {
  694. cell.alignment = .left
  695. cell.wraps = true
  696. }
  697. descriptionField.setContentHuggingPriority(.defaultLow, for: .horizontal)
  698. descriptionField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  699. descriptionField.tag = 502
  700. descriptionField.translatesAutoresizingMaskIntoConstraints = false
  701. let applyButton = JobPayloadButton(title: "Apply", target: self, action: #selector(didTapJobApply(_:)))
  702. applyButton.jobPayload = job
  703. applyButton.cardContext = context
  704. applyButton.isBordered = false
  705. applyButton.bezelStyle = .rounded
  706. applyButton.font = .systemFont(ofSize: 13, weight: .semibold)
  707. applyButton.wantsLayer = true
  708. applyButton.layer?.cornerRadius = 8
  709. applyButton.layer?.backgroundColor = Theme.brandBlue.cgColor
  710. applyButton.contentTintColor = Theme.proCTAText
  711. applyButton.focusRingType = .none
  712. applyButton.pointerCursor = true
  713. applyButton.hoverHandler = { [weak applyButton] hovering in
  714. applyButton?.layer?.backgroundColor = (hovering ? Theme.brandBlueHover : Theme.brandBlue).cgColor
  715. }
  716. applyButton.setContentHuggingPriority(.required, for: .horizontal)
  717. applyButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  718. let savedOn = isJobSaved(job)
  719. let savedButton = JobPayloadButton(title: savedOn ? "Saved" : "Save", target: self, action: #selector(didTapJobSaved(_:)))
  720. savedButton.jobPayload = job
  721. savedButton.cardContext = context
  722. savedButton.setButtonType(.toggle)
  723. savedButton.isBordered = false
  724. savedButton.bezelStyle = .rounded
  725. savedButton.font = .systemFont(ofSize: 13, weight: .semibold)
  726. savedButton.image = NSImage(systemSymbolName: savedOn ? "heart.fill" : "heart", accessibilityDescription: nil)
  727. savedButton.imagePosition = .imageLeading
  728. savedButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .semibold)
  729. savedButton.focusRingType = .none
  730. savedButton.state = savedOn ? .on : .off
  731. savedButton.pointerCursor = true
  732. savedButton.hoverHandler = { [weak self, weak savedButton] _ in
  733. guard let savedButton = savedButton else { return }
  734. self?.styleJobSavedButton(savedButton)
  735. }
  736. styleJobSavedButton(savedButton)
  737. savedButton.setContentHuggingPriority(.required, for: .horizontal)
  738. savedButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  739. let dismissButton = JobPayloadButton()
  740. dismissButton.jobPayload = job
  741. dismissButton.cardContext = context
  742. dismissButton.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Dismiss")
  743. dismissButton.imagePosition = .imageOnly
  744. dismissButton.imageScaling = .scaleProportionallyDown
  745. dismissButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
  746. dismissButton.isBordered = false
  747. dismissButton.bezelStyle = .rounded
  748. dismissButton.contentTintColor = Theme.secondaryText
  749. dismissButton.target = self
  750. dismissButton.action = #selector(didTapJobDismiss(_:))
  751. dismissButton.toolTip = context == .savedJobsPage ? "Remove from saved" : "Dismiss"
  752. dismissButton.focusRingType = .none
  753. dismissButton.wantsLayer = true
  754. dismissButton.layer?.cornerRadius = 8
  755. dismissButton.layer?.backgroundColor = NSColor.clear.cgColor
  756. dismissButton.pointerCursor = true
  757. dismissButton.hoverHandler = { [weak dismissButton] hovering in
  758. dismissButton?.layer?.backgroundColor = (hovering ? Theme.neutralHoverFill : NSColor.clear).cgColor
  759. dismissButton?.contentTintColor = hovering ? Theme.primaryText : Theme.secondaryText
  760. }
  761. dismissButton.setContentHuggingPriority(.required, for: .horizontal)
  762. let buttonRow = NSStackView(views: [applyButton, savedButton, dismissButton])
  763. buttonRow.orientation = .horizontal
  764. buttonRow.spacing = 8
  765. buttonRow.alignment = .top
  766. buttonRow.translatesAutoresizingMaskIntoConstraints = false
  767. buttonRow.setContentHuggingPriority(.required, for: .horizontal)
  768. buttonRow.setContentCompressionResistancePriority(.required, for: .horizontal)
  769. buttonRow.setContentHuggingPriority(.required, for: .vertical)
  770. buttonRow.setContentCompressionResistancePriority(.required, for: .vertical)
  771. applyButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  772. savedButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  773. dismissButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  774. let middleColumn = NSStackView(views: [titleField, companyRow, descriptionField])
  775. middleColumn.orientation = .vertical
  776. middleColumn.spacing = 5
  777. middleColumn.alignment = .leading
  778. middleColumn.translatesAutoresizingMaskIntoConstraints = false
  779. middleColumn.setContentHuggingPriority(.defaultLow, for: .horizontal)
  780. middleColumn.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  781. let contentRow = NSStackView(views: [iconBox, middleColumn])
  782. contentRow.orientation = .horizontal
  783. contentRow.spacing = 14
  784. contentRow.alignment = .top
  785. contentRow.distribution = .fill
  786. contentRow.translatesAutoresizingMaskIntoConstraints = false
  787. card.addSubview(contentRow)
  788. card.addSubview(buttonRow)
  789. let actionCornerInset: CGFloat = 8
  790. let contentToActionsGap: CGFloat = 12
  791. let bodyTrailingInset: CGFloat = 16
  792. NSLayoutConstraint.activate([
  793. contentRow.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 16),
  794. contentRow.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -bodyTrailingInset),
  795. contentRow.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
  796. contentRow.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -14),
  797. buttonRow.topAnchor.constraint(equalTo: card.topAnchor, constant: actionCornerInset),
  798. buttonRow.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -actionCornerInset),
  799. middleColumn.trailingAnchor.constraint(lessThanOrEqualTo: buttonRow.leadingAnchor, constant: -contentToActionsGap),
  800. iconBox.widthAnchor.constraint(equalToConstant: 58),
  801. iconBox.heightAnchor.constraint(equalToConstant: 58),
  802. categoryIcon.centerXAnchor.constraint(equalTo: iconBox.centerXAnchor),
  803. categoryIcon.centerYAnchor.constraint(equalTo: iconBox.centerYAnchor),
  804. buildingIcon.widthAnchor.constraint(equalToConstant: 14),
  805. buildingIcon.heightAnchor.constraint(equalToConstant: 14),
  806. applyButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 76),
  807. applyButton.heightAnchor.constraint(equalToConstant: 32),
  808. savedButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 84),
  809. savedButton.heightAnchor.constraint(equalToConstant: 32),
  810. dismissButton.widthAnchor.constraint(equalToConstant: 32),
  811. dismissButton.heightAnchor.constraint(equalToConstant: 32),
  812. descriptionField.widthAnchor.constraint(equalTo: middleColumn.widthAnchor)
  813. ])
  814. return card
  815. }
  816. private func styleJobSavedButton(_ button: NSButton) {
  817. button.wantsLayer = true
  818. button.layer?.cornerRadius = 8
  819. let on = button.state == .on
  820. let hovering = (button as? HoverableButton)?.isHovering ?? false
  821. if on {
  822. button.layer?.backgroundColor = (hovering ? Theme.selectionFillHover : Theme.selectionFill).cgColor
  823. button.layer?.borderWidth = 1
  824. button.layer?.borderColor = Theme.brandBlue.cgColor
  825. button.contentTintColor = Theme.brandBlue
  826. } else {
  827. button.layer?.backgroundColor = (hovering ? Theme.proCardFill : Theme.cardBackground).cgColor
  828. button.layer?.borderWidth = 1
  829. button.layer?.borderColor = Theme.brandBlue.cgColor
  830. button.contentTintColor = Theme.brandBlue
  831. }
  832. }
  833. @objc private func didTapJobApply(_ sender: NSButton) {
  834. guard let job = (sender as? JobPayloadButton)?.jobPayload else { return }
  835. if let rawURL = job.url, let url = URL(string: rawURL), !rawURL.isEmpty {
  836. NSWorkspace.shared.open(url)
  837. return
  838. }
  839. let allowed = CharacterSet.urlQueryAllowed
  840. let q = job.title.addingPercentEncoding(withAllowedCharacters: allowed) ?? ""
  841. guard let url = URL(string: "https://www.indeed.com/jobs?q=\(q)") else { return }
  842. NSWorkspace.shared.open(url)
  843. }
  844. @objc private func didTapJobSaved(_ sender: NSButton) {
  845. guard let job = (sender as? JobPayloadButton)?.jobPayload else { return }
  846. let willSave = !isJobSaved(job)
  847. applySavedState(willSave, for: job)
  848. sender.state = willSave ? .on : .off
  849. sender.title = willSave ? "Saved" : "Save"
  850. sender.image = NSImage(systemSymbolName: willSave ? "heart.fill" : "heart", accessibilityDescription: nil)
  851. styleJobSavedButton(sender)
  852. if isSavedJobsSidebarIndex(selectedSidebarIndex) {
  853. reloadSavedJobsListings()
  854. }
  855. }
  856. @objc private func didTapJobDismiss(_ sender: NSButton) {
  857. guard let button = sender as? JobPayloadButton, let job = button.jobPayload else { return }
  858. switch button.cardContext {
  859. case .homeSearchResults:
  860. removeJobCardFromChat(originating: button, job: job)
  861. case .savedJobsPage:
  862. applySavedState(false, for: job)
  863. reloadSavedJobsListings()
  864. }
  865. }
  866. /// Walks up from a dismiss button until it finds the enclosing chat job stack, then removes only the card that owns the button. Other chat history (older searches, the assistant summary text) is untouched.
  867. private func removeJobCardFromChat(originating button: NSView, job: JobListing) {
  868. var node: NSView? = button
  869. var card: NSView?
  870. var stack: ChatJobsStackView?
  871. while let v = node {
  872. if let parent = v.superview as? ChatJobsStackView {
  873. card = v
  874. stack = parent
  875. break
  876. }
  877. node = v.superview
  878. }
  879. guard let card, let stack else { return }
  880. stack.removeArrangedSubview(card)
  881. card.removeFromSuperview()
  882. lastSearchResults.removeAll { $0 == job }
  883. }
  884. private func configureSearchBar() {
  885. let pillCorner: CGFloat = 27
  886. let barHeight: CGFloat = 54
  887. searchBarShadowHost.translatesAutoresizingMaskIntoConstraints = false
  888. searchBarShadowHost.wantsLayer = true
  889. searchBarShadowHost.layer?.masksToBounds = false
  890. searchBarShadowHost.layer?.shadowColor = NSColor.black.withAlphaComponent(0.18).cgColor
  891. searchBarShadowHost.layer?.shadowOffset = CGSize(width: 0, height: 2)
  892. searchBarShadowHost.layer?.shadowRadius = 10
  893. searchBarShadowHost.layer?.shadowOpacity = 1
  894. searchBarShadowHost.setContentHuggingPriority(.defaultHigh, for: .vertical)
  895. searchCard.translatesAutoresizingMaskIntoConstraints = false
  896. searchCard.wantsLayer = true
  897. searchCard.layer?.backgroundColor = Theme.cardBackground.cgColor
  898. searchCard.layer?.cornerRadius = pillCorner
  899. searchCard.layer?.borderWidth = 1
  900. searchCard.layer?.borderColor = Theme.searchBarBorder.cgColor
  901. searchCard.layer?.masksToBounds = true
  902. searchCard.hoverHandler = { [weak self] hovering in
  903. guard let self else { return }
  904. CATransaction.begin()
  905. CATransaction.setAnimationDuration(0.15)
  906. self.searchCard.layer?.backgroundColor = (hovering ? Theme.neutralHoverFill : Theme.cardBackground).cgColor
  907. self.searchCard.layer?.borderColor = (hovering ? Theme.searchBarBorderHover : Theme.searchBarBorder).cgColor
  908. self.searchBarShadowHost.layer?.shadowColor = NSColor.black.withAlphaComponent(hovering ? 0.24 : 0.18).cgColor
  909. self.searchBarShadowHost.layer?.shadowRadius = hovering ? 12 : 10
  910. CATransaction.commit()
  911. }
  912. searchBarShadowHost.addSubview(searchCard)
  913. func configureField(_ field: NSTextField, placeholder: String) {
  914. field.translatesAutoresizingMaskIntoConstraints = false
  915. field.isBordered = false
  916. field.drawsBackground = false
  917. field.focusRingType = .none
  918. field.font = .systemFont(ofSize: 14, weight: .regular)
  919. field.textColor = Theme.primaryText
  920. field.delegate = self
  921. field.placeholderAttributedString = NSAttributedString(
  922. string: placeholder,
  923. attributes: [
  924. .foregroundColor: Theme.secondaryText,
  925. .font: NSFont.systemFont(ofSize: 14, weight: .regular)
  926. ]
  927. )
  928. field.cell?.usesSingleLineMode = true
  929. field.cell?.wraps = false
  930. field.cell?.isScrollable = true
  931. field.target = self
  932. field.action = #selector(didSubmitSearch)
  933. }
  934. jobSearchIcon.translatesAutoresizingMaskIntoConstraints = false
  935. jobSearchIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 16, weight: .semibold)
  936. jobSearchIcon.image = NSImage(systemSymbolName: "sparkles", accessibilityDescription: "Ask AI")
  937. jobSearchIcon.contentTintColor = Theme.brandBlue
  938. configureField(jobKeywordsField, placeholder: "Ask for roles, skills, salary, or job descriptions...")
  939. let ctaHeight: CGFloat = 42
  940. let ctaCorner = ctaHeight / 2
  941. findJobsCTAHost.translatesAutoresizingMaskIntoConstraints = false
  942. findJobsCTAHost.wantsLayer = true
  943. findJobsCTAHost.layer?.masksToBounds = false
  944. findJobsCTAHost.layer?.shadowColor = NSColor.black.cgColor
  945. findJobsCTAHost.layer?.shadowOpacity = 0.16
  946. findJobsCTAHost.layer?.shadowOffset = CGSize(width: 0, height: 2)
  947. findJobsCTAHost.layer?.shadowRadius = 6
  948. findJobsCTAChrome.translatesAutoresizingMaskIntoConstraints = false
  949. findJobsCTAChrome.wantsLayer = true
  950. findJobsCTAChrome.layer?.masksToBounds = true
  951. findJobsCTAChrome.layer?.cornerRadius = ctaCorner
  952. if #available(macOS 11.0, *) {
  953. findJobsCTAChrome.layer?.cornerCurve = .continuous
  954. }
  955. let gradient = CAGradientLayer()
  956. gradient.colors = [Theme.findJobsCTAHighlight.cgColor, Theme.brandBlue.cgColor]
  957. gradient.startPoint = CGPoint(x: 0.5, y: 1)
  958. gradient.endPoint = CGPoint(x: 0.5, y: 0)
  959. findJobsCTAChrome.layer?.addSublayer(gradient)
  960. findJobsCTAGradientLayer = gradient
  961. // 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.
  962. findJobsCTAChrome.pointerCursor = true
  963. findJobsCTAChrome.hoverHandler = { [weak self] hovering in
  964. guard let layer = self?.findJobsCTAGradientLayer else { return }
  965. CATransaction.begin()
  966. CATransaction.setAnimationDuration(0.15)
  967. layer.colors = hovering
  968. ? [Theme.findJobsCTAHighlightHover.cgColor, Theme.brandBlueHover.cgColor]
  969. : [Theme.findJobsCTAHighlight.cgColor, Theme.brandBlue.cgColor]
  970. CATransaction.commit()
  971. }
  972. findJobsButton.translatesAutoresizingMaskIntoConstraints = false
  973. findJobsButton.title = ""
  974. findJobsButton.image = NSImage(systemSymbolName: "paperplane.fill", accessibilityDescription: nil)
  975. findJobsButton.imagePosition = .imageLeading
  976. findJobsButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .semibold)
  977. findJobsButton.attributedTitle = NSAttributedString(
  978. string: " Send",
  979. attributes: [
  980. .font: NSFont.systemFont(ofSize: 14, weight: .semibold),
  981. .foregroundColor: Theme.proCTAText,
  982. .kern: 0.35
  983. ]
  984. )
  985. findJobsButton.contentTintColor = Theme.proCTAText
  986. findJobsButton.isBordered = false
  987. findJobsButton.bezelStyle = .rounded
  988. findJobsButton.wantsLayer = true
  989. findJobsButton.layer?.backgroundColor = NSColor.clear.cgColor
  990. findJobsButton.focusRingType = .none
  991. findJobsButton.target = self
  992. findJobsButton.action = #selector(didSubmitSearch)
  993. findJobsButton.setContentHuggingPriority(.required, for: .horizontal)
  994. findJobsButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  995. findJobsCTAHost.addSubview(findJobsCTAChrome)
  996. findJobsCTAHost.addSubview(findJobsButton)
  997. NSLayoutConstraint.activate([
  998. findJobsCTAChrome.leadingAnchor.constraint(equalTo: findJobsCTAHost.leadingAnchor),
  999. findJobsCTAChrome.trailingAnchor.constraint(equalTo: findJobsCTAHost.trailingAnchor),
  1000. findJobsCTAChrome.topAnchor.constraint(equalTo: findJobsCTAHost.topAnchor),
  1001. findJobsCTAChrome.bottomAnchor.constraint(equalTo: findJobsCTAHost.bottomAnchor),
  1002. findJobsButton.leadingAnchor.constraint(equalTo: findJobsCTAHost.leadingAnchor, constant: 14),
  1003. findJobsButton.trailingAnchor.constraint(equalTo: findJobsCTAHost.trailingAnchor, constant: -14),
  1004. findJobsButton.topAnchor.constraint(equalTo: findJobsCTAHost.topAnchor),
  1005. findJobsButton.bottomAnchor.constraint(equalTo: findJobsCTAHost.bottomAnchor)
  1006. ])
  1007. let keywordsStack = NSStackView(views: [jobSearchIcon, jobKeywordsField])
  1008. keywordsStack.orientation = .horizontal
  1009. keywordsStack.spacing = 10
  1010. keywordsStack.alignment = .centerY
  1011. keywordsStack.translatesAutoresizingMaskIntoConstraints = false
  1012. keywordsStack.edgeInsets = NSEdgeInsets(top: 0, left: 18, bottom: 0, right: 10)
  1013. keywordsStack.setContentHuggingPriority(.defaultLow, for: .horizontal)
  1014. let row = NSStackView(views: [keywordsStack, findJobsCTAHost])
  1015. row.orientation = .horizontal
  1016. row.spacing = 0
  1017. row.alignment = .centerY
  1018. row.distribution = .fill
  1019. row.translatesAutoresizingMaskIntoConstraints = false
  1020. row.edgeInsets = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 7)
  1021. searchCard.addSubview(row)
  1022. NSLayoutConstraint.activate([
  1023. searchCard.leadingAnchor.constraint(equalTo: searchBarShadowHost.leadingAnchor),
  1024. searchCard.trailingAnchor.constraint(equalTo: searchBarShadowHost.trailingAnchor),
  1025. searchCard.topAnchor.constraint(equalTo: searchBarShadowHost.topAnchor),
  1026. searchCard.bottomAnchor.constraint(equalTo: searchBarShadowHost.bottomAnchor),
  1027. searchBarShadowHost.heightAnchor.constraint(equalToConstant: barHeight),
  1028. row.leadingAnchor.constraint(equalTo: searchCard.leadingAnchor),
  1029. row.trailingAnchor.constraint(equalTo: searchCard.trailingAnchor),
  1030. row.topAnchor.constraint(equalTo: searchCard.topAnchor),
  1031. row.bottomAnchor.constraint(equalTo: searchCard.bottomAnchor),
  1032. jobSearchIcon.widthAnchor.constraint(equalToConstant: 18),
  1033. jobSearchIcon.heightAnchor.constraint(equalToConstant: 18),
  1034. findJobsCTAHost.heightAnchor.constraint(equalToConstant: ctaHeight),
  1035. findJobsCTAHost.widthAnchor.constraint(greaterThanOrEqualToConstant: 112)
  1036. ])
  1037. searchCard.hoverHandler = nil
  1038. }
  1039. private func updateFindJobsCTAShadowPath() {
  1040. guard findJobsCTAHost.bounds.width > 0, findJobsCTAHost.bounds.height > 0 else { return }
  1041. let r = findJobsCTAHost.bounds
  1042. let radius = min(r.height / 2, r.width / 2)
  1043. findJobsCTAHost.layer?.shadowPath = CGPath(
  1044. roundedRect: r,
  1045. cornerWidth: radius,
  1046. cornerHeight: radius,
  1047. transform: nil
  1048. )
  1049. }
  1050. private func configureNonHomePlaceholder() {
  1051. nonHomeHost.translatesAutoresizingMaskIntoConstraints = false
  1052. nonHomeHost.wantsLayer = true
  1053. nonHomeHost.layer?.backgroundColor = Theme.mainHostBackground.cgColor
  1054. nonHomeHost.isHidden = true
  1055. nonHomeGenericContainer.translatesAutoresizingMaskIntoConstraints = false
  1056. savedJobsPageContainer.translatesAutoresizingMaskIntoConstraints = false
  1057. settingsPageContainer.translatesAutoresizingMaskIntoConstraints = false
  1058. nonHomeHost.addSubview(nonHomeGenericContainer)
  1059. nonHomeHost.addSubview(savedJobsPageContainer)
  1060. nonHomeHost.addSubview(settingsPageContainer)
  1061. NSLayoutConstraint.activate([
  1062. nonHomeGenericContainer.leadingAnchor.constraint(equalTo: nonHomeHost.leadingAnchor),
  1063. nonHomeGenericContainer.trailingAnchor.constraint(equalTo: nonHomeHost.trailingAnchor),
  1064. nonHomeGenericContainer.topAnchor.constraint(equalTo: nonHomeHost.topAnchor),
  1065. nonHomeGenericContainer.bottomAnchor.constraint(equalTo: nonHomeHost.bottomAnchor),
  1066. savedJobsPageContainer.leadingAnchor.constraint(equalTo: nonHomeHost.leadingAnchor),
  1067. savedJobsPageContainer.trailingAnchor.constraint(equalTo: nonHomeHost.trailingAnchor),
  1068. savedJobsPageContainer.topAnchor.constraint(equalTo: nonHomeHost.topAnchor),
  1069. savedJobsPageContainer.bottomAnchor.constraint(equalTo: nonHomeHost.bottomAnchor),
  1070. settingsPageContainer.leadingAnchor.constraint(equalTo: nonHomeHost.leadingAnchor),
  1071. settingsPageContainer.trailingAnchor.constraint(equalTo: nonHomeHost.trailingAnchor),
  1072. settingsPageContainer.topAnchor.constraint(equalTo: nonHomeHost.topAnchor),
  1073. settingsPageContainer.bottomAnchor.constraint(equalTo: nonHomeHost.bottomAnchor)
  1074. ])
  1075. nonHomeTitleLabel.font = .systemFont(ofSize: 22, weight: .bold)
  1076. nonHomeTitleLabel.textColor = Theme.primaryText
  1077. nonHomeTitleLabel.alignment = .center
  1078. nonHomeTitleLabel.maximumNumberOfLines = 1
  1079. nonHomeSubtitleLabel.font = .systemFont(ofSize: 14, weight: .regular)
  1080. nonHomeSubtitleLabel.textColor = Theme.secondaryText
  1081. nonHomeSubtitleLabel.alignment = .center
  1082. nonHomeSubtitleLabel.maximumNumberOfLines = 0
  1083. nonHomeSubtitleLabel.stringValue = "This area is not available in the preview build. Use Home to search jobs."
  1084. let genericStack = NSStackView(views: [nonHomeTitleLabel, nonHomeSubtitleLabel])
  1085. genericStack.orientation = .vertical
  1086. genericStack.spacing = 10
  1087. genericStack.alignment = .centerX
  1088. genericStack.translatesAutoresizingMaskIntoConstraints = false
  1089. nonHomeGenericContainer.addSubview(genericStack)
  1090. NSLayoutConstraint.activate([
  1091. genericStack.centerXAnchor.constraint(equalTo: nonHomeGenericContainer.centerXAnchor),
  1092. genericStack.centerYAnchor.constraint(equalTo: nonHomeGenericContainer.centerYAnchor),
  1093. genericStack.leadingAnchor.constraint(greaterThanOrEqualTo: nonHomeGenericContainer.leadingAnchor, constant: 32),
  1094. genericStack.trailingAnchor.constraint(lessThanOrEqualTo: nonHomeGenericContainer.trailingAnchor, constant: -32),
  1095. nonHomeSubtitleLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 420)
  1096. ])
  1097. savedJobsPageTitleLabel.font = .systemFont(ofSize: 22, weight: .bold)
  1098. savedJobsPageTitleLabel.textColor = Theme.primaryText
  1099. savedJobsPageTitleLabel.alignment = .left
  1100. savedJobsPageTitleLabel.maximumNumberOfLines = 1
  1101. savedJobsPageSubtitleLabel.font = .systemFont(ofSize: 14, weight: .regular)
  1102. savedJobsPageSubtitleLabel.textColor = Theme.secondaryText
  1103. savedJobsPageSubtitleLabel.alignment = .left
  1104. savedJobsPageSubtitleLabel.maximumNumberOfLines = 0
  1105. savedJobsDocumentView.translatesAutoresizingMaskIntoConstraints = false
  1106. savedJobsStack.orientation = .vertical
  1107. savedJobsStack.spacing = 14
  1108. savedJobsStack.alignment = .leading
  1109. savedJobsStack.distribution = .fill
  1110. savedJobsStack.translatesAutoresizingMaskIntoConstraints = false
  1111. savedJobsStack.setContentHuggingPriority(.defaultHigh, for: .vertical)
  1112. savedJobsStack.setHuggingPriority(.defaultLow, for: .horizontal)
  1113. savedJobsDocumentView.addSubview(savedJobsStack)
  1114. NSLayoutConstraint.activate([
  1115. savedJobsStack.leadingAnchor.constraint(equalTo: savedJobsDocumentView.leadingAnchor),
  1116. savedJobsStack.trailingAnchor.constraint(equalTo: savedJobsDocumentView.trailingAnchor),
  1117. savedJobsStack.topAnchor.constraint(equalTo: savedJobsDocumentView.topAnchor),
  1118. savedJobsStack.bottomAnchor.constraint(equalTo: savedJobsDocumentView.bottomAnchor)
  1119. ])
  1120. savedJobsScrollView.translatesAutoresizingMaskIntoConstraints = false
  1121. savedJobsScrollView.hasVerticalScroller = true
  1122. savedJobsScrollView.hasHorizontalScroller = false
  1123. savedJobsScrollView.scrollerStyle = .legacy
  1124. savedJobsScrollView.autohidesScrollers = true
  1125. savedJobsScrollView.drawsBackground = false
  1126. savedJobsScrollView.borderType = .noBorder
  1127. savedJobsScrollView.documentView = savedJobsDocumentView
  1128. savedJobsScrollView.setContentHuggingPriority(.defaultLow, for: .vertical)
  1129. savedJobsScrollView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  1130. let savedHeaderStack = NSStackView(views: [savedJobsPageTitleLabel, savedJobsPageSubtitleLabel])
  1131. savedHeaderStack.orientation = .vertical
  1132. savedHeaderStack.spacing = 6
  1133. savedHeaderStack.alignment = .leading
  1134. savedHeaderStack.translatesAutoresizingMaskIntoConstraints = false
  1135. let savedOuterStack = NSStackView(views: [savedHeaderStack, savedJobsScrollView])
  1136. savedOuterStack.orientation = .vertical
  1137. savedOuterStack.spacing = 16
  1138. // Leading alignment plus explicit column width keeps the title and subtitle on the same edge as the cards.
  1139. savedOuterStack.alignment = .leading
  1140. savedOuterStack.translatesAutoresizingMaskIntoConstraints = false
  1141. savedJobsPageContainer.userInterfaceLayoutDirection = .leftToRight
  1142. savedJobsPageContainer.addSubview(savedOuterStack)
  1143. NSLayoutConstraint.activate([
  1144. savedOuterStack.leadingAnchor.constraint(equalTo: savedJobsPageContainer.leadingAnchor, constant: 32),
  1145. savedOuterStack.trailingAnchor.constraint(equalTo: savedJobsPageContainer.trailingAnchor, constant: -32),
  1146. savedOuterStack.topAnchor.constraint(equalTo: savedJobsPageContainer.topAnchor, constant: 8),
  1147. savedOuterStack.bottomAnchor.constraint(equalTo: savedJobsPageContainer.bottomAnchor),
  1148. savedHeaderStack.widthAnchor.constraint(equalTo: savedOuterStack.widthAnchor),
  1149. savedJobsScrollView.widthAnchor.constraint(equalTo: savedOuterStack.widthAnchor),
  1150. savedJobsDocumentView.topAnchor.constraint(equalTo: savedJobsScrollView.contentView.topAnchor),
  1151. savedJobsDocumentView.leadingAnchor.constraint(equalTo: savedJobsScrollView.contentView.leadingAnchor),
  1152. savedJobsDocumentView.widthAnchor.constraint(equalTo: savedJobsScrollView.contentView.widthAnchor)
  1153. ])
  1154. configureSettingsPage()
  1155. }
  1156. private func configureSettingsPage() {
  1157. settingsPageContainer.wantsLayer = true
  1158. settingsPageContainer.layer?.backgroundColor = Theme.settingsPageBackground.cgColor
  1159. settingsPageContainer.isHidden = true
  1160. let contentStack = NSStackView()
  1161. contentStack.orientation = .vertical
  1162. contentStack.spacing = 26
  1163. contentStack.alignment = .leading
  1164. contentStack.translatesAutoresizingMaskIntoConstraints = false
  1165. let settingsSection = makeSettingsSection(rows: [
  1166. makeSettingsRow(title: "Share App", systemImage: "square.and.arrow.up", accessory: nil),
  1167. makeSettingsRow(title: "Theme", systemImage: "circle.lefthalf.filled", accessory: makeThemeControl()),
  1168. makeSettingsRow(title: "More Apps", systemImage: "square.grid.2x2", accessory: nil)
  1169. ])
  1170. let aboutTitle = NSTextField(labelWithString: "About")
  1171. aboutTitle.font = .systemFont(ofSize: 12, weight: .semibold)
  1172. aboutTitle.textColor = Theme.secondaryText
  1173. aboutTitle.alignment = .left
  1174. let aboutSection = makeSettingsSection(rows: [
  1175. makeSettingsRow(title: "Support", systemImage: "questionmark.circle", accessory: nil),
  1176. makeSettingsRow(title: "Terms of Use", systemImage: "doc.text", accessory: nil),
  1177. makeSettingsRow(title: "Privacy Policy", systemImage: "shield", accessory: nil)
  1178. ])
  1179. let aboutStack = NSStackView(views: [aboutTitle, aboutSection])
  1180. aboutStack.orientation = .vertical
  1181. aboutStack.spacing = 14
  1182. aboutStack.alignment = .leading
  1183. aboutStack.translatesAutoresizingMaskIntoConstraints = false
  1184. contentStack.addArrangedSubview(settingsSection)
  1185. contentStack.addArrangedSubview(aboutStack)
  1186. settingsPageContainer.addSubview(contentStack)
  1187. NSLayoutConstraint.activate([
  1188. contentStack.leadingAnchor.constraint(equalTo: settingsPageContainer.leadingAnchor, constant: 42),
  1189. contentStack.trailingAnchor.constraint(lessThanOrEqualTo: settingsPageContainer.trailingAnchor, constant: -42),
  1190. contentStack.topAnchor.constraint(equalTo: settingsPageContainer.topAnchor, constant: 48),
  1191. settingsSection.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  1192. aboutStack.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  1193. aboutSection.widthAnchor.constraint(equalTo: aboutStack.widthAnchor),
  1194. contentStack.widthAnchor.constraint(equalTo: settingsPageContainer.widthAnchor, constant: -84)
  1195. ])
  1196. }
  1197. private func makeThemeControl() -> NSSegmentedControl {
  1198. themeControl.target = self
  1199. themeControl.action = #selector(didChangeThemeSelection(_:))
  1200. themeControl.selectedSegment = 0
  1201. themeControl.segmentStyle = .rounded
  1202. themeControl.controlSize = .large
  1203. themeControl.font = .systemFont(ofSize: 13, weight: .semibold)
  1204. themeControl.translatesAutoresizingMaskIntoConstraints = false
  1205. themeControl.widthAnchor.constraint(equalToConstant: 204).isActive = true
  1206. themeControl.heightAnchor.constraint(equalToConstant: 30).isActive = true
  1207. return themeControl
  1208. }
  1209. private func makeSettingsSection(rows: [NSView]) -> NSView {
  1210. let section = NSStackView()
  1211. section.orientation = .vertical
  1212. section.spacing = 0
  1213. section.alignment = .leading
  1214. section.translatesAutoresizingMaskIntoConstraints = false
  1215. section.wantsLayer = true
  1216. section.layer?.backgroundColor = Theme.settingsGroupBackground.cgColor
  1217. section.layer?.cornerRadius = 14
  1218. section.layer?.borderWidth = 1
  1219. section.layer?.borderColor = Theme.border.cgColor
  1220. section.layer?.masksToBounds = true
  1221. for (index, row) in rows.enumerated() {
  1222. section.addArrangedSubview(row)
  1223. row.widthAnchor.constraint(equalTo: section.widthAnchor).isActive = true
  1224. if index < rows.count - 1 {
  1225. let divider = NSView()
  1226. divider.translatesAutoresizingMaskIntoConstraints = false
  1227. divider.wantsLayer = true
  1228. divider.layer?.backgroundColor = Theme.settingsDivider.cgColor
  1229. section.addArrangedSubview(divider)
  1230. NSLayoutConstraint.activate([
  1231. divider.heightAnchor.constraint(equalToConstant: 1),
  1232. divider.leadingAnchor.constraint(equalTo: section.leadingAnchor),
  1233. divider.trailingAnchor.constraint(equalTo: section.trailingAnchor)
  1234. ])
  1235. }
  1236. }
  1237. return section
  1238. }
  1239. private func makeSettingsRow(title: String, systemImage: String, accessory: NSView?) -> NSView {
  1240. let row = NSView()
  1241. row.translatesAutoresizingMaskIntoConstraints = false
  1242. row.wantsLayer = true
  1243. let iconTile = NSView()
  1244. iconTile.translatesAutoresizingMaskIntoConstraints = false
  1245. iconTile.wantsLayer = true
  1246. iconTile.layer?.backgroundColor = Theme.settingsIconBackground.cgColor
  1247. iconTile.layer?.cornerRadius = 9
  1248. let icon = NSImageView()
  1249. icon.translatesAutoresizingMaskIntoConstraints = false
  1250. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .medium)
  1251. icon.image = NSImage(systemSymbolName: systemImage, accessibilityDescription: title)
  1252. icon.contentTintColor = Theme.brandBlue
  1253. let titleLabel = NSTextField(labelWithString: title)
  1254. titleLabel.font = .systemFont(ofSize: 14, weight: .medium)
  1255. titleLabel.textColor = Theme.secondaryText
  1256. titleLabel.alignment = .left
  1257. let rowStack = NSStackView()
  1258. rowStack.orientation = .horizontal
  1259. rowStack.spacing = 16
  1260. rowStack.alignment = .centerY
  1261. rowStack.translatesAutoresizingMaskIntoConstraints = false
  1262. let spacer = NSView()
  1263. spacer.translatesAutoresizingMaskIntoConstraints = false
  1264. spacer.setContentHuggingPriority(NSLayoutConstraint.Priority(1), for: .horizontal)
  1265. iconTile.addSubview(icon)
  1266. rowStack.addArrangedSubview(iconTile)
  1267. rowStack.addArrangedSubview(titleLabel)
  1268. rowStack.addArrangedSubview(spacer)
  1269. if let accessory {
  1270. rowStack.addArrangedSubview(accessory)
  1271. }
  1272. row.addSubview(rowStack)
  1273. NSLayoutConstraint.activate([
  1274. row.heightAnchor.constraint(equalToConstant: 68),
  1275. iconTile.widthAnchor.constraint(equalToConstant: 38),
  1276. iconTile.heightAnchor.constraint(equalToConstant: 38),
  1277. icon.centerXAnchor.constraint(equalTo: iconTile.centerXAnchor),
  1278. icon.centerYAnchor.constraint(equalTo: iconTile.centerYAnchor),
  1279. icon.widthAnchor.constraint(equalToConstant: 20),
  1280. icon.heightAnchor.constraint(equalToConstant: 20),
  1281. rowStack.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 16),
  1282. rowStack.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -16),
  1283. rowStack.topAnchor.constraint(equalTo: row.topAnchor),
  1284. rowStack.bottomAnchor.constraint(equalTo: row.bottomAnchor)
  1285. ])
  1286. return row
  1287. }
  1288. private func reloadSavedJobsListings() {
  1289. savedJobsStack.arrangedSubviews.forEach {
  1290. savedJobsStack.removeArrangedSubview($0)
  1291. $0.removeFromSuperview()
  1292. }
  1293. if savedJobOrder.isEmpty {
  1294. savedJobsPageSubtitleLabel.stringValue = "Save jobs from Home to see them here."
  1295. let empty = NSTextField(wrappingLabelWithString: "No saved jobs yet. Search on Home, then tap Save on a listing.")
  1296. empty.font = .systemFont(ofSize: 14, weight: .regular)
  1297. empty.textColor = Theme.secondaryText
  1298. empty.alignment = .left
  1299. empty.maximumNumberOfLines = 0
  1300. empty.translatesAutoresizingMaskIntoConstraints = false
  1301. savedJobsStack.addArrangedSubview(empty)
  1302. empty.widthAnchor.constraint(equalTo: savedJobsStack.widthAnchor).isActive = true
  1303. return
  1304. }
  1305. savedJobsPageSubtitleLabel.stringValue = "\(savedJobOrder.count) saved \(savedJobOrder.count == 1 ? "position" : "positions")"
  1306. for job in savedJobOrder {
  1307. let card = makeJobListingCard(job, context: .savedJobsPage)
  1308. savedJobsStack.addArrangedSubview(card)
  1309. card.widthAnchor.constraint(equalTo: savedJobsStack.widthAnchor).isActive = true
  1310. }
  1311. }
  1312. private func isSavedJobsSidebarIndex(_ index: Int) -> Bool {
  1313. guard index >= 0, index < currentSidebarItems.count else { return false }
  1314. return currentSidebarItems[index].title == "Saved Jobs"
  1315. }
  1316. private func isHomeSidebarIndex(_ index: Int) -> Bool {
  1317. guard index >= 0, index < currentSidebarItems.count else { return false }
  1318. return currentSidebarItems[index].title == "Home"
  1319. }
  1320. private func isSettingsSidebarIndex(_ index: Int) -> Bool {
  1321. guard index >= 0, index < currentSidebarItems.count else { return false }
  1322. return currentSidebarItems[index].title == "Settings"
  1323. }
  1324. private func updateMainContentVisibility() {
  1325. let home = isHomeSidebarIndex(selectedSidebarIndex)
  1326. let savedJobs = isSavedJobsSidebarIndex(selectedSidebarIndex)
  1327. let settings = isSettingsSidebarIndex(selectedSidebarIndex)
  1328. mainOverlay.isHidden = !home
  1329. nonHomeHost.isHidden = home
  1330. nonHomeGenericContainer.isHidden = savedJobs || settings
  1331. savedJobsPageContainer.isHidden = !savedJobs
  1332. settingsPageContainer.isHidden = !settings
  1333. if !home, selectedSidebarIndex < currentSidebarItems.count {
  1334. if savedJobs {
  1335. reloadSavedJobsListings()
  1336. } else if settings {
  1337. window?.makeFirstResponder(nil)
  1338. } else {
  1339. nonHomeTitleLabel.stringValue = currentSidebarItems[selectedSidebarIndex].title
  1340. }
  1341. }
  1342. if home {
  1343. syncWelcomeSubtitleBreathingAnimation()
  1344. syncChatStatusSparkleAnimation()
  1345. } else {
  1346. stopWelcomeSubtitleBreathingAnimation()
  1347. stopChatStatusSparkleAnimation()
  1348. }
  1349. }
  1350. /// Restores the main job-search experience: cleared query and a fresh chat history.
  1351. private func applyHomeState() {
  1352. jobKeywordsField.stringValue = ""
  1353. resetChatState()
  1354. window?.makeFirstResponder(nil)
  1355. }
  1356. private func updateSearchBarShadowPath() {
  1357. guard searchBarShadowHost.bounds.width > 0, searchBarShadowHost.bounds.height > 0 else { return }
  1358. let r = searchBarShadowHost.bounds
  1359. let radius = min(r.height / 2, 27)
  1360. searchBarShadowHost.layer?.shadowPath = CGPath(
  1361. roundedRect: r,
  1362. cornerWidth: radius,
  1363. cornerHeight: radius,
  1364. transform: nil
  1365. )
  1366. }
  1367. @objc private func didSubmitSearch() {
  1368. let prompt = jobKeywordsField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)
  1369. guard !prompt.isEmpty, !isAwaitingResponse else { return }
  1370. let isContinuation = isContinuationPrompt(prompt)
  1371. let effectiveQuery = resolvedSearchQuery(for: prompt)
  1372. appendChatBubble(text: prompt, isUser: true)
  1373. chatMessages.append(ChatMessage(role: "user", content: prompt))
  1374. jobKeywordsField.stringValue = ""
  1375. startJobSearchRequest(effectiveQuery: effectiveQuery, isContinuation: isContinuation)
  1376. window?.makeFirstResponder(nil)
  1377. }
  1378. @objc private func didTapFeatureRole() {
  1379. focusSearchField(seed: "Find roles similar to: ")
  1380. }
  1381. @objc private func didTapFeatureCompany() {
  1382. focusSearchField(seed: "Find jobs at company: ")
  1383. }
  1384. @objc private func didTapFeatureSkill() {
  1385. focusSearchField(seed: "Find jobs that require skill: ")
  1386. }
  1387. private func focusSearchField(seed: String) {
  1388. jobKeywordsField.stringValue = seed
  1389. window?.makeFirstResponder(jobKeywordsField)
  1390. if let editor = jobKeywordsField.window?.fieldEditor(true, for: jobKeywordsField) as? NSTextView {
  1391. editor.moveToEndOfDocument(nil)
  1392. }
  1393. }
  1394. @objc private func didTapLoadMoreJobs() {
  1395. let prompt = "Show more jobs"
  1396. guard !isAwaitingResponse, isContinuationPrompt(prompt) else { return }
  1397. if anchorUserJobQuery(excludingLatestUserMessage: prompt) == nil { return }
  1398. appendChatBubble(text: prompt, isUser: true)
  1399. chatMessages.append(ChatMessage(role: "user", content: prompt))
  1400. let effectiveQuery = resolvedSearchQuery(for: prompt)
  1401. startJobSearchRequest(effectiveQuery: effectiveQuery, isContinuation: true)
  1402. }
  1403. private func startJobSearchRequest(effectiveQuery: String, isContinuation: Bool) {
  1404. isAwaitingResponse = true
  1405. setChatStatusLabel("Thinking...")
  1406. setInputEnabled(false)
  1407. let contextMessages = chatMessages
  1408. let maxJobs = Self.clampedJobsPerRequest()
  1409. jobSearchService.searchJobs(query: effectiveQuery, conversation: contextMessages, maxJobs: maxJobs) { [weak self] result in
  1410. DispatchQueue.main.async {
  1411. guard let self else { return }
  1412. self.isAwaitingResponse = false
  1413. self.setInputEnabled(true)
  1414. switch result {
  1415. case .success(let output):
  1416. let normalizedJobs = self.normalizedJobs(output.jobs)
  1417. let freshJobs: [JobListing]
  1418. if isContinuation {
  1419. // Continuations append only the *new* matches; previous cards already live in their own assistant message above.
  1420. let alreadySeen = Set(self.lastSearchResults)
  1421. freshJobs = normalizedJobs.filter { !alreadySeen.contains($0) }
  1422. } else {
  1423. freshJobs = normalizedJobs
  1424. }
  1425. self.lastSearchResults.append(contentsOf: freshJobs)
  1426. let reply = self.makeAssistantSearchReply(
  1427. query: effectiveQuery,
  1428. newJobsCount: freshJobs.count,
  1429. isContinuation: isContinuation
  1430. )
  1431. self.chatMessages.append(ChatMessage(role: "assistant", content: reply))
  1432. self.appendChatBubble(text: reply, isUser: false, jobs: freshJobs)
  1433. self.setChatStatusLabel(reply)
  1434. case .failure(let error):
  1435. self.appendChatBubble(text: error.localizedDescription, isUser: false)
  1436. if error is URLError {
  1437. self.setChatStatusLabel("Could not reach API. Try again.")
  1438. } else {
  1439. self.setChatStatusLabel("Search did not finish. Try again.")
  1440. }
  1441. }
  1442. }
  1443. }
  1444. }
  1445. private func normalizedJobs(_ jobs: [JobListing]) -> [JobListing] {
  1446. let trimmed = jobs.map {
  1447. JobListing(
  1448. title: $0.title.trimmingCharacters(in: .whitespacesAndNewlines),
  1449. description: $0.description.trimmingCharacters(in: .whitespacesAndNewlines),
  1450. url: $0.url?.trimmingCharacters(in: .whitespacesAndNewlines)
  1451. )
  1452. }
  1453. return trimmed.filter { !$0.title.isEmpty && !$0.description.isEmpty }
  1454. }
  1455. private func makeAssistantSearchReply(query: String, newJobsCount: Int, isContinuation: Bool) -> String {
  1456. if newJobsCount == 0 {
  1457. if isContinuation {
  1458. return "I couldn't find new matches for \u{201C}\(query)\u{201D}. Try a different angle or a more specific keyword."
  1459. }
  1460. return "No jobs found for \u{201C}\(query)\u{201D}. Try another title, skill, company, or location."
  1461. }
  1462. let plural = newJobsCount == 1 ? "match" : "matches"
  1463. if isContinuation {
  1464. return "Here are \(newJobsCount) more \(plural) for \u{201C}\(query)\u{201D}."
  1465. }
  1466. return "Found \(newJobsCount) \(plural) for \u{201C}\(query)\u{201D}. Tap Apply to open the listing or Save to revisit later."
  1467. }
  1468. private func resolvedSearchQuery(for prompt: String) -> String {
  1469. let anchor = anchorUserJobQuery(excludingLatestUserMessage: prompt)
  1470. if isContinuationPrompt(prompt), !isRefinementPrompt(prompt) {
  1471. if let anchor { return anchor }
  1472. return prompt
  1473. }
  1474. if isRefinementPrompt(prompt), let anchor {
  1475. return "\(anchor). User follow-up (apply on top of the same search topic): \(prompt)"
  1476. }
  1477. return prompt
  1478. }
  1479. /// First prior user message that looks like an original job query (skips short continuations and refinements so follow-ups keep a stable topic anchor).
  1480. private func anchorUserJobQuery(excludingLatestUserMessage latest: String) -> String? {
  1481. let prior = Array(chatMessages.dropLast())
  1482. for message in prior.reversed() where message.role == "user" {
  1483. let candidate = message.content.trimmingCharacters(in: .whitespacesAndNewlines)
  1484. guard !candidate.isEmpty, candidate != latest else { continue }
  1485. if isContinuationPrompt(candidate) { continue }
  1486. if isRefinementPrompt(candidate) { continue }
  1487. return candidate
  1488. }
  1489. return nil
  1490. }
  1491. private func isContinuationPrompt(_ prompt: String) -> Bool {
  1492. let normalized = prompt.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
  1493. let continuationPhrases: Set<String> = [
  1494. "more",
  1495. "show more",
  1496. "more jobs",
  1497. "more results",
  1498. "do more searches",
  1499. "more searches",
  1500. "search more",
  1501. "continue",
  1502. "next"
  1503. ]
  1504. if continuationPhrases.contains(normalized) {
  1505. return true
  1506. }
  1507. return normalized.contains("more search") || normalized.contains("more job")
  1508. }
  1509. /// Follow-ups that narrow, re-rank, or re-frame results rather than starting a brand-new role search.
  1510. /// Strong phrases always count. Single-word cues (e.g. "remote") only count after we already showed results, so first searches like "Senior iOS remote" stay anchored as primary queries.
  1511. private func isRefinementPrompt(_ prompt: String) -> Bool {
  1512. let n = prompt.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
  1513. if n.isEmpty { return false }
  1514. let strongPhrases = [
  1515. "higher pay", "high pay", "better pay", "more pay", "top pay", "best pay",
  1516. "higher salary", "better salary", "more salary", "pay rate", "hourly rate",
  1517. "paid more", "paying more", "earn more", "better paid", "paying better",
  1518. "work from home", "in office", "in-office", "on-site only", "remote only",
  1519. "hybrid only", "onsite only", "visa sponsorship", "h1b",
  1520. "entry level", "entry-level", "mid level", "mid-level", "full time", "full-time",
  1521. "part time", "part-time",
  1522. "closer to", "nearer", "different city", "different state", "relocate",
  1523. "filter", "only show", "just show", "exclude", "without", "sort by", "rank by",
  1524. "cheaper", "lower pay", "less travel",
  1525. "better benefits", "equity", "bonus", "overtime",
  1526. "get me the jobs", "show me the jobs", "give me the jobs", "narrow", "refine"
  1527. ]
  1528. if strongPhrases.contains(where: { n.contains($0) }) { return true }
  1529. if n.hasPrefix("only ") || n.hasPrefix("just ") { return true }
  1530. guard !lastSearchResults.isEmpty, n.count <= 52 else { return false }
  1531. let softAfterResults = [
  1532. "remote", "hybrid", "onsite", "on-site", "senior", "junior", "staff", "lead",
  1533. "principal", "intern", "contract", "location"
  1534. ]
  1535. return softAfterResults.contains(where: { n.contains($0) })
  1536. }
  1537. func controlTextDidBeginEditing(_ obj: Notification) {
  1538. applySearchFieldInsertionPoint(obj.object)
  1539. if (obj.object as? NSTextField) === jobKeywordsField {
  1540. setChatStatusLabel("Opening the vault...")
  1541. }
  1542. }
  1543. func controlTextDidChange(_ obj: Notification) {
  1544. applySearchFieldInsertionPoint(obj.object)
  1545. }
  1546. func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
  1547. guard control === jobKeywordsField, commandSelector == #selector(NSResponder.insertNewline(_:)) else {
  1548. return false
  1549. }
  1550. didSubmitSearch()
  1551. return true
  1552. }
  1553. private func applySearchFieldInsertionPoint(_ object: Any?) {
  1554. guard let field = object as? NSTextField,
  1555. field === jobKeywordsField,
  1556. let textView = field.window?.fieldEditor(true, for: field) as? NSTextView else { return }
  1557. textView.insertionPointColor = Theme.primaryText
  1558. }
  1559. private func resetChatState() {
  1560. trailingLoadMoreJobsRow = nil
  1561. trailingLoadMoreJobsButton = nil
  1562. chatMessages.removeAll()
  1563. lastSearchResults.removeAll()
  1564. chatStack.arrangedSubviews.forEach {
  1565. chatStack.removeArrangedSubview($0)
  1566. $0.removeFromSuperview()
  1567. }
  1568. let welcome = "Tell me what role you want and I will return job descriptions, key skills, and a quick fit summary."
  1569. chatMessages.append(ChatMessage(role: "assistant", content: welcome))
  1570. appendChatBubble(text: welcome, isUser: false)
  1571. setChatStatusLabel("Ask me to find jobs")
  1572. }
  1573. private func appendChatBubble(text: String, isUser: Bool, jobs: [JobListing]? = nil) {
  1574. let host = NSView()
  1575. host.translatesAutoresizingMaskIntoConstraints = false
  1576. if isUser {
  1577. installUserBubble(text: text, into: host)
  1578. } else {
  1579. installAssistantBubble(text: text, jobs: jobs, into: host)
  1580. }
  1581. chatStack.addArrangedSubview(host)
  1582. host.widthAnchor.constraint(equalTo: chatStack.widthAnchor).isActive = true
  1583. if prefersReducedMotion {
  1584. host.alphaValue = 1
  1585. } else {
  1586. host.alphaValue = 0
  1587. }
  1588. DispatchQueue.main.async { [weak self] in
  1589. guard let self else { return }
  1590. if self.prefersReducedMotion {
  1591. self.updateChatBubbleWidths()
  1592. self.scrollChatToBottom()
  1593. return
  1594. }
  1595. NSAnimationContext.runAnimationGroup { ctx in
  1596. ctx.duration = 0.3
  1597. ctx.timingFunction = CAMediaTimingFunction(name: .easeOut)
  1598. host.animator().alphaValue = 1
  1599. }
  1600. self.updateChatBubbleWidths()
  1601. self.scrollChatToBottom()
  1602. }
  1603. }
  1604. private func installUserBubble(text: String, into host: NSView) {
  1605. let bubble = makeChatBubbleContainer(text: text, isUser: true)
  1606. host.addSubview(bubble)
  1607. NSLayoutConstraint.activate([
  1608. bubble.topAnchor.constraint(equalTo: host.topAnchor),
  1609. bubble.bottomAnchor.constraint(equalTo: host.bottomAnchor),
  1610. bubble.trailingAnchor.constraint(equalTo: host.trailingAnchor),
  1611. bubble.leadingAnchor.constraint(greaterThanOrEqualTo: host.leadingAnchor, constant: 64),
  1612. bubble.widthAnchor.constraint(lessThanOrEqualTo: host.widthAnchor, multiplier: 0.78)
  1613. ])
  1614. }
  1615. private func installAssistantBubble(text: String, jobs: [JobListing]?, into host: NSView) {
  1616. let avatar = makeAssistantAvatarView()
  1617. let nameLabel = NSTextField(labelWithString: "AI Job Finder")
  1618. nameLabel.font = .systemFont(ofSize: 11, weight: .semibold)
  1619. nameLabel.textColor = Theme.secondaryText
  1620. nameLabel.translatesAutoresizingMaskIntoConstraints = false
  1621. let bubble = makeChatBubbleContainer(text: text, isUser: false)
  1622. let column = NSStackView(views: [nameLabel, bubble])
  1623. column.orientation = .vertical
  1624. column.spacing = 6
  1625. column.alignment = .width
  1626. column.translatesAutoresizingMaskIntoConstraints = false
  1627. if let jobs, !jobs.isEmpty {
  1628. trailingLoadMoreJobsRow?.removeFromSuperview()
  1629. trailingLoadMoreJobsRow = nil
  1630. trailingLoadMoreJobsButton = nil
  1631. let jobsStack = makeChatJobsStackView(jobs: jobs)
  1632. column.addArrangedSubview(jobsStack)
  1633. jobsStack.widthAnchor.constraint(equalTo: column.widthAnchor).isActive = true
  1634. let moreRow = makeLoadMoreJobsRowView()
  1635. column.addArrangedSubview(moreRow)
  1636. moreRow.widthAnchor.constraint(equalTo: column.widthAnchor).isActive = true
  1637. trailingLoadMoreJobsRow = moreRow
  1638. }
  1639. host.addSubview(avatar)
  1640. host.addSubview(column)
  1641. NSLayoutConstraint.activate([
  1642. avatar.leadingAnchor.constraint(equalTo: host.leadingAnchor),
  1643. avatar.topAnchor.constraint(equalTo: host.topAnchor),
  1644. avatar.widthAnchor.constraint(equalToConstant: 36),
  1645. avatar.heightAnchor.constraint(equalToConstant: 36),
  1646. column.leadingAnchor.constraint(equalTo: avatar.trailingAnchor, constant: 12),
  1647. column.trailingAnchor.constraint(equalTo: host.trailingAnchor),
  1648. column.topAnchor.constraint(equalTo: host.topAnchor),
  1649. column.bottomAnchor.constraint(equalTo: host.bottomAnchor)
  1650. ])
  1651. }
  1652. private func makeChatBubbleContainer(text: String, isUser: Bool) -> NSView {
  1653. let container = NSView()
  1654. container.translatesAutoresizingMaskIntoConstraints = false
  1655. container.wantsLayer = true
  1656. container.layer?.cornerRadius = 14
  1657. if #available(macOS 11.0, *) {
  1658. container.layer?.cornerCurve = .continuous
  1659. }
  1660. container.layer?.masksToBounds = true
  1661. if isUser {
  1662. container.layer?.backgroundColor = Theme.brandBlue.cgColor
  1663. } else {
  1664. container.layer?.backgroundColor = Theme.chromeBackground.cgColor
  1665. container.layer?.borderWidth = 1
  1666. container.layer?.borderColor = Theme.border.cgColor
  1667. }
  1668. let label = ChatBubbleLabel(wrappingLabelWithString: text)
  1669. label.font = .systemFont(ofSize: 13.5, weight: .regular)
  1670. label.textColor = isUser ? .white : Theme.primaryText
  1671. label.maximumNumberOfLines = 0
  1672. label.lineBreakMode = .byWordWrapping
  1673. label.alignment = .left
  1674. label.translatesAutoresizingMaskIntoConstraints = false
  1675. label.setContentHuggingPriority(.defaultLow, for: .horizontal)
  1676. label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  1677. container.addSubview(label)
  1678. NSLayoutConstraint.activate([
  1679. label.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 14),
  1680. label.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -14),
  1681. label.topAnchor.constraint(equalTo: container.topAnchor, constant: 10),
  1682. label.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: -10)
  1683. ])
  1684. return container
  1685. }
  1686. private func makeAssistantAvatarView() -> NSView {
  1687. let view = NSView()
  1688. view.translatesAutoresizingMaskIntoConstraints = false
  1689. view.wantsLayer = true
  1690. view.layer?.cornerRadius = 18
  1691. if #available(macOS 11.0, *) {
  1692. view.layer?.cornerCurve = .continuous
  1693. }
  1694. view.layer?.backgroundColor = Theme.settingsIconBackground.cgColor
  1695. view.layer?.borderWidth = 1
  1696. view.layer?.borderColor = Theme.proCardBorder.cgColor
  1697. let icon = NSImageView()
  1698. icon.translatesAutoresizingMaskIntoConstraints = false
  1699. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 15, weight: .semibold)
  1700. icon.image = NSImage(systemSymbolName: "sparkles", accessibilityDescription: "AI Job Finder")
  1701. icon.contentTintColor = Theme.brandBlue
  1702. view.addSubview(icon)
  1703. NSLayoutConstraint.activate([
  1704. icon.centerXAnchor.constraint(equalTo: view.centerXAnchor),
  1705. icon.centerYAnchor.constraint(equalTo: view.centerYAnchor)
  1706. ])
  1707. return view
  1708. }
  1709. private func makeLoadMoreJobsRowView() -> NSView {
  1710. let row = NSView()
  1711. row.translatesAutoresizingMaskIntoConstraints = false
  1712. let button = HoverableButton()
  1713. button.pointerCursor = true
  1714. button.title = "Show more jobs"
  1715. button.font = .systemFont(ofSize: 12, weight: .semibold)
  1716. button.bezelStyle = .rounded
  1717. button.controlSize = .regular
  1718. button.contentTintColor = Theme.brandBlue
  1719. button.target = self
  1720. button.action = #selector(didTapLoadMoreJobs)
  1721. button.translatesAutoresizingMaskIntoConstraints = false
  1722. trailingLoadMoreJobsButton = button
  1723. row.addSubview(button)
  1724. NSLayoutConstraint.activate([
  1725. button.leadingAnchor.constraint(equalTo: row.leadingAnchor),
  1726. button.topAnchor.constraint(equalTo: row.topAnchor, constant: 2),
  1727. button.bottomAnchor.constraint(equalTo: row.bottomAnchor, constant: -2)
  1728. ])
  1729. return row
  1730. }
  1731. private func makeChatJobsStackView(jobs: [JobListing]) -> ChatJobsStackView {
  1732. let stack = ChatJobsStackView()
  1733. stack.orientation = .vertical
  1734. stack.spacing = 10
  1735. stack.alignment = .width
  1736. stack.distribution = .fill
  1737. stack.translatesAutoresizingMaskIntoConstraints = false
  1738. for job in jobs {
  1739. let card = makeJobListingCard(job, context: .homeSearchResults)
  1740. stack.addArrangedSubview(card)
  1741. card.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  1742. }
  1743. return stack
  1744. }
  1745. private func scrollChatToBottom() {
  1746. let maxY = max(0, chatDocumentView.bounds.height - chatScrollView.contentView.bounds.height)
  1747. chatScrollView.contentView.scroll(to: NSPoint(x: 0, y: maxY))
  1748. chatScrollView.reflectScrolledClipView(chatScrollView.contentView)
  1749. }
  1750. private func setInputEnabled(_ enabled: Bool) {
  1751. jobKeywordsField.isEnabled = enabled
  1752. findJobsButton.isEnabled = enabled
  1753. findJobsButton.alphaValue = enabled ? 1 : 0.65
  1754. trailingLoadMoreJobsButton?.isEnabled = enabled
  1755. trailingLoadMoreJobsButton?.alphaValue = enabled ? 1 : 0.65
  1756. }
  1757. private func configureSidebar() {
  1758. let items = currentSidebarItems
  1759. sidebar.arrangedSubviews.forEach {
  1760. sidebar.removeArrangedSubview($0)
  1761. $0.removeFromSuperview()
  1762. }
  1763. let brand = NSTextField(labelWithString: "Indeed AI\nJob Finder")
  1764. brand.font = .systemFont(ofSize: 18, weight: .bold)
  1765. brand.textColor = Theme.brandBlue
  1766. brand.alignment = .left
  1767. brand.maximumNumberOfLines = 2
  1768. // Tight multiline height in the sidebar stack (zero width makes intrinsic height unreliable).
  1769. brand.preferredMaxLayoutWidth = 194
  1770. sidebar.addArrangedSubview(brand)
  1771. sidebar.setCustomSpacing(10, after: brand)
  1772. items.enumerated().forEach { index, item in
  1773. let isSelected = index == selectedSidebarIndex
  1774. let rowHost = SidebarNavRowView { [weak self] in
  1775. self?.selectSidebarItem(at: index)
  1776. }
  1777. rowHost.translatesAutoresizingMaskIntoConstraints = false
  1778. rowHost.wantsLayer = true
  1779. rowHost.layer?.cornerRadius = 8
  1780. rowHost.restingBackgroundColor = isSelected ? Theme.selectionFill : nil
  1781. rowHost.hoverBackgroundColor = isSelected ? Theme.selectionFillHover : Theme.sidebarRowHoverFill
  1782. rowHost.setAccessibilityLabel(item.title)
  1783. rowHost.setAccessibilityRole(.button)
  1784. rowHost.setAccessibilitySelected(isSelected)
  1785. let row = NSStackView()
  1786. row.orientation = .horizontal
  1787. row.spacing = 8
  1788. row.alignment = .centerY
  1789. row.translatesAutoresizingMaskIntoConstraints = false
  1790. let icon = NSImageView()
  1791. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .medium)
  1792. icon.image = NSImage(systemSymbolName: item.systemImage, accessibilityDescription: item.title)
  1793. icon.contentTintColor = isSelected ? Theme.brandBlue : Theme.secondaryText
  1794. let text = NSTextField(labelWithString: item.title)
  1795. text.font = .systemFont(ofSize: 14, weight: .medium)
  1796. text.textColor = isSelected ? Theme.brandBlue : Theme.secondaryText
  1797. text.refusesFirstResponder = true
  1798. row.addArrangedSubview(icon)
  1799. row.addArrangedSubview(text)
  1800. if let badge = item.badge {
  1801. let badgeField = NSTextField(labelWithString: badge)
  1802. badgeField.font = .systemFont(ofSize: 11, weight: .semibold)
  1803. badgeField.textColor = Theme.primaryText
  1804. badgeField.wantsLayer = true
  1805. badgeField.layer?.backgroundColor = Theme.toggleBackground.cgColor
  1806. badgeField.layer?.cornerRadius = 8
  1807. badgeField.alignment = .center
  1808. badgeField.maximumNumberOfLines = 1
  1809. badgeField.lineBreakMode = .byClipping
  1810. badgeField.refusesFirstResponder = true
  1811. badgeField.translatesAutoresizingMaskIntoConstraints = false
  1812. badgeField.widthAnchor.constraint(equalToConstant: 42).isActive = true
  1813. row.addArrangedSubview(NSView())
  1814. row.addArrangedSubview(badgeField)
  1815. }
  1816. rowHost.addSubview(row)
  1817. NSLayoutConstraint.activate([
  1818. row.leadingAnchor.constraint(equalTo: rowHost.leadingAnchor, constant: 10),
  1819. row.trailingAnchor.constraint(equalTo: rowHost.trailingAnchor, constant: -10),
  1820. row.topAnchor.constraint(equalTo: rowHost.topAnchor, constant: 8),
  1821. row.bottomAnchor.constraint(equalTo: rowHost.bottomAnchor, constant: -8)
  1822. ])
  1823. rowHost.setContentHuggingPriority(.defaultLow, for: .horizontal)
  1824. sidebar.addArrangedSubview(rowHost)
  1825. let sidebarHorizontalInset = sidebar.edgeInsets.left + sidebar.edgeInsets.right
  1826. rowHost.widthAnchor.constraint(equalTo: sidebar.widthAnchor, constant: -sidebarHorizontalInset).isActive = true
  1827. }
  1828. let sidebarBottomSpacer = NSView()
  1829. sidebarBottomSpacer.translatesAutoresizingMaskIntoConstraints = false
  1830. sidebarBottomSpacer.setContentHuggingPriority(.defaultLow, for: .vertical)
  1831. sidebarBottomSpacer.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  1832. sidebar.addArrangedSubview(sidebarBottomSpacer)
  1833. let upgradeCard = NSView()
  1834. upgradeCard.translatesAutoresizingMaskIntoConstraints = false
  1835. upgradeCard.wantsLayer = true
  1836. upgradeCard.layer?.backgroundColor = Theme.proCardFill.cgColor
  1837. upgradeCard.layer?.cornerRadius = 14
  1838. upgradeCard.layer?.borderWidth = 1
  1839. upgradeCard.layer?.borderColor = Theme.proCardBorder.cgColor
  1840. upgradeCard.layer?.masksToBounds = true
  1841. let accentBar = NSView()
  1842. accentBar.translatesAutoresizingMaskIntoConstraints = false
  1843. accentBar.wantsLayer = true
  1844. accentBar.layer?.backgroundColor = Theme.proAccent.cgColor
  1845. let inner = NSStackView()
  1846. inner.translatesAutoresizingMaskIntoConstraints = false
  1847. inner.orientation = .vertical
  1848. inner.spacing = 10
  1849. inner.alignment = .centerX
  1850. let proIcon = NSImageView()
  1851. proIcon.translatesAutoresizingMaskIntoConstraints = false
  1852. proIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .semibold)
  1853. proIcon.image = NSImage(systemSymbolName: "sparkles", accessibilityDescription: nil)
  1854. proIcon.contentTintColor = Theme.proAccent
  1855. let proEyebrow = NSTextField(labelWithString: "Premium")
  1856. proEyebrow.font = .systemFont(ofSize: 11, weight: .heavy)
  1857. proEyebrow.textColor = Theme.proAccent
  1858. proEyebrow.alignment = .center
  1859. let eyebrowRow = NSStackView(views: [proIcon, proEyebrow])
  1860. eyebrowRow.orientation = .horizontal
  1861. eyebrowRow.spacing = 6
  1862. eyebrowRow.alignment = .centerY
  1863. let headline = NSTextField(labelWithString: "Upgrade to Pro")
  1864. headline.font = .systemFont(ofSize: 16, weight: .bold)
  1865. headline.textColor = Theme.primaryText
  1866. headline.alignment = .center
  1867. let upgradeDescription = NSTextField(wrappingLabelWithString: "Unlimited AI matches, smart alerts, and interview prep—all in one place.")
  1868. upgradeDescription.font = .systemFont(ofSize: 12, weight: .regular)
  1869. upgradeDescription.textColor = Theme.secondaryText
  1870. upgradeDescription.alignment = .center
  1871. // Sidebar content width is the fixed sidebar width minus horizontal edge insets; card must stay within that band.
  1872. let cardWidth: CGFloat = 186
  1873. let innerContentWidth = cardWidth - 28
  1874. upgradeDescription.preferredMaxLayoutWidth = innerContentWidth
  1875. let upgradeButton = HoverableButton(title: "Upgrade to Pro", target: self, action: #selector(didTapUpgradeToPro))
  1876. upgradeButton.isBordered = false
  1877. upgradeButton.bezelStyle = .rounded
  1878. upgradeButton.font = .systemFont(ofSize: 13, weight: .bold)
  1879. upgradeButton.contentTintColor = Theme.proCTAText
  1880. upgradeButton.alignment = .center
  1881. upgradeButton.wantsLayer = true
  1882. upgradeButton.layer?.backgroundColor = Theme.proCTABackground.cgColor
  1883. upgradeButton.layer?.cornerRadius = 20
  1884. upgradeButton.translatesAutoresizingMaskIntoConstraints = false
  1885. upgradeButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
  1886. upgradeButton.pointerCursor = true
  1887. upgradeButton.hoverHandler = { [weak upgradeButton] hovering in
  1888. upgradeButton?.layer?.backgroundColor = (hovering ? Theme.brandBlueHover : Theme.proCTABackground).cgColor
  1889. }
  1890. inner.addArrangedSubview(eyebrowRow)
  1891. inner.addArrangedSubview(headline)
  1892. inner.addArrangedSubview(upgradeDescription)
  1893. inner.addArrangedSubview(upgradeButton)
  1894. upgradeCard.addSubview(accentBar)
  1895. upgradeCard.addSubview(inner)
  1896. NSLayoutConstraint.activate([
  1897. upgradeCard.widthAnchor.constraint(equalToConstant: cardWidth),
  1898. accentBar.topAnchor.constraint(equalTo: upgradeCard.topAnchor),
  1899. accentBar.leadingAnchor.constraint(equalTo: upgradeCard.leadingAnchor),
  1900. accentBar.trailingAnchor.constraint(equalTo: upgradeCard.trailingAnchor),
  1901. accentBar.heightAnchor.constraint(equalToConstant: 2),
  1902. inner.leadingAnchor.constraint(equalTo: upgradeCard.leadingAnchor, constant: 14),
  1903. inner.trailingAnchor.constraint(equalTo: upgradeCard.trailingAnchor, constant: -14),
  1904. inner.topAnchor.constraint(equalTo: accentBar.bottomAnchor, constant: 12),
  1905. inner.bottomAnchor.constraint(equalTo: upgradeCard.bottomAnchor, constant: -14),
  1906. upgradeButton.widthAnchor.constraint(equalTo: inner.widthAnchor)
  1907. ])
  1908. sidebar.addArrangedSubview(upgradeCard)
  1909. }
  1910. @objc private func didTapUpgradeToPro() {
  1911. guard let url = URL(string: "https://www.indeed.com") else { return }
  1912. NSWorkspace.shared.open(url)
  1913. }
  1914. @objc private func didChangeThemeSelection(_ sender: NSSegmentedControl) {
  1915. switch sender.selectedSegment {
  1916. case 1:
  1917. NSApp.appearance = NSAppearance(named: .aqua)
  1918. case 2:
  1919. NSApp.appearance = NSAppearance(named: .darkAqua)
  1920. default:
  1921. NSApp.appearance = nil
  1922. }
  1923. }
  1924. private func selectSidebarItem(at index: Int) {
  1925. guard index >= 0, index < currentSidebarItems.count else { return }
  1926. let selectingHome = isHomeSidebarIndex(index)
  1927. if index == selectedSidebarIndex {
  1928. if selectingHome {
  1929. applyHomeState()
  1930. }
  1931. return
  1932. }
  1933. selectedSidebarIndex = index
  1934. configureSidebar()
  1935. updateMainContentVisibility()
  1936. if selectingHome {
  1937. applyHomeState()
  1938. }
  1939. }
  1940. }
  1941. private struct ChatMessage: Codable {
  1942. let role: String
  1943. let content: String
  1944. }
  1945. private final class OpenAIJobSearchService {
  1946. private let endpoint = URL(string: "https://api.openai.com/v1/responses")!
  1947. private let session = URLSession(configuration: .ephemeral)
  1948. func searchJobs(query: String, conversation: [ChatMessage], maxJobs: Int, completion: @escaping (Result<JobSearchOutput, Error>) -> Void) {
  1949. let jobLimit = max(1, min(maxJobs, 25))
  1950. let apiKey = OpenAIConfiguration.apiKey
  1951. guard OpenAIConfiguration.hasAPIKey else {
  1952. completion(.failure(NSError(
  1953. domain: "OpenAIJobSearchService",
  1954. code: 1,
  1955. userInfo: [NSLocalizedDescriptionKey: "Missing API key. Set OPENAI_API_KEY in Xcode Build Settings."]
  1956. )))
  1957. return
  1958. }
  1959. var request = URLRequest(url: endpoint)
  1960. request.httpMethod = "POST"
  1961. request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  1962. request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
  1963. request.timeoutInterval = 45
  1964. let recentContext = conversation.suffix(8)
  1965. .map { "\($0.role.uppercased()): \($0.content)" }
  1966. .joined(separator: "\n")
  1967. let contextBlock: String
  1968. if recentContext.isEmpty {
  1969. contextBlock = "No prior conversation context."
  1970. } else {
  1971. contextBlock = recentContext
  1972. }
  1973. let instructions = """
  1974. Continue this same job-search conversation. Use prior context when useful. The line "Latest user query" is the primary task; earlier USER/ASSISTANT lines are context (previous role, location, or results).
  1975. Conversation context:
  1976. \(contextBlock)
  1977. Latest user query: "\(query)"
  1978. Use web search to find currently posted jobs that satisfy this query. If the user refines pay, seniority, work location, or similar, run a new search that applies those constraints to the same career topic as in the context.
  1979. CRITICAL OUTPUT RULES:
  1980. - Reply with NOTHING except one JSON object. No markdown, no code fences, no prose before or after, no labels like "Here is the JSON".
  1981. - The JSON must match exactly this shape (lowercase key "jobs"):
  1982. {"jobs":[{"title":"...","description":"...","url":"https://..."}]}
  1983. - If you find no suitable listings, return {"jobs":[]} — still valid JSON only.
  1984. Return up to \(jobLimit) jobs in the jobs array (fewer only if the web has no additional distinct matches). Do not repeat titles or URLs already implied in the conversation context above.
  1985. Keep each description to one sentence; prefer real listing URLs.
  1986. """
  1987. let payload = OpenAIResponsesRequest(
  1988. model: "gpt-4o-mini",
  1989. input: instructions,
  1990. tools: [OpenAIResponsesTool(type: "web_search_preview")]
  1991. )
  1992. do {
  1993. request.httpBody = try JSONEncoder().encode(payload)
  1994. } catch {
  1995. completion(.failure(error))
  1996. return
  1997. }
  1998. session.dataTask(with: request) { data, response, error in
  1999. if let error {
  2000. completion(.failure(error))
  2001. return
  2002. }
  2003. guard let data else {
  2004. completion(.failure(NSError(
  2005. domain: "OpenAIJobSearchService",
  2006. code: 2,
  2007. userInfo: [NSLocalizedDescriptionKey: "API returned an empty response."]
  2008. )))
  2009. return
  2010. }
  2011. if let http = response as? HTTPURLResponse, !(200...299).contains(http.statusCode) {
  2012. if let apiError = try? JSONDecoder().decode(OpenAIAPIErrorResponse.self, from: data) {
  2013. completion(.failure(NSError(
  2014. domain: "OpenAIJobSearchService",
  2015. code: http.statusCode,
  2016. userInfo: [NSLocalizedDescriptionKey: apiError.error.message]
  2017. )))
  2018. } else {
  2019. completion(.failure(NSError(
  2020. domain: "OpenAIJobSearchService",
  2021. code: http.statusCode,
  2022. userInfo: [NSLocalizedDescriptionKey: "Job search request failed with status \(http.statusCode)."]
  2023. )))
  2024. }
  2025. return
  2026. }
  2027. do {
  2028. let modelText = try Self.extractModelTextFromResponsesBody(data)
  2029. let trimmed = modelText.trimmingCharacters(in: .whitespacesAndNewlines)
  2030. guard !trimmed.isEmpty else {
  2031. throw NSError(
  2032. domain: "OpenAIJobSearchService",
  2033. code: 4,
  2034. userInfo: [NSLocalizedDescriptionKey: "The API returned an empty text payload."]
  2035. )
  2036. }
  2037. let jobs = try Self.parseJobListings(fromModelText: trimmed)
  2038. completion(.success(JobSearchOutput(jobs: jobs)))
  2039. } catch {
  2040. completion(.failure(error))
  2041. }
  2042. }.resume()
  2043. }
  2044. /// Walks the `/v1/responses` JSON without strict Codable so tool calls, refusals, and future output item types do not break decoding. Collects only `output_text` segments from assistant `message` items (and any other output items that expose a `content` array).
  2045. private static func extractModelTextFromResponsesBody(_ data: Data) throws -> String {
  2046. let rootObject: Any
  2047. do {
  2048. rootObject = try JSONSerialization.jsonObject(with: data, options: [])
  2049. } catch {
  2050. throw NSError(
  2051. domain: "OpenAIJobSearchService",
  2052. code: 5,
  2053. userInfo: [NSLocalizedDescriptionKey: "The job search service returned data that was not valid JSON."]
  2054. )
  2055. }
  2056. guard let root = rootObject as? [String: Any] else {
  2057. throw NSError(
  2058. domain: "OpenAIJobSearchService",
  2059. code: 5,
  2060. userInfo: [NSLocalizedDescriptionKey: "Unexpected response shape from the job search service."]
  2061. )
  2062. }
  2063. if let status = root["status"] as? String {
  2064. if status == "failed" {
  2065. let message = (root["error"] as? [String: Any])?["message"] as? String ?? "The search request failed."
  2066. throw NSError(domain: "OpenAIJobSearchService", code: 7, userInfo: [NSLocalizedDescriptionKey: message])
  2067. }
  2068. if status == "incomplete",
  2069. let details = root["incomplete_details"] as? [String: Any],
  2070. let reason = details["reason"] as? String {
  2071. throw NSError(
  2072. domain: "OpenAIJobSearchService",
  2073. code: 8,
  2074. userInfo: [NSLocalizedDescriptionKey: "Search stopped early (\(reason)). Try a simpler query or try again."]
  2075. )
  2076. }
  2077. }
  2078. if let direct = root["output_text"] as? String {
  2079. let trimmed = direct.trimmingCharacters(in: .whitespacesAndNewlines)
  2080. if !trimmed.isEmpty { return trimmed }
  2081. }
  2082. guard let output = root["output"] as? [Any] else {
  2083. throw NSError(
  2084. domain: "OpenAIJobSearchService",
  2085. code: 9,
  2086. userInfo: [NSLocalizedDescriptionKey: "The search service returned no assistant text. Try again in a moment."]
  2087. )
  2088. }
  2089. var segments: [String] = []
  2090. for case let item as [String: Any] in output where (item["type"] as? String) == "message" {
  2091. collectOutputTextSegments(fromOutputItem: item, into: &segments)
  2092. }
  2093. if segments.isEmpty {
  2094. for case let item as [String: Any] in output {
  2095. collectOutputTextSegments(fromOutputItem: item, into: &segments)
  2096. }
  2097. }
  2098. let combined = segments.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
  2099. if !combined.isEmpty {
  2100. return combined
  2101. }
  2102. throw NSError(
  2103. domain: "OpenAIJobSearchService",
  2104. code: 9,
  2105. userInfo: [NSLocalizedDescriptionKey: "The model did not return readable job-search text. Try again."]
  2106. )
  2107. }
  2108. private static func collectOutputTextSegments(fromOutputItem item: [String: Any], into segments: inout [String]) {
  2109. guard let content = item["content"] as? [Any] else { return }
  2110. for case let part as [String: Any] in content {
  2111. guard (part["type"] as? String) == "output_text" else { continue }
  2112. if let s = part["text"] as? String {
  2113. segments.append(s)
  2114. } else if let nested = part["text"] as? [String: Any], let value = nested["value"] as? String {
  2115. segments.append(value)
  2116. }
  2117. }
  2118. }
  2119. private static func parseJobListings(fromModelText text: String) throws -> [JobListing] {
  2120. let jsonString = extractJobJSONObjectString(from: text) ?? extractJSONObject(from: text)
  2121. let jsonData = Data(jsonString.utf8)
  2122. if let payload = try? JSONDecoder().decode(JobSearchResultsPayload.self, from: jsonData) {
  2123. return payload.jobs
  2124. }
  2125. if let listings = try? JSONDecoder().decode([JobListing].self, from: jsonData) {
  2126. return listings
  2127. }
  2128. if let obj = try? JSONSerialization.jsonObject(with: jsonData, options: []) {
  2129. if let dict = obj as? [String: Any], let jobs = jobListings(fromFlexibleJSONObject: dict) {
  2130. return jobs
  2131. }
  2132. if let arr = obj as? [[String: Any]], let jobs = jobListings(fromFlexibleJobArray: arr) {
  2133. return jobs
  2134. }
  2135. }
  2136. throw NSError(
  2137. domain: "OpenAIJobSearchService",
  2138. code: 10,
  2139. userInfo: [NSLocalizedDescriptionKey: "The assistant reply did not include job listings in the expected JSON format. Try your search again."]
  2140. )
  2141. }
  2142. private static func jobListings(fromFlexibleJSONObject dict: [String: Any]) -> [JobListing]? {
  2143. for (key, value) in dict {
  2144. guard key.caseInsensitiveCompare("jobs") == .orderedSame, let arr = value as? [[String: Any]] else { continue }
  2145. if let jobs = jobListings(fromFlexibleJobArray: arr) { return jobs }
  2146. }
  2147. for wrapKey in ["data", "result", "results", "payload"] {
  2148. if let inner = dict[wrapKey] as? [String: Any], let nested = jobListings(fromFlexibleJSONObject: inner) {
  2149. return nested
  2150. }
  2151. }
  2152. return nil
  2153. }
  2154. private static func jobListings(fromFlexibleJobArray jobs: [[String: Any]]) -> [JobListing]? {
  2155. var out: [JobListing] = []
  2156. for item in jobs {
  2157. guard let title = firstString(valuesForKeys: ["title", "job_title", "name", "position"], in: item)?.trimmingCharacters(in: .whitespacesAndNewlines),
  2158. !title.isEmpty,
  2159. let desc = firstString(valuesForKeys: ["description", "snippet", "summary", "desc"], in: item)?.trimmingCharacters(in: .whitespacesAndNewlines),
  2160. !desc.isEmpty else { continue }
  2161. let urlRaw = firstString(valuesForKeys: ["url", "link", "apply_url", "job_url"], in: item)?.trimmingCharacters(in: .whitespacesAndNewlines)
  2162. let url: String? = (urlRaw?.isEmpty == true) ? nil : urlRaw
  2163. out.append(JobListing(title: title, description: desc, url: url))
  2164. }
  2165. return out.isEmpty ? nil : out
  2166. }
  2167. private static func firstString(valuesForKeys keys: [String], in dict: [String: Any]) -> String? {
  2168. for wanted in keys {
  2169. for (dk, dv) in dict {
  2170. guard dk.caseInsensitiveCompare(wanted) == .orderedSame, let s = dv as? String else { continue }
  2171. return s
  2172. }
  2173. }
  2174. return nil
  2175. }
  2176. private static func stripMarkdownCodeFence(_ text: String) -> String {
  2177. var s = text.trimmingCharacters(in: .whitespacesAndNewlines)
  2178. guard s.hasPrefix("```") else { return s }
  2179. s.removeFirst(3)
  2180. if s.lowercased().hasPrefix("json") {
  2181. s.removeFirst(4)
  2182. }
  2183. s = s.trimmingCharacters(in: .whitespacesAndNewlines)
  2184. if let fence = s.range(of: "```", options: .backwards) {
  2185. s = String(s[..<fence.lowerBound])
  2186. }
  2187. return s.trimmingCharacters(in: .whitespacesAndNewlines)
  2188. }
  2189. private static func balancedJSONObject(from openBrace: String.Index, in s: String) -> String? {
  2190. var depth = 0
  2191. var inString = false
  2192. var escaped = false
  2193. var i = openBrace
  2194. while i < s.endIndex {
  2195. let ch = s[i]
  2196. if inString {
  2197. if escaped {
  2198. escaped = false
  2199. } else if ch == "\\" {
  2200. escaped = true
  2201. } else if ch == "\"" {
  2202. inString = false
  2203. }
  2204. } else {
  2205. switch ch {
  2206. case "\"":
  2207. inString = true
  2208. case "{":
  2209. depth += 1
  2210. case "}":
  2211. depth -= 1
  2212. if depth == 0 {
  2213. return String(s[openBrace...i])
  2214. }
  2215. default:
  2216. break
  2217. }
  2218. }
  2219. i = s.index(after: i)
  2220. }
  2221. return nil
  2222. }
  2223. /// Prefers the JSON object that contains a `"jobs"` key so prose before/after the payload does not confuse the decoder.
  2224. private static func extractJobJSONObjectString(from text: String) -> String? {
  2225. let s = stripMarkdownCodeFence(text)
  2226. guard let jobsRange = s.range(of: "\"jobs\"", options: .caseInsensitive) else { return nil }
  2227. let head = s[..<jobsRange.lowerBound]
  2228. guard let open = head.lastIndex(of: "{") else { return nil }
  2229. return balancedJSONObject(from: open, in: s)
  2230. }
  2231. private static func extractJSONObject(from text: String) -> String {
  2232. if let extracted = extractJobJSONObjectString(from: text) {
  2233. return extracted
  2234. }
  2235. let stripped = stripMarkdownCodeFence(text)
  2236. if let first = stripped.firstIndex(of: "{"), let balanced = balancedJSONObject(from: first, in: stripped) {
  2237. return balanced
  2238. }
  2239. if let range = text.range(of: "\\{[\\s\\S]*\\}", options: .regularExpression) {
  2240. return String(text[range])
  2241. }
  2242. return text
  2243. }
  2244. }
  2245. private struct OpenAIResponsesRequest: Codable {
  2246. let model: String
  2247. let input: String
  2248. let tools: [OpenAIResponsesTool]
  2249. }
  2250. private struct OpenAIResponsesTool: Codable {
  2251. let type: String
  2252. }
  2253. private struct JobSearchResultsPayload: Codable {
  2254. let jobs: [JobListing]
  2255. }
  2256. private struct JobSearchOutput {
  2257. let jobs: [JobListing]
  2258. }
  2259. private struct OpenAIAPIErrorResponse: Codable {
  2260. let error: APIError
  2261. struct APIError: Codable {
  2262. let message: String
  2263. }
  2264. }
  2265. /// Home welcome row: three tappable shortcuts that seed the main search field (matches the reference dashboard tiles).
  2266. private final class FeatureShortcutCardView: NSView {
  2267. private weak var actionTarget: AnyObject?
  2268. private var actionSelector: Selector
  2269. init(symbolName: String, title: String, subtitle: String, target: AnyObject?, action: Selector) {
  2270. self.actionTarget = target
  2271. self.actionSelector = action
  2272. super.init(frame: .zero)
  2273. translatesAutoresizingMaskIntoConstraints = false
  2274. wantsLayer = true
  2275. layer?.cornerRadius = 14
  2276. if #available(macOS 11.0, *) {
  2277. layer?.cornerCurve = .continuous
  2278. }
  2279. layer?.backgroundColor = NSColor.white.cgColor
  2280. layer?.masksToBounds = false
  2281. layer?.shadowColor = NSColor.black.withAlphaComponent(0.12).cgColor
  2282. layer?.shadowOffset = CGSize(width: 0, height: 2)
  2283. layer?.shadowRadius = 10
  2284. layer?.shadowOpacity = 1
  2285. let brandBlue = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 1)
  2286. let iconWellColor = NSColor(srgbRed: 220 / 255, green: 235 / 255, blue: 252 / 255, alpha: 1)
  2287. let secondary = NSColor(srgbRed: 118 / 255, green: 118 / 255, blue: 118 / 255, alpha: 1)
  2288. let iconHost = NSView()
  2289. iconHost.translatesAutoresizingMaskIntoConstraints = false
  2290. iconHost.wantsLayer = true
  2291. iconHost.layer?.backgroundColor = iconWellColor.cgColor
  2292. iconHost.layer?.cornerRadius = 22
  2293. let icon = NSImageView()
  2294. icon.translatesAutoresizingMaskIntoConstraints = false
  2295. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 16, weight: .semibold)
  2296. icon.image = NSImage(systemSymbolName: symbolName, accessibilityDescription: nil)
  2297. icon.contentTintColor = brandBlue
  2298. iconHost.addSubview(icon)
  2299. let titleField = NSTextField(wrappingLabelWithString: title)
  2300. titleField.font = .systemFont(ofSize: 15, weight: .bold)
  2301. titleField.textColor = brandBlue
  2302. titleField.maximumNumberOfLines = 1
  2303. titleField.isEditable = false
  2304. titleField.isBordered = false
  2305. titleField.drawsBackground = false
  2306. titleField.alignment = .left
  2307. let subtitleField = NSTextField(wrappingLabelWithString: subtitle)
  2308. subtitleField.font = .systemFont(ofSize: 11, weight: .regular)
  2309. subtitleField.textColor = secondary
  2310. subtitleField.maximumNumberOfLines = 2
  2311. subtitleField.isEditable = false
  2312. subtitleField.isBordered = false
  2313. subtitleField.drawsBackground = false
  2314. subtitleField.alignment = .left
  2315. subtitleField.preferredMaxLayoutWidth = 160
  2316. let textColumn = NSStackView(views: [titleField, subtitleField])
  2317. textColumn.orientation = .vertical
  2318. textColumn.spacing = 4
  2319. textColumn.alignment = .leading
  2320. textColumn.translatesAutoresizingMaskIntoConstraints = false
  2321. textColumn.setContentHuggingPriority(.defaultLow, for: .horizontal)
  2322. textColumn.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  2323. let chevron = NSImageView()
  2324. chevron.translatesAutoresizingMaskIntoConstraints = false
  2325. chevron.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .semibold)
  2326. chevron.image = NSImage(systemSymbolName: "arrow.right", accessibilityDescription: nil)
  2327. chevron.contentTintColor = brandBlue
  2328. chevron.setContentHuggingPriority(.required, for: .horizontal)
  2329. chevron.setContentCompressionResistancePriority(.required, for: .horizontal)
  2330. iconHost.setContentHuggingPriority(.required, for: .horizontal)
  2331. iconHost.setContentCompressionResistancePriority(.required, for: .horizontal)
  2332. let row = NSStackView(views: [iconHost, textColumn, chevron])
  2333. row.orientation = .horizontal
  2334. row.spacing = 12
  2335. row.alignment = .centerY
  2336. row.distribution = .fill
  2337. row.translatesAutoresizingMaskIntoConstraints = false
  2338. addSubview(row)
  2339. NSLayoutConstraint.activate([
  2340. row.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 14),
  2341. row.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -14),
  2342. row.topAnchor.constraint(equalTo: topAnchor, constant: 16),
  2343. row.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16),
  2344. iconHost.widthAnchor.constraint(equalToConstant: 44),
  2345. iconHost.heightAnchor.constraint(equalToConstant: 44),
  2346. icon.centerXAnchor.constraint(equalTo: iconHost.centerXAnchor),
  2347. icon.centerYAnchor.constraint(equalTo: iconHost.centerYAnchor)
  2348. ])
  2349. setAccessibilityElement(true)
  2350. setAccessibilityRole(.button)
  2351. setAccessibilityLabel("\(title). \(subtitle)")
  2352. }
  2353. @available(*, unavailable)
  2354. required init?(coder: NSCoder) {
  2355. fatalError("init(coder:) has not been implemented")
  2356. }
  2357. override func layout() {
  2358. super.layout()
  2359. guard let layer = layer, bounds.width > 0, bounds.height > 0 else { return }
  2360. let r = bounds
  2361. layer.shadowPath = CGPath(roundedRect: r, cornerWidth: 14, cornerHeight: 14, transform: nil)
  2362. }
  2363. override func mouseDown(with event: NSEvent) {
  2364. if let target = actionTarget {
  2365. _ = target.perform(actionSelector, with: nil)
  2366. }
  2367. }
  2368. override func resetCursorRects() {
  2369. super.resetCursorRects()
  2370. addCursorRect(bounds, cursor: .pointingHand)
  2371. }
  2372. }
  2373. /// `NSButton` that carries a `JobListing` for card actions (`representedObject` is unavailable on `NSButton` in this target).
  2374. private final class JobPayloadButton: HoverableButton {
  2375. var jobPayload: JobListing?
  2376. var cardContext: JobListingCardContext = .homeSearchResults
  2377. }
  2378. /// `NSButton` with a tracking area that reports hover transitions and (optionally) swaps in a pointing-hand cursor while hovered.
  2379. private class HoverableButton: NSButton {
  2380. var hoverHandler: ((Bool) -> Void)?
  2381. var pointerCursor: Bool = false
  2382. private(set) var isHovering: Bool = false
  2383. private var trackingArea: NSTrackingArea?
  2384. private var didPushCursor: Bool = false
  2385. override func updateTrackingAreas() {
  2386. super.updateTrackingAreas()
  2387. if let area = trackingArea { removeTrackingArea(area) }
  2388. let area = NSTrackingArea(
  2389. rect: bounds,
  2390. options: [.activeInKeyWindow, .mouseEnteredAndExited, .inVisibleRect],
  2391. owner: self,
  2392. userInfo: nil
  2393. )
  2394. addTrackingArea(area)
  2395. trackingArea = area
  2396. }
  2397. override func mouseEntered(with event: NSEvent) {
  2398. super.mouseEntered(with: event)
  2399. isHovering = true
  2400. hoverHandler?(true)
  2401. if pointerCursor, !didPushCursor {
  2402. NSCursor.pointingHand.push()
  2403. didPushCursor = true
  2404. }
  2405. }
  2406. override func mouseExited(with event: NSEvent) {
  2407. super.mouseExited(with: event)
  2408. isHovering = false
  2409. hoverHandler?(false)
  2410. if didPushCursor {
  2411. NSCursor.pop()
  2412. didPushCursor = false
  2413. }
  2414. }
  2415. override func viewWillMove(toWindow newWindow: NSWindow?) {
  2416. super.viewWillMove(toWindow: newWindow)
  2417. // Guard against an unbalanced cursor stack if the button is removed mid-hover (e.g. job card replaced after a search).
  2418. if newWindow == nil, didPushCursor {
  2419. NSCursor.pop()
  2420. didPushCursor = false
  2421. isHovering = false
  2422. }
  2423. }
  2424. }
  2425. /// `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.
  2426. private class HoverableView: NSView {
  2427. var hoverHandler: ((Bool) -> Void)?
  2428. var pointerCursor: Bool = false
  2429. private(set) var isHovering: Bool = false
  2430. private var trackingArea: NSTrackingArea?
  2431. private var didPushCursor: Bool = false
  2432. override func updateTrackingAreas() {
  2433. super.updateTrackingAreas()
  2434. if let area = trackingArea { removeTrackingArea(area) }
  2435. let area = NSTrackingArea(
  2436. rect: bounds,
  2437. options: [.activeInKeyWindow, .mouseEnteredAndExited, .inVisibleRect],
  2438. owner: self,
  2439. userInfo: nil
  2440. )
  2441. addTrackingArea(area)
  2442. trackingArea = area
  2443. }
  2444. override func mouseEntered(with event: NSEvent) {
  2445. super.mouseEntered(with: event)
  2446. isHovering = true
  2447. hoverHandler?(true)
  2448. if pointerCursor, !didPushCursor {
  2449. NSCursor.pointingHand.push()
  2450. didPushCursor = true
  2451. }
  2452. }
  2453. override func mouseExited(with event: NSEvent) {
  2454. super.mouseExited(with: event)
  2455. isHovering = false
  2456. hoverHandler?(false)
  2457. if didPushCursor {
  2458. NSCursor.pop()
  2459. didPushCursor = false
  2460. }
  2461. }
  2462. override func viewWillMove(toWindow newWindow: NSWindow?) {
  2463. super.viewWillMove(toWindow: newWindow)
  2464. if newWindow == nil, didPushCursor {
  2465. NSCursor.pop()
  2466. didPushCursor = false
  2467. isHovering = false
  2468. }
  2469. }
  2470. }
  2471. /// 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).
  2472. private final class JobListingsDocumentView: NSView {
  2473. override var isFlipped: Bool { true }
  2474. }
  2475. /// Marker subclass for the per-assistant-message job stack embedded inside a chat bubble. `NSView.tag` is read-only on macOS, so a typed subclass is the cleanest way to identify these stacks during dismiss and layout passes.
  2476. private final class ChatJobsStackView: NSStackView {}
  2477. /// Marker subclass for the wrapping label inside a chat bubble. Lets the layout pass find each bubble label to update its `preferredMaxLayoutWidth` when the chat width changes.
  2478. private final class ChatBubbleLabel: NSTextField {}
  2479. /// 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.
  2480. private final class SidebarNavRowView: NSView {
  2481. private let onSelect: () -> Void
  2482. var restingBackgroundColor: NSColor? {
  2483. didSet { applyBackground() }
  2484. }
  2485. var hoverBackgroundColor: NSColor?
  2486. private var isHovering: Bool = false
  2487. private var didPushCursor: Bool = false
  2488. init(onSelect: @escaping () -> Void) {
  2489. self.onSelect = onSelect
  2490. super.init(frame: .zero)
  2491. }
  2492. @available(*, unavailable)
  2493. required init?(coder: NSCoder) {
  2494. fatalError("init(coder:) has not been implemented")
  2495. }
  2496. override func hitTest(_ point: NSPoint) -> NSView? {
  2497. guard let superview else { return super.hitTest(point) }
  2498. let local = convert(point, from: superview)
  2499. return bounds.contains(local) ? self : nil
  2500. }
  2501. override func mouseDown(with event: NSEvent) {
  2502. onSelect()
  2503. }
  2504. override func updateTrackingAreas() {
  2505. super.updateTrackingAreas()
  2506. trackingAreas.forEach { removeTrackingArea($0) }
  2507. addTrackingArea(NSTrackingArea(
  2508. rect: bounds,
  2509. options: [.activeInKeyWindow, .mouseEnteredAndExited, .inVisibleRect],
  2510. owner: self,
  2511. userInfo: nil
  2512. ))
  2513. }
  2514. override func mouseEntered(with event: NSEvent) {
  2515. super.mouseEntered(with: event)
  2516. isHovering = true
  2517. applyBackground()
  2518. if !didPushCursor {
  2519. NSCursor.pointingHand.push()
  2520. didPushCursor = true
  2521. }
  2522. }
  2523. override func mouseExited(with event: NSEvent) {
  2524. super.mouseExited(with: event)
  2525. isHovering = false
  2526. applyBackground()
  2527. if didPushCursor {
  2528. NSCursor.pop()
  2529. didPushCursor = false
  2530. }
  2531. }
  2532. override func viewWillMove(toWindow newWindow: NSWindow?) {
  2533. super.viewWillMove(toWindow: newWindow)
  2534. if newWindow == nil, didPushCursor {
  2535. NSCursor.pop()
  2536. didPushCursor = false
  2537. isHovering = false
  2538. }
  2539. }
  2540. private func applyBackground() {
  2541. let color = isHovering ? (hoverBackgroundColor ?? restingBackgroundColor) : restingBackgroundColor
  2542. layer?.backgroundColor = color?.cgColor
  2543. }
  2544. }