Aucune description

DashboardView.swift 186KB

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