説明なし

DashboardView.swift 180KB

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