Sen descrición

DashboardView.swift 163KB

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