Sin descripción

ViewController.swift 327KB

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