DashboardView.swift 190 KB

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