Bez popisu

ViewController.swift 280KB

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