Nenhuma descrição

DashboardView.swift 155KB

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