説明なし

DashboardView.swift 163KB

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