DashboardView.swift 189 KB

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