Нет описания

ViewController.swift 299KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891
  1. //
  2. // ViewController.swift
  3. // meetings_app
  4. //
  5. // Created by Dev Mac 1 on 06/04/2026.
  6. //
  7. import Cocoa
  8. import QuartzCore
  9. import WebKit
  10. import AuthenticationServices
  11. import StoreKit
  12. private enum SidebarPage: Int {
  13. case joinMeetings = 0
  14. case photo = 1
  15. case video = 2
  16. case settings = 3
  17. }
  18. private enum ZoomJoinMode: Int {
  19. case id = 0
  20. case url = 1
  21. }
  22. private enum SettingsAction: Int {
  23. case restore = 0
  24. case rateUs = 1
  25. case support = 2
  26. case moreApps = 3
  27. case shareApp = 4
  28. case upgrade = 5
  29. }
  30. private enum PremiumPlan: Int {
  31. case weekly = 0
  32. case monthly = 1
  33. case yearly = 2
  34. case lifetime = 3
  35. }
  36. private enum PremiumStoreProduct {
  37. static let weekly = "com.mqldev.meetingsapp.premium.weekly"
  38. static let monthly = "com.mqldev.meetingsapp.premium.monthly"
  39. static let yearly = "com.mqldev.meetingsapp.premium.yearly"
  40. static let lifetime = "com.mqldev.meetingsapp.premium.lifetime"
  41. static let allIDs = [weekly, monthly, yearly, lifetime]
  42. static func productID(for plan: PremiumPlan) -> String {
  43. switch plan {
  44. case .weekly: return weekly
  45. case .monthly: return monthly
  46. case .yearly: return yearly
  47. case .lifetime: return lifetime
  48. }
  49. }
  50. static func plan(for productID: String) -> PremiumPlan? {
  51. switch productID {
  52. case weekly: return .weekly
  53. case monthly: return .monthly
  54. case yearly: return .yearly
  55. case lifetime: return .lifetime
  56. default: return nil
  57. }
  58. }
  59. }
  60. @MainActor
  61. private final class StoreKitCoordinator {
  62. enum PurchaseOutcome {
  63. case success
  64. case cancelled
  65. case pending
  66. case unavailable
  67. case alreadyOwned
  68. case failed(String)
  69. }
  70. private(set) var productsByID: [String: Product] = [:]
  71. private(set) var activeEntitlementProductIDs: Set<String> = []
  72. private(set) var lastProductLoadError: String?
  73. var onEntitlementsChanged: ((Bool) -> Void)?
  74. var hasPremiumAccess: Bool { !activeEntitlementProductIDs.isEmpty }
  75. var hasLifetimeAccess: Bool { activeEntitlementProductIDs.contains(PremiumStoreProduct.lifetime) }
  76. var activeNonLifetimePlan: PremiumPlan? {
  77. activeEntitlementProductIDs
  78. .compactMap { PremiumStoreProduct.plan(for: $0) }
  79. .filter { $0 != .lifetime }
  80. .max(by: { $0.rawValue < $1.rawValue })
  81. }
  82. private var transactionUpdatesTask: Task<Void, Never>?
  83. deinit {
  84. transactionUpdatesTask?.cancel()
  85. }
  86. func start() async {
  87. if transactionUpdatesTask == nil {
  88. transactionUpdatesTask = Task { [weak self] in
  89. await self?.observeTransactionUpdates()
  90. }
  91. }
  92. await refreshProducts()
  93. await refreshEntitlements()
  94. }
  95. func refreshProducts() async {
  96. do {
  97. let products = try await Product.products(for: PremiumStoreProduct.allIDs)
  98. productsByID = Dictionary(uniqueKeysWithValues: products.map { ($0.id, $0) })
  99. lastProductLoadError = nil
  100. } catch {
  101. productsByID = [:]
  102. lastProductLoadError = error.localizedDescription
  103. }
  104. }
  105. func refreshEntitlements() async {
  106. let previousHasPremiumAccess = hasPremiumAccess
  107. var active = Set<String>()
  108. for await entitlement in Transaction.currentEntitlements {
  109. guard case .verified(let transaction) = entitlement else { continue }
  110. guard PremiumStoreProduct.allIDs.contains(transaction.productID) else { continue }
  111. if Self.isTransactionActive(transaction) {
  112. active.insert(transaction.productID)
  113. }
  114. }
  115. // Some StoreKit test timelines can briefly report empty current entitlements
  116. // even though a latest verified transaction exists for a non-consumable.
  117. // Merge in latest transactions to keep launch access state accurate.
  118. for productID in PremiumStoreProduct.allIDs {
  119. guard let latest = await Transaction.latest(for: productID),
  120. case .verified(let transaction) = latest,
  121. Self.isTransactionActive(transaction) else { continue }
  122. active.insert(productID)
  123. }
  124. activeEntitlementProductIDs = active
  125. let newHasPremiumAccess = hasPremiumAccess
  126. if newHasPremiumAccess != previousHasPremiumAccess {
  127. onEntitlementsChanged?(newHasPremiumAccess)
  128. }
  129. }
  130. func purchase(plan: PremiumPlan) async -> PurchaseOutcome {
  131. let productID = PremiumStoreProduct.productID(for: plan)
  132. if activeEntitlementProductIDs.contains(productID) {
  133. return .alreadyOwned
  134. }
  135. guard let product = productsByID[productID] else {
  136. await refreshProducts()
  137. guard let refreshed = productsByID[productID] else {
  138. if let lastProductLoadError, !lastProductLoadError.isEmpty {
  139. return .failed("Unable to load products: \(lastProductLoadError)")
  140. }
  141. let loadedIDs = productsByID.keys.sorted().joined(separator: ", ")
  142. let debugIDs = loadedIDs.isEmpty ? "none" : loadedIDs
  143. return .failed("Product ID not found in StoreKit response. Requested: \(productID). Loaded IDs: \(debugIDs)")
  144. }
  145. return await purchase(product: refreshed)
  146. }
  147. return await purchase(product: product)
  148. }
  149. func restorePurchases() async -> String {
  150. do {
  151. try await AppStore.sync()
  152. await refreshEntitlements()
  153. if hasPremiumAccess {
  154. return "Purchases restored successfully."
  155. }
  156. return "No previous premium purchase was found for this Apple ID."
  157. } catch {
  158. return "Restore failed: \(error.localizedDescription)"
  159. }
  160. }
  161. private func purchase(product: Product) async -> PurchaseOutcome {
  162. do {
  163. let result = try await product.purchase()
  164. switch result {
  165. case .success(let verificationResult):
  166. guard case .verified(let transaction) = verificationResult else {
  167. return .failed("Purchase verification failed.")
  168. }
  169. await transaction.finish()
  170. await refreshEntitlements()
  171. return .success
  172. case .pending:
  173. return .pending
  174. case .userCancelled:
  175. return .cancelled
  176. @unknown default:
  177. return .failed("Unknown purchase state.")
  178. }
  179. } catch {
  180. return .failed(error.localizedDescription)
  181. }
  182. }
  183. private func observeTransactionUpdates() async {
  184. for await update in Transaction.updates {
  185. guard case .verified(let transaction) = update else { continue }
  186. if PremiumStoreProduct.allIDs.contains(transaction.productID) {
  187. await refreshEntitlements()
  188. }
  189. await transaction.finish()
  190. }
  191. }
  192. private static func isTransactionActive(_ transaction: Transaction) -> Bool {
  193. if transaction.revocationDate != nil { return false }
  194. if let expirationDate = transaction.expirationDate {
  195. return expirationDate > Date()
  196. }
  197. return true
  198. }
  199. }
  200. final class ViewController: NSViewController {
  201. private struct GoogleProfileDisplay {
  202. let name: String
  203. let email: String
  204. let pictureURL: URL?
  205. }
  206. private var palette = Palette(isDarkMode: true)
  207. private let typography = Typography()
  208. private let launchContentSize = NSSize(width: 920, height: 690)
  209. private let launchMinContentSize = NSSize(width: 760, height: 600)
  210. private var mainContentHost: NSView?
  211. /// Pin constraints for the current page inside `mainContentHost`; deactivated before each swap so relayout never stacks duplicates.
  212. private var mainContentHostPinConstraints: [NSLayoutConstraint] = []
  213. private var sidebarRowViews: [SidebarPage: NSView] = [:]
  214. private var selectedSidebarPage: SidebarPage = .joinMeetings
  215. private var selectedZoomJoinMode: ZoomJoinMode = .id
  216. private var pageCache: [SidebarPage: NSView] = [:]
  217. private var sidebarPageByView = [ObjectIdentifier: SidebarPage]()
  218. private var zoomJoinModeByView = [ObjectIdentifier: ZoomJoinMode]()
  219. private var zoomJoinModeViews: [ZoomJoinMode: NSView] = [:]
  220. private var settingsActionByView = [ObjectIdentifier: SettingsAction]()
  221. private weak var centeredTitleLabel: NSTextField?
  222. private var paywallWindow: NSWindow?
  223. private let paywallContentWidth: CGFloat = 520
  224. private let launchWindowLeftOffset: CGFloat = 80
  225. private var selectedPremiumPlan: PremiumPlan = .monthly
  226. private var paywallPlanViews: [PremiumPlan: NSView] = [:]
  227. private var premiumPlanByView = [ObjectIdentifier: PremiumPlan]()
  228. private weak var paywallOfferLabel: NSTextField?
  229. private weak var paywallContinueLabel: NSTextField?
  230. private weak var paywallContinueButton: NSView?
  231. private weak var sidebarPremiumTitleLabel: NSTextField?
  232. private weak var sidebarPremiumIconView: NSImageView?
  233. private weak var sidebarPremiumButtonView: HoverTrackingView?
  234. private weak var instantMeetCardView: HoverSurfaceView?
  235. private weak var instantMeetTitleLabel: NSTextField?
  236. private weak var instantMeetSubtitleLabel: NSTextField?
  237. private weak var joinWithLinkCardView: HoverSurfaceView?
  238. private weak var joinWithLinkTitleLabel: NSTextField?
  239. private weak var joinMeetPrimaryButton: NSButton?
  240. private weak var meetLinkField: NSTextField?
  241. private weak var browseAddressField: NSTextField?
  242. private var inAppBrowserWindowController: InAppBrowserWindowController?
  243. private let googleOAuth = GoogleOAuthService.shared
  244. private let calendarClient = GoogleCalendarClient()
  245. private let storeKitCoordinator = StoreKitCoordinator()
  246. private var storeKitStartupTask: Task<Void, Never>?
  247. private var paywallPurchaseTask: Task<Void, Never>?
  248. private var paywallPriceLabels: [PremiumPlan: NSTextField] = [:]
  249. private var paywallSubtitleLabels: [PremiumPlan: NSTextField] = [:]
  250. private var paywallContinueEnabled = true
  251. private var paywallUpgradeFlowEnabled = false
  252. private let launchPaywallDelay: TimeInterval = 3
  253. private var hasCompletedInitialStoreKitSync = false
  254. private var hasPresentedLaunchPaywall = false
  255. private var launchPaywallWorkItem: DispatchWorkItem?
  256. private var hasViewAppearedOnce = false
  257. private var lastKnownPremiumAccess = false
  258. private var displayedScheduleMeetings: [ScheduledMeeting] = []
  259. private var appUsageSessionStartDate: Date?
  260. private var hasObservedAppLifecycleForUsage = false
  261. private var premiumUpgradeRatingPromptWorkItem: DispatchWorkItem?
  262. private enum ScheduleFilter: Int {
  263. case all = 0
  264. case today = 1
  265. case week = 2
  266. }
  267. private enum SchedulePageFilter: Int {
  268. case all = 0
  269. case today = 1
  270. case week = 2
  271. case month = 3
  272. case customRange = 4
  273. }
  274. private var scheduleFilter: ScheduleFilter = .all
  275. private weak var scheduleDateHeadingLabel: NSTextField?
  276. private weak var scheduleCardsStack: NSStackView?
  277. private weak var scheduleCardsScrollView: NSScrollView?
  278. private weak var scheduleScrollLeftButton: NSView?
  279. private weak var scheduleScrollRightButton: NSView?
  280. private weak var scheduleFilterDropdown: NSPopUpButton?
  281. private weak var scheduleGoogleAuthButton: NSButton?
  282. private weak var scheduleGoogleAuthHostView: GoogleProfileAuthHostView?
  283. private var scheduleGoogleAuthHostPadWidthConstraint: NSLayoutConstraint?
  284. private var scheduleGoogleAuthHostPadHeightConstraint: NSLayoutConstraint?
  285. private var scheduleGoogleAuthButtonWidthConstraint: NSLayoutConstraint?
  286. private var scheduleGoogleAuthButtonHeightConstraint: NSLayoutConstraint?
  287. /// Circular avatar size when signed in (top-right, Google-style).
  288. private let scheduleGoogleSignedInAvatarSize: CGFloat = 36
  289. private var scheduleGoogleAuthHovering = false
  290. private var scheduleCurrentProfile: GoogleProfileDisplay?
  291. /// Larger copy of the header avatar for the account popover (optional).
  292. private var scheduleProfileMenuAvatar: NSImage?
  293. private var scheduleProfileImageTask: Task<Void, Never>?
  294. private var googleAccountPopover: NSPopover?
  295. private var scheduleCachedMeetings: [ScheduledMeeting] = []
  296. private var schedulePageFilter: SchedulePageFilter = .all
  297. private var schedulePageFromDate: Date = Calendar.current.startOfDay(for: Date())
  298. private var schedulePageToDate: Date = Calendar.current.startOfDay(for: Date())
  299. private var schedulePageFilteredMeetings: [ScheduledMeeting] = []
  300. private var schedulePageVisibleCount: Int = 0
  301. private let schedulePageBatchSize: Int = 6
  302. private let schedulePageCardsPerRow: Int = 3
  303. private let schedulePageCardSpacing: CGFloat = 20
  304. private let schedulePageCardHeight: CGFloat = 182
  305. /// Match `makeJoinMeetingsContent` vertical rhythm between sections.
  306. private let schedulePageStackSpacing: CGFloat = 14
  307. /// Tighter gap from header block (title + filters) to the date line below.
  308. private let schedulePageHeaderToDateSpacing: CGFloat = 10
  309. /// Join Meetings: gap from “Schedule” row to date heading, and date heading to card strip (keeps cards aligned with the rest of the column).
  310. private let joinPageScheduleHeaderToDateSpacing: CGFloat = 8
  311. private let joinPageDateToMeetingCardsSpacing: CGFloat = 8
  312. /// Match Join Meetings main content insets so the top auth/profile bar lines up with page edges.
  313. private let schedulePageLeadingInset: CGFloat = 28
  314. private let schedulePageTrailingInset: CGFloat = 28
  315. private var schedulePageScrollObservation: NSObjectProtocol?
  316. private weak var schedulePageDateHeadingLabel: NSTextField?
  317. private weak var schedulePageFilterDropdown: NSPopUpButton?
  318. private weak var schedulePageFromDatePicker: NSDatePicker?
  319. private weak var schedulePageToDatePicker: NSDatePicker?
  320. private weak var schedulePageRangeErrorLabel: NSTextField?
  321. private weak var schedulePageCardsStack: NSStackView?
  322. private weak var schedulePageCardsScrollView: NSScrollView?
  323. // MARK: - Calendar page (custom month UI)
  324. private var calendarPageMonthAnchor: Date = Calendar.current.startOfDay(for: Date())
  325. private var calendarPageSelectedDate: Date = Calendar.current.startOfDay(for: Date())
  326. private weak var calendarPageMonthLabel: NSTextField?
  327. private weak var calendarPageGridStack: NSStackView?
  328. private var calendarPageGridHeightConstraint: NSLayoutConstraint?
  329. private weak var calendarPageDaySummaryLabel: NSTextField?
  330. private var calendarPageActionPopover: NSPopover?
  331. private var calendarPageCreatePopover: NSPopover?
  332. private weak var topToastView: NSVisualEffectView?
  333. private var topToastHideWorkItem: DispatchWorkItem?
  334. /// In-app browser navigation: `.allowAll` or `.whitelist(hostSuffixes:)` (e.g. `["google.com"]` matches `meet.google.com`).
  335. private let inAppBrowserDefaultPolicy: InAppBrowserURLPolicy = .allowAll
  336. private let darkModeDefaultsKey = "settings.darkModeEnabled"
  337. private let appUsageAccumulatedSecondsDefaultsKey = "rating.appUsageAccumulatedSeconds"
  338. private let userHasRatedDefaultsKey = "rating.userHasRated"
  339. private let ratingStateMigrationV2DoneDefaultsKey = "rating.stateMigrationV2Done"
  340. private let ratingEligibleUsageSeconds: TimeInterval = 30 * 60
  341. private var darkModeEnabled: Bool {
  342. get {
  343. let hasValue = UserDefaults.standard.object(forKey: darkModeDefaultsKey) != nil
  344. return hasValue ? UserDefaults.standard.bool(forKey: darkModeDefaultsKey) : systemPrefersDarkMode()
  345. }
  346. set { UserDefaults.standard.set(newValue, forKey: darkModeDefaultsKey) }
  347. }
  348. private func makeSettingsPopover() -> NSPopover {
  349. let popover = NSPopover()
  350. popover.behavior = .transient
  351. popover.animates = true
  352. let showUpgradeInSettings = storeKitCoordinator.hasPremiumAccess && !storeKitCoordinator.hasLifetimeAccess
  353. let showRateUsInSettings = shouldShowRateUsInSettings
  354. popover.contentViewController = SettingsMenuViewController(
  355. palette: palette,
  356. typography: typography,
  357. darkModeEnabled: darkModeEnabled,
  358. showRateUsInSettings: showRateUsInSettings,
  359. showUpgradeInSettings: showUpgradeInSettings,
  360. onToggleDarkMode: { [weak self] enabled in
  361. self?.setDarkMode(enabled)
  362. },
  363. onAction: { [weak self] action in
  364. self?.handleSettingsAction(action)
  365. }
  366. )
  367. return popover
  368. }
  369. private var settingsPopover: NSPopover?
  370. override func viewDidLoad() {
  371. super.viewDidLoad()
  372. // Sync toggle + palette with current macOS appearance on launch.
  373. darkModeEnabled = systemPrefersDarkMode()
  374. palette = Palette(isDarkMode: darkModeEnabled)
  375. storeKitCoordinator.onEntitlementsChanged = { [weak self] hasPremiumAccess in
  376. guard let self else { return }
  377. self.handlePremiumAccessChanged(hasPremiumAccess)
  378. }
  379. migrateLegacyRatingStateIfNeeded()
  380. beginUsageTrackingSessionIfNeeded()
  381. observeAppLifecycleForUsageTrackingIfNeeded()
  382. setupRootView()
  383. buildMainLayout()
  384. startStoreKit()
  385. }
  386. override func viewDidAppear() {
  387. super.viewDidAppear()
  388. hasViewAppearedOnce = true
  389. presentLaunchPaywallIfNeeded()
  390. applyWindowTitle(for: selectedSidebarPage)
  391. guard let window = view.window else { return }
  392. // Ensure launch size is applied even when macOS tries to restore prior window state.
  393. window.isRestorable = false
  394. window.setFrameAutosaveName("")
  395. DispatchQueue.main.async { [weak self, weak window] in
  396. guard let self, let window else { return }
  397. let frameSize = window.frameRect(forContentRect: NSRect(origin: .zero, size: self.launchContentSize)).size
  398. var newFrame = window.frame
  399. newFrame.size = frameSize
  400. window.setFrame(newFrame, display: true)
  401. window.center()
  402. if let screen = window.screen ?? NSScreen.main {
  403. var adjustedFrame = window.frame
  404. adjustedFrame.origin.x -= self.launchWindowLeftOffset
  405. let minX = screen.visibleFrame.minX
  406. adjustedFrame.origin.x = max(minX, adjustedFrame.origin.x)
  407. window.setFrame(adjustedFrame, display: true)
  408. }
  409. window.minSize = window.frameRect(forContentRect: NSRect(origin: .zero, size: self.launchMinContentSize)).size
  410. self.installCenteredTitleIfNeeded(on: window)
  411. }
  412. }
  413. override var representedObject: Any? {
  414. didSet {}
  415. }
  416. deinit {
  417. premiumUpgradeRatingPromptWorkItem?.cancel()
  418. endUsageTrackingSession()
  419. if hasObservedAppLifecycleForUsage {
  420. NotificationCenter.default.removeObserver(self)
  421. }
  422. if let observer = schedulePageScrollObservation {
  423. NotificationCenter.default.removeObserver(observer)
  424. }
  425. storeKitStartupTask?.cancel()
  426. paywallPurchaseTask?.cancel()
  427. launchPaywallWorkItem?.cancel()
  428. }
  429. }
  430. private extension ViewController {
  431. func setupRootView() {
  432. view.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
  433. view.wantsLayer = true
  434. view.layer?.backgroundColor = palette.pageBackground.cgColor
  435. }
  436. func systemPrefersDarkMode() -> Bool {
  437. // Use the system-wide appearance setting (not app/window effective appearance).
  438. // When the key is missing, macOS is in Light mode.
  439. let global = UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain)
  440. let style = global?["AppleInterfaceStyle"] as? String
  441. return style?.lowercased() == "dark"
  442. }
  443. func buildMainLayout() {
  444. let splitContainer = NSStackView()
  445. splitContainer.translatesAutoresizingMaskIntoConstraints = false
  446. splitContainer.orientation = .horizontal
  447. splitContainer.spacing = 14
  448. splitContainer.distribution = .fill
  449. splitContainer.alignment = .top
  450. view.addSubview(splitContainer)
  451. NSLayoutConstraint.activate([
  452. splitContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  453. splitContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  454. splitContainer.topAnchor.constraint(equalTo: view.topAnchor),
  455. splitContainer.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  456. ])
  457. let sidebar = makeSidebar()
  458. let mainPanel = makeMainPanel()
  459. sidebar.setContentHuggingPriority(.required, for: .horizontal)
  460. sidebar.setContentCompressionResistancePriority(.required, for: .horizontal)
  461. mainPanel.setContentHuggingPriority(.defaultLow, for: .horizontal)
  462. mainPanel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  463. splitContainer.addArrangedSubview(sidebar)
  464. splitContainer.addArrangedSubview(mainPanel)
  465. }
  466. @objc private func sidebarItemClicked(_ sender: NSClickGestureRecognizer) {
  467. guard let view = sender.view else { return }
  468. activateSidebarItem(view)
  469. }
  470. private func activateSidebarItem(_ view: NSView) {
  471. guard let page = sidebarPageByView[ObjectIdentifier(view)],
  472. page != selectedSidebarPage || page == .settings else { return }
  473. if page == .settings {
  474. showSettingsPopover()
  475. return
  476. }
  477. showSidebarPage(page)
  478. }
  479. @objc private func zoomJoinModeClicked(_ sender: NSClickGestureRecognizer) {
  480. guard let view = sender.view,
  481. let mode = zoomJoinModeByView[ObjectIdentifier(view)],
  482. mode != selectedZoomJoinMode else { return }
  483. selectedZoomJoinMode = mode
  484. updateZoomJoinModeAppearance()
  485. if selectedSidebarPage == .joinMeetings {
  486. pageCache[.joinMeetings] = nil
  487. showSidebarPage(.joinMeetings)
  488. }
  489. }
  490. @objc private func premiumButtonClicked(_ sender: NSClickGestureRecognizer) {
  491. if storeKitCoordinator.hasPremiumAccess {
  492. openManageSubscriptions()
  493. } else {
  494. showPaywall()
  495. }
  496. }
  497. @objc private func sidebarButtonClicked(_ sender: NSButton) {
  498. guard let page = SidebarPage(rawValue: sender.tag),
  499. page != selectedSidebarPage || page == .settings else { return }
  500. if page == .settings {
  501. showSettingsPopover()
  502. return
  503. }
  504. showSidebarPage(page)
  505. }
  506. @objc private func joinMeetClicked(_ sender: Any?) {
  507. let rawInput = meetLinkField?.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
  508. guard let url = normalizedMeetJoinURL(from: rawInput) else {
  509. showSimpleAlert(
  510. title: "Invalid Meet link",
  511. message: "Enter a valid Google Meet link or meeting code (for example nkd-grps-duv, meet.google.com/nkd-grps-duv, or https://meet.google.com/nkd-grps-duv)."
  512. )
  513. return
  514. }
  515. openInDefaultBrowser(url: url)
  516. }
  517. @objc private func joinWithLinkCardClicked(_ sender: NSClickGestureRecognizer) {
  518. meetLinkField?.window?.makeFirstResponder(meetLinkField)
  519. }
  520. @objc private func cancelMeetJoinClicked(_ sender: Any?) {
  521. meetLinkField?.stringValue = ""
  522. }
  523. @objc private func browseOpenAddressClicked(_ sender: Any?) {
  524. let raw = browseAddressField?.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
  525. guard raw.isEmpty == false else {
  526. showSimpleAlert(title: "Browse", message: "Enter a web address (for example meet.google.com).")
  527. return
  528. }
  529. let normalized = normalizedURLString(from: raw)
  530. guard let url = URL(string: normalized), url.scheme == "http" || url.scheme == "https" else {
  531. showSimpleAlert(title: "Invalid address", message: "Enter a valid http or https URL.")
  532. return
  533. }
  534. openInAppBrowser(with: url, policy: inAppBrowserDefaultPolicy)
  535. }
  536. @objc private func browseQuickLinkMeetClicked(_ sender: Any?) {
  537. guard let url = URL(string: "https://meet.google.com/") else { return }
  538. openInDefaultBrowser(url: url)
  539. }
  540. @objc private func browseQuickLinkMeetHelpClicked(_ sender: Any?) {
  541. guard let url = URL(string: "https://support.google.com/meet") else { return }
  542. openInAppBrowser(with: url, policy: inAppBrowserDefaultPolicy)
  543. }
  544. @objc private func browseQuickLinkZoomHelpClicked(_ sender: Any?) {
  545. guard let url = URL(string: "https://support.zoom.us") else { return }
  546. openInAppBrowser(with: url, policy: inAppBrowserDefaultPolicy)
  547. }
  548. @objc private func instantMeetClicked(_ sender: NSClickGestureRecognizer) {
  549. guard let url = URL(string: "https://meet.google.com/new") else { return }
  550. openInDefaultBrowser(url: url)
  551. }
  552. private func normalizedURLString(from value: String) -> String {
  553. if value.lowercased().hasPrefix("http://") || value.lowercased().hasPrefix("https://") {
  554. return value
  555. }
  556. return "https://\(value)"
  557. }
  558. /// Typical Meet meeting code shape: three hyphen-separated groups (e.g. `nkd-grps-duv`).
  559. private func isValidMeetMeetingCode(_ code: String) -> Bool {
  560. let trimmed = code.trimmingCharacters(in: .whitespacesAndNewlines)
  561. guard trimmed.isEmpty == false else { return false }
  562. let pattern = "^[a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{3}$"
  563. return trimmed.range(of: pattern, options: [.regularExpression, .caseInsensitive]) != nil
  564. }
  565. /// Accepts `https://meet.google.com/...`, `meet.google.com/...`, or a bare code; returns canonical Meet URL or `nil`.
  566. private func normalizedMeetJoinURL(from rawInput: String) -> URL? {
  567. let trimmed = rawInput.trimmingCharacters(in: .whitespacesAndNewlines)
  568. guard trimmed.isEmpty == false else { return nil }
  569. let lower = trimmed.lowercased()
  570. if lower.hasPrefix("http://") || lower.hasPrefix("https://") {
  571. guard let url = URL(string: trimmed),
  572. let host = url.host?.lowercased(),
  573. host == "meet.google.com" || host.hasSuffix(".meet.google.com") else {
  574. return nil
  575. }
  576. let path = url.path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
  577. guard path.isEmpty == false else { return nil }
  578. let firstSegment = path.split(separator: "/").first.map(String.init) ?? path
  579. guard isValidMeetMeetingCode(firstSegment) else { return nil }
  580. return URL(string: "https://meet.google.com/\(firstSegment.lowercased())")
  581. }
  582. if lower.hasPrefix("meet.google.com/") {
  583. let afterHost = trimmed.dropFirst("meet.google.com/".count)
  584. let beforeQuery = String(afterHost).split(separator: "?").first.map(String.init) ?? String(afterHost)
  585. let firstSegment = beforeQuery.split(separator: "/").first.map(String.init) ?? beforeQuery
  586. guard isValidMeetMeetingCode(firstSegment) else { return nil }
  587. return URL(string: "https://meet.google.com/\(firstSegment.lowercased())")
  588. }
  589. if isValidMeetMeetingCode(trimmed) {
  590. return URL(string: "https://meet.google.com/\(trimmed.lowercased())")
  591. }
  592. return nil
  593. }
  594. private func openInAppBrowser(with url: URL, policy: InAppBrowserURLPolicy = .allowAll) {
  595. let browserController: InAppBrowserWindowController
  596. if let existing = inAppBrowserWindowController {
  597. browserController = existing
  598. } else {
  599. browserController = InAppBrowserWindowController()
  600. inAppBrowserWindowController = browserController
  601. }
  602. browserController.load(url: url, policy: policy)
  603. browserController.applyDefaultFrameCenteredOnVisibleScreen()
  604. browserController.showWindow(nil)
  605. browserController.window?.makeKeyAndOrderFront(nil)
  606. browserController.window?.orderFrontRegardless()
  607. NSApp.activate(ignoringOtherApps: true)
  608. }
  609. private func openInDefaultBrowser(url: URL) {
  610. NSWorkspace.shared.open(url, configuration: NSWorkspace.OpenConfiguration()) { [weak self] _, error in
  611. if let error {
  612. DispatchQueue.main.async {
  613. self?.showSimpleAlert(title: "Unable to open browser", message: error.localizedDescription)
  614. }
  615. }
  616. }
  617. }
  618. private func openRateUsDestination() {
  619. let configured = (Bundle.main.object(forInfoDictionaryKey: "RateUsURL") as? String)?
  620. .trimmingCharacters(in: .whitespacesAndNewlines)
  621. let placeholder = (Bundle.main.object(forInfoDictionaryKey: "AppLaunchPlaceholderURL") as? String)?
  622. .trimmingCharacters(in: .whitespacesAndNewlines)
  623. let hardcodedRateUsURL = "https://apps.apple.com/pk/app/meeting-app-for-google-meet/id6654920763?mt=12"
  624. var candidateStrings = [String]()
  625. if let configured, !configured.isEmpty {
  626. candidateStrings.append(configured)
  627. if let appID = extractAppleAppID(from: configured) {
  628. candidateStrings.append("macappstore://apps.apple.com/app/id\(appID)")
  629. candidateStrings.append("macappstore://itunes.apple.com/app/id\(appID)")
  630. }
  631. }
  632. candidateStrings.append(hardcodedRateUsURL)
  633. candidateStrings.append("macappstore://apps.apple.com/app/id6654920763")
  634. candidateStrings.append("macappstore://itunes.apple.com/app/id6654920763")
  635. if let placeholder, !placeholder.isEmpty {
  636. candidateStrings.append(placeholder)
  637. }
  638. for candidate in candidateStrings {
  639. guard let url = URL(string: candidate) else { continue }
  640. if NSWorkspace.shared.open(url) {
  641. return
  642. }
  643. }
  644. showSimpleAlert(
  645. title: "Unable to Open Rate Page",
  646. message: "Could not open the App Store rating page. Please try again."
  647. )
  648. requestAppRatingIfEligible(markAsRated: true)
  649. }
  650. private func extractAppleAppID(from urlString: String) -> String? {
  651. guard let match = urlString.range(of: "id[0-9]+", options: .regularExpression) else {
  652. return nil
  653. }
  654. let token = String(urlString[match])
  655. return String(token.dropFirst())
  656. }
  657. private func openInSafari(url: URL) {
  658. guard let safariAppURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Safari") else {
  659. NSWorkspace.shared.open(url)
  660. return
  661. }
  662. let configuration = NSWorkspace.OpenConfiguration()
  663. NSWorkspace.shared.open([url], withApplicationAt: safariAppURL, configuration: configuration) { _, error in
  664. if let error {
  665. self.showSimpleAlert(title: "Unable to Open Safari", message: error.localizedDescription)
  666. }
  667. }
  668. }
  669. private func openManageSubscriptions() {
  670. guard let url = URL(string: "https://apps.apple.com/account/subscriptions") else {
  671. showSimpleAlert(title: "Unable to Open Subscriptions", message: "The subscriptions URL is invalid.")
  672. return
  673. }
  674. openInDefaultBrowser(url: url)
  675. }
  676. private func shareAppURL() -> URL? {
  677. if let configured = Bundle.main.object(forInfoDictionaryKey: "AppShareURL") as? String {
  678. let trimmed = configured.trimmingCharacters(in: .whitespacesAndNewlines)
  679. if trimmed.isEmpty == false, let url = URL(string: trimmed) {
  680. return url
  681. }
  682. }
  683. return nil
  684. }
  685. private func shareAppFromSettingsMenu() {
  686. let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
  687. ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String
  688. ?? "Meetings App"
  689. let message = "Check out \(appName) for managing and joining meetings."
  690. let appURL = shareAppURL()
  691. let shareItems: [Any] = appURL.map { [message, $0] } ?? [message]
  692. let picker = NSSharingServicePicker(items: shareItems)
  693. let anchorView = sidebarRowViews[.settings] ?? view
  694. picker.show(relativeTo: anchorView.bounds, of: anchorView, preferredEdge: .maxX)
  695. let clipboardText = ([message, appURL?.absoluteString].compactMap { $0 }).joined(separator: "\n")
  696. NSPasteboard.general.clearContents()
  697. NSPasteboard.general.setString(clipboardText, forType: .string)
  698. }
  699. private func showSidebarPage(_ page: SidebarPage) {
  700. selectedSidebarPage = page
  701. updateSidebarAppearance()
  702. applyWindowTitle(for: page)
  703. guard let host = mainContentHost else { return }
  704. NSLayoutConstraint.deactivate(mainContentHostPinConstraints)
  705. mainContentHostPinConstraints.removeAll()
  706. host.subviews.forEach { $0.removeFromSuperview() }
  707. let child = viewForPage(page)
  708. child.translatesAutoresizingMaskIntoConstraints = false
  709. host.addSubview(child)
  710. mainContentHostPinConstraints = [
  711. child.leadingAnchor.constraint(equalTo: host.leadingAnchor),
  712. child.trailingAnchor.constraint(equalTo: host.trailingAnchor),
  713. child.topAnchor.constraint(equalTo: host.topAnchor),
  714. child.bottomAnchor.constraint(equalTo: host.bottomAnchor)
  715. ]
  716. NSLayoutConstraint.activate(mainContentHostPinConstraints)
  717. }
  718. private func showSettingsPopover() {
  719. guard let anchor = sidebarRowViews[.settings] else { return }
  720. if settingsPopover?.isShown == true {
  721. settingsPopover?.performClose(nil)
  722. return
  723. }
  724. settingsPopover = makeSettingsPopover()
  725. if let menu = settingsPopover?.contentViewController as? SettingsMenuViewController {
  726. menu.setDarkModeEnabled(darkModeEnabled)
  727. }
  728. settingsPopover?.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxX)
  729. }
  730. private func setDarkMode(_ enabled: Bool) {
  731. darkModeEnabled = enabled
  732. NSApp.appearance = NSAppearance(named: enabled ? .darkAqua : .aqua)
  733. view.appearance = NSAppearance(named: enabled ? .darkAqua : .aqua)
  734. palette = Palette(isDarkMode: enabled)
  735. settingsPopover?.performClose(nil)
  736. settingsPopover = nil
  737. reloadTheme()
  738. }
  739. private func reloadTheme() {
  740. pageCache.removeAll()
  741. if let observer = schedulePageScrollObservation {
  742. NotificationCenter.default.removeObserver(observer)
  743. }
  744. schedulePageScrollObservation = nil
  745. sidebarRowViews.removeAll()
  746. sidebarPageByView.removeAll()
  747. zoomJoinModeByView.removeAll()
  748. zoomJoinModeViews.removeAll()
  749. settingsActionByView.removeAll()
  750. paywallPlanViews.removeAll()
  751. premiumPlanByView.removeAll()
  752. paywallPriceLabels.removeAll()
  753. paywallSubtitleLabels.removeAll()
  754. paywallContinueLabel = nil
  755. paywallContinueButton = nil
  756. paywallContinueEnabled = true
  757. googleAccountPopover?.performClose(nil)
  758. googleAccountPopover = nil
  759. NSLayoutConstraint.deactivate(mainContentHostPinConstraints)
  760. mainContentHostPinConstraints.removeAll()
  761. mainContentHost = nil
  762. view.subviews.forEach { $0.removeFromSuperview() }
  763. setupRootView()
  764. buildMainLayout()
  765. showSidebarPage(selectedSidebarPage)
  766. }
  767. private func handleSettingsAction(_ action: SettingsAction) {
  768. switch action {
  769. case .restore:
  770. settingsPopover?.performClose(nil)
  771. settingsPopover = nil
  772. Task { [weak self] in
  773. guard let self else { return }
  774. let message = await self.storeKitCoordinator.restorePurchases()
  775. self.refreshPaywallStoreUI()
  776. self.showSimpleAlert(title: "Restore Purchases", message: message)
  777. }
  778. case .rateUs:
  779. settingsPopover?.performClose(nil)
  780. settingsPopover = nil
  781. openRateUsDestination()
  782. case .support:
  783. settingsPopover?.performClose(nil)
  784. settingsPopover = nil
  785. if let supportURL = Bundle.main.object(forInfoDictionaryKey: "SupportURL") as? String,
  786. let url = URL(string: supportURL) {
  787. openInAppBrowser(with: url, policy: inAppBrowserDefaultPolicy)
  788. }
  789. case .moreApps:
  790. settingsPopover?.performClose(nil)
  791. settingsPopover = nil
  792. if let moreAppsURL = Bundle.main.object(forInfoDictionaryKey: "MoreAppsURL") as? String,
  793. let url = URL(string: moreAppsURL) {
  794. openInAppBrowser(with: url, policy: inAppBrowserDefaultPolicy)
  795. }
  796. case .shareApp:
  797. settingsPopover?.performClose(nil)
  798. settingsPopover = nil
  799. shareAppFromSettingsMenu()
  800. case .upgrade:
  801. settingsPopover?.performClose(nil)
  802. settingsPopover = nil
  803. showPaywall(upgradeFlow: true, preferredPlan: .lifetime)
  804. }
  805. }
  806. private func showSimpleAlert(title: String, message: String) {
  807. let alert = NSAlert()
  808. alert.messageText = title
  809. alert.informativeText = message
  810. alert.addButton(withTitle: "OK")
  811. alert.runModal()
  812. }
  813. private func showTopToast(message: String, isError: Bool) {
  814. topToastHideWorkItem?.cancel()
  815. topToastHideWorkItem = nil
  816. topToastView?.removeFromSuperview()
  817. topToastView = nil
  818. let toast = NSVisualEffectView()
  819. toast.translatesAutoresizingMaskIntoConstraints = false
  820. toast.material = darkModeEnabled ? .hudWindow : .popover
  821. toast.blendingMode = .withinWindow
  822. toast.state = .active
  823. toast.wantsLayer = true
  824. toast.layer?.cornerRadius = 10
  825. toast.layer?.masksToBounds = true
  826. toast.layer?.borderWidth = 1
  827. toast.layer?.borderColor = NSColor.white.withAlphaComponent(darkModeEnabled ? 0.10 : 0.18).cgColor
  828. toast.layer?.backgroundColor = NSColor.black.withAlphaComponent(darkModeEnabled ? 0.68 : 0.78).cgColor
  829. toast.alphaValue = 0
  830. let row = NSStackView()
  831. row.translatesAutoresizingMaskIntoConstraints = false
  832. row.orientation = .horizontal
  833. row.alignment = .centerY
  834. row.spacing = 8
  835. row.distribution = .fill
  836. let icon = NSImageView()
  837. icon.translatesAutoresizingMaskIntoConstraints = false
  838. icon.imageScaling = .scaleProportionallyDown
  839. icon.image = NSImage(
  840. systemSymbolName: isError ? "xmark.circle.fill" : "checkmark.circle.fill",
  841. accessibilityDescription: isError ? "Error" : "Success"
  842. )
  843. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 16, weight: .semibold)
  844. icon.contentTintColor = isError ? NSColor.systemRed : NSColor.systemGreen
  845. let label = textLabel(
  846. message,
  847. font: NSFont.systemFont(ofSize: 13, weight: .semibold),
  848. color: NSColor.white
  849. )
  850. label.alignment = .left
  851. label.maximumNumberOfLines = 2
  852. label.lineBreakMode = .byWordWrapping
  853. row.addArrangedSubview(icon)
  854. row.addArrangedSubview(label)
  855. toast.addSubview(row)
  856. view.addSubview(toast)
  857. NSLayoutConstraint.activate([
  858. toast.topAnchor.constraint(equalTo: view.topAnchor, constant: 14),
  859. toast.centerXAnchor.constraint(equalTo: view.centerXAnchor),
  860. toast.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, constant: -40),
  861. toast.heightAnchor.constraint(greaterThanOrEqualToConstant: 40),
  862. icon.widthAnchor.constraint(equalToConstant: 16),
  863. icon.heightAnchor.constraint(equalToConstant: 16),
  864. row.leadingAnchor.constraint(equalTo: toast.leadingAnchor, constant: 14),
  865. row.trailingAnchor.constraint(equalTo: toast.trailingAnchor, constant: -14),
  866. row.topAnchor.constraint(equalTo: toast.topAnchor, constant: 10),
  867. row.bottomAnchor.constraint(equalTo: toast.bottomAnchor, constant: -10)
  868. ])
  869. topToastView = toast
  870. NSAnimationContext.runAnimationGroup { context in
  871. context.duration = 0.18
  872. context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  873. toast.animator().alphaValue = 1
  874. }
  875. let hideWorkItem = DispatchWorkItem { [weak self, weak toast] in
  876. guard let self, let toast else { return }
  877. NSAnimationContext.runAnimationGroup({ context in
  878. context.duration = 0.2
  879. context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  880. toast.animator().alphaValue = 0
  881. }, completionHandler: {
  882. toast.removeFromSuperview()
  883. if self.topToastView === toast {
  884. self.topToastView = nil
  885. }
  886. })
  887. }
  888. topToastHideWorkItem = hideWorkItem
  889. DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: hideWorkItem)
  890. }
  891. private func confirmPremiumUpgrade() -> Bool {
  892. let alert = NSAlert()
  893. alert.messageText = "Already Premium"
  894. alert.informativeText = "You are already premium. Do you want to continue with this purchase?"
  895. alert.addButton(withTitle: "Continue")
  896. alert.addButton(withTitle: "Cancel")
  897. return alert.runModal() == .alertFirstButtonReturn
  898. }
  899. private func showPaywall(upgradeFlow: Bool = false, preferredPlan: PremiumPlan? = nil) {
  900. paywallUpgradeFlowEnabled = upgradeFlow
  901. if let preferredPlan {
  902. selectedPremiumPlan = preferredPlan
  903. }
  904. if let existing = paywallWindow {
  905. refreshPaywallStoreUI()
  906. animatePaywallPresentation(existing)
  907. existing.makeKeyAndOrderFront(nil)
  908. NSApp.activate(ignoringOtherApps: true)
  909. return
  910. }
  911. let content = makePaywallContent()
  912. let controller = NSViewController()
  913. controller.view = content
  914. let panel = NSPanel(
  915. contentRect: NSRect(x: 0, y: 0, width: 640, height: 820),
  916. styleMask: [.titled, .closable, .fullSizeContentView],
  917. backing: .buffered,
  918. defer: false
  919. )
  920. panel.title = "Get Premium"
  921. panel.titleVisibility = .hidden
  922. panel.titlebarAppearsTransparent = true
  923. panel.isFloatingPanel = false
  924. panel.level = .normal
  925. panel.hidesOnDeactivate = true
  926. panel.isReleasedWhenClosed = false
  927. panel.delegate = self
  928. panel.standardWindowButton(.closeButton)?.isHidden = true
  929. panel.standardWindowButton(.miniaturizeButton)?.isHidden = true
  930. panel.standardWindowButton(.zoomButton)?.isHidden = true
  931. panel.center()
  932. panel.contentViewController = controller
  933. panel.alphaValue = 0
  934. panel.makeKeyAndOrderFront(nil)
  935. NSApp.activate(ignoringOtherApps: true)
  936. paywallWindow = panel
  937. animatePaywallPresentation(panel)
  938. Task { [weak self] in
  939. guard let self else { return }
  940. await self.storeKitCoordinator.refreshProducts()
  941. self.refreshPaywallStoreUI()
  942. }
  943. }
  944. private func animatePaywallPresentation(_ window: NSWindow) {
  945. let finalFrame = window.frame
  946. let targetScreen = window.screen ?? NSScreen.main
  947. let startY: CGFloat
  948. if let screen = targetScreen {
  949. startY = screen.visibleFrame.maxY + 12
  950. } else {
  951. startY = finalFrame.origin.y + 120
  952. }
  953. let startFrame = NSRect(x: finalFrame.origin.x, y: startY, width: finalFrame.width, height: finalFrame.height)
  954. window.setFrame(startFrame, display: false)
  955. window.alphaValue = 0
  956. NSAnimationContext.runAnimationGroup { context in
  957. context.duration = 0.28
  958. context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  959. window.animator().alphaValue = 1
  960. window.animator().setFrame(finalFrame, display: true)
  961. }
  962. }
  963. @objc private func closePaywallClicked(_ sender: Any?) {
  964. if let win = paywallWindow {
  965. win.performClose(nil)
  966. return
  967. }
  968. if let gesture = sender as? NSGestureRecognizer, let win = gesture.view?.window {
  969. win.performClose(nil)
  970. return
  971. }
  972. if let view = sender as? NSView, let win = view.window {
  973. win.performClose(nil)
  974. return
  975. }
  976. }
  977. @objc private func paywallFooterLinkClicked(_ sender: NSClickGestureRecognizer) {
  978. guard let view = sender.view else { return }
  979. let text = (view.subviews.first { $0 is NSTextField } as? NSTextField)?.stringValue ?? "Link"
  980. let defaultURL = (Bundle.main.object(forInfoDictionaryKey: "AppLaunchPlaceholderURL") as? String) ?? "https://example.com/app-link-coming-soon"
  981. let map: [String: String] = [
  982. "Privacy Policy": (Bundle.main.object(forInfoDictionaryKey: "PrivacyPolicyURL") as? String) ?? defaultURL,
  983. "Support": (Bundle.main.object(forInfoDictionaryKey: "SupportURL") as? String) ?? defaultURL,
  984. "Terms of Services": (Bundle.main.object(forInfoDictionaryKey: "TermsOfServiceURL") as? String) ?? defaultURL
  985. ]
  986. if let urlString = map[text], let url = URL(string: urlString) {
  987. openInAppBrowser(with: url, policy: inAppBrowserDefaultPolicy)
  988. return
  989. }
  990. showSimpleAlert(title: text, message: "\(text) tapped.")
  991. }
  992. @objc private func paywallPlanClicked(_ sender: NSClickGestureRecognizer) {
  993. guard let view = sender.view,
  994. let plan = premiumPlanByView[ObjectIdentifier(view)] else { return }
  995. selectedPremiumPlan = plan
  996. updatePaywallPlanSelection()
  997. }
  998. @objc private func paywallPlanButtonClicked(_ sender: NSButton) {
  999. guard let plan = PremiumPlan(rawValue: sender.tag) else { return }
  1000. selectedPremiumPlan = plan
  1001. updatePaywallPlanSelection()
  1002. }
  1003. private func updatePaywallPlanSelection() {
  1004. for (plan, view) in paywallPlanViews {
  1005. applyPaywallPlanStyle(view, isSelected: plan == selectedPremiumPlan)
  1006. }
  1007. paywallOfferLabel?.stringValue = paywallOfferText(for: selectedPremiumPlan)
  1008. }
  1009. private func paywallOfferText(for plan: PremiumPlan) -> String {
  1010. if storeKitCoordinator.hasPremiumAccess {
  1011. if storeKitCoordinator.hasLifetimeAccess {
  1012. return "Lifetime premium is active on this Apple ID."
  1013. }
  1014. if paywallUpgradeFlowEnabled {
  1015. let currentPlanName = storeKitCoordinator.activeNonLifetimePlan?.displayName ?? "Premium"
  1016. if plan == .lifetime {
  1017. return "Current plan: \(currentPlanName). Tap Continue to upgrade to Lifetime."
  1018. }
  1019. return "Current plan: \(currentPlanName). Select Lifetime to upgrade."
  1020. }
  1021. return "Premium is active on this Apple ID."
  1022. }
  1023. let productID = PremiumStoreProduct.productID(for: plan)
  1024. if let product = storeKitCoordinator.productsByID[productID] {
  1025. let pkrPrice = pkrDisplayPrice(product.displayPrice)
  1026. if product.type == .nonConsumable {
  1027. return "\(pkrPrice) one-time purchase"
  1028. }
  1029. if let period = product.subscription?.subscriptionPeriod {
  1030. return "\(pkrPrice)/\(subscriptionUnitText(period.unit))"
  1031. }
  1032. return pkrPrice
  1033. }
  1034. switch plan {
  1035. case .weekly:
  1036. return "PKR 1,100.00/week"
  1037. case .monthly:
  1038. return "Free for 3 Days then PKR 2,500.00/month"
  1039. case .yearly:
  1040. return "PKR 9,900.00/year (about 190.38/week)"
  1041. case .lifetime:
  1042. return "PKR 14,900.00 one-time purchase"
  1043. }
  1044. }
  1045. private func pkrDisplayPrice(_ value: String) -> String {
  1046. if value.hasPrefix("PKR ") { return value }
  1047. if value.hasPrefix("Rs ") {
  1048. return "PKR " + value.dropFirst(3)
  1049. }
  1050. if value.contains("PKR") { return value }
  1051. return "PKR \(value)"
  1052. }
  1053. private func subscriptionUnitText(_ unit: Product.SubscriptionPeriod.Unit) -> String {
  1054. switch unit {
  1055. case .day: return "day"
  1056. case .week: return "week"
  1057. case .month: return "month"
  1058. case .year: return "year"
  1059. @unknown default: return "period"
  1060. }
  1061. }
  1062. private func startStoreKit() {
  1063. storeKitStartupTask?.cancel()
  1064. storeKitStartupTask = Task { [weak self] in
  1065. guard let self else { return }
  1066. await self.storeKitCoordinator.start()
  1067. self.hasCompletedInitialStoreKitSync = true
  1068. self.refreshPaywallStoreUI()
  1069. self.presentLaunchPaywallIfNeeded()
  1070. }
  1071. }
  1072. private func refreshPaywallStoreUI() {
  1073. for (plan, label) in paywallPriceLabels {
  1074. let productID = PremiumStoreProduct.productID(for: plan)
  1075. if let product = storeKitCoordinator.productsByID[productID] {
  1076. label.stringValue = pkrDisplayPrice(product.displayPrice)
  1077. }
  1078. }
  1079. for (plan, label) in paywallSubtitleLabels {
  1080. let productID = PremiumStoreProduct.productID(for: plan)
  1081. guard let product = storeKitCoordinator.productsByID[productID],
  1082. let period = product.subscription?.subscriptionPeriod else { continue }
  1083. label.stringValue = "\(pkrDisplayPrice(product.displayPrice))/\(subscriptionUnitText(period.unit))"
  1084. }
  1085. refreshSidebarPremiumButton()
  1086. refreshInstantMeetPremiumState()
  1087. updatePaywallPlanSelection()
  1088. updatePaywallContinueState(isLoading: false)
  1089. }
  1090. private func refreshInstantMeetPremiumState() {
  1091. instantMeetCardView?.alphaValue = 1.0
  1092. instantMeetTitleLabel?.alphaValue = 1.0
  1093. instantMeetSubtitleLabel?.alphaValue = 1.0
  1094. instantMeetCardView?.toolTip = nil
  1095. instantMeetCardView?.onHoverChanged?(false)
  1096. joinWithLinkCardView?.alphaValue = 1.0
  1097. joinWithLinkTitleLabel?.alphaValue = 1.0
  1098. meetLinkField?.isEditable = true
  1099. meetLinkField?.isSelectable = true
  1100. meetLinkField?.alphaValue = 1.0
  1101. joinMeetPrimaryButton?.isEnabled = true
  1102. joinMeetPrimaryButton?.alphaValue = 1.0
  1103. joinWithLinkCardView?.toolTip = nil
  1104. }
  1105. private func handlePremiumAccessChanged(_ hasPremiumAccess: Bool) {
  1106. let hadPremiumAccess = lastKnownPremiumAccess
  1107. lastKnownPremiumAccess = hasPremiumAccess
  1108. premiumUpgradeRatingPromptWorkItem?.cancel()
  1109. refreshPaywallStoreUI()
  1110. refreshScheduleCardsForPremiumStateChange()
  1111. pageCache[.joinMeetings] = nil
  1112. pageCache[.video] = nil
  1113. if selectedSidebarPage == .joinMeetings {
  1114. showSidebarPage(.joinMeetings)
  1115. } else if selectedSidebarPage == .video {
  1116. showSidebarPage(.video)
  1117. }
  1118. if !hadPremiumAccess && hasPremiumAccess {
  1119. if selectedSidebarPage != .joinMeetings {
  1120. Task { [weak self] in
  1121. await self?.loadSchedule()
  1122. }
  1123. }
  1124. // Skip delayed review prompt during initial launch entitlement sync.
  1125. // We only want this after a real in-session upgrade.
  1126. if hasCompletedInitialStoreKitSync {
  1127. scheduleRatingPromptAfterPremiumUpgrade()
  1128. }
  1129. }
  1130. if hadPremiumAccess && !hasPremiumAccess {
  1131. showPaywall()
  1132. }
  1133. }
  1134. private var userHasRated: Bool {
  1135. UserDefaults.standard.bool(forKey: userHasRatedDefaultsKey)
  1136. }
  1137. private var accumulatedAppUsageSeconds: TimeInterval {
  1138. get {
  1139. UserDefaults.standard.double(forKey: appUsageAccumulatedSecondsDefaultsKey)
  1140. }
  1141. set {
  1142. UserDefaults.standard.set(newValue, forKey: appUsageAccumulatedSecondsDefaultsKey)
  1143. }
  1144. }
  1145. private var totalTrackedUsageSeconds: TimeInterval {
  1146. let liveSessionSeconds: TimeInterval
  1147. if let start = appUsageSessionStartDate {
  1148. liveSessionSeconds = max(0, Date().timeIntervalSince(start))
  1149. } else {
  1150. liveSessionSeconds = 0
  1151. }
  1152. return accumulatedAppUsageSeconds + liveSessionSeconds
  1153. }
  1154. private var hasReachedRatingUsageThreshold: Bool {
  1155. totalTrackedUsageSeconds >= ratingEligibleUsageSeconds
  1156. }
  1157. private var shouldShowRateUsInSettings: Bool {
  1158. true
  1159. }
  1160. private func migrateLegacyRatingStateIfNeeded() {
  1161. let defaults = UserDefaults.standard
  1162. guard !defaults.bool(forKey: ratingStateMigrationV2DoneDefaultsKey) else { return }
  1163. // Legacy behavior marked "rated" immediately after requesting review.
  1164. // Clear once so testing and new logic can run correctly.
  1165. defaults.set(false, forKey: userHasRatedDefaultsKey)
  1166. defaults.set(true, forKey: ratingStateMigrationV2DoneDefaultsKey)
  1167. }
  1168. private func beginUsageTrackingSessionIfNeeded() {
  1169. guard appUsageSessionStartDate == nil else { return }
  1170. appUsageSessionStartDate = Date()
  1171. }
  1172. private func endUsageTrackingSession() {
  1173. guard let start = appUsageSessionStartDate else { return }
  1174. let sessionElapsedSeconds = max(0, Date().timeIntervalSince(start))
  1175. accumulatedAppUsageSeconds += sessionElapsedSeconds
  1176. appUsageSessionStartDate = nil
  1177. }
  1178. private func observeAppLifecycleForUsageTrackingIfNeeded() {
  1179. guard !hasObservedAppLifecycleForUsage else { return }
  1180. hasObservedAppLifecycleForUsage = true
  1181. NotificationCenter.default.addObserver(
  1182. self,
  1183. selector: #selector(applicationDidBecomeActiveForUsageTracking),
  1184. name: NSApplication.didBecomeActiveNotification,
  1185. object: nil
  1186. )
  1187. NotificationCenter.default.addObserver(
  1188. self,
  1189. selector: #selector(applicationWillResignActiveForUsageTracking),
  1190. name: NSApplication.willResignActiveNotification,
  1191. object: nil
  1192. )
  1193. NotificationCenter.default.addObserver(
  1194. self,
  1195. selector: #selector(applicationWillTerminateForUsageTracking),
  1196. name: NSApplication.willTerminateNotification,
  1197. object: nil
  1198. )
  1199. }
  1200. @objc private func applicationDidBecomeActiveForUsageTracking() {
  1201. beginUsageTrackingSessionIfNeeded()
  1202. }
  1203. @objc private func applicationWillResignActiveForUsageTracking() {
  1204. endUsageTrackingSession()
  1205. }
  1206. @objc private func applicationWillTerminateForUsageTracking() {
  1207. endUsageTrackingSession()
  1208. }
  1209. private func scheduleRatingPromptAfterPremiumUpgrade() {
  1210. guard !userHasRated else { return }
  1211. let workItem = DispatchWorkItem { [weak self] in
  1212. self?.requestAppRatingIfEligible(markAsRated: false)
  1213. }
  1214. premiumUpgradeRatingPromptWorkItem = workItem
  1215. DispatchQueue.main.asyncAfter(deadline: .now() + 10, execute: workItem)
  1216. }
  1217. private func requestAppRatingIfEligible(markAsRated: Bool) {
  1218. guard storeKitCoordinator.hasPremiumAccess, !userHasRated else { return }
  1219. SKStoreReviewController.requestReview()
  1220. if markAsRated {
  1221. UserDefaults.standard.set(true, forKey: userHasRatedDefaultsKey)
  1222. }
  1223. }
  1224. private func refreshScheduleCardsForPremiumStateChange() {
  1225. if let stack = scheduleCardsStack {
  1226. renderScheduleCards(into: stack, meetings: displayedScheduleMeetings)
  1227. }
  1228. applySchedulePageFiltersAndRender()
  1229. }
  1230. private func refreshSidebarPremiumButton() {
  1231. let isPremium = storeKitCoordinator.hasPremiumAccess
  1232. if isPremium {
  1233. sidebarPremiumTitleLabel?.stringValue = "Manage Subscription"
  1234. sidebarPremiumIconView?.image = premiumButtonSymbolImage(named: "crown.fill")
  1235. } else {
  1236. sidebarPremiumTitleLabel?.stringValue = "Get Premium"
  1237. sidebarPremiumIconView?.image = premiumButtonSymbolImage(named: "star.fill")
  1238. }
  1239. sidebarPremiumIconView?.contentTintColor = .white
  1240. sidebarPremiumButtonView?.onHoverChanged?(false)
  1241. }
  1242. private func premiumButtonSymbolImage(named symbolName: String) -> NSImage? {
  1243. let configuration = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
  1244. return NSImage(systemSymbolName: symbolName, accessibilityDescription: nil)?
  1245. .withSymbolConfiguration(configuration)
  1246. }
  1247. private func presentLaunchPaywallIfNeeded() {
  1248. guard hasCompletedInitialStoreKitSync, hasViewAppearedOnce, !hasPresentedLaunchPaywall else { return }
  1249. hasPresentedLaunchPaywall = true
  1250. if !storeKitCoordinator.hasPremiumAccess {
  1251. launchPaywallWorkItem?.cancel()
  1252. let workItem = DispatchWorkItem { [weak self] in
  1253. guard let self else { return }
  1254. self.launchPaywallWorkItem = nil
  1255. guard !self.storeKitCoordinator.hasPremiumAccess else { return }
  1256. self.showPaywall()
  1257. }
  1258. launchPaywallWorkItem = workItem
  1259. DispatchQueue.main.asyncAfter(deadline: .now() + launchPaywallDelay, execute: workItem)
  1260. }
  1261. }
  1262. @objc private func paywallContinueClicked(_ sender: Any?) {
  1263. startSelectedPlanPurchase()
  1264. }
  1265. private func startSelectedPlanPurchase() {
  1266. guard paywallContinueEnabled else {
  1267. if storeKitCoordinator.hasPremiumAccess {
  1268. showSimpleAlert(title: "Premium Active", message: "This Apple ID already has premium access.")
  1269. } else {
  1270. showSimpleAlert(title: "Please Wait", message: "A purchase is already being processed.")
  1271. }
  1272. return
  1273. }
  1274. if paywallUpgradeFlowEnabled && storeKitCoordinator.hasPremiumAccess && !confirmPremiumUpgrade() {
  1275. return
  1276. }
  1277. paywallPurchaseTask?.cancel()
  1278. updatePaywallContinueState(isLoading: true)
  1279. let selectedPlan = selectedPremiumPlan
  1280. paywallPurchaseTask = Task { [weak self] in
  1281. guard let self else { return }
  1282. let result = await self.storeKitCoordinator.purchase(plan: selectedPlan)
  1283. self.updatePaywallContinueState(isLoading: false)
  1284. self.refreshPaywallStoreUI()
  1285. switch result {
  1286. case .success:
  1287. self.showSimpleAlert(title: "Purchase Complete", message: "Premium has been unlocked successfully.")
  1288. self.paywallWindow?.performClose(nil)
  1289. self.scheduleRatingPromptAfterPremiumUpgrade()
  1290. case .cancelled:
  1291. break
  1292. case .pending:
  1293. self.showSimpleAlert(title: "Purchase Pending", message: "Your purchase is pending approval. You can continue once it completes.")
  1294. case .unavailable:
  1295. self.showSimpleAlert(title: "Product Not Available", message: "Unable to load this product. Check your StoreKit configuration and product IDs.")
  1296. case .alreadyOwned:
  1297. self.showSimpleAlert(title: "Already Purchased", message: "This plan is already active on your Apple ID.")
  1298. case .failed(let message):
  1299. self.showSimpleAlert(title: "Purchase Failed", message: message)
  1300. }
  1301. }
  1302. }
  1303. private func updatePaywallContinueState(isLoading: Bool) {
  1304. if isLoading {
  1305. paywallContinueEnabled = false
  1306. paywallContinueLabel?.stringValue = "Processing..."
  1307. paywallContinueButton?.alphaValue = 0.75
  1308. return
  1309. }
  1310. if storeKitCoordinator.hasLifetimeAccess {
  1311. paywallContinueEnabled = false
  1312. paywallContinueLabel?.stringValue = "Premium Active"
  1313. paywallContinueButton?.alphaValue = 0.75
  1314. } else if paywallUpgradeFlowEnabled && storeKitCoordinator.hasPremiumAccess {
  1315. paywallContinueEnabled = true
  1316. paywallContinueLabel?.stringValue = "Continue"
  1317. paywallContinueButton?.alphaValue = 1.0
  1318. } else {
  1319. paywallContinueEnabled = true
  1320. paywallContinueLabel?.stringValue = "Continue"
  1321. paywallContinueButton?.alphaValue = 1.0
  1322. }
  1323. }
  1324. private func applyPaywallPlanStyle(_ card: NSView, isSelected: Bool, hovering: Bool = false) {
  1325. let selectedBorder = NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1)
  1326. let idleBorder = palette.inputBorder
  1327. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  1328. let hoverIdleBackground =
  1329. palette.sectionCard.blended(withFraction: 0.10, of: hoverBlend) ?? palette.sectionCard
  1330. let selectedBackground = darkModeEnabled
  1331. ? NSColor(calibratedRed: 30.0 / 255.0, green: 34.0 / 255.0, blue: 42.0 / 255.0, alpha: 1)
  1332. : NSColor(calibratedRed: 255.0 / 255.0, green: 246.0 / 255.0, blue: 236.0 / 255.0, alpha: 1)
  1333. card.layer?.backgroundColor = (isSelected ? selectedBackground : (hovering ? hoverIdleBackground : palette.sectionCard)).cgColor
  1334. card.layer?.borderColor = (isSelected ? selectedBorder : (hovering ? selectedBorder.withAlphaComponent(0.55) : idleBorder)).cgColor
  1335. card.layer?.borderWidth = isSelected ? 2 : 1
  1336. card.layer?.shadowColor = NSColor.black.cgColor
  1337. card.layer?.shadowOpacity = isSelected ? (darkModeEnabled ? 0.26 : 0.10) : (hovering ? 0.18 : 0.12)
  1338. card.layer?.shadowOffset = CGSize(width: 0, height: -1)
  1339. card.layer?.shadowRadius = isSelected ? (darkModeEnabled ? 10 : 6) : (hovering ? 7 : 5)
  1340. }
  1341. private func viewForPage(_ page: SidebarPage) -> NSView {
  1342. if let cached = pageCache[page] { return cached }
  1343. let built: NSView
  1344. switch page {
  1345. case .joinMeetings:
  1346. built = makeJoinMeetingsContent()
  1347. case .photo:
  1348. built = makeSchedulePageContent()
  1349. case .video:
  1350. built = makeCalendarPageContent()
  1351. case .settings:
  1352. built = makePlaceholderPage(title: "Settings", subtitle: "Preferences and account options.")
  1353. }
  1354. pageCache[page] = built
  1355. return built
  1356. }
  1357. private func makePlaceholderPage(title: String, subtitle: String) -> NSView {
  1358. let panel = NSView()
  1359. panel.translatesAutoresizingMaskIntoConstraints = false
  1360. let titleLabel = textLabel(title, font: typography.pageTitle, color: palette.textPrimary)
  1361. titleLabel.translatesAutoresizingMaskIntoConstraints = false
  1362. let sub = textLabel(subtitle, font: typography.fieldLabel, color: palette.textSecondary)
  1363. sub.translatesAutoresizingMaskIntoConstraints = false
  1364. panel.addSubview(titleLabel)
  1365. panel.addSubview(sub)
  1366. NSLayoutConstraint.activate([
  1367. titleLabel.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
  1368. titleLabel.topAnchor.constraint(equalTo: panel.topAnchor),
  1369. sub.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
  1370. sub.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8)
  1371. ])
  1372. return panel
  1373. }
  1374. func makeBrowseWebContent() -> NSView {
  1375. let panel = NSView()
  1376. panel.translatesAutoresizingMaskIntoConstraints = false
  1377. let titleLabel = textLabel("Browse the web", font: typography.pageTitle, color: palette.textPrimary)
  1378. titleLabel.translatesAutoresizingMaskIntoConstraints = false
  1379. let sub = textLabel(
  1380. "Open sites in the in-app browser (back, forward, reload, address bar). OAuth and “Continue in browser” flows stay inside the app.",
  1381. font: typography.fieldLabel,
  1382. color: palette.textSecondary
  1383. )
  1384. sub.translatesAutoresizingMaskIntoConstraints = false
  1385. sub.maximumNumberOfLines = 0
  1386. sub.lineBreakMode = .byWordWrapping
  1387. let fieldShell = roundedContainer(cornerRadius: 8, color: palette.inputBackground)
  1388. fieldShell.translatesAutoresizingMaskIntoConstraints = false
  1389. fieldShell.heightAnchor.constraint(equalToConstant: 44).isActive = true
  1390. styleSurface(fieldShell, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  1391. let field = NSTextField(string: "")
  1392. field.translatesAutoresizingMaskIntoConstraints = false
  1393. field.isEditable = true
  1394. field.isBordered = false
  1395. field.drawsBackground = false
  1396. field.focusRingType = .none
  1397. field.font = NSFont.systemFont(ofSize: 14, weight: .regular)
  1398. field.textColor = palette.textPrimary
  1399. field.placeholderString = "https://example.com or example.com"
  1400. field.delegate = self
  1401. browseAddressField = field
  1402. fieldShell.addSubview(field)
  1403. let openBtn = meetActionButton(
  1404. title: "Open in app browser",
  1405. color: palette.primaryBlue,
  1406. textColor: .white,
  1407. width: 220,
  1408. action: #selector(browseOpenAddressClicked(_:))
  1409. )
  1410. let quickTitle = textLabel("Quick links", font: typography.joinWithURLTitle, color: palette.textPrimary)
  1411. quickTitle.translatesAutoresizingMaskIntoConstraints = false
  1412. let quickRow = NSStackView()
  1413. quickRow.translatesAutoresizingMaskIntoConstraints = false
  1414. quickRow.orientation = .horizontal
  1415. quickRow.spacing = 10
  1416. quickRow.addArrangedSubview(browseQuickLinkButton(title: "Google Meet", action: #selector(browseQuickLinkMeetClicked(_:))))
  1417. quickRow.addArrangedSubview(browseQuickLinkButton(title: "Meet help", action: #selector(browseQuickLinkMeetHelpClicked(_:))))
  1418. quickRow.addArrangedSubview(browseQuickLinkButton(title: "Zoom help", action: #selector(browseQuickLinkZoomHelpClicked(_:))))
  1419. panel.addSubview(titleLabel)
  1420. panel.addSubview(sub)
  1421. panel.addSubview(fieldShell)
  1422. panel.addSubview(openBtn)
  1423. panel.addSubview(quickTitle)
  1424. panel.addSubview(quickRow)
  1425. NSLayoutConstraint.activate([
  1426. titleLabel.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
  1427. titleLabel.topAnchor.constraint(equalTo: panel.topAnchor, constant: 26),
  1428. titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: panel.trailingAnchor, constant: -28),
  1429. sub.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
  1430. sub.trailingAnchor.constraint(lessThanOrEqualTo: panel.trailingAnchor, constant: -28),
  1431. sub.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10),
  1432. fieldShell.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
  1433. fieldShell.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
  1434. fieldShell.topAnchor.constraint(equalTo: sub.bottomAnchor, constant: 18),
  1435. field.leadingAnchor.constraint(equalTo: fieldShell.leadingAnchor, constant: 12),
  1436. field.trailingAnchor.constraint(equalTo: fieldShell.trailingAnchor, constant: -12),
  1437. field.centerYAnchor.constraint(equalTo: fieldShell.centerYAnchor),
  1438. openBtn.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
  1439. openBtn.topAnchor.constraint(equalTo: fieldShell.bottomAnchor, constant: 12),
  1440. openBtn.heightAnchor.constraint(equalToConstant: 36),
  1441. quickTitle.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
  1442. quickTitle.topAnchor.constraint(equalTo: openBtn.bottomAnchor, constant: 28),
  1443. quickRow.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
  1444. quickRow.topAnchor.constraint(equalTo: quickTitle.bottomAnchor, constant: 10)
  1445. ])
  1446. return panel
  1447. }
  1448. private func browseQuickLinkButton(title: String, action: Selector) -> NSButton {
  1449. let b = NSButton(title: title, target: self, action: action)
  1450. b.translatesAutoresizingMaskIntoConstraints = false
  1451. b.bezelStyle = .rounded
  1452. b.font = NSFont.systemFont(ofSize: 13, weight: .medium)
  1453. return b
  1454. }
  1455. private func applyWindowTitle(for page: SidebarPage) {
  1456. let title: String
  1457. switch page {
  1458. case .joinMeetings:
  1459. title = "App for Google Meet"
  1460. case .photo:
  1461. title = "Schedule"
  1462. case .video:
  1463. title = "Calendar"
  1464. case .settings:
  1465. title = "Settings"
  1466. }
  1467. view.window?.title = title
  1468. centeredTitleLabel?.stringValue = title
  1469. }
  1470. private func installCenteredTitleIfNeeded(on window: NSWindow) {
  1471. guard centeredTitleLabel == nil else { return }
  1472. guard let titlebarView = window.standardWindowButton(.closeButton)?.superview else { return }
  1473. let label = NSTextField(labelWithString: window.title)
  1474. label.translatesAutoresizingMaskIntoConstraints = false
  1475. label.alignment = .center
  1476. label.font = NSFont.titleBarFont(ofSize: 0)
  1477. label.textColor = .labelColor
  1478. label.lineBreakMode = .byTruncatingTail
  1479. label.maximumNumberOfLines = 1
  1480. titlebarView.addSubview(label)
  1481. NSLayoutConstraint.activate([
  1482. label.centerXAnchor.constraint(equalTo: titlebarView.centerXAnchor),
  1483. label.centerYAnchor.constraint(equalTo: titlebarView.centerYAnchor),
  1484. label.leadingAnchor.constraint(greaterThanOrEqualTo: titlebarView.leadingAnchor, constant: 90),
  1485. label.trailingAnchor.constraint(lessThanOrEqualTo: titlebarView.trailingAnchor, constant: -90)
  1486. ])
  1487. window.titleVisibility = .hidden
  1488. centeredTitleLabel = label
  1489. }
  1490. private func updateSidebarAppearance() {
  1491. for (page, row) in sidebarRowViews {
  1492. applySidebarRowStyle(row, page: page, logoTemplate: logoTemplateForSidebarPage(page))
  1493. }
  1494. }
  1495. private func logoTemplateForSidebarPage(_ page: SidebarPage) -> Bool {
  1496. switch page {
  1497. case .photo: return false
  1498. case .joinMeetings, .video, .settings: return true
  1499. }
  1500. }
  1501. func makeSidebar() -> NSView {
  1502. let sidebar = NSView()
  1503. sidebar.translatesAutoresizingMaskIntoConstraints = false
  1504. sidebar.wantsLayer = true
  1505. sidebar.layer?.backgroundColor = palette.sidebarBackground.cgColor
  1506. sidebar.layer?.borderColor = palette.separator.cgColor
  1507. sidebar.layer?.borderWidth = 1
  1508. sidebar.layer?.shadowColor = NSColor.black.cgColor
  1509. sidebar.layer?.shadowOpacity = 0.18
  1510. sidebar.layer?.shadowOffset = CGSize(width: 2, height: 0)
  1511. sidebar.layer?.shadowRadius = 10
  1512. sidebar.widthAnchor.constraint(equalToConstant: 210).isActive = true
  1513. let appIconView = NSImageView()
  1514. if let headerLogo = NSImage(named: "HeaderLogo") {
  1515. headerLogo.isTemplate = false
  1516. appIconView.image = headerLogo
  1517. } else if let appIconImage = NSApplication.shared.applicationIconImage {
  1518. appIconImage.isTemplate = false
  1519. appIconView.image = appIconImage
  1520. }
  1521. appIconView.translatesAutoresizingMaskIntoConstraints = false
  1522. appIconView.imageScaling = NSImageScaling.scaleProportionallyDown
  1523. appIconView.imageAlignment = NSImageAlignment.alignCenter
  1524. appIconView.contentTintColor = nil
  1525. appIconView.widthAnchor.constraint(equalToConstant: 44).isActive = true
  1526. appIconView.heightAnchor.constraint(equalToConstant: 44).isActive = true
  1527. let titleRow = NSStackView(views: [
  1528. appIconView,
  1529. textLabel("Meetings", font: typography.sidebarBrand, color: palette.textPrimary)
  1530. ])
  1531. titleRow.translatesAutoresizingMaskIntoConstraints = false
  1532. titleRow.orientation = NSUserInterfaceLayoutOrientation.horizontal
  1533. titleRow.alignment = NSLayoutConstraint.Attribute.centerY
  1534. titleRow.spacing = 16
  1535. let menuStack = NSStackView()
  1536. menuStack.translatesAutoresizingMaskIntoConstraints = false
  1537. menuStack.orientation = .vertical
  1538. menuStack.alignment = .leading
  1539. menuStack.spacing = 10
  1540. menuStack.addArrangedSubview(sidebarSectionTitle("Meetings"))
  1541. let joinRow = sidebarItem("Join Meetings", icon: "􀉣", page: .joinMeetings, logoImageName: "JoinMeetingsLogo", logoIconWidth: 24, logoHeightMultiplier: 56.0 / 52.0)
  1542. menuStack.addArrangedSubview(joinRow)
  1543. sidebarRowViews[.joinMeetings] = joinRow
  1544. menuStack.addArrangedSubview(sidebarSectionTitle("Planning"))
  1545. let photoRow = sidebarItem("Schedule", icon: "􀏂", page: .photo, systemSymbolName: "clock.badge.checkmark")
  1546. menuStack.addArrangedSubview(photoRow)
  1547. sidebarRowViews[.photo] = photoRow
  1548. let videoRow = sidebarItem("Calendar", icon: "􀎚", page: .video, systemSymbolName: "calendar")
  1549. menuStack.addArrangedSubview(videoRow)
  1550. sidebarRowViews[.video] = videoRow
  1551. menuStack.addArrangedSubview(sidebarSectionTitle("Additional"))
  1552. let settingsRow = sidebarItem("Settings", icon: "􀍟", page: .settings, logoImageName: "SidebarSettingsLogo", logoIconWidth: 28, logoHeightMultiplier: 68.0 / 62.0, showsDisclosure: true)
  1553. menuStack.addArrangedSubview(settingsRow)
  1554. sidebarRowViews[.settings] = settingsRow
  1555. let premiumButton = sidebarPremiumButton()
  1556. sidebar.addSubview(titleRow)
  1557. sidebar.addSubview(menuStack)
  1558. sidebar.addSubview(premiumButton)
  1559. NSLayoutConstraint.activate([
  1560. titleRow.leadingAnchor.constraint(equalTo: sidebar.leadingAnchor, constant: 16),
  1561. titleRow.topAnchor.constraint(equalTo: sidebar.topAnchor, constant: 24),
  1562. titleRow.trailingAnchor.constraint(lessThanOrEqualTo: sidebar.trailingAnchor, constant: -16),
  1563. menuStack.leadingAnchor.constraint(equalTo: sidebar.leadingAnchor, constant: 12),
  1564. menuStack.trailingAnchor.constraint(equalTo: sidebar.trailingAnchor, constant: -12),
  1565. menuStack.topAnchor.constraint(equalTo: titleRow.bottomAnchor, constant: 20),
  1566. menuStack.bottomAnchor.constraint(lessThanOrEqualTo: premiumButton.topAnchor, constant: -16),
  1567. premiumButton.leadingAnchor.constraint(equalTo: sidebar.leadingAnchor, constant: 12),
  1568. premiumButton.trailingAnchor.constraint(equalTo: sidebar.trailingAnchor, constant: -12),
  1569. premiumButton.bottomAnchor.constraint(equalTo: sidebar.bottomAnchor, constant: -14)
  1570. ])
  1571. for subview in menuStack.arrangedSubviews {
  1572. subview.widthAnchor.constraint(equalTo: menuStack.widthAnchor).isActive = true
  1573. }
  1574. return sidebar
  1575. }
  1576. func sidebarPremiumButton() -> NSView {
  1577. let button = HoverTrackingView()
  1578. button.translatesAutoresizingMaskIntoConstraints = false
  1579. button.wantsLayer = true
  1580. button.layer?.cornerRadius = 17
  1581. button.layer?.backgroundColor = palette.primaryBlue.cgColor
  1582. button.heightAnchor.constraint(equalToConstant: 34).isActive = true
  1583. styleSurface(button, borderColor: palette.primaryBlueBorder, borderWidth: 1, shadow: false)
  1584. let icon = NSImageView()
  1585. icon.translatesAutoresizingMaskIntoConstraints = false
  1586. icon.imageScaling = .scaleProportionallyUpOrDown
  1587. icon.contentTintColor = .white
  1588. icon.image = premiumButtonSymbolImage(named: "star.fill")
  1589. let title = textLabel("Get Premium", font: NSFont.systemFont(ofSize: 14, weight: .semibold), color: .white)
  1590. button.addSubview(icon)
  1591. button.addSubview(title)
  1592. NSLayoutConstraint.activate([
  1593. icon.leadingAnchor.constraint(equalTo: button.leadingAnchor, constant: 12),
  1594. icon.centerYAnchor.constraint(equalTo: button.centerYAnchor),
  1595. icon.widthAnchor.constraint(equalToConstant: 14),
  1596. icon.heightAnchor.constraint(equalToConstant: 14),
  1597. title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 8),
  1598. title.centerYAnchor.constraint(equalTo: button.centerYAnchor),
  1599. title.trailingAnchor.constraint(lessThanOrEqualTo: button.trailingAnchor, constant: -12)
  1600. ])
  1601. button.onHoverChanged = { [weak self, weak button] hovering in
  1602. guard let self, let button else { return }
  1603. let isPremium = self.storeKitCoordinator.hasPremiumAccess
  1604. let baseColor = isPremium
  1605. ? NSColor(calibratedRed: 0.93, green: 0.73, blue: 0.16, alpha: 1.0)
  1606. : self.palette.primaryBlue
  1607. let borderColor = isPremium
  1608. ? NSColor(calibratedRed: 0.78, green: 0.56, blue: 0.10, alpha: 1.0)
  1609. : self.palette.primaryBlueBorder
  1610. let hoverColor: NSColor
  1611. let hoverBorderColor: NSColor
  1612. if isPremium {
  1613. // Darker rich-gold hover for stronger premium feedback.
  1614. hoverColor = NSColor(calibratedRed: 0.84, green: 0.62, blue: 0.11, alpha: 1.0)
  1615. hoverBorderColor = NSColor(calibratedRed: 0.67, green: 0.46, blue: 0.07, alpha: 1.0)
  1616. } else {
  1617. let hoverBlend = self.darkModeEnabled ? NSColor.white : NSColor.black
  1618. hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  1619. hoverBorderColor = borderColor
  1620. }
  1621. button.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  1622. button.layer?.shadowColor = NSColor.black.cgColor
  1623. button.layer?.shadowOpacity = hovering ? (isPremium ? 0.30 : 0.20) : 0.14
  1624. button.layer?.shadowOffset = CGSize(width: 0, height: -1)
  1625. button.layer?.shadowRadius = hovering ? (isPremium ? 8 : 6) : 4
  1626. self.styleSurface(button, borderColor: (hovering ? hoverBorderColor : borderColor), borderWidth: hovering ? 1.5 : 1, shadow: false)
  1627. }
  1628. button.onHoverChanged?(false)
  1629. sidebarPremiumTitleLabel = title
  1630. sidebarPremiumIconView = icon
  1631. sidebarPremiumButtonView = button
  1632. refreshSidebarPremiumButton()
  1633. let click = NSClickGestureRecognizer(target: self, action: #selector(premiumButtonClicked(_:)))
  1634. button.addGestureRecognizer(click)
  1635. return button
  1636. }
  1637. func makeMainPanel() -> NSView {
  1638. let panel = NSView()
  1639. panel.translatesAutoresizingMaskIntoConstraints = false
  1640. panel.wantsLayer = true
  1641. panel.layer?.backgroundColor = palette.pageBackground.cgColor
  1642. let authBar = scheduleTopAuthRow()
  1643. authBar.translatesAutoresizingMaskIntoConstraints = false
  1644. panel.addSubview(authBar)
  1645. let host = NSView()
  1646. host.translatesAutoresizingMaskIntoConstraints = false
  1647. panel.addSubview(host)
  1648. NSLayoutConstraint.activate([
  1649. authBar.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
  1650. authBar.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
  1651. authBar.topAnchor.constraint(equalTo: panel.topAnchor, constant: 26),
  1652. host.leadingAnchor.constraint(equalTo: panel.leadingAnchor),
  1653. host.trailingAnchor.constraint(equalTo: panel.trailingAnchor),
  1654. host.topAnchor.constraint(equalTo: authBar.bottomAnchor, constant: 20),
  1655. host.bottomAnchor.constraint(equalTo: panel.bottomAnchor)
  1656. ])
  1657. mainContentHost = host
  1658. if googleOAuth.loadTokens() != nil, let profile = scheduleCurrentProfile {
  1659. applyGoogleProfile(profile)
  1660. }
  1661. // Preserve the currently selected page during rebuilds (e.g. dark mode toggle).
  1662. showSidebarPage(selectedSidebarPage)
  1663. return panel
  1664. }
  1665. func makeJoinMeetingsContent() -> NSView {
  1666. let panel = NSView()
  1667. panel.translatesAutoresizingMaskIntoConstraints = false
  1668. let contentStack = NSStackView()
  1669. contentStack.translatesAutoresizingMaskIntoConstraints = false
  1670. contentStack.orientation = .vertical
  1671. contentStack.spacing = 14
  1672. contentStack.alignment = .leading
  1673. let joinActions = meetJoinActionsRow()
  1674. contentStack.addArrangedSubview(textLabel("Join Meetings", font: typography.pageTitle, color: palette.textPrimary))
  1675. contentStack.addArrangedSubview(meetJoinSectionRow())
  1676. contentStack.addArrangedSubview(joinActions)
  1677. contentStack.setCustomSpacing(26, after: joinActions)
  1678. let scheduleHeaderView = scheduleHeader()
  1679. contentStack.addArrangedSubview(scheduleHeaderView)
  1680. contentStack.setCustomSpacing(joinPageScheduleHeaderToDateSpacing, after: scheduleHeaderView)
  1681. let dateHeading = textLabel(scheduleInitialHeadingText(), font: typography.dateHeading, color: palette.textSecondary)
  1682. scheduleDateHeadingLabel = dateHeading
  1683. contentStack.addArrangedSubview(dateHeading)
  1684. contentStack.setCustomSpacing(joinPageDateToMeetingCardsSpacing, after: dateHeading)
  1685. let cardsRow = scheduleCardsRow(meetings: [])
  1686. contentStack.addArrangedSubview(cardsRow)
  1687. panel.addSubview(contentStack)
  1688. NSLayoutConstraint.activate([
  1689. contentStack.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
  1690. contentStack.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
  1691. contentStack.topAnchor.constraint(equalTo: panel.topAnchor)
  1692. ])
  1693. Task { [weak self] in
  1694. await self?.loadSchedule()
  1695. }
  1696. return panel
  1697. }
  1698. func makeSchedulePageContent() -> NSView {
  1699. let panel = NSView()
  1700. panel.translatesAutoresizingMaskIntoConstraints = false
  1701. panel.userInterfaceLayoutDirection = .leftToRight
  1702. let contentStack = NSStackView()
  1703. contentStack.translatesAutoresizingMaskIntoConstraints = false
  1704. contentStack.userInterfaceLayoutDirection = .leftToRight
  1705. contentStack.orientation = .vertical
  1706. contentStack.spacing = schedulePageStackSpacing
  1707. contentStack.alignment = .width
  1708. contentStack.distribution = .fill
  1709. let header = schedulePageHeader()
  1710. header.setContentHuggingPriority(.required, for: .vertical)
  1711. header.setContentCompressionResistancePriority(.required, for: .vertical)
  1712. contentStack.addArrangedSubview(header)
  1713. contentStack.setCustomSpacing(schedulePageHeaderToDateSpacing, after: header)
  1714. let heading = textLabel(schedulePageInitialHeadingText(), font: typography.dateHeading, color: palette.textSecondary)
  1715. heading.alignment = .left
  1716. heading.setContentHuggingPriority(.required, for: .vertical)
  1717. heading.setContentCompressionResistancePriority(.required, for: .vertical)
  1718. schedulePageDateHeadingLabel = heading
  1719. contentStack.addArrangedSubview(heading)
  1720. let rangeError = textLabel("", font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: .systemRed)
  1721. rangeError.alignment = .left
  1722. rangeError.isHidden = true
  1723. rangeError.setContentHuggingPriority(.required, for: .vertical)
  1724. rangeError.setContentCompressionResistancePriority(.required, for: .vertical)
  1725. schedulePageRangeErrorLabel = rangeError
  1726. contentStack.addArrangedSubview(rangeError)
  1727. let cardsContainer = makeSchedulePageCardsContainer()
  1728. cardsContainer.setContentHuggingPriority(.defaultLow, for: .vertical)
  1729. contentStack.addArrangedSubview(cardsContainer)
  1730. panel.addSubview(contentStack)
  1731. NSLayoutConstraint.activate([
  1732. contentStack.leftAnchor.constraint(equalTo: panel.leftAnchor, constant: schedulePageLeadingInset),
  1733. contentStack.rightAnchor.constraint(equalTo: panel.rightAnchor, constant: -schedulePageTrailingInset),
  1734. contentStack.topAnchor.constraint(equalTo: panel.topAnchor),
  1735. contentStack.bottomAnchor.constraint(equalTo: panel.bottomAnchor, constant: -16),
  1736. header.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  1737. heading.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  1738. rangeError.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  1739. cardsContainer.widthAnchor.constraint(equalTo: contentStack.widthAnchor)
  1740. ])
  1741. Task { [weak self] in
  1742. await self?.loadSchedule()
  1743. }
  1744. return panel
  1745. }
  1746. func makeCalendarPageContent() -> NSView {
  1747. let panel = NSView()
  1748. panel.translatesAutoresizingMaskIntoConstraints = false
  1749. panel.userInterfaceLayoutDirection = .leftToRight
  1750. let contentStack = NSStackView()
  1751. contentStack.translatesAutoresizingMaskIntoConstraints = false
  1752. contentStack.userInterfaceLayoutDirection = .leftToRight
  1753. contentStack.orientation = .vertical
  1754. contentStack.spacing = 14
  1755. contentStack.alignment = .width
  1756. contentStack.distribution = .fill
  1757. let titleRow = NSStackView()
  1758. titleRow.translatesAutoresizingMaskIntoConstraints = false
  1759. titleRow.userInterfaceLayoutDirection = .leftToRight
  1760. titleRow.orientation = .horizontal
  1761. titleRow.alignment = .centerY
  1762. titleRow.distribution = .fill
  1763. titleRow.spacing = 10
  1764. let titleLabel = textLabel("Calendar", font: typography.pageTitle, color: palette.textPrimary)
  1765. titleLabel.alignment = .left
  1766. titleLabel.maximumNumberOfLines = 1
  1767. titleLabel.lineBreakMode = .byTruncatingTail
  1768. titleLabel.setContentHuggingPriority(.required, for: .horizontal)
  1769. titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
  1770. let spacer = NSView()
  1771. spacer.translatesAutoresizingMaskIntoConstraints = false
  1772. spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  1773. spacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  1774. let prevButton = makeCalendarHeaderPillButton(title: "‹", action: #selector(calendarPrevMonthPressed(_:)))
  1775. prevButton.widthAnchor.constraint(equalToConstant: 46).isActive = true
  1776. let nextButton = makeCalendarHeaderPillButton(title: "›", action: #selector(calendarNextMonthPressed(_:)))
  1777. nextButton.widthAnchor.constraint(equalToConstant: 46).isActive = true
  1778. let monthLabel = textLabel("", font: NSFont.systemFont(ofSize: 16, weight: .semibold), color: palette.textSecondary)
  1779. monthLabel.alignment = .right
  1780. monthLabel.maximumNumberOfLines = 1
  1781. monthLabel.lineBreakMode = .byTruncatingTail
  1782. monthLabel.setContentHuggingPriority(.required, for: .horizontal)
  1783. monthLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
  1784. calendarPageMonthLabel = monthLabel
  1785. let refreshButton = HoverButton(title: "", target: self, action: #selector(calendarRefreshPressed(_:)))
  1786. refreshButton.translatesAutoresizingMaskIntoConstraints = false
  1787. refreshButton.isBordered = false
  1788. refreshButton.bezelStyle = .regularSquare
  1789. refreshButton.wantsLayer = true
  1790. refreshButton.layer?.cornerRadius = 15
  1791. refreshButton.layer?.masksToBounds = true
  1792. refreshButton.layer?.backgroundColor = palette.inputBackground.cgColor
  1793. refreshButton.layer?.borderColor = palette.inputBorder.cgColor
  1794. refreshButton.layer?.borderWidth = 1
  1795. refreshButton.setButtonType(.momentaryChange)
  1796. refreshButton.contentTintColor = palette.textSecondary
  1797. refreshButton.image = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: "Sync calendar")
  1798. refreshButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .semibold)
  1799. refreshButton.imagePosition = .imageOnly
  1800. refreshButton.imageScaling = .scaleProportionallyDown
  1801. refreshButton.focusRingType = .none
  1802. refreshButton.heightAnchor.constraint(equalToConstant: 32).isActive = true
  1803. refreshButton.widthAnchor.constraint(equalToConstant: 32).isActive = true
  1804. titleRow.addArrangedSubview(titleLabel)
  1805. titleRow.addArrangedSubview(spacer)
  1806. titleRow.addArrangedSubview(prevButton)
  1807. titleRow.addArrangedSubview(nextButton)
  1808. titleRow.addArrangedSubview(monthLabel)
  1809. titleRow.addArrangedSubview(refreshButton)
  1810. let weekdayRow = NSStackView()
  1811. weekdayRow.translatesAutoresizingMaskIntoConstraints = false
  1812. weekdayRow.userInterfaceLayoutDirection = .leftToRight
  1813. weekdayRow.orientation = .horizontal
  1814. weekdayRow.alignment = .centerY
  1815. weekdayRow.distribution = .fillEqually
  1816. weekdayRow.spacing = 12
  1817. for symbol in calendarWeekdaySymbolsStartingAtFirstWeekday() {
  1818. let label = textLabel(symbol, font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: palette.textMuted)
  1819. label.alignment = .center
  1820. label.maximumNumberOfLines = 1
  1821. label.lineBreakMode = .byClipping
  1822. weekdayRow.addArrangedSubview(label)
  1823. }
  1824. let gridStack = NSStackView()
  1825. gridStack.translatesAutoresizingMaskIntoConstraints = false
  1826. gridStack.userInterfaceLayoutDirection = .leftToRight
  1827. gridStack.orientation = .vertical
  1828. gridStack.alignment = .width
  1829. gridStack.distribution = .fillEqually
  1830. gridStack.spacing = 10
  1831. calendarPageGridStack = gridStack
  1832. let gridCard = roundedContainer(cornerRadius: 14, color: palette.sectionCard)
  1833. gridCard.translatesAutoresizingMaskIntoConstraints = false
  1834. styleSurface(gridCard, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  1835. let gridHeightConstraint = gridCard.heightAnchor.constraint(equalToConstant: 360)
  1836. gridHeightConstraint.isActive = true
  1837. calendarPageGridHeightConstraint = gridHeightConstraint
  1838. gridCard.heightAnchor.constraint(greaterThanOrEqualToConstant: 360).isActive = true
  1839. gridCard.addSubview(gridStack)
  1840. NSLayoutConstraint.activate([
  1841. gridStack.leadingAnchor.constraint(equalTo: gridCard.leadingAnchor, constant: 16),
  1842. gridStack.trailingAnchor.constraint(equalTo: gridCard.trailingAnchor, constant: -16),
  1843. gridStack.topAnchor.constraint(equalTo: gridCard.topAnchor, constant: 16),
  1844. gridStack.bottomAnchor.constraint(equalTo: gridCard.bottomAnchor, constant: -16)
  1845. ])
  1846. let daySummary = textLabel("", font: typography.dateHeading, color: palette.textSecondary)
  1847. daySummary.alignment = .left
  1848. daySummary.maximumNumberOfLines = 2
  1849. daySummary.lineBreakMode = .byWordWrapping
  1850. calendarPageDaySummaryLabel = daySummary
  1851. contentStack.addArrangedSubview(titleRow)
  1852. contentStack.setCustomSpacing(16, after: titleRow)
  1853. contentStack.addArrangedSubview(weekdayRow)
  1854. contentStack.setCustomSpacing(10, after: weekdayRow)
  1855. contentStack.addArrangedSubview(gridCard)
  1856. contentStack.setCustomSpacing(16, after: gridCard)
  1857. contentStack.addArrangedSubview(daySummary)
  1858. panel.addSubview(contentStack)
  1859. NSLayoutConstraint.activate([
  1860. contentStack.leftAnchor.constraint(equalTo: panel.leftAnchor, constant: 28),
  1861. contentStack.rightAnchor.constraint(equalTo: panel.rightAnchor, constant: -28),
  1862. contentStack.topAnchor.constraint(equalTo: panel.topAnchor),
  1863. contentStack.bottomAnchor.constraint(lessThanOrEqualTo: panel.bottomAnchor, constant: -16),
  1864. titleRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  1865. weekdayRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  1866. gridCard.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  1867. daySummary.widthAnchor.constraint(equalTo: contentStack.widthAnchor)
  1868. ])
  1869. if !storeKitCoordinator.hasPremiumAccess {
  1870. let lockOverlay = NSVisualEffectView()
  1871. lockOverlay.translatesAutoresizingMaskIntoConstraints = false
  1872. lockOverlay.material = darkModeEnabled ? .hudWindow : .popover
  1873. lockOverlay.blendingMode = .withinWindow
  1874. lockOverlay.state = .active
  1875. lockOverlay.wantsLayer = true
  1876. lockOverlay.layer?.cornerRadius = 14
  1877. lockOverlay.layer?.masksToBounds = true
  1878. lockOverlay.layer?.backgroundColor = NSColor.black.withAlphaComponent(darkModeEnabled ? 0.30 : 0.12).cgColor
  1879. panel.addSubview(lockOverlay)
  1880. let message = textLabel("Premium required. Get Premium now to unlock Calendar.", font: NSFont.systemFont(ofSize: 14, weight: .semibold), color: darkModeEnabled ? .white : .black)
  1881. message.alignment = .center
  1882. message.maximumNumberOfLines = 2
  1883. message.lineBreakMode = .byWordWrapping
  1884. lockOverlay.addSubview(message)
  1885. let hit = HoverTrackingView()
  1886. hit.translatesAutoresizingMaskIntoConstraints = false
  1887. hit.wantsLayer = true
  1888. hit.layer?.backgroundColor = NSColor.clear.cgColor
  1889. hit.onClick = { [weak self] in
  1890. self?.showPaywall()
  1891. }
  1892. hit.toolTip = "Premium required. Click to open paywall."
  1893. lockOverlay.addSubview(hit)
  1894. NSLayoutConstraint.activate([
  1895. lockOverlay.leadingAnchor.constraint(equalTo: contentStack.leadingAnchor),
  1896. lockOverlay.trailingAnchor.constraint(equalTo: contentStack.trailingAnchor),
  1897. lockOverlay.topAnchor.constraint(equalTo: contentStack.topAnchor),
  1898. lockOverlay.bottomAnchor.constraint(equalTo: contentStack.bottomAnchor),
  1899. message.centerXAnchor.constraint(equalTo: lockOverlay.centerXAnchor),
  1900. message.centerYAnchor.constraint(equalTo: lockOverlay.centerYAnchor),
  1901. message.leadingAnchor.constraint(greaterThanOrEqualTo: lockOverlay.leadingAnchor, constant: 22),
  1902. message.trailingAnchor.constraint(lessThanOrEqualTo: lockOverlay.trailingAnchor, constant: -22),
  1903. hit.leadingAnchor.constraint(equalTo: lockOverlay.leadingAnchor),
  1904. hit.trailingAnchor.constraint(equalTo: lockOverlay.trailingAnchor),
  1905. hit.topAnchor.constraint(equalTo: lockOverlay.topAnchor),
  1906. hit.bottomAnchor.constraint(equalTo: lockOverlay.bottomAnchor)
  1907. ])
  1908. }
  1909. let calendar = Calendar.current
  1910. calendarPageMonthAnchor = calendarStartOfMonth(for: Date())
  1911. calendarPageSelectedDate = calendar.startOfDay(for: Date())
  1912. calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
  1913. renderCalendarMonthGrid()
  1914. renderCalendarSelectedDay()
  1915. Task { [weak self] in
  1916. await self?.loadSchedule()
  1917. }
  1918. return panel
  1919. }
  1920. func meetJoinSectionRow() -> NSView {
  1921. let row = NSStackView()
  1922. row.translatesAutoresizingMaskIntoConstraints = false
  1923. row.orientation = .horizontal
  1924. row.spacing = 12
  1925. row.alignment = .top
  1926. row.distribution = .fillEqually
  1927. row.widthAnchor.constraint(greaterThanOrEqualToConstant: 880).isActive = true
  1928. row.heightAnchor.constraint(equalToConstant: 140).isActive = true
  1929. let instant = HoverSurfaceView()
  1930. instant.translatesAutoresizingMaskIntoConstraints = false
  1931. instant.wantsLayer = true
  1932. instant.layer?.cornerRadius = 14
  1933. instant.layer?.backgroundColor = palette.sectionCard.cgColor
  1934. styleSurface(instant, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  1935. let iconWrap = roundedContainer(cornerRadius: 12, color: NSColor.clear)
  1936. iconWrap.translatesAutoresizingMaskIntoConstraints = false
  1937. iconWrap.widthAnchor.constraint(equalToConstant: 58).isActive = true
  1938. iconWrap.heightAnchor.constraint(equalToConstant: 58).isActive = true
  1939. iconWrap.layer?.borderWidth = 0
  1940. let meetLogoImage = NSImage(named: "MeetLogo") ?? NSImage()
  1941. meetLogoImage.isTemplate = false
  1942. let meetLogo = NSImageView(image: meetLogoImage)
  1943. meetLogo.translatesAutoresizingMaskIntoConstraints = false
  1944. meetLogo.imageScaling = .scaleProportionallyDown
  1945. meetLogo.contentTintColor = nil
  1946. iconWrap.addSubview(meetLogo)
  1947. let instantTitle = textLabel("New Instant Meet", font: NSFont.systemFont(ofSize: 40 / 2, weight: .semibold), color: palette.textPrimary)
  1948. let instantSub = textLabel("Start instant Meet in more section with\nGoogle Meet meet.", font: NSFont.systemFont(ofSize: 16 / 2, weight: .medium), color: palette.textSecondary)
  1949. instantSub.maximumNumberOfLines = 2
  1950. instant.addSubview(iconWrap)
  1951. instant.addSubview(instantTitle)
  1952. instant.addSubview(instantSub)
  1953. let codeCard = HoverSurfaceView()
  1954. codeCard.translatesAutoresizingMaskIntoConstraints = false
  1955. codeCard.wantsLayer = true
  1956. codeCard.layer?.cornerRadius = 14
  1957. codeCard.layer?.backgroundColor = palette.sectionCard.cgColor
  1958. styleSurface(codeCard, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  1959. let codeTitle = textLabel("Join with Link", font: NSFont.systemFont(ofSize: 40 / 2, weight: .semibold), color: palette.textPrimary)
  1960. let codeInputShell = roundedContainer(cornerRadius: 8, color: palette.inputBackground)
  1961. codeInputShell.translatesAutoresizingMaskIntoConstraints = false
  1962. codeInputShell.heightAnchor.constraint(equalToConstant: 52).isActive = true
  1963. styleSurface(codeInputShell, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  1964. let codeField = NSTextField(string: "")
  1965. codeField.translatesAutoresizingMaskIntoConstraints = false
  1966. codeField.isEditable = true
  1967. codeField.isBordered = false
  1968. codeField.drawsBackground = false
  1969. codeField.focusRingType = .none
  1970. codeField.font = NSFont.systemFont(ofSize: 36 / 2, weight: .regular)
  1971. codeField.textColor = palette.textPrimary
  1972. codeField.placeholderString = "Code or meet.google.com/…"
  1973. codeInputShell.addSubview(codeField)
  1974. meetLinkField = codeField
  1975. codeCard.addSubview(codeTitle)
  1976. codeCard.addSubview(codeInputShell)
  1977. NSLayoutConstraint.activate([
  1978. meetLogo.centerXAnchor.constraint(equalTo: iconWrap.centerXAnchor),
  1979. meetLogo.centerYAnchor.constraint(equalTo: iconWrap.centerYAnchor),
  1980. meetLogo.widthAnchor.constraint(equalToConstant: 46),
  1981. meetLogo.heightAnchor.constraint(equalToConstant: 46),
  1982. iconWrap.leadingAnchor.constraint(equalTo: instant.leadingAnchor, constant: 18),
  1983. iconWrap.topAnchor.constraint(equalTo: instant.topAnchor, constant: 22),
  1984. instantTitle.leadingAnchor.constraint(equalTo: iconWrap.trailingAnchor, constant: 14),
  1985. instantTitle.topAnchor.constraint(equalTo: instant.topAnchor, constant: 24),
  1986. instantSub.leadingAnchor.constraint(equalTo: instantTitle.leadingAnchor),
  1987. instantSub.topAnchor.constraint(equalTo: instantTitle.bottomAnchor, constant: 6),
  1988. instantSub.trailingAnchor.constraint(lessThanOrEqualTo: instant.trailingAnchor, constant: -16),
  1989. codeTitle.leadingAnchor.constraint(equalTo: codeCard.leadingAnchor, constant: 18),
  1990. codeTitle.topAnchor.constraint(equalTo: codeCard.topAnchor, constant: 22),
  1991. codeInputShell.leadingAnchor.constraint(equalTo: codeCard.leadingAnchor, constant: 18),
  1992. codeInputShell.trailingAnchor.constraint(equalTo: codeCard.trailingAnchor, constant: -18),
  1993. codeInputShell.topAnchor.constraint(equalTo: codeTitle.bottomAnchor, constant: 12),
  1994. codeField.leadingAnchor.constraint(equalTo: codeInputShell.leadingAnchor, constant: 14),
  1995. codeField.trailingAnchor.constraint(equalTo: codeInputShell.trailingAnchor, constant: -14),
  1996. codeField.centerYAnchor.constraint(equalTo: codeInputShell.centerYAnchor)
  1997. ])
  1998. let baseColor = palette.sectionCard
  1999. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  2000. let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  2001. instant.onHoverChanged = { [weak self] hovering in
  2002. guard let self else { return }
  2003. instant.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  2004. }
  2005. codeCard.onHoverChanged = { [weak self] hovering in
  2006. guard let self else { return }
  2007. codeCard.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  2008. }
  2009. instant.onHoverChanged?(false)
  2010. codeCard.onHoverChanged?(false)
  2011. let instantClick = NSClickGestureRecognizer(target: self, action: #selector(instantMeetClicked(_:)))
  2012. instant.addGestureRecognizer(instantClick)
  2013. let joinWithLinkClick = NSClickGestureRecognizer(target: self, action: #selector(joinWithLinkCardClicked(_:)))
  2014. codeCard.addGestureRecognizer(joinWithLinkClick)
  2015. instantMeetCardView = instant
  2016. instantMeetTitleLabel = instantTitle
  2017. instantMeetSubtitleLabel = instantSub
  2018. joinWithLinkCardView = codeCard
  2019. joinWithLinkTitleLabel = codeTitle
  2020. refreshInstantMeetPremiumState()
  2021. row.addArrangedSubview(instant)
  2022. row.addArrangedSubview(codeCard)
  2023. return row
  2024. }
  2025. func meetJoinActionsRow() -> NSView {
  2026. let row = NSStackView()
  2027. row.translatesAutoresizingMaskIntoConstraints = false
  2028. row.orientation = .horizontal
  2029. row.spacing = 12
  2030. row.alignment = .centerY
  2031. row.widthAnchor.constraint(greaterThanOrEqualToConstant: 880).isActive = true
  2032. let spacer = NSView()
  2033. spacer.translatesAutoresizingMaskIntoConstraints = false
  2034. row.addArrangedSubview(spacer)
  2035. row.addArrangedSubview(meetActionButton(
  2036. title: "Cancel",
  2037. color: palette.cancelButton,
  2038. textColor: palette.textSecondary,
  2039. width: 110,
  2040. action: #selector(cancelMeetJoinClicked(_:))
  2041. ))
  2042. let joinButton = meetActionButton(
  2043. title: "Join",
  2044. color: palette.primaryBlue,
  2045. textColor: .white,
  2046. width: 116,
  2047. action: #selector(joinMeetClicked(_:))
  2048. )
  2049. joinMeetPrimaryButton = joinButton
  2050. row.addArrangedSubview(joinButton)
  2051. refreshInstantMeetPremiumState()
  2052. return row
  2053. }
  2054. func meetActionButton(title: String, color: NSColor, textColor: NSColor, width: CGFloat, action: Selector) -> NSButton {
  2055. let button = HoverButton(title: title, target: self, action: action)
  2056. button.translatesAutoresizingMaskIntoConstraints = false
  2057. button.isBordered = false
  2058. button.bezelStyle = .regularSquare
  2059. button.wantsLayer = true
  2060. button.layer?.cornerRadius = 9
  2061. let baseBackground = color
  2062. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  2063. let hoverBackground = baseBackground.blended(withFraction: 0.10, of: hoverBlend) ?? baseBackground
  2064. let baseBorder = (title == "Cancel" ? palette.inputBorder : palette.primaryBlueBorder)
  2065. let hoverBorder = baseBorder.blended(withFraction: 0.18, of: hoverBlend) ?? baseBorder
  2066. button.layer?.backgroundColor = baseBackground.cgColor
  2067. button.layer?.borderColor = baseBorder.cgColor
  2068. button.layer?.borderWidth = 1
  2069. button.font = typography.buttonText
  2070. button.contentTintColor = textColor
  2071. button.widthAnchor.constraint(equalToConstant: width).isActive = true
  2072. button.heightAnchor.constraint(equalToConstant: 36).isActive = true
  2073. button.onHoverChanged = { [weak self, weak button] hovering in
  2074. guard let self, let button else { return }
  2075. button.layer?.backgroundColor = (hovering ? hoverBackground : baseBackground).cgColor
  2076. button.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
  2077. if title == "Cancel" {
  2078. button.contentTintColor = hovering ? (self.darkModeEnabled ? .white : self.palette.textPrimary) : textColor
  2079. }
  2080. }
  2081. button.onHoverChanged?(false)
  2082. return button
  2083. }
  2084. func makePaywallContent() -> NSView {
  2085. paywallPlanViews.removeAll()
  2086. premiumPlanByView.removeAll()
  2087. let panel = NSView()
  2088. panel.translatesAutoresizingMaskIntoConstraints = false
  2089. panel.wantsLayer = true
  2090. panel.layer?.backgroundColor = palette.pageBackground.cgColor
  2091. let contentStack = NSStackView()
  2092. contentStack.translatesAutoresizingMaskIntoConstraints = false
  2093. contentStack.orientation = .vertical
  2094. contentStack.spacing = 12
  2095. contentStack.alignment = .leading
  2096. panel.addSubview(contentStack)
  2097. let topRow = NSStackView()
  2098. topRow.translatesAutoresizingMaskIntoConstraints = false
  2099. topRow.orientation = .horizontal
  2100. topRow.alignment = .centerY
  2101. topRow.distribution = .fill
  2102. topRow.spacing = 10
  2103. topRow.addArrangedSubview(textLabel("Get Premium", font: NSFont.systemFont(ofSize: 24, weight: .bold), color: palette.textPrimary))
  2104. let topSpacer = NSView()
  2105. topSpacer.translatesAutoresizingMaskIntoConstraints = false
  2106. topRow.addArrangedSubview(topSpacer)
  2107. let closeButton = HoverButton(title: "✕", target: self, action: #selector(closePaywallClicked(_:)))
  2108. closeButton.translatesAutoresizingMaskIntoConstraints = false
  2109. closeButton.isBordered = false
  2110. closeButton.bezelStyle = .regularSquare
  2111. closeButton.wantsLayer = true
  2112. closeButton.layer?.cornerRadius = 14
  2113. closeButton.layer?.backgroundColor = palette.inputBackground.cgColor
  2114. closeButton.layer?.borderColor = palette.inputBorder.cgColor
  2115. closeButton.layer?.borderWidth = 1
  2116. closeButton.font = typography.iconButton
  2117. closeButton.contentTintColor = palette.textSecondary
  2118. closeButton.widthAnchor.constraint(equalToConstant: 28).isActive = true
  2119. closeButton.heightAnchor.constraint(equalToConstant: 28).isActive = true
  2120. closeButton.onHoverChanged = { [weak closeButton, weak self] hovering in
  2121. guard let closeButton, let self else { return }
  2122. let base = self.palette.inputBackground
  2123. let hoverBlend = self.darkModeEnabled ? NSColor.white : NSColor.black
  2124. let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
  2125. closeButton.layer?.backgroundColor = (hovering ? hover : base).cgColor
  2126. closeButton.contentTintColor = hovering ? (self.darkModeEnabled ? .white : self.palette.textPrimary) : self.palette.textSecondary
  2127. }
  2128. topRow.addArrangedSubview(closeButton)
  2129. topRow.widthAnchor.constraint(greaterThanOrEqualToConstant: paywallContentWidth).isActive = true
  2130. contentStack.addArrangedSubview(topRow)
  2131. contentStack.addArrangedSubview(textLabel("Upgrade to unlock premium features.", font: NSFont.systemFont(ofSize: 12, weight: .medium), color: palette.textSecondary))
  2132. let benefits = paywallBenefitsSection()
  2133. contentStack.addArrangedSubview(benefits)
  2134. contentStack.setCustomSpacing(18, after: benefits)
  2135. let weeklyCard = paywallPlanCard(
  2136. title: "Weekly",
  2137. price: "PKR 1,100.00",
  2138. badge: "Basic Deal",
  2139. badgeColor: NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1),
  2140. subtitle: nil,
  2141. plan: .weekly,
  2142. strikePrice: nil
  2143. )
  2144. contentStack.addArrangedSubview(weeklyCard)
  2145. let monthlyCard = paywallPlanCard(
  2146. title: "Monthly",
  2147. price: "PKR 2,500.00",
  2148. badge: "Free Trial",
  2149. badgeColor: NSColor(calibratedRed: 0.19, green: 0.82, blue: 0.39, alpha: 1),
  2150. subtitle: "625.00/week",
  2151. plan: .monthly,
  2152. strikePrice: nil
  2153. )
  2154. contentStack.addArrangedSubview(monthlyCard)
  2155. let yearlyCard = paywallPlanCard(
  2156. title: "Yearly",
  2157. price: "PKR 9,900.00",
  2158. badge: "Best Deal",
  2159. badgeColor: NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1),
  2160. subtitle: "190.38/week",
  2161. plan: .yearly,
  2162. strikePrice: nil
  2163. )
  2164. contentStack.addArrangedSubview(yearlyCard)
  2165. let lifetimeCard = paywallPlanCard(
  2166. title: "Lifetime",
  2167. price: "PKR 14,900.00",
  2168. badge: "Save 50%",
  2169. badgeColor: NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1),
  2170. subtitle: nil,
  2171. plan: .lifetime,
  2172. strikePrice: "PKR 29,800.00"
  2173. )
  2174. contentStack.addArrangedSubview(lifetimeCard)
  2175. updatePaywallPlanSelection()
  2176. contentStack.setCustomSpacing(20, after: lifetimeCard)
  2177. let offer = textLabel(paywallOfferText(for: selectedPremiumPlan), font: NSFont.systemFont(ofSize: 13, weight: .semibold), color: palette.textPrimary)
  2178. offer.alignment = .center
  2179. paywallOfferLabel = offer
  2180. let offerWrap = NSView()
  2181. offerWrap.translatesAutoresizingMaskIntoConstraints = false
  2182. offerWrap.addSubview(offer)
  2183. NSLayoutConstraint.activate([
  2184. offerWrap.widthAnchor.constraint(greaterThanOrEqualToConstant: paywallContentWidth),
  2185. offer.centerXAnchor.constraint(equalTo: offerWrap.centerXAnchor),
  2186. offer.topAnchor.constraint(equalTo: offerWrap.topAnchor, constant: 6),
  2187. offer.bottomAnchor.constraint(equalTo: offerWrap.bottomAnchor, constant: -2)
  2188. ])
  2189. contentStack.addArrangedSubview(offerWrap)
  2190. contentStack.setCustomSpacing(18, after: offerWrap)
  2191. let continueButton = HoverButton(title: "", target: self, action: #selector(paywallContinueClicked(_:)))
  2192. continueButton.translatesAutoresizingMaskIntoConstraints = false
  2193. continueButton.isBordered = false
  2194. continueButton.bezelStyle = .regularSquare
  2195. continueButton.wantsLayer = true
  2196. continueButton.layer?.cornerRadius = 14
  2197. continueButton.layer?.backgroundColor = palette.primaryBlue.cgColor
  2198. continueButton.heightAnchor.constraint(equalToConstant: 44).isActive = true
  2199. continueButton.widthAnchor.constraint(greaterThanOrEqualToConstant: paywallContentWidth).isActive = true
  2200. styleSurface(continueButton, borderColor: palette.primaryBlueBorder, borderWidth: 1, shadow: true)
  2201. let continueLabel = textLabel("Continue", font: NSFont.systemFont(ofSize: 16, weight: .bold), color: .white)
  2202. continueButton.addSubview(continueLabel)
  2203. NSLayoutConstraint.activate([
  2204. continueLabel.centerXAnchor.constraint(equalTo: continueButton.centerXAnchor),
  2205. continueLabel.centerYAnchor.constraint(equalTo: continueButton.centerYAnchor)
  2206. ])
  2207. let baseBlue = palette.primaryBlue
  2208. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  2209. let hoverBlue = baseBlue.blended(withFraction: 0.10, of: hoverBlend) ?? baseBlue
  2210. continueButton.onHoverChanged = { hovering in
  2211. continueButton.layer?.backgroundColor = (hovering ? hoverBlue : baseBlue).cgColor
  2212. }
  2213. continueButton.onHoverChanged?(false)
  2214. paywallContinueButton = continueButton
  2215. paywallContinueLabel = continueLabel
  2216. contentStack.addArrangedSubview(continueButton)
  2217. contentStack.setCustomSpacing(16, after: continueButton)
  2218. let secure = textLabel("Secured by Apple. Cancel anytime.", font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: palette.textSecondary)
  2219. secure.alignment = .center
  2220. let secureWrap = NSView()
  2221. secureWrap.translatesAutoresizingMaskIntoConstraints = false
  2222. secureWrap.addSubview(secure)
  2223. NSLayoutConstraint.activate([
  2224. secureWrap.widthAnchor.constraint(greaterThanOrEqualToConstant: paywallContentWidth),
  2225. secure.centerXAnchor.constraint(equalTo: secureWrap.centerXAnchor),
  2226. secure.topAnchor.constraint(equalTo: secureWrap.topAnchor, constant: 4),
  2227. secure.bottomAnchor.constraint(equalTo: secureWrap.bottomAnchor, constant: -8)
  2228. ])
  2229. contentStack.addArrangedSubview(secureWrap)
  2230. contentStack.setCustomSpacing(16, after: secureWrap)
  2231. let footer = paywallFooterLinks()
  2232. contentStack.addArrangedSubview(footer)
  2233. NSLayoutConstraint.activate([
  2234. contentStack.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 18),
  2235. contentStack.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -18),
  2236. contentStack.topAnchor.constraint(equalTo: panel.topAnchor, constant: 16),
  2237. contentStack.bottomAnchor.constraint(lessThanOrEqualTo: panel.bottomAnchor, constant: -12)
  2238. ])
  2239. refreshPaywallStoreUI()
  2240. return panel
  2241. }
  2242. func paywallPlanCard(
  2243. title: String,
  2244. price: String,
  2245. badge: String,
  2246. badgeColor: NSColor,
  2247. subtitle: String?,
  2248. plan: PremiumPlan,
  2249. strikePrice: String?
  2250. ) -> NSView {
  2251. let wrapper = HoverButton(title: "", target: self, action: #selector(paywallPlanButtonClicked(_:)))
  2252. wrapper.translatesAutoresizingMaskIntoConstraints = false
  2253. wrapper.isBordered = false
  2254. wrapper.bezelStyle = .regularSquare
  2255. wrapper.wantsLayer = true
  2256. wrapper.layer?.backgroundColor = NSColor.clear.cgColor
  2257. wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: paywallContentWidth).isActive = true
  2258. wrapper.heightAnchor.constraint(equalToConstant: 94).isActive = true
  2259. wrapper.tag = plan.rawValue
  2260. let card = HoverTrackingView()
  2261. card.translatesAutoresizingMaskIntoConstraints = false
  2262. card.wantsLayer = true
  2263. card.layer?.cornerRadius = 16
  2264. card.layer?.backgroundColor = palette.sectionCard.cgColor
  2265. card.heightAnchor.constraint(equalToConstant: 82).isActive = true
  2266. wrapper.addSubview(card)
  2267. NSLayoutConstraint.activate([
  2268. card.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  2269. card.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  2270. card.topAnchor.constraint(equalTo: wrapper.topAnchor, constant: 12),
  2271. card.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor)
  2272. ])
  2273. styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  2274. let badgeLabel = textLabel(badge, font: NSFont.systemFont(ofSize: 10, weight: .bold), color: .white)
  2275. let badgeWrap = roundedContainer(cornerRadius: 10, color: badgeColor)
  2276. badgeWrap.translatesAutoresizingMaskIntoConstraints = false
  2277. badgeWrap.wantsLayer = true
  2278. badgeWrap.layer?.borderColor = NSColor(calibratedWhite: 1, alpha: 0.22).cgColor
  2279. badgeWrap.layer?.borderWidth = 1
  2280. badgeWrap.layer?.shadowColor = NSColor.black.cgColor
  2281. badgeWrap.layer?.shadowOpacity = 0.20
  2282. badgeWrap.layer?.shadowOffset = CGSize(width: 0, height: -1)
  2283. badgeWrap.layer?.shadowRadius = 3
  2284. badgeWrap.addSubview(badgeLabel)
  2285. NSLayoutConstraint.activate([
  2286. badgeLabel.leadingAnchor.constraint(equalTo: badgeWrap.leadingAnchor, constant: 8),
  2287. badgeLabel.trailingAnchor.constraint(equalTo: badgeWrap.trailingAnchor, constant: -8),
  2288. badgeLabel.topAnchor.constraint(equalTo: badgeWrap.topAnchor, constant: 2),
  2289. badgeLabel.bottomAnchor.constraint(equalTo: badgeWrap.bottomAnchor, constant: -2)
  2290. ])
  2291. wrapper.addSubview(badgeWrap)
  2292. let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: 15, weight: .bold), color: palette.primaryBlue)
  2293. card.addSubview(titleLabel)
  2294. let priceLabel = textLabel(price, font: NSFont.systemFont(ofSize: 12, weight: .bold), color: palette.textPrimary)
  2295. card.addSubview(priceLabel)
  2296. paywallPriceLabels[plan] = priceLabel
  2297. NSLayoutConstraint.activate([
  2298. badgeWrap.centerXAnchor.constraint(equalTo: card.centerXAnchor),
  2299. badgeWrap.centerYAnchor.constraint(equalTo: card.topAnchor),
  2300. titleLabel.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 16),
  2301. titleLabel.topAnchor.constraint(equalTo: card.topAnchor, constant: 34),
  2302. priceLabel.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -16),
  2303. priceLabel.topAnchor.constraint(equalTo: card.topAnchor, constant: 32)
  2304. ])
  2305. if let subtitle {
  2306. let sub = textLabel(subtitle, font: NSFont.systemFont(ofSize: 10, weight: .semibold), color: palette.textSecondary)
  2307. card.addSubview(sub)
  2308. paywallSubtitleLabels[plan] = sub
  2309. NSLayoutConstraint.activate([
  2310. sub.trailingAnchor.constraint(equalTo: priceLabel.trailingAnchor),
  2311. sub.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 0)
  2312. ])
  2313. }
  2314. if let strikePrice {
  2315. let strike = textLabel(strikePrice, font: NSFont.systemFont(ofSize: 12, weight: .medium), color: NSColor.systemRed)
  2316. card.addSubview(strike)
  2317. NSLayoutConstraint.activate([
  2318. strike.trailingAnchor.constraint(equalTo: priceLabel.trailingAnchor),
  2319. strike.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 4)
  2320. ])
  2321. }
  2322. paywallPlanViews[plan] = card
  2323. wrapper.onHoverChanged = { [weak self, weak card] hovering in
  2324. guard let self, let card else { return }
  2325. self.applyPaywallPlanStyle(card, isSelected: plan == self.selectedPremiumPlan, hovering: hovering)
  2326. }
  2327. wrapper.onHoverChanged?(false)
  2328. return wrapper
  2329. }
  2330. func paywallFooterLinks() -> NSView {
  2331. let wrap = NSView()
  2332. wrap.translatesAutoresizingMaskIntoConstraints = false
  2333. wrap.heightAnchor.constraint(equalToConstant: 34).isActive = true
  2334. wrap.widthAnchor.constraint(greaterThanOrEqualToConstant: paywallContentWidth).isActive = true
  2335. let row = NSStackView()
  2336. row.translatesAutoresizingMaskIntoConstraints = false
  2337. row.orientation = .horizontal
  2338. row.distribution = .fillEqually
  2339. row.alignment = .centerY
  2340. row.spacing = 0
  2341. wrap.addSubview(row)
  2342. row.addArrangedSubview(footerLink("Privacy Policy"))
  2343. row.addArrangedSubview(footerLink("Support"))
  2344. row.addArrangedSubview(footerLink("Terms of Services"))
  2345. NSLayoutConstraint.activate([
  2346. row.leadingAnchor.constraint(equalTo: wrap.leadingAnchor),
  2347. row.trailingAnchor.constraint(equalTo: wrap.trailingAnchor),
  2348. row.topAnchor.constraint(equalTo: wrap.topAnchor),
  2349. row.bottomAnchor.constraint(equalTo: wrap.bottomAnchor)
  2350. ])
  2351. return wrap
  2352. }
  2353. func footerLink(_ title: String) -> NSView {
  2354. let container = HoverTrackingView()
  2355. container.translatesAutoresizingMaskIntoConstraints = false
  2356. let label = textLabel(title, font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: palette.textSecondary)
  2357. label.alignment = .center
  2358. container.addSubview(label)
  2359. NSLayoutConstraint.activate([
  2360. label.centerXAnchor.constraint(equalTo: container.centerXAnchor),
  2361. label.centerYAnchor.constraint(equalTo: container.centerYAnchor)
  2362. ])
  2363. let click = NSClickGestureRecognizer(target: self, action: #selector(paywallFooterLinkClicked(_:)))
  2364. container.addGestureRecognizer(click)
  2365. container.onHoverChanged = { hovering in
  2366. label.textColor = hovering ? (self.darkModeEnabled ? .white : self.palette.textPrimary) : self.palette.textSecondary
  2367. }
  2368. container.onHoverChanged?(false)
  2369. return container
  2370. }
  2371. func paywallBenefitsSection() -> NSView {
  2372. let stack = NSStackView()
  2373. stack.translatesAutoresizingMaskIntoConstraints = false
  2374. stack.orientation = .vertical
  2375. stack.spacing = 8
  2376. stack.alignment = .leading
  2377. stack.widthAnchor.constraint(greaterThanOrEqualToConstant: paywallContentWidth).isActive = true
  2378. let rowOne = NSStackView()
  2379. rowOne.translatesAutoresizingMaskIntoConstraints = false
  2380. rowOne.orientation = .horizontal
  2381. rowOne.spacing = 10
  2382. rowOne.distribution = .fillEqually
  2383. rowOne.alignment = .centerY
  2384. rowOne.addArrangedSubview(paywallBenefitItem(icon: "📅", text: "Manage meetings"))
  2385. rowOne.addArrangedSubview(paywallBenefitItem(icon: "🖼️", text: "Virtual backgrounds"))
  2386. let rowTwo = NSStackView()
  2387. rowTwo.translatesAutoresizingMaskIntoConstraints = false
  2388. rowTwo.orientation = .horizontal
  2389. rowTwo.spacing = 10
  2390. rowTwo.distribution = .fillEqually
  2391. rowTwo.alignment = .centerY
  2392. rowTwo.addArrangedSubview(paywallBenefitItem(icon: "⚡", text: "Tools for productivity"))
  2393. rowTwo.addArrangedSubview(paywallBenefitItem(icon: "🛟", text: "24/7 support"))
  2394. stack.addArrangedSubview(rowOne)
  2395. stack.addArrangedSubview(rowTwo)
  2396. return stack
  2397. }
  2398. func paywallBenefitItem(icon: String, text: String) -> NSView {
  2399. let card = HoverTrackingView()
  2400. card.translatesAutoresizingMaskIntoConstraints = false
  2401. card.wantsLayer = true
  2402. card.layer?.cornerRadius = 10
  2403. card.layer?.backgroundColor = palette.inputBackground.cgColor
  2404. card.heightAnchor.constraint(equalToConstant: 36).isActive = true
  2405. styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  2406. let iconWrap = roundedContainer(cornerRadius: 8, color: palette.inputBackground)
  2407. iconWrap.translatesAutoresizingMaskIntoConstraints = false
  2408. iconWrap.widthAnchor.constraint(equalToConstant: 24).isActive = true
  2409. iconWrap.heightAnchor.constraint(equalToConstant: 24).isActive = true
  2410. styleSurface(iconWrap, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  2411. let iconLabel = textLabel(icon, font: NSFont.systemFont(ofSize: 12, weight: .medium), color: palette.primaryBlue)
  2412. iconWrap.addSubview(iconLabel)
  2413. NSLayoutConstraint.activate([
  2414. iconLabel.centerXAnchor.constraint(equalTo: iconWrap.centerXAnchor),
  2415. iconLabel.centerYAnchor.constraint(equalTo: iconWrap.centerYAnchor)
  2416. ])
  2417. let title = textLabel(text, font: NSFont.systemFont(ofSize: 11, weight: .medium), color: palette.textPrimary)
  2418. card.addSubview(iconWrap)
  2419. card.addSubview(title)
  2420. NSLayoutConstraint.activate([
  2421. iconWrap.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 8),
  2422. iconWrap.centerYAnchor.constraint(equalTo: card.centerYAnchor),
  2423. title.leadingAnchor.constraint(equalTo: iconWrap.trailingAnchor, constant: 10),
  2424. title.centerYAnchor.constraint(equalTo: card.centerYAnchor),
  2425. title.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -8)
  2426. ])
  2427. let base = palette.inputBackground
  2428. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  2429. let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
  2430. let hoverBorder = palette.primaryBlueBorder.withAlphaComponent(0.55)
  2431. card.onHoverChanged = { [weak card, weak iconWrap] hovering in
  2432. guard let card else { return }
  2433. card.layer?.backgroundColor = (hovering ? hover : base).cgColor
  2434. card.layer?.borderColor = (hovering ? hoverBorder : self.palette.inputBorder).cgColor
  2435. iconWrap?.layer?.borderColor = (hovering ? hoverBorder : self.palette.inputBorder).cgColor
  2436. }
  2437. card.onHoverChanged?(false)
  2438. return card
  2439. }
  2440. func zoomJoinModeTabs() -> NSView {
  2441. let row = NSStackView()
  2442. row.translatesAutoresizingMaskIntoConstraints = false
  2443. row.orientation = .horizontal
  2444. row.alignment = .centerY
  2445. row.spacing = 28
  2446. row.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
  2447. let idTab = joinModeTab("Join with ID", mode: .id)
  2448. let urlTab = joinModeTab("Join with URL", mode: .url)
  2449. row.addArrangedSubview(idTab)
  2450. row.addArrangedSubview(urlTab)
  2451. let spacer = NSView()
  2452. spacer.translatesAutoresizingMaskIntoConstraints = false
  2453. row.addArrangedSubview(spacer)
  2454. zoomJoinModeViews[.id] = idTab
  2455. zoomJoinModeViews[.url] = urlTab
  2456. updateZoomJoinModeAppearance()
  2457. return row
  2458. }
  2459. func joinModeTab(_ title: String, mode: ZoomJoinMode) -> NSView {
  2460. let tab = HoverTrackingView()
  2461. tab.translatesAutoresizingMaskIntoConstraints = false
  2462. tab.wantsLayer = true
  2463. tab.layer?.cornerRadius = 6
  2464. tab.layer?.backgroundColor = NSColor.clear.cgColor
  2465. tab.heightAnchor.constraint(equalToConstant: 30).isActive = true
  2466. zoomJoinModeByView[ObjectIdentifier(tab)] = mode
  2467. let label = textLabel(title, font: NSFont.systemFont(ofSize: 33 / 2, weight: .medium), color: palette.textPrimary)
  2468. tab.addSubview(label)
  2469. NSLayoutConstraint.activate([
  2470. label.leadingAnchor.constraint(equalTo: tab.leadingAnchor, constant: 4),
  2471. label.trailingAnchor.constraint(equalTo: tab.trailingAnchor, constant: -4),
  2472. label.topAnchor.constraint(equalTo: tab.topAnchor, constant: 4),
  2473. label.bottomAnchor.constraint(equalTo: tab.bottomAnchor, constant: -6)
  2474. ])
  2475. let click = NSClickGestureRecognizer(target: self, action: #selector(zoomJoinModeClicked(_:)))
  2476. tab.addGestureRecognizer(click)
  2477. return tab
  2478. }
  2479. func updateZoomJoinModeAppearance() {
  2480. for (mode, tab) in zoomJoinModeViews {
  2481. let selected = (mode == selectedZoomJoinMode)
  2482. let textColor = selected ? palette.textPrimary : palette.textSecondary
  2483. let label = tab.subviews.first { $0 is NSTextField } as? NSTextField
  2484. label?.textColor = textColor
  2485. // Keep the active tab visually underlined like the reference.
  2486. if selected {
  2487. if tab.subviews.contains(where: { $0.identifier?.rawValue == "modeUnderline" }) == false {
  2488. let underline = NSView()
  2489. underline.identifier = NSUserInterfaceItemIdentifier("modeUnderline")
  2490. underline.translatesAutoresizingMaskIntoConstraints = false
  2491. underline.wantsLayer = true
  2492. underline.layer?.backgroundColor = palette.primaryBlue.cgColor
  2493. tab.addSubview(underline)
  2494. NSLayoutConstraint.activate([
  2495. underline.leadingAnchor.constraint(equalTo: tab.leadingAnchor),
  2496. underline.trailingAnchor.constraint(equalTo: tab.trailingAnchor),
  2497. underline.bottomAnchor.constraint(equalTo: tab.bottomAnchor),
  2498. underline.heightAnchor.constraint(equalToConstant: 2)
  2499. ])
  2500. }
  2501. } else {
  2502. tab.subviews
  2503. .filter { $0.identifier?.rawValue == "modeUnderline" }
  2504. .forEach { $0.removeFromSuperview() }
  2505. }
  2506. }
  2507. }
  2508. func joinWithIDHeading() -> NSView {
  2509. let container = NSView()
  2510. container.translatesAutoresizingMaskIntoConstraints = false
  2511. let title = textLabel("Join with ID", font: typography.joinWithURLTitle, color: palette.textPrimary)
  2512. title.alignment = .left
  2513. title.setContentHuggingPriority(.defaultHigh, for: .horizontal)
  2514. title.setContentCompressionResistancePriority(.required, for: .horizontal)
  2515. let bar = NSView()
  2516. bar.translatesAutoresizingMaskIntoConstraints = false
  2517. bar.wantsLayer = true
  2518. bar.layer?.backgroundColor = palette.primaryBlue.cgColor
  2519. bar.heightAnchor.constraint(equalToConstant: 3).isActive = true
  2520. container.addSubview(title)
  2521. container.addSubview(bar)
  2522. NSLayoutConstraint.activate([
  2523. title.leadingAnchor.constraint(equalTo: container.leadingAnchor),
  2524. title.topAnchor.constraint(equalTo: container.topAnchor),
  2525. bar.leadingAnchor.constraint(equalTo: title.leadingAnchor),
  2526. bar.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 6),
  2527. bar.widthAnchor.constraint(equalTo: title.widthAnchor),
  2528. bar.bottomAnchor.constraint(equalTo: container.bottomAnchor),
  2529. container.trailingAnchor.constraint(equalTo: title.trailingAnchor)
  2530. ])
  2531. return container
  2532. }
  2533. func zoomMeetingIDSection() -> NSView {
  2534. let wrapper = NSView()
  2535. wrapper.translatesAutoresizingMaskIntoConstraints = false
  2536. let fieldsRow = NSStackView()
  2537. fieldsRow.translatesAutoresizingMaskIntoConstraints = false
  2538. fieldsRow.orientation = .horizontal
  2539. fieldsRow.alignment = .top
  2540. fieldsRow.distribution = .fillEqually
  2541. fieldsRow.spacing = 12
  2542. fieldsRow.addArrangedSubview(zoomInputField(title: "Meeting ID", placeholder: "Enter meeting ID..."))
  2543. fieldsRow.addArrangedSubview(zoomInputField(title: "Meeting Passcode", placeholder: "Enter meeting passcode..."))
  2544. let actions = NSStackView()
  2545. actions.orientation = .horizontal
  2546. actions.spacing = 10
  2547. actions.translatesAutoresizingMaskIntoConstraints = false
  2548. actions.alignment = .centerY
  2549. actions.addArrangedSubview(actionButton(title: "Cancel", color: palette.cancelButton, textColor: palette.textSecondary, width: 110))
  2550. actions.addArrangedSubview(actionButton(title: "Join", color: palette.primaryBlue, textColor: .white, width: 116))
  2551. wrapper.addSubview(fieldsRow)
  2552. wrapper.addSubview(actions)
  2553. NSLayoutConstraint.activate([
  2554. wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 780),
  2555. fieldsRow.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  2556. fieldsRow.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  2557. fieldsRow.topAnchor.constraint(equalTo: wrapper.topAnchor),
  2558. actions.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  2559. actions.topAnchor.constraint(equalTo: fieldsRow.bottomAnchor, constant: 14),
  2560. actions.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor)
  2561. ])
  2562. return wrapper
  2563. }
  2564. func zoomInputField(title: String, placeholder: String) -> NSView {
  2565. let wrapper = NSView()
  2566. wrapper.translatesAutoresizingMaskIntoConstraints = false
  2567. let heading = textLabel(title, font: typography.fieldLabel, color: palette.textPrimary)
  2568. let textFieldContainer = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
  2569. textFieldContainer.translatesAutoresizingMaskIntoConstraints = false
  2570. textFieldContainer.heightAnchor.constraint(equalToConstant: 40).isActive = true
  2571. styleSurface(textFieldContainer, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  2572. let field = NSTextField(string: "")
  2573. field.translatesAutoresizingMaskIntoConstraints = false
  2574. field.isEditable = true
  2575. field.isSelectable = true
  2576. field.isBordered = false
  2577. field.drawsBackground = false
  2578. field.placeholderString = placeholder
  2579. field.font = typography.inputPlaceholder
  2580. field.textColor = palette.textPrimary
  2581. field.focusRingType = .none
  2582. textFieldContainer.addSubview(field)
  2583. wrapper.addSubview(heading)
  2584. wrapper.addSubview(textFieldContainer)
  2585. NSLayoutConstraint.activate([
  2586. heading.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  2587. heading.topAnchor.constraint(equalTo: wrapper.topAnchor),
  2588. textFieldContainer.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  2589. textFieldContainer.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  2590. textFieldContainer.topAnchor.constraint(equalTo: heading.bottomAnchor, constant: 10),
  2591. textFieldContainer.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor),
  2592. field.leadingAnchor.constraint(equalTo: textFieldContainer.leadingAnchor, constant: 12),
  2593. field.trailingAnchor.constraint(equalTo: textFieldContainer.trailingAnchor, constant: -12),
  2594. field.centerYAnchor.constraint(equalTo: textFieldContainer.centerYAnchor)
  2595. ])
  2596. return wrapper
  2597. }
  2598. func joinWithURLHeading() -> NSView {
  2599. let container = NSView()
  2600. container.translatesAutoresizingMaskIntoConstraints = false
  2601. let title = textLabel("Join with URL", font: typography.joinWithURLTitle, color: palette.textPrimary)
  2602. title.alignment = .left
  2603. title.setContentHuggingPriority(.defaultHigh, for: .horizontal)
  2604. title.setContentCompressionResistancePriority(.required, for: .horizontal)
  2605. let bar = NSView()
  2606. bar.translatesAutoresizingMaskIntoConstraints = false
  2607. bar.wantsLayer = true
  2608. bar.layer?.backgroundColor = palette.primaryBlue.cgColor
  2609. bar.heightAnchor.constraint(equalToConstant: 3).isActive = true
  2610. container.addSubview(title)
  2611. container.addSubview(bar)
  2612. NSLayoutConstraint.activate([
  2613. title.leadingAnchor.constraint(equalTo: container.leadingAnchor),
  2614. title.topAnchor.constraint(equalTo: container.topAnchor),
  2615. bar.leadingAnchor.constraint(equalTo: title.leadingAnchor),
  2616. bar.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 6),
  2617. bar.widthAnchor.constraint(equalTo: title.widthAnchor),
  2618. bar.bottomAnchor.constraint(equalTo: container.bottomAnchor),
  2619. container.trailingAnchor.constraint(equalTo: title.trailingAnchor)
  2620. ])
  2621. return container
  2622. }
  2623. func meetingUrlSection() -> NSView {
  2624. let wrapper = NSView()
  2625. wrapper.translatesAutoresizingMaskIntoConstraints = false
  2626. let title = textLabel("Meeting URL", font: typography.fieldLabel, color: palette.textSecondary)
  2627. let textFieldContainer = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
  2628. textFieldContainer.translatesAutoresizingMaskIntoConstraints = false
  2629. textFieldContainer.heightAnchor.constraint(equalToConstant: 40).isActive = true
  2630. styleSurface(textFieldContainer, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  2631. let urlField = NSTextField(string: "")
  2632. urlField.translatesAutoresizingMaskIntoConstraints = false
  2633. urlField.isEditable = true
  2634. urlField.isSelectable = true
  2635. urlField.isBordered = false
  2636. urlField.drawsBackground = false
  2637. urlField.placeholderString = "Enter meeting URL..."
  2638. urlField.font = typography.inputPlaceholder
  2639. urlField.textColor = palette.textPrimary
  2640. urlField.focusRingType = .none
  2641. textFieldContainer.addSubview(urlField)
  2642. let actions = NSStackView()
  2643. actions.orientation = .horizontal
  2644. actions.spacing = 10
  2645. actions.translatesAutoresizingMaskIntoConstraints = false
  2646. actions.alignment = .centerY
  2647. actions.addArrangedSubview(actionButton(title: "Cancel", color: palette.cancelButton, textColor: palette.textSecondary, width: 110))
  2648. actions.addArrangedSubview(actionButton(title: "Join", color: palette.primaryBlue, textColor: .white, width: 116))
  2649. wrapper.addSubview(title)
  2650. wrapper.addSubview(textFieldContainer)
  2651. wrapper.addSubview(actions)
  2652. NSLayoutConstraint.activate([
  2653. wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 780),
  2654. title.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  2655. title.topAnchor.constraint(equalTo: wrapper.topAnchor),
  2656. textFieldContainer.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  2657. textFieldContainer.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  2658. textFieldContainer.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 10),
  2659. urlField.leadingAnchor.constraint(equalTo: textFieldContainer.leadingAnchor, constant: 12),
  2660. urlField.trailingAnchor.constraint(equalTo: textFieldContainer.trailingAnchor, constant: -12),
  2661. urlField.centerYAnchor.constraint(equalTo: textFieldContainer.centerYAnchor),
  2662. actions.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  2663. actions.topAnchor.constraint(equalTo: textFieldContainer.bottomAnchor, constant: 14),
  2664. actions.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor)
  2665. ])
  2666. return wrapper
  2667. }
  2668. func scheduleHeader() -> NSView {
  2669. let row = NSStackView()
  2670. row.translatesAutoresizingMaskIntoConstraints = false
  2671. row.orientation = .horizontal
  2672. row.alignment = .centerY
  2673. row.distribution = .fill
  2674. row.spacing = 12
  2675. row.addArrangedSubview(textLabel("Schedule", font: typography.sectionTitleBold, color: palette.textPrimary))
  2676. let spacer = NSView()
  2677. spacer.translatesAutoresizingMaskIntoConstraints = false
  2678. row.addArrangedSubview(spacer)
  2679. spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  2680. row.addArrangedSubview(makeScheduleRefreshButton())
  2681. row.addArrangedSubview(makeScheduleFilterDropdown())
  2682. row.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
  2683. return row
  2684. }
  2685. private func schedulePageHeader() -> NSView {
  2686. let container = NSStackView()
  2687. container.translatesAutoresizingMaskIntoConstraints = false
  2688. container.userInterfaceLayoutDirection = .leftToRight
  2689. container.orientation = .vertical
  2690. container.spacing = 8
  2691. container.alignment = .width
  2692. let titleRow = NSStackView()
  2693. titleRow.translatesAutoresizingMaskIntoConstraints = false
  2694. titleRow.userInterfaceLayoutDirection = .leftToRight
  2695. titleRow.orientation = .horizontal
  2696. titleRow.alignment = .centerY
  2697. titleRow.distribution = .fill
  2698. titleRow.spacing = 0
  2699. let titleLabel = textLabel("Schedule", font: typography.pageTitle, color: palette.textPrimary)
  2700. titleLabel.alignment = .left
  2701. titleLabel.userInterfaceLayoutDirection = .leftToRight
  2702. titleLabel.maximumNumberOfLines = 1
  2703. titleLabel.lineBreakMode = .byTruncatingTail
  2704. titleLabel.setContentHuggingPriority(.required, for: .horizontal)
  2705. titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
  2706. let titleRowSpacer = NSView()
  2707. titleRowSpacer.translatesAutoresizingMaskIntoConstraints = false
  2708. titleRowSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  2709. titleRowSpacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  2710. titleRow.addArrangedSubview(titleLabel)
  2711. titleRow.addArrangedSubview(makeSchedulePageAddButton())
  2712. titleRow.setCustomSpacing(12, after: titleLabel)
  2713. titleRow.addArrangedSubview(titleRowSpacer)
  2714. container.addArrangedSubview(titleRow)
  2715. let filterRow = NSStackView()
  2716. filterRow.translatesAutoresizingMaskIntoConstraints = false
  2717. filterRow.userInterfaceLayoutDirection = .leftToRight
  2718. filterRow.orientation = .horizontal
  2719. filterRow.alignment = .centerY
  2720. filterRow.spacing = 18
  2721. filterRow.distribution = .fill
  2722. let filterDropdown = makeSchedulePageFilterDropdown()
  2723. schedulePageFilterDropdown = filterDropdown
  2724. filterRow.addArrangedSubview(filterDropdown)
  2725. filterRow.setCustomSpacing(20, after: filterDropdown)
  2726. let (fromShell, fromPicker) = makeScheduleDatePicker(date: schedulePageFromDate)
  2727. schedulePageFromDatePicker = fromPicker
  2728. filterRow.addArrangedSubview(fromShell)
  2729. filterRow.setCustomSpacing(16, after: fromShell)
  2730. let (toShell, toPicker) = makeScheduleDatePicker(date: schedulePageToDate)
  2731. schedulePageToDatePicker = toPicker
  2732. filterRow.addArrangedSubview(toShell)
  2733. NSLayoutConstraint.activate([
  2734. fromShell.widthAnchor.constraint(equalTo: toShell.widthAnchor),
  2735. fromShell.widthAnchor.constraint(greaterThanOrEqualToConstant: 152)
  2736. ])
  2737. let filterRowSpacer = NSView()
  2738. filterRowSpacer.translatesAutoresizingMaskIntoConstraints = false
  2739. filterRowSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  2740. filterRowSpacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  2741. filterRow.addArrangedSubview(filterRowSpacer)
  2742. let applyButton = makeSchedulePagePillButton(title: "Apply", action: #selector(schedulePageApplyDateRangePressed(_:)))
  2743. filterRow.addArrangedSubview(applyButton)
  2744. filterRow.setCustomSpacing(22, after: applyButton)
  2745. let resetButton = makeSchedulePagePillButton(title: "Reset", action: #selector(schedulePageResetFiltersPressed(_:)))
  2746. filterRow.addArrangedSubview(resetButton)
  2747. filterRow.setCustomSpacing(22, after: resetButton)
  2748. filterRow.addArrangedSubview(makeScheduleRefreshButton())
  2749. container.addArrangedSubview(filterRow)
  2750. NSLayoutConstraint.activate([
  2751. titleRow.widthAnchor.constraint(equalTo: container.widthAnchor),
  2752. filterRow.widthAnchor.constraint(equalTo: container.widthAnchor)
  2753. ])
  2754. refreshSchedulePageDateFilterUI()
  2755. return container
  2756. }
  2757. private func makeSchedulePageFilterDropdown() -> NSPopUpButton {
  2758. let button = HoverPopUpButton(frame: .zero, pullsDown: false)
  2759. button.translatesAutoresizingMaskIntoConstraints = false
  2760. button.autoenablesItems = false
  2761. button.isBordered = false
  2762. button.bezelStyle = .regularSquare
  2763. button.wantsLayer = true
  2764. button.layer?.cornerRadius = 8
  2765. button.layer?.masksToBounds = true
  2766. button.layer?.backgroundColor = palette.inputBackground.cgColor
  2767. button.layer?.borderColor = palette.inputBorder.cgColor
  2768. button.layer?.borderWidth = 1
  2769. button.font = typography.filterText
  2770. button.contentTintColor = palette.textSecondary
  2771. button.target = self
  2772. button.action = #selector(schedulePageFilterDropdownChanged(_:))
  2773. button.heightAnchor.constraint(equalToConstant: 34).isActive = true
  2774. button.widthAnchor.constraint(equalToConstant: 228).isActive = true
  2775. button.removeAllItems()
  2776. button.addItems(withTitles: ["All", "Today", "This week", "This month", "Custom range"])
  2777. button.selectItem(at: schedulePageFilter.rawValue)
  2778. if let menu = button.menu {
  2779. for (index, item) in menu.items.enumerated() {
  2780. item.tag = index
  2781. }
  2782. }
  2783. let baseColor = palette.inputBackground
  2784. let baseBorder = palette.inputBorder
  2785. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  2786. let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  2787. let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
  2788. button.onHoverChanged = { [weak button] hovering in
  2789. button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  2790. button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
  2791. }
  2792. button.onHoverChanged?(false)
  2793. return button
  2794. }
  2795. /// Rounded shell matching `makeSchedulePageFilterDropdown` (34pt, 8pt corner, border + hover). Both pickers use the same field+stepper style inside the shell.
  2796. private func makeScheduleDatePicker(date: Date) -> (NSView, NSDatePicker) {
  2797. let shell = HoverSurfaceView()
  2798. shell.translatesAutoresizingMaskIntoConstraints = false
  2799. shell.wantsLayer = true
  2800. shell.layer?.cornerRadius = 8
  2801. shell.layer?.masksToBounds = true
  2802. shell.layer?.borderWidth = 1
  2803. let baseColor = palette.inputBackground
  2804. let baseBorder = palette.inputBorder
  2805. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  2806. let hoverBackground = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  2807. let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
  2808. func applyShellIdleAppearance() {
  2809. shell.layer?.backgroundColor = baseColor.cgColor
  2810. shell.layer?.borderColor = baseBorder.cgColor
  2811. }
  2812. applyShellIdleAppearance()
  2813. shell.onHoverChanged = { [weak shell] hovering in
  2814. guard let shell else { return }
  2815. shell.layer?.backgroundColor = (hovering ? hoverBackground : baseColor).cgColor
  2816. shell.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
  2817. }
  2818. let picker = NSDatePicker()
  2819. picker.translatesAutoresizingMaskIntoConstraints = false
  2820. picker.isBordered = false
  2821. picker.drawsBackground = false
  2822. picker.focusRingType = .none
  2823. picker.datePickerStyle = .textFieldAndStepper
  2824. picker.datePickerElements = [.yearMonthDay]
  2825. picker.dateValue = date
  2826. picker.font = typography.filterText
  2827. picker.textColor = palette.textSecondary
  2828. picker.setContentHuggingPriority(.defaultLow, for: .horizontal)
  2829. picker.target = self
  2830. picker.action = #selector(schedulePageDatePickerChanged(_:))
  2831. shell.addSubview(picker)
  2832. NSLayoutConstraint.activate([
  2833. shell.heightAnchor.constraint(equalToConstant: 34),
  2834. picker.leadingAnchor.constraint(equalTo: shell.leadingAnchor, constant: 8),
  2835. picker.trailingAnchor.constraint(equalTo: shell.trailingAnchor, constant: -8),
  2836. picker.centerYAnchor.constraint(equalTo: shell.centerYAnchor)
  2837. ])
  2838. return (shell, picker)
  2839. }
  2840. private func makeSchedulePagePillButton(title: String, action: Selector) -> NSButton {
  2841. let button = makeSchedulePillButton(title: title)
  2842. button.target = self
  2843. button.action = action
  2844. button.widthAnchor.constraint(equalToConstant: 100).isActive = true
  2845. return button
  2846. }
  2847. private func makeSchedulePageCardsContainer() -> NSView {
  2848. if let observer = schedulePageScrollObservation {
  2849. NotificationCenter.default.removeObserver(observer)
  2850. }
  2851. schedulePageScrollObservation = nil
  2852. let wrapper = NSView()
  2853. wrapper.translatesAutoresizingMaskIntoConstraints = false
  2854. wrapper.userInterfaceLayoutDirection = .leftToRight
  2855. let scroll = NSScrollView()
  2856. scroll.translatesAutoresizingMaskIntoConstraints = false
  2857. scroll.userInterfaceLayoutDirection = .leftToRight
  2858. scroll.drawsBackground = false
  2859. scroll.hasHorizontalScroller = false
  2860. scroll.hasVerticalScroller = true
  2861. scroll.autohidesScrollers = true
  2862. scroll.borderType = .noBorder
  2863. scroll.scrollerStyle = .overlay
  2864. scroll.automaticallyAdjustsContentInsets = false
  2865. let clip = TopAlignedClipView()
  2866. clip.drawsBackground = false
  2867. clip.postsBoundsChangedNotifications = true
  2868. scroll.contentView = clip
  2869. schedulePageCardsScrollView = scroll
  2870. wrapper.addSubview(scroll)
  2871. let stack = NSStackView()
  2872. stack.translatesAutoresizingMaskIntoConstraints = false
  2873. stack.userInterfaceLayoutDirection = .leftToRight
  2874. stack.orientation = .vertical
  2875. stack.spacing = schedulePageCardSpacing
  2876. stack.alignment = .width
  2877. schedulePageCardsStack = stack
  2878. scroll.documentView = stack
  2879. NSLayoutConstraint.activate([
  2880. scroll.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  2881. scroll.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  2882. scroll.topAnchor.constraint(equalTo: wrapper.topAnchor),
  2883. scroll.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor),
  2884. scroll.heightAnchor.constraint(greaterThanOrEqualToConstant: 420),
  2885. stack.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
  2886. stack.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
  2887. stack.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
  2888. stack.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor)
  2889. ])
  2890. scroll.contentView.postsBoundsChangedNotifications = true
  2891. schedulePageScrollObservation = NotificationCenter.default.addObserver(
  2892. forName: NSView.boundsDidChangeNotification,
  2893. object: scroll.contentView,
  2894. queue: .main
  2895. ) { [weak self] _ in
  2896. self?.schedulePageScrolled()
  2897. }
  2898. renderSchedulePageCards()
  2899. return wrapper
  2900. }
  2901. private func scheduleTopAuthRow() -> NSView {
  2902. let row = NSStackView()
  2903. row.translatesAutoresizingMaskIntoConstraints = false
  2904. row.orientation = .horizontal
  2905. row.alignment = .centerY
  2906. row.spacing = 10
  2907. let spacer = NSView()
  2908. spacer.translatesAutoresizingMaskIntoConstraints = false
  2909. row.addArrangedSubview(spacer)
  2910. spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  2911. let host = GoogleProfileAuthHostView()
  2912. host.translatesAutoresizingMaskIntoConstraints = false
  2913. let authButton = makeGoogleAuthButton()
  2914. host.authButton = authButton
  2915. scheduleGoogleAuthHostView = host
  2916. scheduleGoogleAuthButton = authButton
  2917. host.addSubview(authButton)
  2918. NSLayoutConstraint.activate([
  2919. authButton.centerXAnchor.constraint(equalTo: host.centerXAnchor),
  2920. authButton.centerYAnchor.constraint(equalTo: host.centerYAnchor)
  2921. ])
  2922. let hostPadW = host.widthAnchor.constraint(equalTo: authButton.widthAnchor, constant: 0)
  2923. let hostPadH = host.heightAnchor.constraint(equalTo: authButton.heightAnchor, constant: 0)
  2924. hostPadW.isActive = true
  2925. hostPadH.isActive = true
  2926. scheduleGoogleAuthHostPadWidthConstraint = hostPadW
  2927. scheduleGoogleAuthHostPadHeightConstraint = hostPadH
  2928. updateGoogleAuthButtonTitle()
  2929. row.addArrangedSubview(host)
  2930. row.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
  2931. return row
  2932. }
  2933. private func makeScheduleFilterDropdown() -> NSPopUpButton {
  2934. let button = HoverPopUpButton(frame: .zero, pullsDown: false)
  2935. button.translatesAutoresizingMaskIntoConstraints = false
  2936. button.autoenablesItems = false
  2937. button.isBordered = false
  2938. button.bezelStyle = .regularSquare
  2939. button.wantsLayer = true
  2940. button.layer?.cornerRadius = 8
  2941. button.layer?.masksToBounds = true
  2942. button.layer?.backgroundColor = palette.inputBackground.cgColor
  2943. button.layer?.borderColor = palette.inputBorder.cgColor
  2944. button.layer?.borderWidth = 1
  2945. button.font = typography.filterText
  2946. button.contentTintColor = palette.textSecondary
  2947. button.target = self
  2948. button.action = #selector(scheduleFilterDropdownChanged(_:))
  2949. button.heightAnchor.constraint(equalToConstant: 34).isActive = true
  2950. button.widthAnchor.constraint(equalToConstant: 156).isActive = true
  2951. button.removeAllItems()
  2952. button.addItems(withTitles: ["All", "Today", "This week"])
  2953. button.selectItem(at: scheduleFilter.rawValue)
  2954. if let menu = button.menu {
  2955. for (index, item) in menu.items.enumerated() {
  2956. item.tag = index
  2957. }
  2958. }
  2959. let baseColor = palette.inputBackground
  2960. let baseBorder = palette.inputBorder
  2961. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  2962. let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  2963. let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
  2964. button.onHoverChanged = { [weak button] hovering in
  2965. button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  2966. button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
  2967. }
  2968. button.onHoverChanged?(false)
  2969. scheduleFilterDropdown = button
  2970. return button
  2971. }
  2972. private func makeSchedulePillButton(title: String) -> NSButton {
  2973. let button = NSButton(title: title, target: nil, action: nil)
  2974. button.translatesAutoresizingMaskIntoConstraints = false
  2975. button.isBordered = false
  2976. button.bezelStyle = .regularSquare
  2977. button.wantsLayer = true
  2978. button.layer?.cornerRadius = 8
  2979. button.layer?.backgroundColor = palette.inputBackground.cgColor
  2980. button.layer?.borderColor = palette.inputBorder.cgColor
  2981. button.layer?.borderWidth = 1
  2982. button.font = typography.filterText
  2983. button.contentTintColor = palette.textSecondary
  2984. button.setButtonType(.momentaryChange)
  2985. button.heightAnchor.constraint(equalToConstant: 34).isActive = true
  2986. button.widthAnchor.constraint(greaterThanOrEqualToConstant: 132).isActive = true
  2987. return button
  2988. }
  2989. private func makeGoogleAuthButton() -> NSButton {
  2990. let button = HoverButton(title: "", target: self, action: #selector(scheduleConnectButtonPressed(_:)))
  2991. button.translatesAutoresizingMaskIntoConstraints = false
  2992. button.isBordered = false
  2993. button.bezelStyle = .regularSquare
  2994. button.wantsLayer = true
  2995. button.layer?.cornerRadius = 16
  2996. button.layer?.borderWidth = 1
  2997. button.font = NSFont.systemFont(ofSize: 14, weight: .semibold)
  2998. button.imagePosition = .imageLeading
  2999. button.alignment = .center
  3000. button.imageHugsTitle = true
  3001. button.lineBreakMode = .byTruncatingTail
  3002. button.contentTintColor = palette.textPrimary
  3003. button.imageScaling = .scaleNone
  3004. button.layer?.masksToBounds = true
  3005. let heightConstraint = button.heightAnchor.constraint(equalToConstant: 42)
  3006. heightConstraint.isActive = true
  3007. scheduleGoogleAuthButtonHeightConstraint = heightConstraint
  3008. let widthConstraint = button.widthAnchor.constraint(equalToConstant: 248)
  3009. widthConstraint.isActive = true
  3010. scheduleGoogleAuthButtonWidthConstraint = widthConstraint
  3011. button.onHoverChanged = { [weak self] hovering in
  3012. self?.scheduleGoogleAuthHovering = hovering
  3013. self?.scheduleGoogleAuthHostView?.setProfileHoverActive(hovering)
  3014. self?.applyGoogleAuthButtonSurface()
  3015. }
  3016. button.onHoverChanged?(false)
  3017. return button
  3018. }
  3019. private func makeSchedulePageAddButton() -> NSButton {
  3020. let diameter: CGFloat = 30
  3021. let button = HoverButton(title: "", target: self, action: #selector(schedulePageAddMeetingPressed(_:)))
  3022. button.translatesAutoresizingMaskIntoConstraints = false
  3023. button.isBordered = false
  3024. button.bezelStyle = .regularSquare
  3025. button.wantsLayer = true
  3026. button.layer?.cornerRadius = diameter / 2
  3027. button.layer?.masksToBounds = true
  3028. button.layer?.backgroundColor = palette.inputBackground.cgColor
  3029. button.layer?.borderColor = palette.inputBorder.cgColor
  3030. button.layer?.borderWidth = 1
  3031. button.setButtonType(.momentaryChange)
  3032. button.contentTintColor = palette.textSecondary
  3033. button.image = NSImage(systemSymbolName: "plus", accessibilityDescription: "Schedule meeting")
  3034. button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .semibold)
  3035. button.imagePosition = .imageOnly
  3036. button.imageScaling = .scaleProportionallyDown
  3037. button.focusRingType = .none
  3038. button.heightAnchor.constraint(equalToConstant: diameter).isActive = true
  3039. button.widthAnchor.constraint(equalToConstant: diameter).isActive = true
  3040. let baseColor = palette.inputBackground
  3041. let baseBorder = palette.inputBorder
  3042. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  3043. let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  3044. let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
  3045. button.onHoverChanged = { [weak button] hovering in
  3046. button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  3047. button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
  3048. }
  3049. button.onHoverChanged?(false)
  3050. return button
  3051. }
  3052. private func makeScheduleRefreshButton() -> NSButton {
  3053. let diameter: CGFloat = 30
  3054. let button = HoverButton(title: "", target: self, action: #selector(scheduleReloadButtonPressed(_:)))
  3055. button.translatesAutoresizingMaskIntoConstraints = false
  3056. button.isBordered = false
  3057. button.bezelStyle = .regularSquare
  3058. button.wantsLayer = true
  3059. button.layer?.cornerRadius = diameter / 2
  3060. button.layer?.masksToBounds = true
  3061. button.layer?.backgroundColor = palette.inputBackground.cgColor
  3062. button.layer?.borderColor = palette.inputBorder.cgColor
  3063. button.layer?.borderWidth = 1
  3064. button.setButtonType(.momentaryChange)
  3065. button.contentTintColor = palette.textSecondary
  3066. button.image = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: "Refresh meetings")
  3067. button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .semibold)
  3068. button.imagePosition = .imageOnly
  3069. button.imageScaling = .scaleProportionallyDown
  3070. button.focusRingType = .none
  3071. button.heightAnchor.constraint(equalToConstant: diameter).isActive = true
  3072. button.widthAnchor.constraint(equalToConstant: diameter).isActive = true
  3073. let baseColor = palette.inputBackground
  3074. let baseBorder = palette.inputBorder
  3075. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  3076. let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  3077. let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
  3078. button.onHoverChanged = { [weak button] hovering in
  3079. button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  3080. button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
  3081. }
  3082. button.onHoverChanged?(false)
  3083. return button
  3084. }
  3085. func scheduleCardsRow(meetings: [ScheduledMeeting]) -> NSView {
  3086. let cardWidth: CGFloat = 240
  3087. let cardsPerViewport: CGFloat = 3
  3088. let viewportWidth = (cardWidth * cardsPerViewport) + (12 * (cardsPerViewport - 1))
  3089. let wrapper = NSStackView()
  3090. wrapper.translatesAutoresizingMaskIntoConstraints = false
  3091. wrapper.orientation = .horizontal
  3092. wrapper.alignment = .centerY
  3093. wrapper.spacing = 10
  3094. let leftButton = makeScheduleScrollButton(systemSymbol: "chevron.left", action: #selector(scheduleScrollLeftPressed(_:)))
  3095. scheduleScrollLeftButton = leftButton
  3096. wrapper.addArrangedSubview(leftButton)
  3097. let scroll = NSScrollView()
  3098. scheduleCardsScrollView = scroll
  3099. scroll.translatesAutoresizingMaskIntoConstraints = false
  3100. scroll.drawsBackground = false
  3101. scroll.hasHorizontalScroller = false
  3102. scroll.hasVerticalScroller = false
  3103. scroll.horizontalScrollElasticity = .allowed
  3104. scroll.verticalScrollElasticity = .none
  3105. scroll.autohidesScrollers = false
  3106. scroll.borderType = .noBorder
  3107. scroll.automaticallyAdjustsContentInsets = false
  3108. scroll.heightAnchor.constraint(equalToConstant: 150).isActive = true
  3109. scroll.widthAnchor.constraint(equalToConstant: viewportWidth).isActive = true
  3110. let row = NSStackView()
  3111. row.translatesAutoresizingMaskIntoConstraints = false
  3112. row.orientation = .horizontal
  3113. row.spacing = 12
  3114. row.alignment = .top
  3115. row.distribution = .gravityAreas
  3116. row.setContentHuggingPriority(.defaultHigh, for: .horizontal)
  3117. row.heightAnchor.constraint(equalToConstant: 150).isActive = true
  3118. scheduleCardsStack = row
  3119. scroll.documentView = row
  3120. scroll.contentView.postsBoundsChangedNotifications = true
  3121. // Pin top/leading/trailing only; avoid bottom == clip so the horizontal stack is not stretched vertically inside the clip (same as Schedule cards scroll).
  3122. NSLayoutConstraint.activate([
  3123. row.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
  3124. row.trailingAnchor.constraint(greaterThanOrEqualTo: scroll.contentView.trailingAnchor),
  3125. row.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
  3126. row.heightAnchor.constraint(equalToConstant: 150)
  3127. ])
  3128. renderScheduleCards(into: row, meetings: meetings)
  3129. wrapper.addArrangedSubview(scroll)
  3130. let rightButton = makeScheduleScrollButton(systemSymbol: "chevron.right", action: #selector(scheduleScrollRightPressed(_:)))
  3131. scheduleScrollRightButton = rightButton
  3132. wrapper.addArrangedSubview(rightButton)
  3133. scroll.setContentHuggingPriority(.defaultLow, for: .horizontal)
  3134. scroll.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  3135. wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
  3136. return wrapper
  3137. }
  3138. func scheduleCard(meeting: ScheduledMeeting, useFlexibleWidth: Bool = false, contentHeight: CGFloat = 150) -> NSView {
  3139. let cardWidth: CGFloat = 240
  3140. let card = roundedContainer(cornerRadius: 12, color: palette.sectionCard)
  3141. styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: true)
  3142. card.translatesAutoresizingMaskIntoConstraints = false
  3143. card.heightAnchor.constraint(equalToConstant: contentHeight).isActive = true
  3144. if useFlexibleWidth {
  3145. card.setContentHuggingPriority(.defaultLow, for: .horizontal)
  3146. card.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  3147. } else {
  3148. card.widthAnchor.constraint(equalToConstant: cardWidth).isActive = true
  3149. card.setContentHuggingPriority(.required, for: .horizontal)
  3150. card.setContentCompressionResistancePriority(.required, for: .horizontal)
  3151. }
  3152. let icon = roundedContainer(cornerRadius: 8, color: palette.meetingBadge)
  3153. icon.translatesAutoresizingMaskIntoConstraints = false
  3154. icon.widthAnchor.constraint(equalToConstant: 28).isActive = true
  3155. icon.heightAnchor.constraint(equalToConstant: 28).isActive = true
  3156. let iconView = NSImageView()
  3157. iconView.translatesAutoresizingMaskIntoConstraints = false
  3158. iconView.image = NSImage(systemSymbolName: "video.circle.fill", accessibilityDescription: "Meeting")
  3159. iconView.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 18, weight: .semibold)
  3160. iconView.contentTintColor = .white
  3161. icon.addSubview(iconView)
  3162. NSLayoutConstraint.activate([
  3163. iconView.centerXAnchor.constraint(equalTo: icon.centerXAnchor),
  3164. iconView.centerYAnchor.constraint(equalTo: icon.centerYAnchor)
  3165. ])
  3166. let title = textLabel(meeting.title, font: typography.cardTitle, color: palette.textPrimary)
  3167. title.lineBreakMode = .byTruncatingTail
  3168. title.maximumNumberOfLines = 1
  3169. title.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  3170. let subtitle = textLabel(meeting.subtitle ?? "Google Calendar", font: typography.cardSubtitle, color: palette.textPrimary)
  3171. let time = textLabel(scheduleTimeText(for: meeting), font: typography.cardTime, color: palette.textSecondary)
  3172. let duration = textLabel(scheduleDurationText(for: meeting), font: NSFont.systemFont(ofSize: 11, weight: .medium), color: palette.textMuted)
  3173. let dayChip = roundedContainer(cornerRadius: 7, color: palette.inputBackground)
  3174. dayChip.translatesAutoresizingMaskIntoConstraints = false
  3175. dayChip.layer?.borderWidth = 1
  3176. dayChip.layer?.borderColor = palette.inputBorder.withAlphaComponent(0.8).cgColor
  3177. let dayText = textLabel(scheduleDayText(for: meeting), font: NSFont.systemFont(ofSize: 11, weight: .semibold), color: palette.textSecondary)
  3178. dayText.translatesAutoresizingMaskIntoConstraints = false
  3179. dayChip.addSubview(dayText)
  3180. NSLayoutConstraint.activate([
  3181. dayText.leadingAnchor.constraint(equalTo: dayChip.leadingAnchor, constant: 8),
  3182. dayText.trailingAnchor.constraint(equalTo: dayChip.trailingAnchor, constant: -8),
  3183. dayText.topAnchor.constraint(equalTo: dayChip.topAnchor, constant: 4),
  3184. dayText.bottomAnchor.constraint(equalTo: dayChip.bottomAnchor, constant: -4)
  3185. ])
  3186. card.addSubview(icon)
  3187. card.addSubview(dayChip)
  3188. card.addSubview(title)
  3189. card.addSubview(subtitle)
  3190. card.addSubview(time)
  3191. card.addSubview(duration)
  3192. var titleConstraints: [NSLayoutConstraint] = [
  3193. icon.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
  3194. icon.topAnchor.constraint(equalTo: card.topAnchor, constant: 10),
  3195. dayChip.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -10),
  3196. dayChip.centerYAnchor.constraint(equalTo: icon.centerYAnchor),
  3197. title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 6),
  3198. title.centerYAnchor.constraint(equalTo: icon.centerYAnchor),
  3199. title.trailingAnchor.constraint(lessThanOrEqualTo: dayChip.leadingAnchor, constant: -8)
  3200. ]
  3201. if !useFlexibleWidth {
  3202. titleConstraints.append(title.widthAnchor.constraint(lessThanOrEqualToConstant: 130))
  3203. }
  3204. NSLayoutConstraint.activate(titleConstraints + [
  3205. subtitle.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
  3206. subtitle.topAnchor.constraint(equalTo: icon.bottomAnchor, constant: 10),
  3207. subtitle.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -10),
  3208. time.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
  3209. time.topAnchor.constraint(equalTo: subtitle.bottomAnchor, constant: 5),
  3210. time.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -10),
  3211. duration.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
  3212. duration.topAnchor.constraint(equalTo: time.bottomAnchor, constant: 4),
  3213. duration.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -10)
  3214. ])
  3215. let hit = HoverButton(title: "", target: self, action: #selector(scheduleCardButtonPressed(_:)))
  3216. hit.translatesAutoresizingMaskIntoConstraints = false
  3217. hit.isBordered = false
  3218. hit.bezelStyle = .regularSquare
  3219. hit.identifier = NSUserInterfaceItemIdentifier(meeting.meetURL.absoluteString)
  3220. hit.heightAnchor.constraint(equalToConstant: contentHeight).isActive = true
  3221. if useFlexibleWidth {
  3222. hit.setContentHuggingPriority(.defaultLow, for: .horizontal)
  3223. hit.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  3224. } else {
  3225. hit.widthAnchor.constraint(equalToConstant: cardWidth).isActive = true
  3226. hit.setContentHuggingPriority(.required, for: .horizontal)
  3227. hit.setContentCompressionResistancePriority(.required, for: .horizontal)
  3228. }
  3229. hit.addSubview(card)
  3230. NSLayoutConstraint.activate([
  3231. card.leadingAnchor.constraint(equalTo: hit.leadingAnchor),
  3232. card.trailingAnchor.constraint(equalTo: hit.trailingAnchor),
  3233. card.topAnchor.constraint(equalTo: hit.topAnchor),
  3234. card.bottomAnchor.constraint(equalTo: hit.bottomAnchor)
  3235. ])
  3236. hit.onHoverChanged = { [weak self] hovering in
  3237. guard let self else { return }
  3238. let base = self.palette.sectionCard
  3239. let hoverBlend = self.darkModeEnabled ? NSColor.white : NSColor.black
  3240. let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
  3241. if self.storeKitCoordinator.hasPremiumAccess {
  3242. card.layer?.backgroundColor = (hovering ? hover : base).cgColor
  3243. } else {
  3244. card.layer?.backgroundColor = base.cgColor
  3245. }
  3246. }
  3247. hit.onHoverChanged?(false)
  3248. if !storeKitCoordinator.hasPremiumAccess {
  3249. let lockOverlay = NSVisualEffectView()
  3250. lockOverlay.translatesAutoresizingMaskIntoConstraints = false
  3251. lockOverlay.material = darkModeEnabled ? .hudWindow : .popover
  3252. lockOverlay.blendingMode = .withinWindow
  3253. lockOverlay.state = .active
  3254. lockOverlay.wantsLayer = true
  3255. lockOverlay.layer?.cornerRadius = 12
  3256. lockOverlay.layer?.masksToBounds = true
  3257. lockOverlay.layer?.backgroundColor = NSColor.black.withAlphaComponent(darkModeEnabled ? 0.28 : 0.12).cgColor
  3258. let lockLabel = textLabel("Get Premium to see events", font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: darkModeEnabled ? .white : .black)
  3259. lockLabel.alignment = .center
  3260. card.addSubview(lockOverlay)
  3261. lockOverlay.addSubview(lockLabel)
  3262. NSLayoutConstraint.activate([
  3263. lockOverlay.leadingAnchor.constraint(equalTo: card.leadingAnchor),
  3264. lockOverlay.trailingAnchor.constraint(equalTo: card.trailingAnchor),
  3265. lockOverlay.topAnchor.constraint(equalTo: card.topAnchor),
  3266. lockOverlay.bottomAnchor.constraint(equalTo: card.bottomAnchor),
  3267. lockLabel.centerXAnchor.constraint(equalTo: lockOverlay.centerXAnchor),
  3268. lockLabel.centerYAnchor.constraint(equalTo: lockOverlay.centerYAnchor),
  3269. lockLabel.leadingAnchor.constraint(greaterThanOrEqualTo: lockOverlay.leadingAnchor, constant: 10),
  3270. lockLabel.trailingAnchor.constraint(lessThanOrEqualTo: lockOverlay.trailingAnchor, constant: -10)
  3271. ])
  3272. hit.toolTip = "Premium required. Click to open paywall."
  3273. }
  3274. return hit
  3275. }
  3276. private func makeScheduleScrollButton(systemSymbol: String, action: Selector) -> NSButton {
  3277. let button = NSButton(title: "", target: self, action: action)
  3278. button.translatesAutoresizingMaskIntoConstraints = false
  3279. button.isBordered = false
  3280. button.bezelStyle = .regularSquare
  3281. button.wantsLayer = true
  3282. button.layer?.cornerRadius = 16
  3283. button.layer?.backgroundColor = palette.inputBackground.cgColor
  3284. button.layer?.borderColor = palette.inputBorder.cgColor
  3285. button.layer?.borderWidth = 1
  3286. button.image = NSImage(systemSymbolName: systemSymbol, accessibilityDescription: "Scroll meetings")
  3287. button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .semibold)
  3288. button.imagePosition = .imageOnly
  3289. button.imageScaling = .scaleProportionallyDown
  3290. button.contentTintColor = palette.textSecondary
  3291. button.focusRingType = .none
  3292. button.heightAnchor.constraint(equalToConstant: 32).isActive = true
  3293. button.widthAnchor.constraint(equalToConstant: 32).isActive = true
  3294. return button
  3295. }
  3296. }
  3297. private extension PremiumPlan {
  3298. var displayName: String {
  3299. switch self {
  3300. case .weekly: return "Weekly"
  3301. case .monthly: return "Monthly"
  3302. case .yearly: return "Yearly"
  3303. case .lifetime: return "Lifetime"
  3304. }
  3305. }
  3306. }
  3307. extension ViewController: NSTextFieldDelegate {
  3308. func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
  3309. if control === browseAddressField, commandSelector == #selector(NSResponder.insertNewline(_:)) {
  3310. browseOpenAddressClicked(nil)
  3311. return true
  3312. }
  3313. return false
  3314. }
  3315. }
  3316. extension ViewController: NSWindowDelegate {
  3317. func windowWillClose(_ notification: Notification) {
  3318. guard let closingWindow = notification.object as? NSWindow else { return }
  3319. if closingWindow === paywallWindow {
  3320. paywallWindow = nil
  3321. paywallUpgradeFlowEnabled = false
  3322. }
  3323. }
  3324. }
  3325. /// Default `NSClipView` uses a non-flipped coordinate system, so a document shorter than the visible area is anchored to the **bottom** of the clip, leaving a large gap above (e.g. Schedule empty state). Flipped coordinates match Auto Layout’s top-leading anchors and keep content top-aligned.
  3326. private final class TopAlignedClipView: NSClipView {
  3327. override var isFlipped: Bool { true }
  3328. }
  3329. /// Wraps the Google auth control and draws a circular accent ring with a light pulse while the signed-in avatar is hovered.
  3330. private final class GoogleProfileAuthHostView: NSView {
  3331. weak var authButton: NSButton? {
  3332. didSet { needsLayout = true }
  3333. }
  3334. private let ringLayer = CAShapeLayer()
  3335. private var avatarRingMode = false
  3336. private static let ringLineWidth: CGFloat = 2.25
  3337. override init(frame frameRect: NSRect) {
  3338. super.init(frame: frameRect)
  3339. wantsLayer = true
  3340. layer?.masksToBounds = false
  3341. ringLayer.fillColor = nil
  3342. ringLayer.strokeColor = NSColor.clear.cgColor
  3343. ringLayer.lineWidth = Self.ringLineWidth
  3344. ringLayer.lineCap = .round
  3345. ringLayer.opacity = 0
  3346. ringLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
  3347. layer?.insertSublayer(ringLayer, at: 0)
  3348. }
  3349. @available(*, unavailable)
  3350. required init?(coder: NSCoder) {
  3351. nil
  3352. }
  3353. func setAvatarRingMode(_ enabled: Bool) {
  3354. avatarRingMode = enabled
  3355. if enabled == false {
  3356. ringLayer.removeAllAnimations()
  3357. ringLayer.opacity = 0
  3358. ringLayer.lineWidth = Self.ringLineWidth
  3359. }
  3360. needsLayout = true
  3361. }
  3362. func updateRingAppearance(isDark: Bool, accent: NSColor) {
  3363. let stroke = isDark
  3364. ? accent.blended(withFraction: 0.22, of: NSColor.white) ?? accent
  3365. : accent
  3366. CATransaction.begin()
  3367. CATransaction.setDisableActions(true)
  3368. ringLayer.strokeColor = stroke.withAlphaComponent(0.95).cgColor
  3369. CATransaction.commit()
  3370. }
  3371. func setProfileHoverActive(_ active: Bool) {
  3372. guard avatarRingMode else { return }
  3373. ringLayer.removeAnimation(forKey: "pulse")
  3374. if active {
  3375. layoutRingPathIfNeeded()
  3376. CATransaction.begin()
  3377. CATransaction.setAnimationDuration(0.22)
  3378. ringLayer.opacity = 1
  3379. CATransaction.commit()
  3380. let pulse = CABasicAnimation(keyPath: "lineWidth")
  3381. pulse.fromValue = Self.ringLineWidth * 0.88
  3382. pulse.toValue = Self.ringLineWidth * 1.45
  3383. pulse.duration = 0.72
  3384. pulse.autoreverses = true
  3385. pulse.repeatCount = .infinity
  3386. pulse.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  3387. ringLayer.add(pulse, forKey: "pulse")
  3388. } else {
  3389. CATransaction.begin()
  3390. CATransaction.setAnimationDuration(0.18)
  3391. ringLayer.opacity = 0
  3392. CATransaction.commit()
  3393. ringLayer.lineWidth = Self.ringLineWidth
  3394. }
  3395. }
  3396. private func layoutRingPathIfNeeded() {
  3397. guard avatarRingMode, let btn = authButton else { return }
  3398. let f = btn.frame
  3399. guard f.width > 1, f.height > 1 else { return }
  3400. let center = CGPoint(x: f.midX, y: f.midY)
  3401. let avatarR = min(f.width, f.height) / 2
  3402. let gap: CGFloat = 3.5
  3403. let ringRadius = avatarR + gap
  3404. let d = ringRadius * 2
  3405. CATransaction.begin()
  3406. CATransaction.setDisableActions(true)
  3407. ringLayer.bounds = CGRect(x: 0, y: 0, width: d, height: d)
  3408. ringLayer.position = center
  3409. ringLayer.path = CGPath(ellipseIn: CGRect(origin: .zero, size: CGSize(width: d, height: d)), transform: nil)
  3410. CATransaction.commit()
  3411. }
  3412. override func layout() {
  3413. super.layout()
  3414. layoutRingPathIfNeeded()
  3415. }
  3416. }
  3417. /// Ensures `NSClickGestureRecognizer` on the row receives clicks instead of child label/image views swallowing them.
  3418. private class RowHitTestView: NSView {
  3419. override func hitTest(_ point: NSPoint) -> NSView? {
  3420. return bounds.contains(point) ? self : nil
  3421. }
  3422. override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
  3423. true
  3424. }
  3425. }
  3426. private final class HoverTrackingView: RowHitTestView {
  3427. var onHoverChanged: ((Bool) -> Void)?
  3428. var onClick: (() -> Void)?
  3429. var showsHandCursor = true
  3430. private var trackingAreaRef: NSTrackingArea?
  3431. private var isHovering = false {
  3432. didSet {
  3433. guard isHovering != oldValue else { return }
  3434. onHoverChanged?(isHovering)
  3435. }
  3436. }
  3437. override func updateTrackingAreas() {
  3438. super.updateTrackingAreas()
  3439. if let trackingAreaRef {
  3440. removeTrackingArea(trackingAreaRef)
  3441. }
  3442. let options: NSTrackingArea.Options = [
  3443. .activeInKeyWindow,
  3444. .inVisibleRect,
  3445. .mouseEnteredAndExited
  3446. ]
  3447. let area = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
  3448. addTrackingArea(area)
  3449. trackingAreaRef = area
  3450. }
  3451. override func mouseEntered(with event: NSEvent) {
  3452. super.mouseEntered(with: event)
  3453. isHovering = true
  3454. }
  3455. override func mouseExited(with event: NSEvent) {
  3456. super.mouseExited(with: event)
  3457. isHovering = false
  3458. }
  3459. override func resetCursorRects() {
  3460. super.resetCursorRects()
  3461. guard showsHandCursor else { return }
  3462. addCursorRect(bounds, cursor: .pointingHand)
  3463. }
  3464. override func mouseUp(with event: NSEvent) {
  3465. super.mouseUp(with: event)
  3466. guard event.type == .leftMouseUp else { return }
  3467. onClick?()
  3468. }
  3469. }
  3470. /// Hover tracking without overriding hit-testing; keeps controls like text fields interactive.
  3471. private final class HoverSurfaceView: NSView {
  3472. var onHoverChanged: ((Bool) -> Void)?
  3473. private var trackingAreaRef: NSTrackingArea?
  3474. private var isHovering = false {
  3475. didSet {
  3476. guard isHovering != oldValue else { return }
  3477. onHoverChanged?(isHovering)
  3478. }
  3479. }
  3480. override func updateTrackingAreas() {
  3481. super.updateTrackingAreas()
  3482. if let trackingAreaRef {
  3483. removeTrackingArea(trackingAreaRef)
  3484. }
  3485. let options: NSTrackingArea.Options = [
  3486. .activeInKeyWindow,
  3487. .inVisibleRect,
  3488. .mouseEnteredAndExited
  3489. ]
  3490. let area = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
  3491. addTrackingArea(area)
  3492. trackingAreaRef = area
  3493. }
  3494. override func mouseEntered(with event: NSEvent) {
  3495. super.mouseEntered(with: event)
  3496. isHovering = true
  3497. }
  3498. override func mouseExited(with event: NSEvent) {
  3499. super.mouseExited(with: event)
  3500. isHovering = false
  3501. }
  3502. }
  3503. private final class HoverButton: NSButton {
  3504. var onHoverChanged: ((Bool) -> Void)?
  3505. var showsHandCursor = true
  3506. private var trackingAreaRef: NSTrackingArea?
  3507. private var isHovering = false {
  3508. didSet {
  3509. guard isHovering != oldValue else { return }
  3510. onHoverChanged?(isHovering)
  3511. }
  3512. }
  3513. override func updateTrackingAreas() {
  3514. super.updateTrackingAreas()
  3515. if let trackingAreaRef {
  3516. removeTrackingArea(trackingAreaRef)
  3517. }
  3518. let options: NSTrackingArea.Options = [
  3519. .activeInKeyWindow,
  3520. .inVisibleRect,
  3521. .mouseEnteredAndExited
  3522. ]
  3523. let tracking = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
  3524. addTrackingArea(tracking)
  3525. trackingAreaRef = tracking
  3526. }
  3527. override func mouseEntered(with event: NSEvent) {
  3528. super.mouseEntered(with: event)
  3529. if showsHandCursor {
  3530. NSCursor.pointingHand.set()
  3531. }
  3532. isHovering = true
  3533. }
  3534. override func mouseExited(with event: NSEvent) {
  3535. super.mouseExited(with: event)
  3536. isHovering = false
  3537. }
  3538. }
  3539. private final class HoverPopUpButton: NSPopUpButton {
  3540. var onHoverChanged: ((Bool) -> Void)?
  3541. private var trackingAreaRef: NSTrackingArea?
  3542. private var isHovering = false {
  3543. didSet {
  3544. guard isHovering != oldValue else { return }
  3545. onHoverChanged?(isHovering)
  3546. }
  3547. }
  3548. override func updateTrackingAreas() {
  3549. super.updateTrackingAreas()
  3550. if let trackingAreaRef {
  3551. removeTrackingArea(trackingAreaRef)
  3552. }
  3553. let options: NSTrackingArea.Options = [
  3554. .activeInKeyWindow,
  3555. .inVisibleRect,
  3556. .mouseEnteredAndExited
  3557. ]
  3558. let tracking = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
  3559. addTrackingArea(tracking)
  3560. trackingAreaRef = tracking
  3561. }
  3562. override func mouseEntered(with event: NSEvent) {
  3563. super.mouseEntered(with: event)
  3564. isHovering = true
  3565. }
  3566. override func mouseExited(with event: NSEvent) {
  3567. super.mouseExited(with: event)
  3568. isHovering = false
  3569. }
  3570. }
  3571. private func circularNSImage(_ image: NSImage, diameter: CGFloat) -> NSImage {
  3572. let size = NSSize(width: diameter, height: diameter)
  3573. let result = NSImage(size: size)
  3574. result.lockFocus()
  3575. if let ctx = NSGraphicsContext.current {
  3576. ctx.imageInterpolation = .high
  3577. }
  3578. let rect = NSRect(origin: .zero, size: size)
  3579. let path = NSBezierPath(ovalIn: rect)
  3580. path.addClip()
  3581. let src = image.size.width > 0 && image.size.height > 0
  3582. ? NSRect(origin: .zero, size: image.size)
  3583. : NSRect(origin: .zero, size: size)
  3584. image.draw(in: rect, from: src, operation: .copy, fraction: 1.0)
  3585. result.unlockFocus()
  3586. result.isTemplate = false
  3587. return result
  3588. }
  3589. private final class GoogleAccountMenuViewController: NSViewController {
  3590. private let palette: Palette
  3591. private let darkModeEnabled: Bool
  3592. private let displayName: String
  3593. private let email: String
  3594. private let avatar: NSImage?
  3595. private let onSignOut: () -> Void
  3596. init(
  3597. palette: Palette,
  3598. darkModeEnabled: Bool,
  3599. displayName: String,
  3600. email: String,
  3601. avatar: NSImage?,
  3602. onSignOut: @escaping () -> Void
  3603. ) {
  3604. self.palette = palette
  3605. self.darkModeEnabled = darkModeEnabled
  3606. self.displayName = displayName
  3607. self.email = email
  3608. self.avatar = avatar
  3609. self.onSignOut = onSignOut
  3610. super.init(nibName: nil, bundle: nil)
  3611. view = makeContentView()
  3612. view.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
  3613. preferredContentSize = NSSize(width: 300, height: 158)
  3614. }
  3615. @available(*, unavailable)
  3616. required init?(coder: NSCoder) {
  3617. nil
  3618. }
  3619. private func makeContentView() -> NSView {
  3620. let root = NSView()
  3621. root.translatesAutoresizingMaskIntoConstraints = false
  3622. let card = NSView()
  3623. card.translatesAutoresizingMaskIntoConstraints = false
  3624. card.wantsLayer = true
  3625. card.layer?.cornerRadius = 14
  3626. card.layer?.backgroundColor = palette.sectionCard.cgColor
  3627. card.layer?.borderColor = palette.inputBorder.cgColor
  3628. card.layer?.borderWidth = 1
  3629. card.layer?.shadowColor = NSColor.black.cgColor
  3630. card.layer?.shadowOpacity = darkModeEnabled ? 0.5 : 0.2
  3631. card.layer?.shadowOffset = CGSize(width: 0, height: 6)
  3632. card.layer?.shadowRadius = 18
  3633. card.layer?.masksToBounds = false
  3634. root.addSubview(card)
  3635. NSLayoutConstraint.activate([
  3636. card.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 8),
  3637. card.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -8),
  3638. card.topAnchor.constraint(equalTo: root.topAnchor, constant: 8),
  3639. card.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -8),
  3640. root.widthAnchor.constraint(equalToConstant: 300)
  3641. ])
  3642. let inner = NSStackView()
  3643. inner.translatesAutoresizingMaskIntoConstraints = false
  3644. inner.orientation = .vertical
  3645. inner.spacing = 0
  3646. inner.alignment = .leading
  3647. card.addSubview(inner)
  3648. NSLayoutConstraint.activate([
  3649. inner.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 18),
  3650. inner.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -18),
  3651. inner.topAnchor.constraint(equalTo: card.topAnchor, constant: 18),
  3652. inner.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -10)
  3653. ])
  3654. let headerRow = NSView()
  3655. headerRow.translatesAutoresizingMaskIntoConstraints = false
  3656. let avatarBox = NSView()
  3657. avatarBox.translatesAutoresizingMaskIntoConstraints = false
  3658. avatarBox.wantsLayer = true
  3659. avatarBox.layer?.cornerRadius = 24
  3660. avatarBox.layer?.masksToBounds = true
  3661. avatarBox.layer?.borderColor = palette.inputBorder.cgColor
  3662. avatarBox.layer?.borderWidth = 1
  3663. let avatarView = NSImageView()
  3664. avatarView.translatesAutoresizingMaskIntoConstraints = false
  3665. avatarView.imageScaling = .scaleAxesIndependently
  3666. avatarView.image = resolvedAvatarImage()
  3667. avatarBox.addSubview(avatarView)
  3668. NSLayoutConstraint.activate([
  3669. avatarBox.widthAnchor.constraint(equalToConstant: 48),
  3670. avatarBox.heightAnchor.constraint(equalToConstant: 48),
  3671. avatarView.leadingAnchor.constraint(equalTo: avatarBox.leadingAnchor),
  3672. avatarView.trailingAnchor.constraint(equalTo: avatarBox.trailingAnchor),
  3673. avatarView.topAnchor.constraint(equalTo: avatarBox.topAnchor),
  3674. avatarView.bottomAnchor.constraint(equalTo: avatarBox.bottomAnchor)
  3675. ])
  3676. let textColumn = NSStackView()
  3677. textColumn.translatesAutoresizingMaskIntoConstraints = false
  3678. textColumn.orientation = .vertical
  3679. textColumn.spacing = 3
  3680. textColumn.alignment = .leading
  3681. let nameField = NSTextField(labelWithString: displayName)
  3682. nameField.translatesAutoresizingMaskIntoConstraints = false
  3683. nameField.font = NSFont.systemFont(ofSize: 15, weight: .semibold)
  3684. nameField.textColor = palette.textPrimary
  3685. nameField.lineBreakMode = .byTruncatingTail
  3686. nameField.maximumNumberOfLines = 1
  3687. nameField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  3688. let emailField = NSTextField(labelWithString: email)
  3689. emailField.translatesAutoresizingMaskIntoConstraints = false
  3690. emailField.font = NSFont.systemFont(ofSize: 12, weight: .regular)
  3691. emailField.textColor = palette.textTertiary
  3692. emailField.lineBreakMode = .byTruncatingTail
  3693. emailField.maximumNumberOfLines = 1
  3694. emailField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  3695. textColumn.addArrangedSubview(nameField)
  3696. textColumn.addArrangedSubview(emailField)
  3697. headerRow.addSubview(avatarBox)
  3698. headerRow.addSubview(textColumn)
  3699. NSLayoutConstraint.activate([
  3700. avatarBox.leadingAnchor.constraint(equalTo: headerRow.leadingAnchor),
  3701. avatarBox.topAnchor.constraint(equalTo: headerRow.topAnchor),
  3702. avatarBox.bottomAnchor.constraint(lessThanOrEqualTo: headerRow.bottomAnchor),
  3703. textColumn.leadingAnchor.constraint(equalTo: avatarBox.trailingAnchor, constant: 14),
  3704. textColumn.trailingAnchor.constraint(equalTo: headerRow.trailingAnchor),
  3705. textColumn.centerYAnchor.constraint(equalTo: avatarBox.centerYAnchor),
  3706. textColumn.topAnchor.constraint(greaterThanOrEqualTo: headerRow.topAnchor),
  3707. textColumn.bottomAnchor.constraint(lessThanOrEqualTo: headerRow.bottomAnchor)
  3708. ])
  3709. inner.addArrangedSubview(headerRow)
  3710. headerRow.widthAnchor.constraint(equalTo: inner.widthAnchor).isActive = true
  3711. inner.setCustomSpacing(14, after: headerRow)
  3712. let separator = NSView()
  3713. separator.translatesAutoresizingMaskIntoConstraints = false
  3714. separator.wantsLayer = true
  3715. separator.layer?.backgroundColor = palette.separator.cgColor
  3716. separator.heightAnchor.constraint(equalToConstant: 1).isActive = true
  3717. inner.addArrangedSubview(separator)
  3718. separator.widthAnchor.constraint(equalTo: inner.widthAnchor).isActive = true
  3719. inner.setCustomSpacing(6, after: separator)
  3720. let signOutRow = HoverTrackingView()
  3721. signOutRow.translatesAutoresizingMaskIntoConstraints = false
  3722. signOutRow.heightAnchor.constraint(equalToConstant: 44).isActive = true
  3723. signOutRow.wantsLayer = true
  3724. signOutRow.layer?.cornerRadius = 10
  3725. let signOutIcon = NSImageView()
  3726. signOutIcon.translatesAutoresizingMaskIntoConstraints = false
  3727. signOutIcon.imageScaling = .scaleProportionallyDown
  3728. if let sym = NSImage(systemSymbolName: "rectangle.portrait.and.arrow.right", accessibilityDescription: nil) {
  3729. signOutIcon.image = sym
  3730. signOutIcon.contentTintColor = palette.textSecondary
  3731. signOutIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .medium)
  3732. }
  3733. let signOutLabel = NSTextField(labelWithString: "Log out")
  3734. signOutLabel.translatesAutoresizingMaskIntoConstraints = false
  3735. signOutLabel.font = NSFont.systemFont(ofSize: 14, weight: .medium)
  3736. signOutLabel.textColor = palette.textPrimary
  3737. signOutRow.addSubview(signOutIcon)
  3738. signOutRow.addSubview(signOutLabel)
  3739. NSLayoutConstraint.activate([
  3740. signOutIcon.leadingAnchor.constraint(equalTo: signOutRow.leadingAnchor, constant: 10),
  3741. signOutIcon.centerYAnchor.constraint(equalTo: signOutRow.centerYAnchor),
  3742. signOutIcon.widthAnchor.constraint(equalToConstant: 20),
  3743. signOutIcon.heightAnchor.constraint(equalToConstant: 20),
  3744. signOutLabel.leadingAnchor.constraint(equalTo: signOutIcon.trailingAnchor, constant: 10),
  3745. signOutLabel.centerYAnchor.constraint(equalTo: signOutRow.centerYAnchor),
  3746. signOutLabel.trailingAnchor.constraint(lessThanOrEqualTo: signOutRow.trailingAnchor, constant: -10)
  3747. ])
  3748. let signOutClick = NSClickGestureRecognizer(target: self, action: #selector(signOutClicked))
  3749. signOutRow.addGestureRecognizer(signOutClick)
  3750. signOutRow.onHoverChanged = { [weak self] hovering in
  3751. guard let self else { return }
  3752. signOutRow.layer?.backgroundColor = (hovering ? self.palette.inputBackground : NSColor.clear).cgColor
  3753. }
  3754. signOutRow.onHoverChanged?(false)
  3755. inner.addArrangedSubview(signOutRow)
  3756. signOutRow.widthAnchor.constraint(equalTo: inner.widthAnchor).isActive = true
  3757. return root
  3758. }
  3759. private func resolvedAvatarImage() -> NSImage {
  3760. if let a = avatar {
  3761. return circularNSImage(a, diameter: 48)
  3762. }
  3763. return initialLetterAvatar()
  3764. }
  3765. private func initialLetterAvatar() -> NSImage {
  3766. let d: CGFloat = 48
  3767. let letter = displayName.trimmingCharacters(in: .whitespacesAndNewlines).first.map { String($0).uppercased() } ?? "?"
  3768. let img = NSImage(size: NSSize(width: d, height: d))
  3769. img.lockFocus()
  3770. palette.primaryBlue.setFill()
  3771. NSBezierPath(ovalIn: NSRect(x: 0, y: 0, width: d, height: d)).fill()
  3772. let attrs: [NSAttributedString.Key: Any] = [
  3773. .font: NSFont.systemFont(ofSize: 20, weight: .semibold),
  3774. .foregroundColor: NSColor.white
  3775. ]
  3776. let sz = (letter as NSString).size(withAttributes: attrs)
  3777. let origin = NSPoint(x: (d - sz.width) / 2, y: (d - sz.height) / 2)
  3778. (letter as NSString).draw(at: origin, withAttributes: attrs)
  3779. img.unlockFocus()
  3780. img.isTemplate = false
  3781. return img
  3782. }
  3783. @objc private func signOutClicked() {
  3784. onSignOut()
  3785. }
  3786. }
  3787. private final class SettingsMenuViewController: NSViewController {
  3788. private let palette: Palette
  3789. private let typography: Typography
  3790. private let onToggleDarkMode: (Bool) -> Void
  3791. private let onAction: (SettingsAction) -> Void
  3792. private var darkToggle: NSSwitch?
  3793. init(
  3794. palette: Palette,
  3795. typography: Typography,
  3796. darkModeEnabled: Bool,
  3797. showRateUsInSettings: Bool,
  3798. showUpgradeInSettings: Bool,
  3799. onToggleDarkMode: @escaping (Bool) -> Void,
  3800. onAction: @escaping (SettingsAction) -> Void
  3801. ) {
  3802. self.palette = palette
  3803. self.typography = typography
  3804. self.onToggleDarkMode = onToggleDarkMode
  3805. self.onAction = onAction
  3806. super.init(nibName: nil, bundle: nil)
  3807. self.view = makeView(
  3808. darkModeEnabled: darkModeEnabled,
  3809. showRateUsInSettings: showRateUsInSettings,
  3810. showUpgradeInSettings: showUpgradeInSettings
  3811. )
  3812. }
  3813. @available(*, unavailable)
  3814. required init?(coder: NSCoder) {
  3815. nil
  3816. }
  3817. func setDarkModeEnabled(_ enabled: Bool) {
  3818. darkToggle?.state = enabled ? .on : .off
  3819. }
  3820. private func makeView(
  3821. darkModeEnabled: Bool,
  3822. showRateUsInSettings: Bool,
  3823. showUpgradeInSettings: Bool
  3824. ) -> NSView {
  3825. let root = NSView()
  3826. root.translatesAutoresizingMaskIntoConstraints = false
  3827. let card = roundedCard()
  3828. root.addSubview(card)
  3829. NSLayoutConstraint.activate([
  3830. card.leadingAnchor.constraint(equalTo: root.leadingAnchor),
  3831. card.trailingAnchor.constraint(equalTo: root.trailingAnchor),
  3832. card.topAnchor.constraint(equalTo: root.topAnchor),
  3833. card.bottomAnchor.constraint(equalTo: root.bottomAnchor),
  3834. root.widthAnchor.constraint(equalToConstant: 260)
  3835. ])
  3836. let stack = NSStackView()
  3837. stack.translatesAutoresizingMaskIntoConstraints = false
  3838. stack.orientation = .vertical
  3839. stack.spacing = 6
  3840. stack.alignment = .leading
  3841. card.addSubview(stack)
  3842. NSLayoutConstraint.activate([
  3843. stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 14),
  3844. stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -14),
  3845. stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
  3846. stack.bottomAnchor.constraint(lessThanOrEqualTo: card.bottomAnchor, constant: -14)
  3847. ])
  3848. stack.addArrangedSubview(settingsDarkModeRow(enabled: darkModeEnabled))
  3849. if showRateUsInSettings {
  3850. stack.addArrangedSubview(settingsActionRow(icon: "★", title: "Rate Us", action: .rateUs))
  3851. }
  3852. stack.addArrangedSubview(settingsActionRow(icon: "💬", title: "Support", action: .support))
  3853. stack.addArrangedSubview(settingsActionRow(icon: "⤴︎", title: "Share App", action: .shareApp))
  3854. if showUpgradeInSettings {
  3855. stack.addArrangedSubview(settingsActionRow(icon: "⬆︎", title: "Upgrade", action: .upgrade))
  3856. }
  3857. for v in stack.arrangedSubviews {
  3858. v.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  3859. }
  3860. return root
  3861. }
  3862. private func roundedCard() -> NSView {
  3863. let view = NSView()
  3864. view.translatesAutoresizingMaskIntoConstraints = false
  3865. view.wantsLayer = true
  3866. view.layer?.cornerRadius = 12
  3867. view.layer?.backgroundColor = palette.sectionCard.cgColor
  3868. view.layer?.borderColor = palette.inputBorder.cgColor
  3869. view.layer?.borderWidth = 1
  3870. view.layer?.shadowColor = NSColor.black.cgColor
  3871. view.layer?.shadowOpacity = 0.28
  3872. view.layer?.shadowOffset = CGSize(width: 0, height: -1)
  3873. view.layer?.shadowRadius = 10
  3874. return view
  3875. }
  3876. private func settingsDarkModeRow(enabled: Bool) -> NSView {
  3877. let row = NSView()
  3878. row.translatesAutoresizingMaskIntoConstraints = false
  3879. row.heightAnchor.constraint(equalToConstant: 44).isActive = true
  3880. row.wantsLayer = true
  3881. row.layer?.cornerRadius = 10
  3882. let icon = NSTextField(labelWithString: "◐")
  3883. icon.translatesAutoresizingMaskIntoConstraints = false
  3884. icon.font = NSFont.systemFont(ofSize: 18, weight: .medium)
  3885. icon.textColor = palette.textPrimary
  3886. let title = NSTextField(labelWithString: "Dark Mode")
  3887. title.translatesAutoresizingMaskIntoConstraints = false
  3888. title.font = NSFont.systemFont(ofSize: 16, weight: .semibold)
  3889. title.textColor = palette.textPrimary
  3890. let toggle = NSSwitch()
  3891. toggle.translatesAutoresizingMaskIntoConstraints = false
  3892. toggle.state = enabled ? .on : .off
  3893. toggle.target = self
  3894. toggle.action = #selector(darkModeToggled(_:))
  3895. darkToggle = toggle
  3896. row.addSubview(icon)
  3897. row.addSubview(title)
  3898. row.addSubview(toggle)
  3899. row.layer?.backgroundColor = NSColor.clear.cgColor
  3900. NSLayoutConstraint.activate([
  3901. icon.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 4),
  3902. icon.centerYAnchor.constraint(equalTo: row.centerYAnchor),
  3903. title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 10),
  3904. title.centerYAnchor.constraint(equalTo: row.centerYAnchor),
  3905. toggle.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -2),
  3906. toggle.centerYAnchor.constraint(equalTo: row.centerYAnchor)
  3907. ])
  3908. return row
  3909. }
  3910. private func settingsActionRow(icon: String, title: String, action: SettingsAction) -> NSView {
  3911. let row = HoverButton(title: "", target: self, action: #selector(settingsActionButtonPressed(_:)))
  3912. row.tag = action.rawValue
  3913. row.isBordered = false
  3914. row.translatesAutoresizingMaskIntoConstraints = false
  3915. row.heightAnchor.constraint(equalToConstant: 42).isActive = true
  3916. row.wantsLayer = true
  3917. row.layer?.cornerRadius = 10
  3918. row.layer?.backgroundColor = NSColor.clear.cgColor
  3919. let iconLabel = NSTextField(labelWithString: icon)
  3920. iconLabel.translatesAutoresizingMaskIntoConstraints = false
  3921. iconLabel.font = NSFont.systemFont(ofSize: 18, weight: .medium)
  3922. iconLabel.textColor = palette.textPrimary
  3923. let titleLabel = NSTextField(labelWithString: title)
  3924. titleLabel.translatesAutoresizingMaskIntoConstraints = false
  3925. titleLabel.font = NSFont.systemFont(ofSize: 16, weight: .semibold)
  3926. titleLabel.textColor = palette.textPrimary
  3927. row.addSubview(iconLabel)
  3928. row.addSubview(titleLabel)
  3929. NSLayoutConstraint.activate([
  3930. iconLabel.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 4),
  3931. iconLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor),
  3932. titleLabel.leadingAnchor.constraint(equalTo: iconLabel.trailingAnchor, constant: 10),
  3933. titleLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor)
  3934. ])
  3935. row.onHoverChanged = { hovering in
  3936. row.layer?.backgroundColor = (hovering ? self.palette.inputBackground : NSColor.clear).cgColor
  3937. }
  3938. row.onHoverChanged?(false)
  3939. return row
  3940. }
  3941. @objc private func darkModeToggled(_ sender: NSSwitch) {
  3942. onToggleDarkMode(sender.state == .on)
  3943. }
  3944. @objc private func settingsActionButtonPressed(_ sender: NSButton) {
  3945. guard let action = SettingsAction(rawValue: sender.tag) else { return }
  3946. onAction(action)
  3947. }
  3948. }
  3949. private extension ViewController {
  3950. private func requireGoogleLoginForCalendarScheduling() -> Bool {
  3951. guard googleOAuth.loadTokens() != nil else {
  3952. showSimpleAlert(
  3953. title: "Connect Google",
  3954. message: "Sign in with Google first to schedule a meeting from Calendar."
  3955. )
  3956. return false
  3957. }
  3958. return true
  3959. }
  3960. func roundedContainer(cornerRadius: CGFloat, color: NSColor) -> NSView {
  3961. let view = NSView()
  3962. view.wantsLayer = true
  3963. view.layer?.backgroundColor = color.cgColor
  3964. view.layer?.cornerRadius = cornerRadius
  3965. return view
  3966. }
  3967. func styleSurface(_ view: NSView, borderColor: NSColor, borderWidth: CGFloat, shadow: Bool) {
  3968. view.layer?.borderColor = borderColor.cgColor
  3969. view.layer?.borderWidth = borderWidth
  3970. if shadow {
  3971. view.layer?.shadowColor = NSColor.black.cgColor
  3972. view.layer?.shadowOpacity = 0.18
  3973. view.layer?.shadowOffset = CGSize(width: 0, height: -1)
  3974. view.layer?.shadowRadius = 5
  3975. }
  3976. }
  3977. func textLabel(_ text: String, font: NSFont, color: NSColor) -> NSTextField {
  3978. let label = NSTextField(labelWithString: text)
  3979. label.translatesAutoresizingMaskIntoConstraints = false
  3980. label.textColor = color
  3981. label.font = font
  3982. return label
  3983. }
  3984. func iconLabel(_ text: String, size: CGFloat) -> NSTextField {
  3985. let label = NSTextField(labelWithString: text)
  3986. label.translatesAutoresizingMaskIntoConstraints = false
  3987. label.font = NSFont.systemFont(ofSize: size)
  3988. return label
  3989. }
  3990. func sidebarSectionTitle(_ text: String) -> NSTextField {
  3991. let field = textLabel(text, font: typography.sidebarSection, color: palette.textMuted)
  3992. field.alignment = .left
  3993. return field
  3994. }
  3995. func sidebarItem(_ text: String, icon: String, page: SidebarPage, logoImageName: String? = nil, systemSymbolName: String? = nil, logoIconWidth: CGFloat = 18, logoHeightMultiplier: CGFloat = 1, logoTemplate: Bool = true, showsDisclosure: Bool = false) -> NSView {
  3996. let item = HoverButton(title: "", target: self, action: #selector(sidebarButtonClicked(_:)))
  3997. item.tag = page.rawValue
  3998. item.isBordered = false
  3999. item.wantsLayer = true
  4000. item.layer?.cornerRadius = 10
  4001. item.layer?.backgroundColor = NSColor.clear.cgColor
  4002. item.translatesAutoresizingMaskIntoConstraints = false
  4003. item.heightAnchor.constraint(equalToConstant: 36).isActive = true
  4004. item.layer?.borderWidth = 0
  4005. sidebarPageByView[ObjectIdentifier(item)] = page
  4006. let leadingView: NSView
  4007. if let name = logoImageName, let logo = NSImage(named: name) {
  4008. logo.isTemplate = true
  4009. let imageView = NSImageView(image: logo)
  4010. imageView.translatesAutoresizingMaskIntoConstraints = false
  4011. imageView.imageScaling = .scaleProportionallyDown
  4012. imageView.imageAlignment = .alignCenter
  4013. imageView.isEditable = false
  4014. leadingView = imageView
  4015. } else if let symbolName = systemSymbolName, let symbol = NSImage(systemSymbolName: symbolName, accessibilityDescription: text) {
  4016. symbol.isTemplate = true
  4017. let imageView = NSImageView(image: symbol)
  4018. imageView.translatesAutoresizingMaskIntoConstraints = false
  4019. imageView.imageScaling = .scaleProportionallyDown
  4020. imageView.imageAlignment = .alignCenter
  4021. imageView.isEditable = false
  4022. leadingView = imageView
  4023. } else {
  4024. leadingView = textLabel(icon, font: typography.sidebarIcon, color: palette.textSecondary)
  4025. }
  4026. let titleLabel = textLabel(text, font: typography.sidebarItem, color: palette.textSecondary)
  4027. titleLabel.alignment = .left
  4028. item.addSubview(leadingView)
  4029. item.addSubview(titleLabel)
  4030. var constraints: [NSLayoutConstraint] = [
  4031. leadingView.leadingAnchor.constraint(equalTo: item.leadingAnchor, constant: 12),
  4032. leadingView.centerYAnchor.constraint(equalTo: item.centerYAnchor),
  4033. titleLabel.leadingAnchor.constraint(equalTo: leadingView.trailingAnchor, constant: 8),
  4034. titleLabel.centerYAnchor.constraint(equalTo: item.centerYAnchor)
  4035. ]
  4036. if showsDisclosure {
  4037. let chevron = textLabel("›", font: NSFont.systemFont(ofSize: 22, weight: .semibold), color: palette.textSecondary)
  4038. chevron.translatesAutoresizingMaskIntoConstraints = false
  4039. chevron.alignment = .right
  4040. item.addSubview(chevron)
  4041. constraints.append(contentsOf: [
  4042. chevron.trailingAnchor.constraint(equalTo: item.trailingAnchor, constant: -10),
  4043. chevron.centerYAnchor.constraint(equalTo: item.centerYAnchor),
  4044. titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: chevron.leadingAnchor, constant: -8)
  4045. ])
  4046. } else {
  4047. constraints.append(titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: item.trailingAnchor, constant: -10))
  4048. }
  4049. if logoImageName != nil || systemSymbolName != nil {
  4050. let h = logoIconWidth * logoHeightMultiplier
  4051. constraints.append(contentsOf: [
  4052. leadingView.widthAnchor.constraint(equalToConstant: logoIconWidth),
  4053. leadingView.heightAnchor.constraint(equalToConstant: h)
  4054. ])
  4055. }
  4056. NSLayoutConstraint.activate(constraints)
  4057. applySidebarRowStyle(item, page: page, logoTemplate: logoTemplate)
  4058. item.onHoverChanged = { [weak self, weak item] hovering in
  4059. guard let self, let item else { return }
  4060. self.applySidebarRowStyle(item, page: page, logoTemplate: logoTemplate, hovering: hovering)
  4061. }
  4062. return item
  4063. }
  4064. func applySidebarRowStyle(_ item: NSView, page: SidebarPage, logoTemplate: Bool, hovering: Bool = false) {
  4065. let selected = (page == selectedSidebarPage)
  4066. let hoverColor = darkModeEnabled ? NSColor(calibratedWhite: 1, alpha: 0.07) : NSColor(calibratedWhite: 0, alpha: 0.08)
  4067. item.layer?.backgroundColor = (selected ? palette.primaryBlue : (hovering ? hoverColor : NSColor.clear)).cgColor
  4068. let tint = selected ? NSColor.white : palette.textSecondary
  4069. let sidebarIconTint = darkModeEnabled ? tint : NSColor.black
  4070. guard item.subviews.count >= 2 else { return }
  4071. let leading = item.subviews[0]
  4072. let title = item.subviews.first { $0 is NSTextField } as? NSTextField
  4073. title?.textColor = tint
  4074. // Optional disclosure chevron (if present) is the last text field.
  4075. if let chevron = item.subviews.last as? NSTextField, chevron !== title {
  4076. chevron.textColor = sidebarIconTint
  4077. }
  4078. if let imageView = leading as? NSImageView {
  4079. if logoTemplate {
  4080. imageView.contentTintColor = sidebarIconTint
  4081. }
  4082. } else if let iconField = leading as? NSTextField {
  4083. iconField.textColor = sidebarIconTint
  4084. }
  4085. }
  4086. func actionButton(title: String, color: NSColor, textColor: NSColor, width: CGFloat) -> NSView {
  4087. let button = HoverTrackingView()
  4088. button.wantsLayer = true
  4089. button.layer?.cornerRadius = 9
  4090. button.layer?.backgroundColor = color.cgColor
  4091. button.translatesAutoresizingMaskIntoConstraints = false
  4092. button.widthAnchor.constraint(equalToConstant: width).isActive = true
  4093. button.heightAnchor.constraint(equalToConstant: 36).isActive = true
  4094. styleSurface(button, borderColor: title == "Cancel" ? palette.inputBorder : palette.primaryBlueBorder, borderWidth: 1, shadow: false)
  4095. if title == "Cancel" {
  4096. button.layer?.backgroundColor = palette.cancelButton.cgColor
  4097. }
  4098. let label = textLabel(title, font: typography.buttonText, color: textColor)
  4099. button.addSubview(label)
  4100. NSLayoutConstraint.activate([
  4101. label.centerXAnchor.constraint(equalTo: button.centerXAnchor),
  4102. label.centerYAnchor.constraint(equalTo: button.centerYAnchor)
  4103. ])
  4104. let baseColor = (title == "Cancel") ? palette.cancelButton : color
  4105. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  4106. let hoverColor = baseColor.blended(withFraction: 0.12, of: hoverBlend) ?? baseColor
  4107. button.onHoverChanged = { hovering in
  4108. button.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  4109. }
  4110. button.onHoverChanged?(false)
  4111. return button
  4112. }
  4113. func iconRoundButton(systemSymbol: String, size: CGFloat, iconPointSize: CGFloat = 16, onClick: (() -> Void)? = nil) -> NSView {
  4114. let button = HoverTrackingView()
  4115. button.wantsLayer = true
  4116. button.layer?.cornerRadius = size / 2
  4117. button.layer?.backgroundColor = palette.inputBackground.cgColor
  4118. button.translatesAutoresizingMaskIntoConstraints = false
  4119. button.widthAnchor.constraint(equalToConstant: size).isActive = true
  4120. button.heightAnchor.constraint(equalToConstant: size).isActive = true
  4121. styleSurface(button, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  4122. let symbolConfig = NSImage.SymbolConfiguration(pointSize: iconPointSize, weight: .semibold)
  4123. let iconView = NSImageView()
  4124. iconView.translatesAutoresizingMaskIntoConstraints = false
  4125. iconView.image = NSImage(systemSymbolName: systemSymbol, accessibilityDescription: "Refresh")
  4126. iconView.symbolConfiguration = symbolConfig
  4127. iconView.contentTintColor = palette.textSecondary
  4128. button.addSubview(iconView)
  4129. NSLayoutConstraint.activate([
  4130. iconView.centerXAnchor.constraint(equalTo: button.centerXAnchor),
  4131. iconView.centerYAnchor.constraint(equalTo: button.centerYAnchor)
  4132. ])
  4133. let baseColor = palette.inputBackground
  4134. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  4135. let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  4136. button.onHoverChanged = { hovering in
  4137. button.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  4138. }
  4139. button.onHoverChanged?(false)
  4140. button.onClick = onClick
  4141. return button
  4142. }
  4143. }
  4144. private let calendarDayKeyFormatter: DateFormatter = {
  4145. let f = DateFormatter()
  4146. f.calendar = Calendar(identifier: .gregorian)
  4147. f.locale = Locale(identifier: "en_US_POSIX")
  4148. f.timeZone = TimeZone.current
  4149. f.dateFormat = "yyyy-MM-dd"
  4150. return f
  4151. }()
  4152. // MARK: - Calendar page actions + rendering
  4153. private extension ViewController {
  4154. private func makeCalendarHeaderPillButton(title: String, action: Selector) -> NSButton {
  4155. let button = makeSchedulePillButton(title: title)
  4156. button.target = self
  4157. button.action = action
  4158. button.heightAnchor.constraint(equalToConstant: 30).isActive = true
  4159. return button
  4160. }
  4161. private func calendarStartOfMonth(for date: Date) -> Date {
  4162. let calendar = Calendar.current
  4163. let comps = calendar.dateComponents([.year, .month], from: date)
  4164. return calendar.date(from: comps) ?? calendar.startOfDay(for: date)
  4165. }
  4166. private func calendarMonthTitleText(for monthAnchor: Date) -> String {
  4167. let f = DateFormatter()
  4168. f.locale = Locale.current
  4169. f.timeZone = TimeZone.current
  4170. f.dateFormat = "MMMM yyyy"
  4171. return f.string(from: monthAnchor)
  4172. }
  4173. private func calendarWeekdaySymbolsStartingAtFirstWeekday() -> [String] {
  4174. // Align weekday header to Calendar.current.firstWeekday
  4175. let calendar = Calendar.current
  4176. var symbols = DateFormatter().veryShortWeekdaySymbols ?? ["S", "M", "T", "W", "T", "F", "S"]
  4177. // veryShortWeekdaySymbols starts with Sunday in most locales; rotate to firstWeekday.
  4178. let first = max(1, min(7, calendar.firstWeekday)) // 1..7
  4179. let shift = (first - 1) % 7
  4180. if shift == 0 { return symbols }
  4181. let head = Array(symbols[shift...])
  4182. let tail = Array(symbols[..<shift])
  4183. symbols = head + tail
  4184. return symbols
  4185. }
  4186. @objc func calendarPrevMonthPressed(_ sender: NSButton) {
  4187. let calendar = Calendar.current
  4188. calendarPageMonthAnchor = calendar.date(byAdding: .month, value: -1, to: calendarPageMonthAnchor).map(calendarStartOfMonth(for:)) ?? calendarPageMonthAnchor
  4189. calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
  4190. renderCalendarMonthGrid()
  4191. }
  4192. @objc func calendarNextMonthPressed(_ sender: NSButton) {
  4193. let calendar = Calendar.current
  4194. calendarPageMonthAnchor = calendar.date(byAdding: .month, value: 1, to: calendarPageMonthAnchor).map(calendarStartOfMonth(for:)) ?? calendarPageMonthAnchor
  4195. calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
  4196. renderCalendarMonthGrid()
  4197. }
  4198. @objc func calendarRefreshPressed(_ sender: NSButton) {
  4199. Task { [weak self] in
  4200. await self?.loadSchedule()
  4201. }
  4202. }
  4203. @objc func calendarDayCellPressed(_ sender: NSButton) {
  4204. guard requireGoogleLoginForCalendarScheduling() else { return }
  4205. guard let raw = sender.identifier?.rawValue,
  4206. let date = calendarDayKeyFormatter.date(from: raw) else { return }
  4207. calendarPageSelectedDate = Calendar.current.startOfDay(for: date)
  4208. renderCalendarMonthGrid()
  4209. renderCalendarSelectedDay()
  4210. if let refreshedButton = calendarButton(forDateKey: raw) {
  4211. showCalendarDayActionPopover(relativeTo: refreshedButton)
  4212. }
  4213. }
  4214. private func showCalendarDayActionPopover(relativeTo anchor: NSView) {
  4215. guard anchor.window != nil else { return }
  4216. calendarPageActionPopover?.performClose(nil)
  4217. let popover = NSPopover()
  4218. popover.behavior = .transient
  4219. popover.animates = true
  4220. popover.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
  4221. popover.contentViewController = CalendarDayActionMenuViewController(
  4222. palette: palette,
  4223. onSchedule: { [weak self] in
  4224. self?.calendarPageActionPopover?.performClose(nil)
  4225. self?.calendarPageActionPopover = nil
  4226. self?.presentCreateMeetingPopover(relativeTo: anchor)
  4227. }
  4228. )
  4229. calendarPageActionPopover = popover
  4230. popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxY)
  4231. }
  4232. private func presentCreateMeetingPopover(relativeTo anchor: NSView) {
  4233. guard anchor.window != nil else { return }
  4234. calendarPageCreatePopover?.performClose(nil)
  4235. let popover = NSPopover()
  4236. popover.behavior = .transient
  4237. popover.animates = true
  4238. popover.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
  4239. let selectedDate = Calendar.current.startOfDay(for: calendarPageSelectedDate)
  4240. let vc = CreateMeetingPopoverViewController(
  4241. palette: palette,
  4242. typography: typography,
  4243. selectedDate: selectedDate,
  4244. onCancel: { [weak self] in
  4245. self?.calendarPageCreatePopover?.performClose(nil)
  4246. self?.calendarPageCreatePopover = nil
  4247. },
  4248. onSave: { [weak self] draft in
  4249. guard let self else { return }
  4250. self.calendarPageCreatePopover?.performClose(nil)
  4251. self.calendarPageCreatePopover = nil
  4252. self.calendarCreateMeeting(title: draft.title, notes: draft.notes, start: draft.startDate, end: draft.endDate)
  4253. }
  4254. )
  4255. popover.contentViewController = vc
  4256. calendarPageCreatePopover = popover
  4257. popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxY)
  4258. }
  4259. private func calendarCreateMeeting(title: String, notes: String?, start: Date, end: Date) {
  4260. Task { [weak self] in
  4261. guard let self else { return }
  4262. do {
  4263. try await self.ensureGoogleClientIdConfigured(presentingWindow: self.view.window)
  4264. let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
  4265. _ = try await self.calendarClient.createEvent(
  4266. accessToken: token,
  4267. title: title,
  4268. description: notes,
  4269. start: start,
  4270. end: end,
  4271. timeZone: .current
  4272. )
  4273. await self.loadSchedule()
  4274. await MainActor.run {
  4275. let calendar = Calendar.current
  4276. self.calendarPageSelectedDate = calendar.startOfDay(for: start)
  4277. self.calendarPageMonthAnchor = self.calendarStartOfMonth(for: start)
  4278. self.calendarPageMonthLabel?.stringValue = self.calendarMonthTitleText(for: self.calendarPageMonthAnchor)
  4279. self.renderCalendarMonthGrid()
  4280. self.renderCalendarSelectedDay()
  4281. self.showTopToast(message: "Meeting added successfully.", isError: false)
  4282. }
  4283. } catch {
  4284. await MainActor.run {
  4285. self.showTopToast(message: "An issue occurred. Please try again.", isError: true)
  4286. }
  4287. }
  4288. }
  4289. }
  4290. private func renderCalendarMonthGrid() {
  4291. guard let gridStack = calendarPageGridStack else { return }
  4292. gridStack.arrangedSubviews.forEach { v in
  4293. gridStack.removeArrangedSubview(v)
  4294. v.removeFromSuperview()
  4295. }
  4296. let calendar = Calendar.current
  4297. let monthStart = calendarStartOfMonth(for: calendarPageMonthAnchor)
  4298. guard let dayRange = calendar.range(of: .day, in: .month, for: monthStart),
  4299. let monthEnd = calendar.date(byAdding: DateComponents(month: 1, day: 0), to: monthStart) else { return }
  4300. let firstWeekday = calendar.component(.weekday, from: monthStart) // 1..7
  4301. let leadingEmpty = (firstWeekday - calendar.firstWeekday + 7) % 7
  4302. let totalDays = dayRange.count
  4303. let totalCells = leadingEmpty + totalDays
  4304. let rowCount = Int(ceil(Double(totalCells) / 7.0))
  4305. let rowHeight: CGFloat = 56
  4306. let rowSpacing: CGFloat = 12
  4307. let verticalPadding: CGFloat = 32
  4308. calendarPageGridHeightConstraint?.constant = verticalPadding + (CGFloat(rowCount) * rowHeight) + (CGFloat(max(0, rowCount - 1)) * rowSpacing)
  4309. let meetingCounts = calendarMeetingCountsByDay(from: scheduleCachedMeetings, monthStart: monthStart, monthEnd: monthEnd)
  4310. var day = 1
  4311. for _ in 0..<rowCount {
  4312. let row = NSStackView()
  4313. row.translatesAutoresizingMaskIntoConstraints = false
  4314. row.userInterfaceLayoutDirection = .leftToRight
  4315. row.orientation = .horizontal
  4316. row.alignment = .top
  4317. row.distribution = .fillEqually
  4318. row.spacing = rowSpacing
  4319. row.heightAnchor.constraint(equalToConstant: rowHeight).isActive = true
  4320. for col in 0..<7 {
  4321. let cellIndex = (gridStack.arrangedSubviews.count * 7) + col
  4322. if cellIndex < leadingEmpty || day > totalDays {
  4323. row.addArrangedSubview(calendarEmptyDayCell())
  4324. continue
  4325. }
  4326. guard let date = calendar.date(byAdding: .day, value: day - 1, to: monthStart) else {
  4327. row.addArrangedSubview(calendarEmptyDayCell())
  4328. continue
  4329. }
  4330. let isSelected = calendar.isDate(date, inSameDayAs: calendarPageSelectedDate)
  4331. let key = calendarDayKeyFormatter.string(from: calendar.startOfDay(for: date))
  4332. let count = meetingCounts[key] ?? 0
  4333. row.addArrangedSubview(calendarDayCell(dayNumber: day, dateKey: key, meetingCount: count, isSelected: isSelected))
  4334. day += 1
  4335. }
  4336. gridStack.addArrangedSubview(row)
  4337. row.widthAnchor.constraint(equalTo: gridStack.widthAnchor).isActive = true
  4338. }
  4339. }
  4340. private func calendarButton(forDateKey key: String) -> NSButton? {
  4341. guard let gridStack = calendarPageGridStack else { return nil }
  4342. for rowView in gridStack.arrangedSubviews {
  4343. guard let row = rowView as? NSStackView else { continue }
  4344. for cell in row.arrangedSubviews {
  4345. if let button = cell as? NSButton, button.identifier?.rawValue == key {
  4346. return button
  4347. }
  4348. }
  4349. }
  4350. return nil
  4351. }
  4352. private func renderCalendarSelectedDay() {
  4353. let calendar = Calendar.current
  4354. let selectedDay = calendar.startOfDay(for: calendarPageSelectedDate)
  4355. let nextDay = calendar.date(byAdding: .day, value: 1, to: selectedDay) ?? selectedDay.addingTimeInterval(86400)
  4356. let meetings = scheduleCachedMeetings
  4357. .filter { $0.startDate >= selectedDay && $0.startDate < nextDay }
  4358. .sorted(by: { $0.startDate < $1.startDate })
  4359. let f = DateFormatter()
  4360. f.locale = Locale.current
  4361. f.timeZone = TimeZone.current
  4362. f.dateFormat = "EEE, d MMM"
  4363. if meetings.isEmpty {
  4364. calendarPageDaySummaryLabel?.stringValue = googleOAuth.loadTokens() == nil
  4365. ? "Connect Google to see meetings"
  4366. : "No meetings on \(f.string(from: selectedDay))"
  4367. } else if meetings.count == 1 {
  4368. calendarPageDaySummaryLabel?.stringValue = "1 meeting on \(f.string(from: selectedDay))"
  4369. } else {
  4370. calendarPageDaySummaryLabel?.stringValue = "\(meetings.count) meetings on \(f.string(from: selectedDay))"
  4371. }
  4372. }
  4373. private func calendarMeetingCountsByDay(from meetings: [ScheduledMeeting], monthStart: Date, monthEnd: Date) -> [String: Int] {
  4374. let calendar = Calendar.current
  4375. var counts: [String: Int] = [:]
  4376. for meeting in meetings {
  4377. guard meeting.startDate >= monthStart && meeting.startDate < monthEnd else { continue }
  4378. let key = calendarDayKeyFormatter.string(from: calendar.startOfDay(for: meeting.startDate))
  4379. counts[key, default: 0] += 1
  4380. }
  4381. return counts
  4382. }
  4383. private func calendarEmptyDayCell() -> NSView {
  4384. let v = NSView()
  4385. v.translatesAutoresizingMaskIntoConstraints = false
  4386. v.heightAnchor.constraint(equalToConstant: 56).isActive = true
  4387. return v
  4388. }
  4389. private func calendarDayCell(dayNumber: Int, dateKey: String, meetingCount: Int, isSelected: Bool) -> NSButton {
  4390. let button = HoverButton(title: "", target: self, action: #selector(calendarDayCellPressed(_:)))
  4391. button.translatesAutoresizingMaskIntoConstraints = false
  4392. button.isBordered = false
  4393. button.bezelStyle = .regularSquare
  4394. button.wantsLayer = true
  4395. button.layer?.cornerRadius = 12
  4396. button.layer?.masksToBounds = true
  4397. button.identifier = NSUserInterfaceItemIdentifier(dateKey)
  4398. button.heightAnchor.constraint(equalToConstant: 56).isActive = true
  4399. button.setContentHuggingPriority(.required, for: .vertical)
  4400. button.setContentCompressionResistancePriority(.required, for: .vertical)
  4401. button.alignment = .left
  4402. button.imagePosition = .noImage
  4403. let base = palette.inputBackground
  4404. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  4405. let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
  4406. let selectedBackground = darkModeEnabled
  4407. ? NSColor(calibratedRed: 30.0 / 255.0, green: 34.0 / 255.0, blue: 42.0 / 255.0, alpha: 1)
  4408. : NSColor(calibratedRed: 255.0 / 255.0, green: 246.0 / 255.0, blue: 236.0 / 255.0, alpha: 1)
  4409. let borderIdle = palette.inputBorder
  4410. let borderSelected = palette.primaryBlueBorder
  4411. func applyAppearance(hovering: Bool) {
  4412. button.layer?.backgroundColor = (isSelected ? selectedBackground : (hovering ? hover : base)).cgColor
  4413. button.layer?.borderWidth = isSelected ? 1.5 : 1
  4414. button.layer?.borderColor = (isSelected ? borderSelected : borderIdle).cgColor
  4415. }
  4416. applyAppearance(hovering: false)
  4417. button.onHoverChanged = { hovering in
  4418. applyAppearance(hovering: hovering)
  4419. }
  4420. button.attributedTitle = NSAttributedString(
  4421. string: " \(dayNumber)",
  4422. attributes: [
  4423. .font: NSFont.systemFont(ofSize: 14, weight: .bold),
  4424. .foregroundColor: palette.textPrimary
  4425. ]
  4426. )
  4427. if meetingCount > 0 {
  4428. let dot = roundedContainer(cornerRadius: 4, color: palette.meetingBadge)
  4429. dot.translatesAutoresizingMaskIntoConstraints = false
  4430. dot.layer?.borderWidth = 0
  4431. button.addSubview(dot)
  4432. NSLayoutConstraint.activate([
  4433. dot.trailingAnchor.constraint(equalTo: button.trailingAnchor, constant: -10),
  4434. dot.centerYAnchor.constraint(equalTo: button.centerYAnchor),
  4435. dot.widthAnchor.constraint(equalToConstant: 8),
  4436. dot.heightAnchor.constraint(equalToConstant: 8)
  4437. ])
  4438. }
  4439. return button
  4440. }
  4441. }
  4442. private final class CalendarDayActionMenuViewController: NSViewController {
  4443. private let palette: Palette
  4444. private let onSchedule: () -> Void
  4445. init(palette: Palette, onSchedule: @escaping () -> Void) {
  4446. self.palette = palette
  4447. self.onSchedule = onSchedule
  4448. super.init(nibName: nil, bundle: nil)
  4449. }
  4450. required init?(coder: NSCoder) { nil }
  4451. override func loadView() {
  4452. let root = NSView()
  4453. root.translatesAutoresizingMaskIntoConstraints = false
  4454. let stack = NSStackView()
  4455. stack.translatesAutoresizingMaskIntoConstraints = false
  4456. stack.orientation = .vertical
  4457. stack.alignment = .leading
  4458. stack.spacing = 10
  4459. let title = NSTextField(labelWithString: "Actions")
  4460. title.font = NSFont.systemFont(ofSize: 12, weight: .semibold)
  4461. title.textColor = palette.textMuted
  4462. let schedule = NSButton(title: "Schedule meeting", target: self, action: #selector(schedulePressed(_:)))
  4463. schedule.bezelStyle = .rounded
  4464. schedule.font = NSFont.systemFont(ofSize: 13, weight: .medium)
  4465. stack.addArrangedSubview(title)
  4466. stack.addArrangedSubview(schedule)
  4467. root.addSubview(stack)
  4468. NSLayoutConstraint.activate([
  4469. root.widthAnchor.constraint(equalToConstant: 220),
  4470. root.heightAnchor.constraint(greaterThanOrEqualToConstant: 86),
  4471. stack.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 14),
  4472. stack.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -14),
  4473. stack.topAnchor.constraint(equalTo: root.topAnchor, constant: 12),
  4474. stack.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -12)
  4475. ])
  4476. view = root
  4477. }
  4478. @objc private func schedulePressed(_ sender: NSButton) {
  4479. onSchedule()
  4480. }
  4481. }
  4482. private final class CreateMeetingPopoverViewController: NSViewController, NSTextViewDelegate {
  4483. struct Draft {
  4484. let title: String
  4485. let notes: String?
  4486. let startDate: Date
  4487. let endDate: Date
  4488. }
  4489. private let palette: Palette
  4490. private let typography: Typography
  4491. private let selectedDate: Date
  4492. private let onCancel: () -> Void
  4493. private let onSave: (Draft) -> Void
  4494. private var titleField: NSTextField?
  4495. private var timePicker: NSDatePicker?
  4496. private var durationField: NSTextField?
  4497. private var notesView: NSTextView?
  4498. private var notesScrollView: NSScrollView?
  4499. private var errorLabel: NSTextField?
  4500. private var notesBorderIdle = NSColor.clear
  4501. private var notesBorderHover = NSColor.clear
  4502. private var notesBorderFocused = NSColor.clear
  4503. private var notesIsHovered = false
  4504. private var notesIsFocused = false
  4505. init(palette: Palette,
  4506. typography: Typography,
  4507. selectedDate: Date,
  4508. onCancel: @escaping () -> Void,
  4509. onSave: @escaping (Draft) -> Void) {
  4510. self.palette = palette
  4511. self.typography = typography
  4512. self.selectedDate = selectedDate
  4513. self.onCancel = onCancel
  4514. self.onSave = onSave
  4515. super.init(nibName: nil, bundle: nil)
  4516. }
  4517. required init?(coder: NSCoder) { nil }
  4518. override func loadView() {
  4519. let root = NSView()
  4520. root.translatesAutoresizingMaskIntoConstraints = false
  4521. root.userInterfaceLayoutDirection = .leftToRight
  4522. root.wantsLayer = true
  4523. root.layer?.cornerRadius = 14
  4524. root.layer?.masksToBounds = true
  4525. root.layer?.backgroundColor = palette.sectionCard.cgColor
  4526. root.layer?.borderWidth = 1
  4527. root.layer?.borderColor = palette.inputBorder.withAlphaComponent(0.9).cgColor
  4528. let stack = NSStackView()
  4529. stack.translatesAutoresizingMaskIntoConstraints = false
  4530. stack.orientation = .vertical
  4531. stack.alignment = .leading
  4532. stack.spacing = 14
  4533. stack.userInterfaceLayoutDirection = .leftToRight
  4534. let inputSurface = palette.inputBackground.blended(withFraction: 0.18, of: palette.sectionCard) ?? palette.inputBackground
  4535. let fieldBorder = palette.textSecondary.withAlphaComponent(0.4)
  4536. notesBorderIdle = fieldBorder
  4537. notesBorderHover = palette.textSecondary.withAlphaComponent(0.72)
  4538. notesBorderFocused = palette.primaryBlueBorder
  4539. let header = NSTextField(labelWithString: "Schedule meeting")
  4540. header.font = NSFont.systemFont(ofSize: 16, weight: .semibold)
  4541. header.textColor = palette.textPrimary
  4542. header.alignment = .left
  4543. header.userInterfaceLayoutDirection = .leftToRight
  4544. header.baseWritingDirection = .leftToRight
  4545. let titleLabel = NSTextField(labelWithString: "Title")
  4546. titleLabel.font = typography.fieldLabel
  4547. titleLabel.textColor = palette.textSecondary
  4548. titleLabel.alignment = .left
  4549. titleLabel.userInterfaceLayoutDirection = .leftToRight
  4550. titleLabel.baseWritingDirection = .leftToRight
  4551. let titleShell = NSView()
  4552. titleShell.translatesAutoresizingMaskIntoConstraints = false
  4553. titleShell.wantsLayer = true
  4554. titleShell.layer?.cornerRadius = 8
  4555. titleShell.layer?.backgroundColor = inputSurface.cgColor
  4556. titleShell.layer?.borderColor = fieldBorder.cgColor
  4557. titleShell.layer?.borderWidth = 1.2
  4558. titleShell.heightAnchor.constraint(equalToConstant: 40).isActive = true
  4559. let titleField = NSTextField(string: "")
  4560. titleField.translatesAutoresizingMaskIntoConstraints = false
  4561. titleField.isBordered = false
  4562. titleField.drawsBackground = false
  4563. titleField.focusRingType = .none
  4564. titleField.font = NSFont.systemFont(ofSize: 14, weight: .regular)
  4565. titleField.textColor = palette.textPrimary
  4566. titleField.placeholderString = "Team sync"
  4567. titleShell.addSubview(titleField)
  4568. NSLayoutConstraint.activate([
  4569. titleField.leadingAnchor.constraint(equalTo: titleShell.leadingAnchor, constant: 10),
  4570. titleField.trailingAnchor.constraint(equalTo: titleShell.trailingAnchor, constant: -10),
  4571. titleField.centerYAnchor.constraint(equalTo: titleShell.centerYAnchor)
  4572. ])
  4573. self.titleField = titleField
  4574. let timeRow = NSStackView()
  4575. timeRow.translatesAutoresizingMaskIntoConstraints = false
  4576. timeRow.orientation = .horizontal
  4577. timeRow.alignment = .centerY
  4578. timeRow.spacing = 10
  4579. timeRow.distribution = .fill
  4580. let startLabel = NSTextField(labelWithString: "Start")
  4581. startLabel.font = typography.fieldLabel
  4582. startLabel.textColor = palette.textSecondary
  4583. startLabel.alignment = .left
  4584. startLabel.userInterfaceLayoutDirection = .leftToRight
  4585. startLabel.baseWritingDirection = .leftToRight
  4586. let pickerShell = NSView()
  4587. pickerShell.translatesAutoresizingMaskIntoConstraints = false
  4588. pickerShell.wantsLayer = true
  4589. pickerShell.layer?.cornerRadius = 8
  4590. pickerShell.layer?.backgroundColor = inputSurface.cgColor
  4591. pickerShell.layer?.borderColor = fieldBorder.cgColor
  4592. pickerShell.layer?.borderWidth = 1.2
  4593. pickerShell.heightAnchor.constraint(equalToConstant: 34).isActive = true
  4594. let timePicker = NSDatePicker()
  4595. timePicker.translatesAutoresizingMaskIntoConstraints = false
  4596. timePicker.isBordered = false
  4597. timePicker.drawsBackground = false
  4598. timePicker.focusRingType = .none
  4599. timePicker.datePickerStyle = .textFieldAndStepper
  4600. timePicker.datePickerElements = [.hourMinute]
  4601. timePicker.font = typography.filterText
  4602. timePicker.textColor = palette.textSecondary
  4603. timePicker.dateValue = Date()
  4604. pickerShell.addSubview(timePicker)
  4605. NSLayoutConstraint.activate([
  4606. timePicker.leadingAnchor.constraint(equalTo: pickerShell.leadingAnchor, constant: 8),
  4607. timePicker.trailingAnchor.constraint(equalTo: pickerShell.trailingAnchor, constant: -8),
  4608. timePicker.centerYAnchor.constraint(equalTo: pickerShell.centerYAnchor)
  4609. ])
  4610. self.timePicker = timePicker
  4611. let durationLabel = NSTextField(labelWithString: "Duration (min)")
  4612. durationLabel.font = typography.fieldLabel
  4613. durationLabel.textColor = palette.textSecondary
  4614. durationLabel.alignment = .left
  4615. durationLabel.userInterfaceLayoutDirection = .leftToRight
  4616. durationLabel.baseWritingDirection = .leftToRight
  4617. let durationShell = NSView()
  4618. durationShell.translatesAutoresizingMaskIntoConstraints = false
  4619. durationShell.wantsLayer = true
  4620. durationShell.layer?.cornerRadius = 8
  4621. durationShell.layer?.backgroundColor = inputSurface.cgColor
  4622. durationShell.layer?.borderColor = fieldBorder.cgColor
  4623. durationShell.layer?.borderWidth = 1.2
  4624. durationShell.heightAnchor.constraint(equalToConstant: 34).isActive = true
  4625. let durationField = NSTextField(string: "30")
  4626. durationField.translatesAutoresizingMaskIntoConstraints = false
  4627. durationField.isBordered = false
  4628. durationField.drawsBackground = false
  4629. durationField.focusRingType = .none
  4630. durationField.font = typography.filterText
  4631. durationField.textColor = palette.textSecondary
  4632. durationField.formatter = NumberFormatter()
  4633. durationShell.addSubview(durationField)
  4634. NSLayoutConstraint.activate([
  4635. durationField.leadingAnchor.constraint(equalTo: durationShell.leadingAnchor, constant: 8),
  4636. durationField.trailingAnchor.constraint(equalTo: durationShell.trailingAnchor, constant: -8),
  4637. durationField.centerYAnchor.constraint(equalTo: durationShell.centerYAnchor)
  4638. ])
  4639. self.durationField = durationField
  4640. let startGroup = NSStackView(views: [startLabel, pickerShell])
  4641. startGroup.translatesAutoresizingMaskIntoConstraints = false
  4642. startGroup.orientation = .vertical
  4643. startGroup.alignment = .leading
  4644. startGroup.spacing = 6
  4645. let durationGroup = NSStackView(views: [durationLabel, durationShell])
  4646. durationGroup.translatesAutoresizingMaskIntoConstraints = false
  4647. durationGroup.orientation = .vertical
  4648. durationGroup.alignment = .leading
  4649. durationGroup.spacing = 6
  4650. timeRow.addArrangedSubview(startGroup)
  4651. timeRow.addArrangedSubview(durationGroup)
  4652. startGroup.widthAnchor.constraint(equalTo: durationGroup.widthAnchor).isActive = true
  4653. let notesLabel = NSTextField(labelWithString: "Notes")
  4654. notesLabel.font = typography.fieldLabel
  4655. notesLabel.textColor = palette.textSecondary
  4656. notesLabel.alignment = .left
  4657. notesLabel.userInterfaceLayoutDirection = .leftToRight
  4658. notesLabel.baseWritingDirection = .leftToRight
  4659. let notesScroll = HoverFocusScrollView()
  4660. notesScroll.translatesAutoresizingMaskIntoConstraints = false
  4661. notesScroll.drawsBackground = true
  4662. notesScroll.backgroundColor = inputSurface
  4663. notesScroll.hasVerticalScroller = true
  4664. notesScroll.hasHorizontalScroller = false
  4665. notesScroll.borderType = .noBorder
  4666. notesScroll.wantsLayer = true
  4667. notesScroll.layer?.cornerRadius = 8
  4668. notesScroll.layer?.masksToBounds = true
  4669. notesScroll.layer?.borderWidth = 1.2
  4670. notesScroll.layer?.borderColor = notesBorderIdle.cgColor
  4671. notesScroll.heightAnchor.constraint(equalToConstant: 100).isActive = true
  4672. notesScroll.onHoverChanged = { [weak self] hovering in
  4673. guard let self else { return }
  4674. self.notesIsHovered = hovering
  4675. self.updateNotesBorderAppearance()
  4676. }
  4677. notesScroll.onMouseDown = { [weak self] in
  4678. guard let self, let notesView = self.notesView as? ImmediateFocusTextView else { return }
  4679. self.view.window?.makeFirstResponder(notesView)
  4680. notesView.ensureCaretVisibleImmediately()
  4681. self.notesIsFocused = true
  4682. self.updateNotesBorderAppearance()
  4683. }
  4684. let notesView = ImmediateFocusTextView(frame: .zero)
  4685. notesView.drawsBackground = false
  4686. notesView.font = NSFont.systemFont(ofSize: 13, weight: .regular)
  4687. notesView.textColor = palette.textPrimary
  4688. notesView.insertionPointColor = palette.textPrimary
  4689. notesView.isEditable = true
  4690. notesView.isSelectable = true
  4691. notesView.isRichText = false
  4692. notesView.importsGraphics = false
  4693. notesView.isHorizontallyResizable = false
  4694. notesView.isVerticallyResizable = true
  4695. notesView.autoresizingMask = [.width]
  4696. notesView.textContainerInset = NSSize(width: 6, height: 6)
  4697. notesView.textContainer?.widthTracksTextView = true
  4698. notesView.textContainer?.containerSize = NSSize(
  4699. width: notesScroll.contentSize.width,
  4700. height: CGFloat.greatestFiniteMagnitude
  4701. )
  4702. notesView.delegate = self
  4703. notesScroll.documentView = notesView
  4704. self.notesView = notesView
  4705. self.notesScrollView = notesScroll
  4706. let error = NSTextField(labelWithString: "")
  4707. error.translatesAutoresizingMaskIntoConstraints = false
  4708. error.textColor = NSColor.systemRed
  4709. error.font = NSFont.systemFont(ofSize: 12, weight: .semibold)
  4710. error.isHidden = true
  4711. self.errorLabel = error
  4712. let actions = NSStackView()
  4713. actions.translatesAutoresizingMaskIntoConstraints = false
  4714. actions.orientation = .horizontal
  4715. actions.alignment = .centerY
  4716. actions.spacing = 10
  4717. let cancel = NSButton(title: "Cancel", target: self, action: #selector(cancelPressed(_:)))
  4718. cancel.bezelStyle = .rounded
  4719. let save = NSButton(title: "Save", target: self, action: #selector(savePressed(_:)))
  4720. save.bezelStyle = .rounded
  4721. save.keyEquivalent = "\r"
  4722. let actionsSpacer = NSView()
  4723. actionsSpacer.translatesAutoresizingMaskIntoConstraints = false
  4724. actionsSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  4725. actions.addArrangedSubview(cancel)
  4726. actions.addArrangedSubview(actionsSpacer)
  4727. actions.addArrangedSubview(save)
  4728. stack.addArrangedSubview(header)
  4729. stack.addArrangedSubview(titleLabel)
  4730. stack.addArrangedSubview(titleShell)
  4731. stack.addArrangedSubview(timeRow)
  4732. stack.addArrangedSubview(notesLabel)
  4733. stack.addArrangedSubview(notesScroll)
  4734. stack.addArrangedSubview(error)
  4735. stack.addArrangedSubview(actions)
  4736. root.addSubview(stack)
  4737. NSLayoutConstraint.activate([
  4738. root.widthAnchor.constraint(equalToConstant: 372),
  4739. stack.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 16),
  4740. stack.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -16),
  4741. stack.topAnchor.constraint(equalTo: root.topAnchor, constant: 16),
  4742. stack.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -16),
  4743. titleShell.widthAnchor.constraint(equalTo: stack.widthAnchor),
  4744. timeRow.widthAnchor.constraint(equalTo: stack.widthAnchor),
  4745. notesScroll.widthAnchor.constraint(equalTo: stack.widthAnchor),
  4746. error.widthAnchor.constraint(equalTo: stack.widthAnchor),
  4747. actions.widthAnchor.constraint(equalTo: stack.widthAnchor)
  4748. ])
  4749. view = root
  4750. }
  4751. @objc private func cancelPressed(_ sender: NSButton) {
  4752. onCancel()
  4753. }
  4754. @objc private func savePressed(_ sender: NSButton) {
  4755. setError(nil)
  4756. let title = (titleField?.stringValue ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
  4757. if title.isEmpty {
  4758. setError("Please enter a title.")
  4759. return
  4760. }
  4761. let durationText = (durationField?.stringValue ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
  4762. let durationMinutes = Int(durationText) ?? 0
  4763. if durationMinutes <= 0 {
  4764. setError("Duration must be a positive number of minutes.")
  4765. return
  4766. }
  4767. let time = timePicker?.dateValue ?? Date()
  4768. let calendar = Calendar.current
  4769. let dateParts = calendar.dateComponents([.year, .month, .day], from: selectedDate)
  4770. let timeParts = calendar.dateComponents([.hour, .minute], from: time)
  4771. var merged = DateComponents()
  4772. merged.year = dateParts.year
  4773. merged.month = dateParts.month
  4774. merged.day = dateParts.day
  4775. merged.hour = timeParts.hour
  4776. merged.minute = timeParts.minute
  4777. guard let start = calendar.date(from: merged) else {
  4778. setError("Invalid start time.")
  4779. return
  4780. }
  4781. let end = start.addingTimeInterval(TimeInterval(durationMinutes * 60))
  4782. let notes = notesView?.string.trimmingCharacters(in: .whitespacesAndNewlines)
  4783. let cleanedNotes = (notes?.isEmpty == false) ? notes : nil
  4784. onSave(Draft(title: title, notes: cleanedNotes, startDate: start, endDate: end))
  4785. }
  4786. private func updateNotesBorderAppearance() {
  4787. let color: NSColor
  4788. let width: CGFloat
  4789. if notesIsFocused {
  4790. color = notesBorderFocused
  4791. width = 1.6
  4792. } else if notesIsHovered {
  4793. color = notesBorderHover
  4794. width = 1.4
  4795. } else {
  4796. color = notesBorderIdle
  4797. width = 1.2
  4798. }
  4799. notesScrollView?.layer?.borderColor = color.cgColor
  4800. notesScrollView?.layer?.borderWidth = width
  4801. }
  4802. private func setError(_ message: String?) {
  4803. guard let errorLabel else { return }
  4804. errorLabel.stringValue = message ?? ""
  4805. errorLabel.isHidden = message == nil
  4806. }
  4807. func textDidBeginEditing(_ notification: Notification) {
  4808. guard let current = notification.object as? NSTextView, current === notesView else { return }
  4809. notesIsFocused = true
  4810. updateNotesBorderAppearance()
  4811. }
  4812. func textDidEndEditing(_ notification: Notification) {
  4813. guard let current = notification.object as? NSTextView, current === notesView else { return }
  4814. notesIsFocused = false
  4815. updateNotesBorderAppearance()
  4816. }
  4817. }
  4818. private final class HoverFocusScrollView: NSScrollView {
  4819. var onHoverChanged: ((Bool) -> Void)?
  4820. var onMouseDown: (() -> Void)?
  4821. private var hoverTrackingArea: NSTrackingArea?
  4822. override func updateTrackingAreas() {
  4823. super.updateTrackingAreas()
  4824. if let hoverTrackingArea {
  4825. removeTrackingArea(hoverTrackingArea)
  4826. }
  4827. let area = NSTrackingArea(
  4828. rect: bounds,
  4829. options: [.activeInActiveApp, .inVisibleRect, .mouseEnteredAndExited],
  4830. owner: self,
  4831. userInfo: nil
  4832. )
  4833. addTrackingArea(area)
  4834. hoverTrackingArea = area
  4835. }
  4836. override func mouseEntered(with event: NSEvent) {
  4837. super.mouseEntered(with: event)
  4838. onHoverChanged?(true)
  4839. }
  4840. override func mouseExited(with event: NSEvent) {
  4841. super.mouseExited(with: event)
  4842. onHoverChanged?(false)
  4843. }
  4844. override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
  4845. true
  4846. }
  4847. override func mouseDown(with event: NSEvent) {
  4848. onMouseDown?()
  4849. if let window, !window.isKeyWindow {
  4850. window.makeKeyAndOrderFront(nil)
  4851. return
  4852. }
  4853. // Forward the click straight to the text view so caret placement/blink starts immediately.
  4854. if let textView = documentView as? NSTextView {
  4855. window?.makeFirstResponder(textView)
  4856. textView.mouseDown(with: event)
  4857. return
  4858. }
  4859. super.mouseDown(with: event)
  4860. }
  4861. }
  4862. private final class ImmediateFocusTextView: NSTextView {
  4863. override var acceptsFirstResponder: Bool { true }
  4864. override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
  4865. true
  4866. }
  4867. @discardableResult
  4868. override func becomeFirstResponder() -> Bool {
  4869. let accepted = super.becomeFirstResponder()
  4870. if accepted {
  4871. ensureCaretVisibleImmediately()
  4872. }
  4873. return accepted
  4874. }
  4875. override func mouseDown(with event: NSEvent) {
  4876. window?.makeFirstResponder(self)
  4877. super.mouseDown(with: event)
  4878. ensureCaretVisibleImmediately()
  4879. }
  4880. func ensureCaretVisibleImmediately() {
  4881. var range = selectedRange()
  4882. if range.location == NSNotFound {
  4883. range = NSRange(location: string.utf16.count, length: 0)
  4884. }
  4885. setSelectedRange(range)
  4886. scrollRangeToVisible(range)
  4887. needsDisplay = true
  4888. displayIfNeeded()
  4889. }
  4890. }
  4891. // MARK: - Schedule actions (OAuth entry)
  4892. private extension ViewController {
  4893. @objc func scheduleReloadButtonPressed(_ sender: NSButton) {
  4894. scheduleReloadClicked()
  4895. }
  4896. @objc func scheduleScrollLeftPressed(_ sender: NSButton) {
  4897. scrollScheduleCards(direction: -1)
  4898. }
  4899. @objc func scheduleScrollRightPressed(_ sender: NSButton) {
  4900. scrollScheduleCards(direction: 1)
  4901. }
  4902. @objc func scheduleCardButtonPressed(_ sender: NSButton) {
  4903. guard storeKitCoordinator.hasPremiumAccess else {
  4904. showPaywall()
  4905. return
  4906. }
  4907. guard let raw = sender.identifier?.rawValue,
  4908. let url = URL(string: raw) else { return }
  4909. openMeetingURL(url)
  4910. }
  4911. @objc func scheduleConnectButtonPressed(_ sender: NSButton) {
  4912. scheduleConnectClicked()
  4913. }
  4914. @objc func schedulePageLoadMorePressed(_ sender: NSButton) {
  4915. appendSchedulePageBatchIfNeeded()
  4916. }
  4917. private func scheduleInitialHeadingText() -> String {
  4918. googleOAuth.loadTokens() == nil ? "Connect Google to see meetings" : "Loading…"
  4919. }
  4920. private func schedulePageInitialHeadingText() -> String {
  4921. googleOAuth.loadTokens() == nil ? "Connect Google to see meetings" : "Loading schedule…"
  4922. }
  4923. @objc func scheduleFilterDropdownChanged(_ sender: NSPopUpButton) {
  4924. guard let selectedItem = sender.selectedItem,
  4925. let filter = ScheduleFilter(rawValue: selectedItem.tag) else { return }
  4926. applyScheduleFilter(filter)
  4927. }
  4928. private func applyScheduleFilter(_ filter: ScheduleFilter) {
  4929. scheduleFilter = filter
  4930. scheduleFilterDropdown?.selectItem(at: filter.rawValue)
  4931. Task { [weak self] in
  4932. await self?.loadSchedule()
  4933. }
  4934. }
  4935. @objc func schedulePageFilterDropdownChanged(_ sender: NSPopUpButton) {
  4936. guard let selectedItem = sender.selectedItem,
  4937. let filter = SchedulePageFilter(rawValue: selectedItem.tag) else { return }
  4938. schedulePageFilter = filter
  4939. refreshSchedulePageDateFilterUI()
  4940. applySchedulePageFiltersAndRender()
  4941. }
  4942. @objc func schedulePageDatePickerChanged(_ sender: NSDatePicker) {
  4943. schedulePageFromDate = schedulePageFromDatePicker?.dateValue ?? schedulePageFromDate
  4944. schedulePageToDate = schedulePageToDatePicker?.dateValue ?? schedulePageToDate
  4945. }
  4946. @objc func schedulePageApplyDateRangePressed(_ sender: NSButton) {
  4947. schedulePageFilter = .customRange
  4948. schedulePageFilterDropdown?.selectItem(at: SchedulePageFilter.customRange.rawValue)
  4949. refreshSchedulePageDateFilterUI()
  4950. applySchedulePageFiltersAndRender()
  4951. }
  4952. @objc func schedulePageResetFiltersPressed(_ sender: NSButton) {
  4953. schedulePageFilter = .all
  4954. schedulePageFilterDropdown?.selectItem(at: SchedulePageFilter.all.rawValue)
  4955. let today = Calendar.current.startOfDay(for: Date())
  4956. schedulePageFromDate = today
  4957. schedulePageToDate = today
  4958. schedulePageFromDatePicker?.dateValue = today
  4959. schedulePageToDatePicker?.dateValue = today
  4960. refreshSchedulePageDateFilterUI()
  4961. applySchedulePageFiltersAndRender()
  4962. }
  4963. @objc func schedulePageAddMeetingPressed(_ sender: NSButton) {
  4964. guard requireGoogleLoginForCalendarScheduling() else { return }
  4965. let accessory = NSView(frame: NSRect(x: 0, y: 0, width: 230, height: 28))
  4966. let datePicker = NSDatePicker(frame: accessory.bounds)
  4967. datePicker.autoresizingMask = [.width, .height]
  4968. datePicker.datePickerMode = .single
  4969. datePicker.datePickerStyle = .textFieldAndStepper
  4970. datePicker.datePickerElements = [.yearMonthDay]
  4971. datePicker.dateValue = Calendar.current.startOfDay(for: Date())
  4972. accessory.addSubview(datePicker)
  4973. let alert = NSAlert()
  4974. alert.messageText = "Select date"
  4975. alert.informativeText = "Choose a date to schedule your meeting."
  4976. alert.alertStyle = .informational
  4977. alert.accessoryView = accessory
  4978. alert.addButton(withTitle: "Continue")
  4979. alert.addButton(withTitle: "Cancel")
  4980. guard alert.runModal() == .alertFirstButtonReturn else { return }
  4981. calendarPageSelectedDate = Calendar.current.startOfDay(for: datePicker.dateValue)
  4982. presentCreateMeetingPopover(relativeTo: sender)
  4983. }
  4984. private func scheduleTimeText(for meeting: ScheduledMeeting) -> String {
  4985. if meeting.isAllDay { return "All day" }
  4986. let f = DateFormatter()
  4987. f.locale = Locale.current
  4988. f.timeZone = TimeZone.current
  4989. f.dateStyle = .none
  4990. f.timeStyle = .short
  4991. return "\(f.string(from: meeting.startDate)) - \(f.string(from: meeting.endDate))"
  4992. }
  4993. private func scheduleDayText(for meeting: ScheduledMeeting) -> String {
  4994. let f = DateFormatter()
  4995. f.locale = Locale.current
  4996. f.timeZone = TimeZone.current
  4997. f.dateFormat = "EEE, d MMM"
  4998. return f.string(from: meeting.startDate)
  4999. }
  5000. private func scheduleDurationText(for meeting: ScheduledMeeting) -> String {
  5001. if meeting.isAllDay { return "Duration: all day" }
  5002. let duration = max(0, meeting.endDate.timeIntervalSince(meeting.startDate))
  5003. let totalMinutes = Int(duration / 60)
  5004. let hours = totalMinutes / 60
  5005. let minutes = totalMinutes % 60
  5006. if hours > 0, minutes > 0 { return "Duration: \(hours)h \(minutes)m" }
  5007. if hours > 0 { return "Duration: \(hours)h" }
  5008. return "Duration: \(minutes)m"
  5009. }
  5010. private func scheduleHeadingText(for meetings: [ScheduledMeeting]) -> String {
  5011. guard let first = meetings.first else {
  5012. return googleOAuth.loadTokens() == nil ? "Connect Google to see meetings" : "No upcoming meetings"
  5013. }
  5014. let day = Calendar.current.startOfDay(for: first.startDate)
  5015. let f = DateFormatter()
  5016. f.locale = Locale.current
  5017. f.timeZone = TimeZone.current
  5018. f.dateFormat = "EEEE, d MMM"
  5019. return f.string(from: day)
  5020. }
  5021. private func openMeetingURL(_ url: URL) {
  5022. NSWorkspace.shared.open(url)
  5023. }
  5024. private func renderScheduleCards(into stack: NSStackView, meetings: [ScheduledMeeting]) {
  5025. displayedScheduleMeetings = meetings
  5026. let shouldShowScrollControls = meetings.count > 3
  5027. scheduleScrollLeftButton?.isHidden = !shouldShowScrollControls
  5028. scheduleScrollRightButton?.isHidden = !shouldShowScrollControls
  5029. scheduleCardsScrollView?.contentView.setBoundsOrigin(.zero)
  5030. if let scroll = scheduleCardsScrollView {
  5031. scroll.reflectScrolledClipView(scroll.contentView)
  5032. }
  5033. stack.arrangedSubviews.forEach { v in
  5034. stack.removeArrangedSubview(v)
  5035. v.removeFromSuperview()
  5036. }
  5037. if meetings.isEmpty {
  5038. let empty = roundedContainer(cornerRadius: 10, color: palette.sectionCard)
  5039. empty.translatesAutoresizingMaskIntoConstraints = false
  5040. empty.widthAnchor.constraint(equalToConstant: 240).isActive = true
  5041. empty.heightAnchor.constraint(equalToConstant: 150).isActive = true
  5042. styleSurface(empty, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  5043. let label = textLabel(googleOAuth.loadTokens() == nil ? "Connect to load schedule" : "No meetings", font: typography.cardSubtitle, color: palette.textSecondary)
  5044. label.translatesAutoresizingMaskIntoConstraints = false
  5045. empty.addSubview(label)
  5046. NSLayoutConstraint.activate([
  5047. label.centerXAnchor.constraint(equalTo: empty.centerXAnchor),
  5048. label.centerYAnchor.constraint(equalTo: empty.centerYAnchor)
  5049. ])
  5050. stack.addArrangedSubview(empty)
  5051. return
  5052. }
  5053. for meeting in meetings {
  5054. stack.addArrangedSubview(scheduleCard(meeting: meeting))
  5055. }
  5056. }
  5057. private func filteredMeetings(_ meetings: [ScheduledMeeting]) -> [ScheduledMeeting] {
  5058. switch scheduleFilter {
  5059. case .all:
  5060. return meetings
  5061. case .today:
  5062. let start = Calendar.current.startOfDay(for: Date())
  5063. let end = Calendar.current.date(byAdding: .day, value: 1, to: start) ?? start.addingTimeInterval(86400)
  5064. return meetings.filter { $0.startDate >= start && $0.startDate < end }
  5065. case .week:
  5066. let now = Date()
  5067. let end = Calendar.current.date(byAdding: .day, value: 7, to: now) ?? now.addingTimeInterval(7 * 86400)
  5068. return meetings.filter { $0.startDate >= now && $0.startDate <= end }
  5069. }
  5070. }
  5071. private func filteredMeetingsForSchedulePage(_ meetings: [ScheduledMeeting]) -> [ScheduledMeeting] {
  5072. let calendar = Calendar.current
  5073. switch schedulePageFilter {
  5074. case .all:
  5075. return meetings
  5076. case .today:
  5077. let start = calendar.startOfDay(for: Date())
  5078. let end = calendar.date(byAdding: .day, value: 1, to: start) ?? start.addingTimeInterval(86400)
  5079. return meetings.filter { $0.startDate >= start && $0.startDate < end }
  5080. case .week:
  5081. let now = Date()
  5082. let end = calendar.date(byAdding: .day, value: 7, to: now) ?? now.addingTimeInterval(7 * 86400)
  5083. return meetings.filter { $0.startDate >= now && $0.startDate <= end }
  5084. case .month:
  5085. let now = Date()
  5086. let end = calendar.date(byAdding: .month, value: 1, to: now) ?? now.addingTimeInterval(30 * 86400)
  5087. return meetings.filter { $0.startDate >= now && $0.startDate <= end }
  5088. case .customRange:
  5089. let start = calendar.startOfDay(for: schedulePageFromDate)
  5090. let inclusiveEndDay = calendar.startOfDay(for: schedulePageToDate)
  5091. guard let end = calendar.date(byAdding: .day, value: 1, to: inclusiveEndDay) else {
  5092. return meetings
  5093. }
  5094. return meetings.filter { $0.startDate >= start && $0.startDate < end }
  5095. }
  5096. }
  5097. private func refreshSchedulePageDateFilterUI() {
  5098. let isCustom = schedulePageFilter == .customRange
  5099. schedulePageFromDatePicker?.isEnabled = isCustom
  5100. schedulePageToDatePicker?.isEnabled = isCustom
  5101. let dim: CGFloat = isCustom ? 1.0 : 0.65
  5102. schedulePageFromDatePicker?.alphaValue = 1
  5103. schedulePageToDatePicker?.alphaValue = 1
  5104. schedulePageFromDatePicker?.superview?.alphaValue = dim
  5105. schedulePageToDatePicker?.superview?.alphaValue = dim
  5106. }
  5107. private func schedulePageHasValidCustomRange() -> Bool {
  5108. let start = Calendar.current.startOfDay(for: schedulePageFromDate)
  5109. let end = Calendar.current.startOfDay(for: schedulePageToDate)
  5110. return start <= end
  5111. }
  5112. private func setSchedulePageRangeError(_ message: String?) {
  5113. guard let label = schedulePageRangeErrorLabel else { return }
  5114. label.stringValue = message ?? ""
  5115. label.isHidden = message == nil
  5116. }
  5117. private func applySchedulePageFiltersAndRender() {
  5118. schedulePageFromDate = schedulePageFromDatePicker?.dateValue ?? schedulePageFromDate
  5119. schedulePageToDate = schedulePageToDatePicker?.dateValue ?? schedulePageToDate
  5120. if schedulePageFilter == .customRange && !schedulePageHasValidCustomRange() {
  5121. setSchedulePageRangeError("Start date must be on or before end date.")
  5122. schedulePageFilteredMeetings = []
  5123. schedulePageVisibleCount = 0
  5124. renderSchedulePageCards()
  5125. schedulePageDateHeadingLabel?.stringValue = "Invalid custom date range"
  5126. return
  5127. }
  5128. setSchedulePageRangeError(nil)
  5129. schedulePageFilteredMeetings = filteredMeetingsForSchedulePage(scheduleCachedMeetings)
  5130. schedulePageVisibleCount = min(schedulePageBatchSize, schedulePageFilteredMeetings.count)
  5131. renderSchedulePageCards()
  5132. schedulePageDateHeadingLabel?.stringValue = scheduleHeadingText(for: schedulePageFilteredMeetings)
  5133. }
  5134. private func appendSchedulePageBatchIfNeeded() {
  5135. guard schedulePageVisibleCount < schedulePageFilteredMeetings.count else { return }
  5136. let nextCount = min(schedulePageVisibleCount + schedulePageBatchSize, schedulePageFilteredMeetings.count)
  5137. guard nextCount > schedulePageVisibleCount else { return }
  5138. schedulePageVisibleCount = nextCount
  5139. renderSchedulePageCards()
  5140. // If we're still near the bottom after adding a batch (large viewport),
  5141. // immediately evaluate again so pagination keeps advancing in chunks of 6.
  5142. DispatchQueue.main.async { [weak self] in
  5143. self?.schedulePageScrolled()
  5144. }
  5145. }
  5146. private func schedulePageScrolled() {
  5147. guard let scroll = schedulePageCardsScrollView else { return }
  5148. let contentBounds = scroll.contentView.bounds
  5149. let contentHeight = scroll.documentView?.bounds.height ?? 0
  5150. guard contentHeight > 0 else { return }
  5151. let remaining = contentHeight - (contentBounds.origin.y + contentBounds.height)
  5152. if remaining <= 200 {
  5153. appendSchedulePageBatchIfNeeded()
  5154. }
  5155. }
  5156. private func renderSchedulePageCards() {
  5157. guard let stack = schedulePageCardsStack else { return }
  5158. stack.arrangedSubviews.forEach { v in
  5159. stack.removeArrangedSubview(v)
  5160. v.removeFromSuperview()
  5161. }
  5162. let visibleMeetings = Array(schedulePageFilteredMeetings.prefix(schedulePageVisibleCount))
  5163. if visibleMeetings.isEmpty {
  5164. let empty = roundedContainer(cornerRadius: 10, color: palette.sectionCard)
  5165. empty.translatesAutoresizingMaskIntoConstraints = false
  5166. empty.heightAnchor.constraint(equalToConstant: 140).isActive = true
  5167. styleSurface(empty, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  5168. let label = textLabel(googleOAuth.loadTokens() == nil ? "Connect to load schedule" : "No meetings for selected filters", font: typography.cardSubtitle, color: palette.textSecondary)
  5169. label.translatesAutoresizingMaskIntoConstraints = false
  5170. empty.addSubview(label)
  5171. NSLayoutConstraint.activate([
  5172. label.centerXAnchor.constraint(equalTo: empty.centerXAnchor),
  5173. label.centerYAnchor.constraint(equalTo: empty.centerYAnchor)
  5174. ])
  5175. stack.addArrangedSubview(empty)
  5176. empty.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  5177. return
  5178. }
  5179. var index = 0
  5180. while index < visibleMeetings.count {
  5181. let row = NSStackView()
  5182. row.translatesAutoresizingMaskIntoConstraints = false
  5183. row.userInterfaceLayoutDirection = .leftToRight
  5184. row.orientation = .horizontal
  5185. row.alignment = .top
  5186. row.spacing = schedulePageCardSpacing
  5187. row.distribution = .fillEqually
  5188. let rowEnd = min(index + schedulePageCardsPerRow, visibleMeetings.count)
  5189. for meeting in visibleMeetings[index..<rowEnd] {
  5190. row.addArrangedSubview(scheduleCard(meeting: meeting, useFlexibleWidth: true, contentHeight: schedulePageCardHeight))
  5191. }
  5192. stack.addArrangedSubview(row)
  5193. row.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  5194. index = rowEnd
  5195. }
  5196. if schedulePageVisibleCount < schedulePageFilteredMeetings.count {
  5197. let pagination = NSStackView()
  5198. pagination.translatesAutoresizingMaskIntoConstraints = false
  5199. pagination.orientation = .horizontal
  5200. pagination.alignment = .centerY
  5201. pagination.spacing = 10
  5202. let moreLabel = textLabel(
  5203. "Showing \(schedulePageVisibleCount) of \(schedulePageFilteredMeetings.count)",
  5204. font: NSFont.systemFont(ofSize: 12, weight: .medium),
  5205. color: palette.textMuted
  5206. )
  5207. pagination.addArrangedSubview(moreLabel)
  5208. let spacer = NSView()
  5209. spacer.translatesAutoresizingMaskIntoConstraints = false
  5210. spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  5211. pagination.addArrangedSubview(spacer)
  5212. stack.addArrangedSubview(pagination)
  5213. pagination.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  5214. }
  5215. }
  5216. private func scrollScheduleCards(direction: Int) {
  5217. guard let scroll = scheduleCardsScrollView else { return }
  5218. let contentBounds = scroll.contentView.bounds
  5219. let step = max(220, contentBounds.width * 0.7)
  5220. let proposedX = contentBounds.origin.x + (CGFloat(direction) * step)
  5221. let maxX = max(0, scroll.documentView?.bounds.width ?? 0 - contentBounds.width)
  5222. let nextX = min(max(0, proposedX), maxX)
  5223. scroll.contentView.animator().setBoundsOrigin(NSPoint(x: nextX, y: 0))
  5224. scroll.reflectScrolledClipView(scroll.contentView)
  5225. }
  5226. private func loadSchedule() async {
  5227. do {
  5228. if googleOAuth.loadTokens() == nil {
  5229. await MainActor.run {
  5230. updateGoogleAuthButtonTitle()
  5231. applyGoogleProfile(nil)
  5232. scheduleDateHeadingLabel?.stringValue = "Connect Google to see meetings"
  5233. schedulePageDateHeadingLabel?.stringValue = "Connect Google to see meetings"
  5234. if let stack = scheduleCardsStack {
  5235. renderScheduleCards(into: stack, meetings: [])
  5236. }
  5237. scheduleCachedMeetings = []
  5238. applySchedulePageFiltersAndRender()
  5239. if calendarPageGridStack != nil {
  5240. calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
  5241. renderCalendarMonthGrid()
  5242. renderCalendarSelectedDay()
  5243. }
  5244. }
  5245. return
  5246. }
  5247. let token = try await googleOAuth.validAccessToken(presentingWindow: view.window)
  5248. let profile = try? await googleOAuth.fetchUserProfile(accessToken: token)
  5249. let meetings = try await calendarClient.fetchUpcomingMeetings(accessToken: token)
  5250. let filtered = filteredMeetings(meetings)
  5251. await MainActor.run {
  5252. updateGoogleAuthButtonTitle()
  5253. applyGoogleProfile(profile.map { self.makeGoogleProfileDisplay(from: $0) })
  5254. scheduleDateHeadingLabel?.stringValue = scheduleHeadingText(for: filtered)
  5255. if let stack = scheduleCardsStack {
  5256. renderScheduleCards(into: stack, meetings: filtered)
  5257. }
  5258. scheduleCachedMeetings = meetings
  5259. applySchedulePageFiltersAndRender()
  5260. if calendarPageGridStack != nil {
  5261. calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
  5262. renderCalendarMonthGrid()
  5263. renderCalendarSelectedDay()
  5264. }
  5265. }
  5266. } catch {
  5267. await MainActor.run {
  5268. updateGoogleAuthButtonTitle()
  5269. if googleOAuth.loadTokens() == nil {
  5270. applyGoogleProfile(nil)
  5271. }
  5272. scheduleDateHeadingLabel?.stringValue = "Couldn’t load schedule"
  5273. schedulePageDateHeadingLabel?.stringValue = "Couldn’t load schedule"
  5274. if let stack = scheduleCardsStack {
  5275. renderScheduleCards(into: stack, meetings: [])
  5276. }
  5277. scheduleCachedMeetings = []
  5278. applySchedulePageFiltersAndRender()
  5279. if calendarPageGridStack != nil {
  5280. calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
  5281. renderCalendarMonthGrid()
  5282. renderCalendarSelectedDay()
  5283. }
  5284. showSimpleError("Couldn’t load schedule.", error: error)
  5285. }
  5286. }
  5287. }
  5288. func showScheduleHelp() {
  5289. let alert = NSAlert()
  5290. alert.messageText = "Google schedule"
  5291. alert.informativeText = "To show scheduled meetings, connect your Google account. You’ll need a Google OAuth client ID (Desktop) and a redirect URI matching the app’s callback scheme."
  5292. alert.addButton(withTitle: "OK")
  5293. alert.runModal()
  5294. }
  5295. func scheduleReloadClicked() {
  5296. Task { [weak self] in
  5297. guard let self else { return }
  5298. do {
  5299. try await self.ensureGoogleClientIdConfigured(presentingWindow: self.view.window)
  5300. _ = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
  5301. await MainActor.run {
  5302. self.scheduleDateHeadingLabel?.stringValue = "Refreshing…"
  5303. self.pageCache[.joinMeetings] = nil
  5304. self.pageCache[.photo] = nil
  5305. self.showSidebarPage(self.selectedSidebarPage)
  5306. }
  5307. await self.loadSchedule()
  5308. } catch {
  5309. await MainActor.run {
  5310. self.showSimpleError("Couldn’t refresh schedule.", error: error)
  5311. }
  5312. }
  5313. }
  5314. }
  5315. func scheduleConnectClicked() {
  5316. Task { [weak self] in
  5317. guard let self else { return }
  5318. do {
  5319. if self.googleOAuth.loadTokens() != nil {
  5320. await MainActor.run { self.showGoogleAccountMenu() }
  5321. return
  5322. }
  5323. try await self.ensureGoogleClientIdConfigured(presentingWindow: self.view.window)
  5324. let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
  5325. let profile = try? await self.googleOAuth.fetchUserProfile(accessToken: token)
  5326. await MainActor.run {
  5327. self.updateGoogleAuthButtonTitle()
  5328. self.applyGoogleProfile(profile.map { self.makeGoogleProfileDisplay(from: $0) })
  5329. self.pageCache[.joinMeetings] = nil
  5330. self.pageCache[.photo] = nil
  5331. self.pageCache[.video] = nil
  5332. self.showSidebarPage(self.selectedSidebarPage)
  5333. }
  5334. } catch {
  5335. self.showSimpleError("Couldn’t connect Google account.", error: error)
  5336. }
  5337. }
  5338. }
  5339. private func showGoogleAccountMenu() {
  5340. guard let button = scheduleGoogleAuthButton else { return }
  5341. if googleAccountPopover?.isShown == true {
  5342. googleAccountPopover?.performClose(nil)
  5343. googleAccountPopover = nil
  5344. return
  5345. }
  5346. let popover = NSPopover()
  5347. popover.behavior = .transient
  5348. popover.animates = true
  5349. popover.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
  5350. let name = scheduleCurrentProfile?.name ?? "Google account"
  5351. let email = scheduleCurrentProfile?.email ?? "Signed in"
  5352. let avatar = scheduleProfileMenuAvatar
  5353. popover.contentViewController = GoogleAccountMenuViewController(
  5354. palette: palette,
  5355. darkModeEnabled: darkModeEnabled,
  5356. displayName: name,
  5357. email: email,
  5358. avatar: avatar,
  5359. onSignOut: { [weak self] in
  5360. self?.googleAccountPopover?.performClose(nil)
  5361. self?.googleAccountPopover = nil
  5362. self?.performGoogleSignOut()
  5363. }
  5364. )
  5365. googleAccountPopover = popover
  5366. popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
  5367. }
  5368. private func performGoogleSignOut() {
  5369. do {
  5370. try googleOAuth.signOut()
  5371. pageCache[.photo] = nil
  5372. if selectedSidebarPage == .photo {
  5373. showSidebarPage(.photo)
  5374. } else {
  5375. Task { [weak self] in
  5376. await self?.loadSchedule()
  5377. }
  5378. }
  5379. } catch {
  5380. showSimpleError("Couldn’t logout Google account.", error: error)
  5381. }
  5382. }
  5383. private func updateGoogleAuthButtonTitle() {
  5384. let signedIn = (googleOAuth.loadTokens() != nil)
  5385. guard let button = scheduleGoogleAuthButton else { return }
  5386. let profileName = scheduleCurrentProfile?.name ?? "Google account"
  5387. let ringHostInset: CGFloat = signedIn ? 14 : 0
  5388. scheduleGoogleAuthHostPadWidthConstraint?.constant = ringHostInset
  5389. scheduleGoogleAuthHostPadHeightConstraint?.constant = ringHostInset
  5390. scheduleGoogleAuthHostView?.setAvatarRingMode(signedIn)
  5391. scheduleGoogleAuthHostView?.updateRingAppearance(isDark: darkModeEnabled, accent: palette.primaryBlue)
  5392. if signedIn == false {
  5393. scheduleGoogleAuthHostView?.setProfileHoverActive(false)
  5394. }
  5395. if signedIn {
  5396. button.setAccessibilityLabel("\(profileName), Google account")
  5397. button.attributedTitle = NSAttributedString(string: "")
  5398. button.imagePosition = .imageOnly
  5399. button.imageScaling = .scaleProportionallyDown
  5400. button.symbolConfiguration = nil
  5401. scheduleGoogleAuthButtonHeightConstraint?.constant = scheduleGoogleSignedInAvatarSize
  5402. scheduleGoogleAuthButtonWidthConstraint?.constant = scheduleGoogleSignedInAvatarSize
  5403. button.layer?.cornerRadius = scheduleGoogleSignedInAvatarSize / 2
  5404. let symbol = NSImage(systemSymbolName: "person.crop.circle.fill", accessibilityDescription: "Profile")
  5405. if let symbol {
  5406. let sized = resizedImage(symbol, to: NSSize(width: scheduleGoogleSignedInAvatarSize, height: scheduleGoogleSignedInAvatarSize))
  5407. button.image = sized
  5408. button.contentTintColor = palette.textSecondary
  5409. } else {
  5410. button.image = nil
  5411. button.contentTintColor = nil
  5412. }
  5413. scheduleProfileMenuAvatar = button.image
  5414. } else {
  5415. button.setAccessibilityLabel("Sign in with Google")
  5416. let title = "Sign in with Google"
  5417. let titleFont = NSFont.systemFont(ofSize: 14, weight: .medium)
  5418. let titleColor = darkModeEnabled ? NSColor(calibratedWhite: 0.96, alpha: 1) : NSColor(calibratedRed: 0.13, green: 0.14, blue: 0.16, alpha: 1)
  5419. button.attributedTitle = NSAttributedString(string: title, attributes: [
  5420. .font: titleFont,
  5421. .foregroundColor: titleColor
  5422. ])
  5423. let textWidth = (title as NSString).size(withAttributes: [.font: titleFont]).width
  5424. let idealWidth = ceil(textWidth + 80)
  5425. scheduleGoogleAuthButtonWidthConstraint?.constant = min(320, max(188, idealWidth))
  5426. scheduleGoogleAuthButtonHeightConstraint?.constant = 42
  5427. button.layer?.cornerRadius = 21
  5428. button.imagePosition = .imageLeading
  5429. button.imageScaling = .scaleNone
  5430. if let g = NSImage(named: "GoogleGLogo") {
  5431. button.image = paddedTrailingImage(g, iconSize: NSSize(width: 22, height: 22), trailingPadding: 8)
  5432. } else {
  5433. button.image = nil
  5434. }
  5435. button.contentTintColor = nil
  5436. }
  5437. applyGoogleAuthButtonSurface()
  5438. }
  5439. private func makeGoogleProfileDisplay(from profile: GoogleUserProfile) -> GoogleProfileDisplay {
  5440. let cleanedName = profile.name?.trimmingCharacters(in: .whitespacesAndNewlines)
  5441. let cleanedEmail = profile.email?.trimmingCharacters(in: .whitespacesAndNewlines)
  5442. return GoogleProfileDisplay(
  5443. name: (cleanedName?.isEmpty == false ? cleanedName : nil) ?? "Google User",
  5444. email: (cleanedEmail?.isEmpty == false ? cleanedEmail : nil) ?? "Signed in",
  5445. pictureURL: profile.picture.flatMap(URL.init(string:))
  5446. )
  5447. }
  5448. private func applyGoogleProfile(_ profile: GoogleProfileDisplay?) {
  5449. scheduleProfileImageTask?.cancel()
  5450. scheduleProfileImageTask = nil
  5451. if profile == nil {
  5452. scheduleProfileMenuAvatar = nil
  5453. }
  5454. scheduleCurrentProfile = profile
  5455. updateGoogleAuthButtonTitle()
  5456. guard let profile, let pictureURL = profile.pictureURL else { return }
  5457. let avatarDiameter = scheduleGoogleSignedInAvatarSize
  5458. scheduleProfileImageTask = Task { [weak self] in
  5459. do {
  5460. let (data, _) = try await URLSession.shared.data(from: pictureURL)
  5461. if Task.isCancelled { return }
  5462. guard let image = NSImage(data: data) else { return }
  5463. await MainActor.run { [weak self] in
  5464. guard let self else { return }
  5465. let rounded = self.circularProfileImage(image, diameter: avatarDiameter)
  5466. self.scheduleProfileMenuAvatar = circularNSImage(rounded, diameter: 48)
  5467. self.scheduleGoogleAuthButton?.image = rounded
  5468. self.scheduleGoogleAuthButton?.contentTintColor = nil
  5469. }
  5470. } catch {
  5471. // Keep placeholder avatar if image fetch fails.
  5472. }
  5473. }
  5474. }
  5475. private func resizedImage(_ image: NSImage, to size: NSSize) -> NSImage {
  5476. let result = NSImage(size: size)
  5477. result.lockFocus()
  5478. image.draw(in: NSRect(origin: .zero, size: size),
  5479. from: NSRect(origin: .zero, size: image.size),
  5480. operation: .copy,
  5481. fraction: 1.0)
  5482. result.unlockFocus()
  5483. result.isTemplate = false
  5484. return result
  5485. }
  5486. /// Clips a photo to a circle for the signed-in avatar (Google userinfo `picture` URLs are usually square).
  5487. private func circularProfileImage(_ image: NSImage, diameter: CGFloat) -> NSImage {
  5488. circularNSImage(image, diameter: diameter)
  5489. }
  5490. private func paddedTrailingImage(_ image: NSImage, iconSize: NSSize, trailingPadding: CGFloat) -> NSImage {
  5491. let base = resizedImage(image, to: iconSize)
  5492. let canvas = NSSize(width: iconSize.width + trailingPadding, height: iconSize.height)
  5493. let result = NSImage(size: canvas)
  5494. result.lockFocus()
  5495. base.draw(in: NSRect(x: 0, y: 0, width: iconSize.width, height: iconSize.height),
  5496. from: NSRect(origin: .zero, size: base.size),
  5497. operation: .copy,
  5498. fraction: 1.0)
  5499. result.unlockFocus()
  5500. result.isTemplate = false
  5501. return result
  5502. }
  5503. private func applyGoogleAuthButtonSurface() {
  5504. guard let button = scheduleGoogleAuthButton else { return }
  5505. let signedIn = (googleOAuth.loadTokens() != nil)
  5506. let isDark = darkModeEnabled
  5507. if signedIn {
  5508. button.layer?.backgroundColor = NSColor.clear.cgColor
  5509. button.layer?.borderWidth = 0
  5510. scheduleGoogleAuthHostView?.updateRingAppearance(isDark: isDark, accent: palette.primaryBlue)
  5511. return
  5512. }
  5513. let baseBackground = isDark
  5514. ? NSColor(calibratedRed: 8.0 / 255.0, green: 14.0 / 255.0, blue: 24.0 / 255.0, alpha: 1)
  5515. : NSColor.white
  5516. let hoverBlend = isDark ? NSColor.white : NSColor.black
  5517. let hoverBackground = baseBackground.blended(withFraction: 0.07, of: hoverBlend) ?? baseBackground
  5518. let baseBorder = isDark
  5519. ? NSColor(calibratedWhite: 0.50, alpha: 1)
  5520. : NSColor(calibratedWhite: 0.72, alpha: 1)
  5521. let hoverBorder = isDark
  5522. ? NSColor(calibratedWhite: 0.62, alpha: 1)
  5523. : NSColor(calibratedWhite: 0.56, alpha: 1)
  5524. button.layer?.borderWidth = 1
  5525. button.layer?.backgroundColor = (scheduleGoogleAuthHovering ? hoverBackground : baseBackground).cgColor
  5526. button.layer?.borderColor = (scheduleGoogleAuthHovering ? hoverBorder : baseBorder).cgColor
  5527. }
  5528. @MainActor
  5529. func ensureGoogleClientIdConfigured(presentingWindow: NSWindow?) async throws {
  5530. if googleOAuth.configuredClientId() != nil, googleOAuth.configuredClientSecret() != nil { return }
  5531. let alert = NSAlert()
  5532. alert.messageText = "Enter Google OAuth credentials"
  5533. alert.informativeText = "Paste the OAuth Client ID and Client Secret from your downloaded Desktop OAuth JSON."
  5534. let accessory = NSStackView()
  5535. accessory.orientation = .vertical
  5536. accessory.spacing = 8
  5537. accessory.alignment = .leading
  5538. let idField = NSTextField(string: googleOAuth.configuredClientId() ?? "")
  5539. idField.placeholderString = "Client ID (....apps.googleusercontent.com)"
  5540. idField.frame = NSRect(x: 0, y: 0, width: 460, height: 24)
  5541. let secretField = NSSecureTextField(string: googleOAuth.configuredClientSecret() ?? "")
  5542. secretField.placeholderString = "Client Secret (GOCSPX-...)"
  5543. secretField.frame = NSRect(x: 0, y: 0, width: 460, height: 24)
  5544. accessory.addArrangedSubview(idField)
  5545. accessory.addArrangedSubview(secretField)
  5546. alert.accessoryView = accessory
  5547. alert.addButton(withTitle: "Save")
  5548. alert.addButton(withTitle: "Cancel")
  5549. // Keep this synchronous to avoid additional sheet state handling.
  5550. let response = alert.runModal()
  5551. if response != .alertFirstButtonReturn { throw GoogleOAuthError.missingClientId }
  5552. let idValue = idField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)
  5553. let secretValue = secretField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)
  5554. if idValue.isEmpty { throw GoogleOAuthError.missingClientId }
  5555. if secretValue.isEmpty { throw GoogleOAuthError.missingClientSecret }
  5556. googleOAuth.setClientIdForTesting(idValue)
  5557. googleOAuth.setClientSecretForTesting(secretValue)
  5558. }
  5559. func showSimpleError(_ title: String, error: Error) {
  5560. DispatchQueue.main.async {
  5561. let alert = NSAlert()
  5562. alert.alertStyle = .warning
  5563. alert.messageText = title
  5564. alert.informativeText = error.localizedDescription
  5565. alert.addButton(withTitle: "OK")
  5566. alert.runModal()
  5567. }
  5568. }
  5569. }
  5570. private struct Palette {
  5571. let pageBackground: NSColor
  5572. let sidebarBackground: NSColor
  5573. let sectionCard: NSColor
  5574. let tabBarBackground: NSColor
  5575. let tabIdleBackground: NSColor
  5576. let inputBackground: NSColor
  5577. let inputBorder: NSColor
  5578. let primaryBlue: NSColor
  5579. let primaryBlueBorder: NSColor
  5580. let cancelButton: NSColor
  5581. let meetingBadge: NSColor
  5582. let separator: NSColor
  5583. let textPrimary: NSColor
  5584. let textSecondary: NSColor
  5585. let textTertiary: NSColor
  5586. let textMuted: NSColor
  5587. init(isDarkMode: Bool) {
  5588. if isDarkMode {
  5589. pageBackground = NSColor(calibratedRed: 10.0 / 255.0, green: 11.0 / 255.0, blue: 12.0 / 255.0, alpha: 1)
  5590. sidebarBackground = NSColor(calibratedRed: 16.0 / 255.0, green: 17.0 / 255.0, blue: 19.0 / 255.0, alpha: 1)
  5591. sectionCard = NSColor(calibratedRed: 22.0 / 255.0, green: 23.0 / 255.0, blue: 26.0 / 255.0, alpha: 1)
  5592. tabBarBackground = NSColor(calibratedRed: 22.0 / 255.0, green: 23.0 / 255.0, blue: 26.0 / 255.0, alpha: 1)
  5593. tabIdleBackground = NSColor(calibratedRed: 22.0 / 255.0, green: 23.0 / 255.0, blue: 26.0 / 255.0, alpha: 1)
  5594. inputBackground = NSColor(calibratedRed: 20.0 / 255.0, green: 21.0 / 255.0, blue: 24.0 / 255.0, alpha: 1)
  5595. inputBorder = NSColor(calibratedRed: 38.0 / 255.0, green: 40.0 / 255.0, blue: 44.0 / 255.0, alpha: 1)
  5596. primaryBlue = NSColor(calibratedRed: 27.0 / 255.0, green: 115.0 / 255.0, blue: 232.0 / 255.0, alpha: 1)
  5597. primaryBlueBorder = NSColor(calibratedRed: 42.0 / 255.0, green: 118.0 / 255.0, blue: 220.0 / 255.0, alpha: 1)
  5598. cancelButton = NSColor(calibratedRed: 20.0 / 255.0, green: 21.0 / 255.0, blue: 24.0 / 255.0, alpha: 1)
  5599. meetingBadge = NSColor(calibratedRed: 0.88, green: 0.66, blue: 0.14, alpha: 1)
  5600. separator = NSColor(calibratedRed: 26.0 / 255.0, green: 27.0 / 255.0, blue: 30.0 / 255.0, alpha: 1)
  5601. textPrimary = NSColor(calibratedWhite: 0.98, alpha: 1)
  5602. textSecondary = NSColor(calibratedWhite: 0.78, alpha: 1)
  5603. textTertiary = NSColor(calibratedWhite: 0.66, alpha: 1)
  5604. textMuted = NSColor(calibratedWhite: 0.44, alpha: 1)
  5605. } else {
  5606. pageBackground = NSColor(calibratedRed: 244.0 / 255.0, green: 246.0 / 255.0, blue: 249.0 / 255.0, alpha: 1)
  5607. sidebarBackground = NSColor(calibratedRed: 232.0 / 255.0, green: 236.0 / 255.0, blue: 242.0 / 255.0, alpha: 1)
  5608. sectionCard = NSColor.white
  5609. tabBarBackground = NSColor.white
  5610. tabIdleBackground = NSColor.white
  5611. inputBackground = NSColor(calibratedRed: 247.0 / 255.0, green: 249.0 / 255.0, blue: 252.0 / 255.0, alpha: 1)
  5612. inputBorder = NSColor(calibratedRed: 211.0 / 255.0, green: 218.0 / 255.0, blue: 228.0 / 255.0, alpha: 1)
  5613. primaryBlue = NSColor(calibratedRed: 27.0 / 255.0, green: 115.0 / 255.0, blue: 232.0 / 255.0, alpha: 1)
  5614. primaryBlueBorder = NSColor(calibratedRed: 42.0 / 255.0, green: 118.0 / 255.0, blue: 220.0 / 255.0, alpha: 1)
  5615. cancelButton = NSColor(calibratedRed: 240.0 / 255.0, green: 243.0 / 255.0, blue: 248.0 / 255.0, alpha: 1)
  5616. meetingBadge = NSColor(calibratedRed: 0.88, green: 0.66, blue: 0.14, alpha: 1)
  5617. separator = NSColor(calibratedRed: 212.0 / 255.0, green: 219.0 / 255.0, blue: 229.0 / 255.0, alpha: 1)
  5618. textPrimary = NSColor(calibratedRed: 32.0 / 255.0, green: 38.0 / 255.0, blue: 47.0 / 255.0, alpha: 1)
  5619. textSecondary = NSColor(calibratedRed: 82.0 / 255.0, green: 92.0 / 255.0, blue: 107.0 / 255.0, alpha: 1)
  5620. textTertiary = NSColor(calibratedRed: 110.0 / 255.0, green: 120.0 / 255.0, blue: 136.0 / 255.0, alpha: 1)
  5621. textMuted = NSColor(calibratedRed: 134.0 / 255.0, green: 145.0 / 255.0, blue: 162.0 / 255.0, alpha: 1)
  5622. }
  5623. }
  5624. }
  5625. private struct Typography {
  5626. let sidebarBrand = NSFont.systemFont(ofSize: 26, weight: .bold)
  5627. let sidebarSection = NSFont.systemFont(ofSize: 11, weight: .medium)
  5628. let sidebarIcon = NSFont.systemFont(ofSize: 12, weight: .medium)
  5629. let sidebarItem = NSFont.systemFont(ofSize: 16, weight: .medium)
  5630. let pageTitle = NSFont.systemFont(ofSize: 27, weight: .semibold)
  5631. let joinWithURLTitle = NSFont.systemFont(ofSize: 17, weight: .semibold)
  5632. let sectionTitleBold = NSFont.systemFont(ofSize: 25, weight: .bold)
  5633. let dateHeading = NSFont.systemFont(ofSize: 18, weight: .medium)
  5634. let tabIcon = NSFont.systemFont(ofSize: 13, weight: .regular)
  5635. let tabTitle = NSFont.systemFont(ofSize: 31 / 2, weight: .semibold)
  5636. let fieldLabel = NSFont.systemFont(ofSize: 15, weight: .medium)
  5637. let inputPlaceholder = NSFont.systemFont(ofSize: 14, weight: .regular)
  5638. let buttonText = NSFont.systemFont(ofSize: 16, weight: .medium)
  5639. let filterText = NSFont.systemFont(ofSize: 15, weight: .regular)
  5640. let filterArrow = NSFont.systemFont(ofSize: 12, weight: .regular)
  5641. let iconButton = NSFont.systemFont(ofSize: 14, weight: .medium)
  5642. let cardIcon = NSFont.systemFont(ofSize: 8, weight: .bold)
  5643. let cardTitle = NSFont.systemFont(ofSize: 15, weight: .semibold)
  5644. let cardSubtitle = NSFont.systemFont(ofSize: 13, weight: .bold)
  5645. let cardTime = NSFont.systemFont(ofSize: 12, weight: .regular)
  5646. }
  5647. // MARK: - In-app browser (macOS WKWebView + chrome)
  5648. // Note: This target is AppKit/macOS. iOS would use WKWebView or SFSafariViewController; Android would use WebView or Custom Tabs.
  5649. private enum InAppBrowserURLPolicy: Equatable {
  5650. case allowAll
  5651. case whitelist(hostSuffixes: [String])
  5652. }
  5653. private func inAppBrowserURLAllowed(_ url: URL, policy: InAppBrowserURLPolicy) -> Bool {
  5654. let scheme = (url.scheme ?? "").lowercased()
  5655. if scheme == "about" { return true }
  5656. guard scheme == "http" || scheme == "https" else { return false }
  5657. guard let host = url.host?.lowercased() else { return false }
  5658. switch policy {
  5659. case .allowAll:
  5660. return true
  5661. case .whitelist(let suffixes):
  5662. for suffix in suffixes {
  5663. let s = suffix.lowercased()
  5664. if host == s || host.hasSuffix("." + s) { return true }
  5665. }
  5666. return false
  5667. }
  5668. }
  5669. private enum InAppBrowserWebKitSupport {
  5670. static func makeWebViewConfiguration() -> WKWebViewConfiguration {
  5671. let config = WKWebViewConfiguration()
  5672. config.websiteDataStore = .default()
  5673. config.preferences.javaScriptCanOpenWindowsAutomatically = true
  5674. if #available(macOS 12.3, *) {
  5675. config.preferences.isElementFullscreenEnabled = true
  5676. }
  5677. config.mediaTypesRequiringUserActionForPlayback = []
  5678. if #available(macOS 11.0, *) {
  5679. config.defaultWebpagePreferences.allowsContentJavaScript = true
  5680. }
  5681. config.applicationNameForUserAgent = "MeetingsApp/1.0"
  5682. return config
  5683. }
  5684. }
  5685. private final class InAppBrowserWindowController: NSWindowController {
  5686. private static let defaultContentSize = NSSize(width: 1100, height: 760)
  5687. private static let minimumContentSize = NSSize(width: 800, height: 520)
  5688. private let browserViewController = InAppBrowserContainerViewController()
  5689. init() {
  5690. let browserWindow = NSWindow(
  5691. contentRect: NSRect(origin: .zero, size: Self.defaultContentSize),
  5692. styleMask: [.titled, .closable, .miniaturizable, .resizable],
  5693. backing: .buffered,
  5694. defer: false
  5695. )
  5696. browserWindow.title = "Browser"
  5697. browserWindow.isRestorable = false
  5698. browserWindow.setFrameAutosaveName("")
  5699. browserWindow.minSize = browserWindow.frameRect(forContentRect: NSRect(origin: .zero, size: Self.minimumContentSize)).size
  5700. browserWindow.center()
  5701. browserWindow.contentViewController = browserViewController
  5702. super.init(window: browserWindow)
  5703. }
  5704. @available(*, unavailable)
  5705. required init?(coder: NSCoder) {
  5706. nil
  5707. }
  5708. /// Resets size and position each time the browser is shown so a previously tiny window is never reused.
  5709. func applyDefaultFrameCenteredOnVisibleScreen() {
  5710. guard let w = window, let screen = w.screen ?? NSScreen.main else { return }
  5711. let windowFrame = w.frameRect(forContentRect: NSRect(origin: .zero, size: Self.defaultContentSize))
  5712. let vf = screen.visibleFrame
  5713. var frame = windowFrame
  5714. frame.origin.x = vf.midX - frame.width / 2
  5715. frame.origin.y = vf.midY - frame.height / 2
  5716. if frame.maxX > vf.maxX { frame.origin.x = vf.maxX - frame.width }
  5717. if frame.minX < vf.minX { frame.origin.x = vf.minX }
  5718. if frame.maxY > vf.maxY { frame.origin.y = vf.maxY - frame.height }
  5719. if frame.minY < vf.minY { frame.origin.y = vf.minY }
  5720. w.setFrame(frame, display: true)
  5721. }
  5722. func load(url: URL, policy: InAppBrowserURLPolicy) {
  5723. browserViewController.setNavigationPolicy(policy)
  5724. browserViewController.load(url: url)
  5725. }
  5726. }
  5727. private final class InAppBrowserContainerViewController: NSViewController, WKNavigationDelegate, WKUIDelegate, NSTextFieldDelegate {
  5728. private var webView: WKWebView!
  5729. private var webContainerView: NSView!
  5730. private weak var urlField: NSTextField?
  5731. private var backButton: NSButton!
  5732. private var forwardButton: NSButton!
  5733. private var reloadStopButton: NSButton!
  5734. private var goButton: NSButton!
  5735. private var progressBar: NSProgressIndicator!
  5736. private var lastLoadedURL: URL?
  5737. private var navigationPolicy: InAppBrowserURLPolicy = .allowAll
  5738. private var processTerminateRetryCount = 0
  5739. /// Includes fresh WKWebView instances so each retry gets a new WebContent process after a crash.
  5740. private let maxProcessTerminateRetries = 3
  5741. private var kvoTokens: [NSKeyValueObservation] = []
  5742. deinit {
  5743. kvoTokens.removeAll()
  5744. }
  5745. func setNavigationPolicy(_ policy: InAppBrowserURLPolicy) {
  5746. navigationPolicy = policy
  5747. }
  5748. override func loadView() {
  5749. let root = NSView()
  5750. root.translatesAutoresizingMaskIntoConstraints = false
  5751. let wv = makeWebView()
  5752. webView = wv
  5753. let webHost = NSView()
  5754. webHost.translatesAutoresizingMaskIntoConstraints = false
  5755. webHost.wantsLayer = true
  5756. webHost.addSubview(wv)
  5757. NSLayoutConstraint.activate([
  5758. wv.leadingAnchor.constraint(equalTo: webHost.leadingAnchor),
  5759. wv.trailingAnchor.constraint(equalTo: webHost.trailingAnchor),
  5760. wv.topAnchor.constraint(equalTo: webHost.topAnchor),
  5761. wv.bottomAnchor.constraint(equalTo: webHost.bottomAnchor)
  5762. ])
  5763. webContainerView = webHost
  5764. let toolbar = NSStackView()
  5765. toolbar.translatesAutoresizingMaskIntoConstraints = false
  5766. toolbar.orientation = .horizontal
  5767. toolbar.spacing = 8
  5768. toolbar.alignment = .centerY
  5769. toolbar.edgeInsets = NSEdgeInsets(top: 6, left: 10, bottom: 6, right: 10)
  5770. backButton = makeToolbarButton(title: "◀", symbolName: "chevron.backward", accessibilityDescription: "Back")
  5771. backButton.target = self
  5772. backButton.action = #selector(goBack)
  5773. forwardButton = makeToolbarButton(title: "▶", symbolName: "chevron.forward", accessibilityDescription: "Forward")
  5774. forwardButton.target = self
  5775. forwardButton.action = #selector(goForward)
  5776. reloadStopButton = makeToolbarButton(title: "Reload", symbolName: "arrow.clockwise", accessibilityDescription: "Reload")
  5777. reloadStopButton.target = self
  5778. reloadStopButton.action = #selector(reloadOrStop)
  5779. let field = NSTextField(string: "")
  5780. field.translatesAutoresizingMaskIntoConstraints = false
  5781. field.font = NSFont.systemFont(ofSize: 13, weight: .regular)
  5782. field.placeholderString = "Address"
  5783. field.cell?.sendsActionOnEndEditing = false
  5784. field.delegate = self
  5785. urlField = field
  5786. goButton = NSButton(title: "Go", target: self, action: #selector(addressFieldSubmitted))
  5787. goButton.translatesAutoresizingMaskIntoConstraints = false
  5788. goButton.bezelStyle = .rounded
  5789. toolbar.addArrangedSubview(backButton)
  5790. toolbar.addArrangedSubview(forwardButton)
  5791. toolbar.addArrangedSubview(reloadStopButton)
  5792. toolbar.addArrangedSubview(field)
  5793. toolbar.addArrangedSubview(goButton)
  5794. field.widthAnchor.constraint(greaterThanOrEqualToConstant: 240).isActive = true
  5795. let bar = NSProgressIndicator()
  5796. bar.translatesAutoresizingMaskIntoConstraints = false
  5797. bar.style = .bar
  5798. bar.isIndeterminate = false
  5799. bar.minValue = 0
  5800. bar.maxValue = 1
  5801. bar.doubleValue = 0
  5802. bar.isHidden = true
  5803. progressBar = bar
  5804. let separator = NSBox()
  5805. separator.translatesAutoresizingMaskIntoConstraints = false
  5806. separator.boxType = .separator
  5807. webView.navigationDelegate = self
  5808. webView.uiDelegate = self
  5809. root.addSubview(toolbar)
  5810. root.addSubview(bar)
  5811. root.addSubview(separator)
  5812. root.addSubview(webHost)
  5813. NSLayoutConstraint.activate([
  5814. toolbar.leadingAnchor.constraint(equalTo: root.leadingAnchor),
  5815. toolbar.trailingAnchor.constraint(equalTo: root.trailingAnchor),
  5816. toolbar.topAnchor.constraint(equalTo: root.topAnchor),
  5817. bar.leadingAnchor.constraint(equalTo: root.leadingAnchor),
  5818. bar.trailingAnchor.constraint(equalTo: root.trailingAnchor),
  5819. bar.topAnchor.constraint(equalTo: toolbar.bottomAnchor),
  5820. bar.heightAnchor.constraint(equalToConstant: 3),
  5821. separator.leadingAnchor.constraint(equalTo: root.leadingAnchor),
  5822. separator.trailingAnchor.constraint(equalTo: root.trailingAnchor),
  5823. separator.topAnchor.constraint(equalTo: bar.bottomAnchor),
  5824. webHost.leadingAnchor.constraint(equalTo: root.leadingAnchor),
  5825. webHost.trailingAnchor.constraint(equalTo: root.trailingAnchor),
  5826. webHost.topAnchor.constraint(equalTo: separator.bottomAnchor),
  5827. webHost.bottomAnchor.constraint(equalTo: root.bottomAnchor)
  5828. ])
  5829. view = root
  5830. installWebViewObservers()
  5831. syncToolbarFromWebView()
  5832. }
  5833. private func makeWebView() -> WKWebView {
  5834. let wv = WKWebView(frame: .zero, configuration: InAppBrowserWebKitSupport.makeWebViewConfiguration())
  5835. wv.translatesAutoresizingMaskIntoConstraints = false
  5836. return wv
  5837. }
  5838. private func teardownWebViewObservers() {
  5839. kvoTokens.removeAll()
  5840. }
  5841. /// New `WKWebView` = new WebContent process (helps after GPU/JS crashes on heavy sites like Meet).
  5842. private func replaceWebViewAndLoad(url: URL) {
  5843. teardownWebViewObservers()
  5844. webView.navigationDelegate = nil
  5845. webView.uiDelegate = nil
  5846. webView.removeFromSuperview()
  5847. let wv = makeWebView()
  5848. webView = wv
  5849. webContainerView.addSubview(wv)
  5850. NSLayoutConstraint.activate([
  5851. wv.leadingAnchor.constraint(equalTo: webContainerView.leadingAnchor),
  5852. wv.trailingAnchor.constraint(equalTo: webContainerView.trailingAnchor),
  5853. wv.topAnchor.constraint(equalTo: webContainerView.topAnchor),
  5854. wv.bottomAnchor.constraint(equalTo: webContainerView.bottomAnchor)
  5855. ])
  5856. webView.navigationDelegate = self
  5857. webView.uiDelegate = self
  5858. installWebViewObservers()
  5859. syncToolbarFromWebView()
  5860. webView.load(URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData))
  5861. }
  5862. private func makeToolbarButton(title: String, symbolName: String, accessibilityDescription: String) -> NSButton {
  5863. let b = NSButton()
  5864. b.translatesAutoresizingMaskIntoConstraints = false
  5865. b.bezelStyle = .texturedRounded
  5866. b.setAccessibilityLabel(accessibilityDescription)
  5867. if #available(macOS 11.0, *), let img = NSImage(systemSymbolName: symbolName, accessibilityDescription: accessibilityDescription) {
  5868. b.image = img
  5869. b.imagePosition = .imageOnly
  5870. } else {
  5871. b.title = title
  5872. }
  5873. b.widthAnchor.constraint(greaterThanOrEqualToConstant: 32).isActive = true
  5874. return b
  5875. }
  5876. private func installWebViewObservers() {
  5877. kvoTokens.append(webView.observe(\.canGoBack, options: [.new]) { [weak self] _, _ in
  5878. self?.syncToolbarFromWebView()
  5879. })
  5880. kvoTokens.append(webView.observe(\.canGoForward, options: [.new]) { [weak self] _, _ in
  5881. self?.syncToolbarFromWebView()
  5882. })
  5883. kvoTokens.append(webView.observe(\.isLoading, options: [.new]) { [weak self] _, _ in
  5884. self?.syncToolbarFromWebView()
  5885. })
  5886. kvoTokens.append(webView.observe(\.estimatedProgress, options: [.new]) { [weak self] _, _ in
  5887. self?.syncProgressFromWebView()
  5888. })
  5889. kvoTokens.append(webView.observe(\.title, options: [.new]) { [weak self] _, _ in
  5890. self?.syncWindowTitle()
  5891. })
  5892. kvoTokens.append(webView.observe(\.url, options: [.new]) { [weak self] _, _ in
  5893. self?.syncAddressFieldFromWebView()
  5894. })
  5895. }
  5896. private func syncToolbarFromWebView() {
  5897. backButton?.isEnabled = webView.canGoBack
  5898. forwardButton?.isEnabled = webView.canGoForward
  5899. if webView.isLoading {
  5900. if #available(macOS 11.0, *), let img = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Stop") {
  5901. reloadStopButton.image = img
  5902. reloadStopButton.imagePosition = .imageOnly
  5903. reloadStopButton.title = ""
  5904. } else {
  5905. reloadStopButton.title = "Stop"
  5906. }
  5907. } else {
  5908. if #available(macOS 11.0, *), let img = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: "Reload") {
  5909. reloadStopButton.image = img
  5910. reloadStopButton.imagePosition = .imageOnly
  5911. reloadStopButton.title = ""
  5912. } else {
  5913. reloadStopButton.title = "Reload"
  5914. }
  5915. }
  5916. syncProgressFromWebView()
  5917. }
  5918. private func syncProgressFromWebView() {
  5919. guard let progressBar else { return }
  5920. if webView.isLoading {
  5921. progressBar.isHidden = false
  5922. progressBar.doubleValue = webView.estimatedProgress
  5923. } else {
  5924. progressBar.isHidden = true
  5925. progressBar.doubleValue = 0
  5926. }
  5927. }
  5928. private func syncAddressFieldFromWebView() {
  5929. guard let urlField, urlField.currentEditor() == nil, let url = webView.url else { return }
  5930. urlField.stringValue = url.absoluteString
  5931. }
  5932. private func syncWindowTitle() {
  5933. let t = webView.title?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
  5934. let host = webView.url?.host ?? ""
  5935. view.window?.title = t.isEmpty ? (host.isEmpty ? "Browser" : host) : t
  5936. }
  5937. func load(url: URL) {
  5938. lastLoadedURL = url
  5939. processTerminateRetryCount = 0
  5940. urlField?.stringValue = url.absoluteString
  5941. webView.load(URLRequest(url: url))
  5942. syncWindowTitle()
  5943. }
  5944. @objc private func goBack() {
  5945. webView.goBack()
  5946. }
  5947. @objc private func goForward() {
  5948. webView.goForward()
  5949. }
  5950. @objc private func reloadOrStop() {
  5951. if webView.isLoading {
  5952. webView.stopLoading()
  5953. } else {
  5954. webView.reload()
  5955. }
  5956. }
  5957. @objc private func addressFieldSubmitted() {
  5958. let raw = urlField?.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
  5959. guard raw.isEmpty == false else { return }
  5960. var normalized = raw
  5961. if normalized.lowercased().hasPrefix("http://") == false && normalized.lowercased().hasPrefix("https://") == false {
  5962. normalized = "https://\(normalized)"
  5963. }
  5964. guard let url = URL(string: normalized),
  5965. let scheme = url.scheme?.lowercased(),
  5966. scheme == "http" || scheme == "https",
  5967. url.host != nil
  5968. else {
  5969. let alert = NSAlert()
  5970. alert.messageText = "Invalid address"
  5971. alert.informativeText = "Enter a valid web address, for example https://example.com"
  5972. alert.addButton(withTitle: "OK")
  5973. alert.runModal()
  5974. return
  5975. }
  5976. guard inAppBrowserURLAllowed(url, policy: navigationPolicy) else {
  5977. presentBlockedHostAlert()
  5978. return
  5979. }
  5980. load(url: url)
  5981. }
  5982. private func presentBlockedHostAlert() {
  5983. let alert = NSAlert()
  5984. alert.messageText = "Address not allowed"
  5985. alert.informativeText = "This URL is not permitted with the current in-app browser policy (whitelist)."
  5986. alert.addButton(withTitle: "OK")
  5987. alert.runModal()
  5988. }
  5989. func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  5990. processTerminateRetryCount = 0
  5991. syncAddressFieldFromWebView()
  5992. syncWindowTitle()
  5993. }
  5994. func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
  5995. let nsError = error as NSError
  5996. if nsError.code == NSURLErrorCancelled {
  5997. return
  5998. }
  5999. let alert = NSAlert()
  6000. alert.messageText = "Unable to load page"
  6001. alert.informativeText = "Could not load this page in the in-app browser.\n\n\(error.localizedDescription)"
  6002. alert.addButton(withTitle: "Try Again")
  6003. alert.addButton(withTitle: "OK")
  6004. if alert.runModal() == .alertFirstButtonReturn, let url = lastLoadedURL {
  6005. processTerminateRetryCount = 0
  6006. webView.load(URLRequest(url: url))
  6007. }
  6008. }
  6009. func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
  6010. guard let url = lastLoadedURL else { return }
  6011. if processTerminateRetryCount < maxProcessTerminateRetries {
  6012. processTerminateRetryCount += 1
  6013. replaceWebViewAndLoad(url: url)
  6014. return
  6015. }
  6016. let alert = NSAlert()
  6017. alert.messageText = "Page stopped loading"
  6018. alert.informativeText =
  6019. "The in-app browser closed this page unexpectedly. You can try loading it again in this same window."
  6020. alert.addButton(withTitle: "Try Again")
  6021. alert.addButton(withTitle: "OK")
  6022. if alert.runModal() == .alertFirstButtonReturn {
  6023. processTerminateRetryCount = 0
  6024. replaceWebViewAndLoad(url: url)
  6025. }
  6026. }
  6027. func webView(
  6028. _ webView: WKWebView,
  6029. decidePolicyFor navigationAction: WKNavigationAction,
  6030. decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
  6031. ) {
  6032. guard let url = navigationAction.request.url else {
  6033. decisionHandler(.allow)
  6034. return
  6035. }
  6036. let scheme = (url.scheme ?? "").lowercased()
  6037. if scheme == "mailto" || scheme == "tel" {
  6038. decisionHandler(.cancel)
  6039. return
  6040. }
  6041. if inAppBrowserURLAllowed(url, policy: navigationPolicy) == false {
  6042. if navigationAction.targetFrame?.isMainFrame != false {
  6043. DispatchQueue.main.async { [weak self] in
  6044. self?.presentBlockedHostAlert()
  6045. }
  6046. }
  6047. decisionHandler(.cancel)
  6048. return
  6049. }
  6050. decisionHandler(.allow)
  6051. }
  6052. func webView(
  6053. _ webView: WKWebView,
  6054. createWebViewWith configuration: WKWebViewConfiguration,
  6055. for navigationAction: WKNavigationAction,
  6056. windowFeatures: WKWindowFeatures
  6057. ) -> WKWebView? {
  6058. if navigationAction.targetFrame == nil, let requestURL = navigationAction.request.url {
  6059. if inAppBrowserURLAllowed(requestURL, policy: navigationPolicy) {
  6060. webView.load(URLRequest(url: requestURL))
  6061. } else {
  6062. presentBlockedHostAlert()
  6063. }
  6064. }
  6065. return nil
  6066. }
  6067. func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
  6068. if control === urlField, commandSelector == #selector(NSResponder.insertNewline(_:)) {
  6069. addressFieldSubmitted()
  6070. return true
  6071. }
  6072. return false
  6073. }
  6074. }