暂无描述

DashboardView.swift 140KB

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