Нет описания

DashboardView.swift 167KB

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