Keine Beschreibung

DashboardView.swift 166KB

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