Нет описания

DashboardView.swift 166KB

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