Aucune description

DashboardView.swift 129KB

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