DashboardView.swift 190 KB

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