Açıklama Yok

DashboardView.swift 174KB

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