No Description

DashboardView.swift 141KB

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