Sin descripción

DashboardView.swift 166KB

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