Aucune description

DashboardView.swift 187KB

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