Brak opisu

DashboardView.swift 166KB

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