Няма описание

DashboardView.swift 162KB

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