script.js 354 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922
  1. document.addEventListener("DOMContentLoaded", function () {
  2. // PERF-002: Lazy script loader for optional heavy libraries
  3. const _loadedScripts = new Set();
  4. function loadScript(url) {
  5. if (_loadedScripts.has(url)) return Promise.resolve();
  6. return new Promise(function(resolve, reject) {
  7. const script = document.createElement('script');
  8. script.src = url;
  9. script.onload = function() { _loadedScripts.add(url); resolve(); };
  10. script.onerror = function() { reject(new Error('Failed to load: ' + url)); };
  11. document.head.appendChild(script);
  12. });
  13. }
  14. const _loadedStyles = new Set();
  15. function loadStyle(url) {
  16. if (_loadedStyles.has(url)) return Promise.resolve();
  17. return new Promise(function(resolve, reject) {
  18. const link = document.createElement('link');
  19. link.rel = 'stylesheet';
  20. link.href = url;
  21. link.onload = function() { _loadedStyles.add(url); resolve(); };
  22. link.onerror = function() { reject(new Error('Failed to load style: ' + url)); };
  23. document.head.appendChild(link);
  24. });
  25. }
  26. // CDN URLs for lazy-loaded libraries
  27. const CDN = {
  28. mermaid: 'https://cdn.jsdelivr.net/npm/mermaid@11.15.0/dist/mermaid.min.js',
  29. mathjax: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.min.js',
  30. jspdf: 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js',
  31. html2canvas: 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js',
  32. pako: 'https://cdnjs.cloudflare.com/ajax/libs/pako/2.1.0/pako.min.js',
  33. joypixels: 'https://cdn.jsdelivr.net/npm/emoji-toolkit@9.0.1/lib/js/joypixels.min.js',
  34. joypixels_css: 'https://cdn.jsdelivr.net/npm/emoji-toolkit@9.0.1/extras/css/joypixels.min.css'
  35. };
  36. let markdownRenderTimeout = null;
  37. let pendingPreviewRenderCancel = null;
  38. let previewRenderGeneration = 0;
  39. let previewHasCommittedRender = false;
  40. let previewLastRenderedTabId = null;
  41. // PERF-003: Track last rendered content to skip redundant renders
  42. let _lastRenderedContent = null;
  43. const LARGE_DOCUMENT_THRESHOLD = 15000;
  44. const HUGE_DOCUMENT_THRESHOLD = 100000;
  45. const PREVIEW_ENGINE_V2_ENABLED = true;
  46. const PREVIEW_WORKER_THRESHOLD = 50000;
  47. const PREVIEW_WORKER_TIMEOUT = 12000;
  48. const PREVIEW_SEGMENT_MIN_BLOCKS = 8;
  49. const PREVIEW_BLOCK_REUSE_LIMIT = 12000;
  50. const PREVIEW_SANITIZE_OPTIONS = {
  51. ADD_TAGS: ['mjx-container', 'input'],
  52. ADD_ATTR: ['id', 'class', 'style', 'align', 'type', 'checked', 'disabled', 'data-original-code'],
  53. ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel|blob):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
  54. };
  55. const RENDER_DELAY = 100;
  56. const LARGE_RENDER_DELAY = 160;
  57. const HUGE_RENDER_DELAY = 240;
  58. let syncScrollingEnabled = true;
  59. let isEditorScrolling = false;
  60. let isPreviewScrolling = false;
  61. let isProgrammaticScrolling = false;
  62. let scrollSyncTimeout = null;
  63. const SCROLL_SYNC_DELAY = 10;
  64. // View Mode State - Story 1.1
  65. let currentViewMode = 'split'; // 'editor', 'split', or 'preview'
  66. const APP_VERSION = '3.7.4';
  67. let activeModal = null;
  68. let lastFocusedElement = null;
  69. let isFindModalOpen = false;
  70. let findMatches = [];
  71. let activeFindIndex = -1;
  72. let lastFindQuery = '';
  73. // Custom Editor History State Manager variables
  74. const tabHistories = {};
  75. let currentHistoryTabId = null;
  76. let lastPushedValue = '';
  77. let typingTimeout = null;
  78. let lastInputType = null; // 'insert', 'delete', 'programmatic', or null
  79. let lastCursorStart = 0;
  80. let lastCursorEnd = 0;
  81. let pendingState = null;
  82. let previewWorker = null;
  83. let previewWorkerUnavailable = false;
  84. let previewWorkerRequestCounter = 0;
  85. let previewWorkerFailureCount = 0;
  86. const previewWorkerRequests = new Map();
  87. const previewSegmentHtmlCache = new Map();
  88. let previewSegmentCacheTabId = null;
  89. const markdownEditor = document.getElementById("markdown-editor");
  90. const markdownPreview = document.getElementById("markdown-preview");
  91. const markdownFormatToolbar = document.getElementById("markdown-format-toolbar");
  92. const themeToggle = document.getElementById("theme-toggle");
  93. const directionToggle = document.getElementById("direction-toggle");
  94. const importFromFileButton = document.getElementById("import-from-file");
  95. const importFromGithubButton = document.getElementById("import-from-github");
  96. const fileInput = document.getElementById("file-input");
  97. const exportMd = document.getElementById("export-md");
  98. const exportHtml = document.getElementById("export-html");
  99. const exportPdf = document.getElementById("export-pdf");
  100. const copyMarkdownButton = document.getElementById("copy-markdown-button");
  101. const dragOverlay = document.getElementById("drag-overlay");
  102. const toggleSyncButton = document.getElementById("toggle-sync");
  103. const editorPane = document.getElementById("markdown-editor");
  104. const previewPane = document.querySelector(".preview-pane");
  105. const readingTimeElement = document.getElementById("reading-time");
  106. const wordCountElement = document.getElementById("word-count");
  107. const charCountElement = document.getElementById("char-count");
  108. // View Mode Elements - Story 1.1
  109. const contentContainer = document.querySelector(".content-container");
  110. const viewModeButtons = document.querySelectorAll(".view-toggle-btn");
  111. // Mobile View Mode Elements - Story 1.4
  112. const mobileViewModeButtons = document.querySelectorAll(".mobile-view-mode-btn");
  113. // Resize Divider Elements - Story 1.3
  114. const resizeDivider = document.querySelector(".resize-divider");
  115. const editorPaneElement = document.querySelector(".editor-pane");
  116. const previewPaneElement = document.querySelector(".preview-pane");
  117. let isResizing = false;
  118. let editorWidthPercent = 50; // Default 50%
  119. const MIN_PANE_PERCENT = 20; // Minimum 20% width
  120. const mobileMenuToggle = document.getElementById("mobile-menu-toggle");
  121. const mobileMenuPanel = document.getElementById("mobile-menu-panel");
  122. const mobileMenuOverlay = document.getElementById("mobile-menu-overlay");
  123. const mobileCloseMenu = document.getElementById("close-mobile-menu");
  124. const mobileReadingTime = document.getElementById("mobile-reading-time");
  125. const mobileWordCount = document.getElementById("mobile-word-count");
  126. const mobileCharCount = document.getElementById("mobile-char-count");
  127. const mobileToggleSync = document.getElementById("mobile-toggle-sync");
  128. const mobileImportBtn = document.getElementById("mobile-import-button");
  129. const mobileImportGithubBtn = document.getElementById("mobile-import-github-button");
  130. const mobileExportMd = document.getElementById("mobile-export-md");
  131. const mobileExportHtml = document.getElementById("mobile-export-html");
  132. const mobileExportPdf = document.getElementById("mobile-export-pdf");
  133. const mobileCopyMarkdown = document.getElementById("mobile-copy-markdown");
  134. const mobileThemeToggle = document.getElementById("mobile-theme-toggle");
  135. const shareButton = document.getElementById("share-button");
  136. const mobileShareButton = document.getElementById("mobile-share-button");
  137. const githubImportModal = document.getElementById("github-import-modal");
  138. const githubImportTitle = document.getElementById("github-import-title");
  139. const githubImportUrlInput = document.getElementById("github-import-url");
  140. const githubImportFileSelect = document.getElementById("github-import-file-select");
  141. const githubImportSelectionToolbar = document.getElementById("github-import-selection-toolbar");
  142. const githubImportSelectedCount = document.getElementById("github-import-selected-count");
  143. const githubImportSelectAllBtn = document.getElementById("github-import-select-all");
  144. const githubImportTree = document.getElementById("github-import-tree");
  145. const githubImportError = document.getElementById("github-import-error");
  146. const githubImportCancelBtn = document.getElementById("github-import-cancel");
  147. const githubImportSubmitBtn = document.getElementById("github-import-submit");
  148. const editorHighlightLayer = document.getElementById("editor-highlight-layer");
  149. const lineNumbers = document.getElementById("line-numbers");
  150. const clearFormattingModal = document.getElementById("clear-formatting-modal");
  151. const clearFormattingConfirm = document.getElementById("clear-formatting-confirm");
  152. const clearFormattingCancel = document.getElementById("clear-formatting-cancel");
  153. const clearFormattingClose = document.getElementById("clear-formatting-close");
  154. const findReplaceModal = document.getElementById("find-replace-modal");
  155. const findReplaceInput = document.getElementById("find-replace-input");
  156. const findReplaceWith = document.getElementById("find-replace-with");
  157. const findReplaceCount = document.getElementById("find-replace-count");
  158. const findReplacePrev = document.getElementById("find-prev");
  159. const findReplaceNext = document.getElementById("find-next");
  160. const findReplaceCurrent = document.getElementById("find-replace-current");
  161. const findReplaceAll = document.getElementById("find-replace-all");
  162. const findReplaceClose = document.getElementById("find-replace-close");
  163. const findReplaceCloseIcon = document.getElementById("find-replace-close-icon");
  164. const helpModal = document.getElementById("help-modal");
  165. const helpModalClose = document.getElementById("help-modal-close");
  166. const helpModalCloseIcon = document.getElementById("help-modal-close-icon");
  167. const aboutModal = document.getElementById("about-modal");
  168. const aboutModalClose = document.getElementById("about-modal-close");
  169. const aboutModalCloseIcon = document.getElementById("about-modal-close-icon");
  170. const aboutVersion = document.getElementById("about-version");
  171. if (aboutVersion) {
  172. aboutVersion.textContent = APP_VERSION;
  173. }
  174. // ========================================
  175. // GLOBAL STATE (persisted across reloads)
  176. // ========================================
  177. const GLOBAL_STATE_KEY = 'markdownViewerGlobalState';
  178. let referenceCounter = 1;
  179. const imageObjectUrls = new Set();
  180. const EMOJI_API_URL = 'https://api.github.com/emojis';
  181. let emojiLoadPromise = null;
  182. let emojiEntries = [];
  183. let emojiUrlMap = new Map();
  184. let emojiLookupLoaded = false;
  185. let emojiRenderScheduled = false;
  186. let emojiItems = [];
  187. const emojiSelection = new Set();
  188. let symbolItems = [];
  189. const symbolSelection = new Set();
  190. const SYMBOL_SECTIONS = [
  191. {
  192. title: 'Common symbols',
  193. items: [
  194. { symbol: '©', entity: '©', name: 'copyright' },
  195. { symbol: '®', entity: '®', name: 'registered' },
  196. { symbol: '™', entity: '™', name: 'trademark' },
  197. { symbol: '✓', entity: '✓', name: 'check' },
  198. { symbol: '★', entity: '☆', name: 'star' },
  199. { symbol: '•', entity: '•', name: 'bullet' },
  200. { symbol: '…', entity: '…', name: 'ellipsis' },
  201. { symbol: '—', entity: '—', name: 'em dash' },
  202. { symbol: '–', entity: '–', name: 'en dash' },
  203. { symbol: '→', entity: '→', name: 'right arrow' },
  204. { symbol: '←', entity: '←', name: 'left arrow' },
  205. { symbol: '↑', entity: '↑', name: 'up arrow' },
  206. { symbol: '↓', entity: '↓', name: 'down arrow' },
  207. ],
  208. },
  209. {
  210. title: 'HTML entities',
  211. items: [
  212. { symbol: '€', entity: '€', name: 'euro' },
  213. { symbol: '£', entity: '£', name: 'pound' },
  214. { symbol: '¥', entity: '¥', name: 'yen' },
  215. { symbol: '§', entity: '§', name: 'section' },
  216. { symbol: '°', entity: '°', name: 'degree' },
  217. { symbol: '±', entity: '±', name: 'plus minus' },
  218. { symbol: '×', entity: '×', name: 'times' },
  219. { symbol: '÷', entity: '÷', name: 'divide' },
  220. { symbol: '≠', entity: '≠', name: 'not equal' },
  221. { symbol: '≤', entity: '≤', name: 'less equal' },
  222. { symbol: '≥', entity: '≥', name: 'greater equal' },
  223. { symbol: '∞', entity: '∞', name: 'infinity' },
  224. { symbol: 'µ', entity: 'µ', name: 'micro' },
  225. { symbol: '¼', entity: '¼', name: 'quarter' },
  226. { symbol: '½', entity: '½', name: 'half' },
  227. { symbol: '¾', entity: '¾', name: 'three quarters' },
  228. { symbol: '«', entity: '«', name: 'left quote' },
  229. { symbol: '»', entity: '»', name: 'right quote' },
  230. ],
  231. },
  232. {
  233. title: 'Markdown-safe characters',
  234. items: [
  235. { symbol: '&', entity: '&', name: 'ampersand' },
  236. { symbol: '<', entity: '&lt;', name: 'less than' },
  237. { symbol: '>', entity: '&gt;', name: 'greater than' },
  238. { symbol: '"', entity: '&quot;', name: 'double quote' },
  239. { symbol: "'", entity: '&#39;', name: 'apostrophe' },
  240. { symbol: '|', entity: '&#124;', name: 'pipe' },
  241. { symbol: '\\', entity: '&#92;', name: 'backslash' },
  242. { symbol: '`', entity: '&#96;', name: 'backtick' },
  243. { symbol: '*', entity: '&#42;', name: 'asterisk' },
  244. { symbol: '_', entity: '&#95;', name: 'underscore' },
  245. { symbol: '{', entity: '&#123;', name: 'left brace' },
  246. { symbol: '}', entity: '&#125;', name: 'right brace' },
  247. { symbol: '[', entity: '&#91;', name: 'left bracket' },
  248. { symbol: ']', entity: '&#93;', name: 'right bracket' },
  249. { symbol: '(', entity: '&#40;', name: 'left parenthesis' },
  250. { symbol: ')', entity: '&#41;', name: 'right parenthesis' },
  251. ],
  252. },
  253. ];
  254. // In-memory cache for global state to avoid repeated JSON parse/stringify round-trips (PERF-008/024)
  255. let _globalStateCache = null;
  256. function loadGlobalState() {
  257. if (_globalStateCache) return _globalStateCache;
  258. try { _globalStateCache = JSON.parse(localStorage.getItem(GLOBAL_STATE_KEY)) || {}; }
  259. catch { _globalStateCache = {}; }
  260. return _globalStateCache;
  261. }
  262. function saveGlobalState(patch) {
  263. _globalStateCache = { ...loadGlobalState(), ...patch };
  264. localStorage.setItem(GLOBAL_STATE_KEY, JSON.stringify(_globalStateCache));
  265. }
  266. // Check dark mode preference first for proper initialization
  267. const prefersDarkMode =
  268. window.matchMedia &&
  269. window.matchMedia("(prefers-color-scheme: dark)").matches;
  270. const savedTheme = loadGlobalState().theme;
  271. const initialTheme = savedTheme ?? (prefersDarkMode ? "dark" : "light");
  272. document.documentElement.setAttribute("data-theme", initialTheme);
  273. themeToggle.innerHTML = initialTheme === "dark"
  274. ? '<i class="bi bi-sun"></i>'
  275. : '<i class="bi bi-moon"></i>';
  276. function updateDirectionToggleUI(direction) {
  277. const isRtl = direction === "rtl";
  278. const toggleLabel = isRtl ? "Switch to LTR" : "Switch to RTL";
  279. if (directionToggle) {
  280. directionToggle.textContent = isRtl ? "R" : "L";
  281. directionToggle.setAttribute("title", toggleLabel);
  282. directionToggle.setAttribute("aria-label", toggleLabel);
  283. directionToggle.setAttribute("aria-pressed", isRtl.toString());
  284. }
  285. }
  286. const savedDirection = loadGlobalState().direction;
  287. const initialDirection = savedDirection === "rtl" ? "rtl" : "ltr";
  288. function applyDirectionToContent(direction) {
  289. if (markdownEditor) markdownEditor.setAttribute("dir", direction);
  290. if (markdownPreview) markdownPreview.setAttribute("dir", direction);
  291. }
  292. applyDirectionToContent(initialDirection);
  293. updateDirectionToggleUI(initialDirection);
  294. // Track last Mermaid theme to avoid redundant re-initialization (PERF-005)
  295. let _lastMermaidTheme = null;
  296. let _mermaidThemeReinitTimeout = null;
  297. let _themeTransitionTimeout = null;
  298. const initMermaid = (forceReinit) => {
  299. if (typeof mermaid === 'undefined') return; // PERF-002: Not loaded yet
  300. const currentTheme = document.documentElement.getAttribute("data-theme");
  301. const mermaidTheme = currentTheme === "dark" ? "dark" : "default";
  302. // Skip re-initialization if theme hasn't changed (PERF-005)
  303. if (!forceReinit && _lastMermaidTheme === mermaidTheme) return;
  304. _lastMermaidTheme = mermaidTheme;
  305. mermaid.initialize({
  306. startOnLoad: false,
  307. theme: mermaidTheme,
  308. securityLevel: 'strict',
  309. flowchart: { useMaxWidth: true, htmlLabels: true },
  310. fontSize: 16
  311. });
  312. };
  313. // PERF-002: Removed eager initMermaid() — mermaid is now lazy-loaded on first use
  314. const markedOptions = {
  315. gfm: true,
  316. breaks: true,
  317. pedantic: false,
  318. sanitize: false,
  319. smartypants: false,
  320. xhtml: false,
  321. headerIds: true,
  322. mangle: false,
  323. };
  324. const LINE_NUMBER_GUTTER_MIN_CH = 3;
  325. const LINE_NUMBER_GUTTER_PADDING_CH = 1;
  326. const LINE_NUMBER_EMPTY_PLACEHOLDER = '\u200b';
  327. const LINE_CACHE_MAX_ENTRIES = 5000;
  328. const LARGE_EDITOR_WORK_DELAY = 180;
  329. const HUGE_EDITOR_WORK_DELAY = 320;
  330. const FIND_REFRESH_DELAY = 120;
  331. const LARGE_FIND_REFRESH_DELAY = 320;
  332. let lineNumberMeasure = null;
  333. let lineNumberUpdateFrame = null;
  334. let lineNumberUpdateTimeout = null;
  335. let editorOverlayScrollFrame = null;
  336. let findRefreshTimeout = null;
  337. const renderer = new marked.Renderer();
  338. const BLOCK_MATH_MARKER_PATTERN = /^\$\$/m;
  339. const BLOCK_MATH_PATTERN = /^\$\$[ \t]*\n?([\s\S]*?)\n?\$\$[ \t]*(?:\n|$)/;
  340. const DEFINITION_LIST_ITEM_PATTERN = /^:[ \t]+(.*)$/;
  341. const SUPERSCRIPT_PATTERN = /^\^(?!\s)([^^\n]*?\S)\^(?!\^)/;
  342. const SUBSCRIPT_PATTERN = /^~(?!~)(?!\s)([^~\n]*?\S)~(?!~)/;
  343. const HIGHLIGHT_PATTERN = /^==(?=\S)([\s\S]*?\S)==/;
  344. const MARKDOWN_LIST_MARKER_PATTERN = /^(\s*)(?:[-*+]\s+|\d+\.\s+|>\s+)/;
  345. const EMPTY_LINE_PATTERN = /^\s*$/;
  346. const footnoteDefinitions = new Map();
  347. const footnoteOrder = [];
  348. const footnoteRefCounts = new Map();
  349. const footnoteFirstRefId = new Map();
  350. let anonymousFootnoteCounter = 0;
  351. let suppressFootnotePreprocess = false;
  352. function resetExtendedMarkdownState() {
  353. footnoteDefinitions.clear();
  354. footnoteOrder.length = 0;
  355. footnoteRefCounts.clear();
  356. footnoteFirstRefId.clear();
  357. anonymousFootnoteCounter = 0;
  358. }
  359. function normalizeFootnoteId(id) {
  360. const normalized = String(id || "")
  361. .trim()
  362. .toLowerCase()
  363. .replace(/[^a-z0-9_-]+/g, "-")
  364. .replace(/^-+|-+$/g, "");
  365. if (normalized) {
  366. return normalized;
  367. }
  368. anonymousFootnoteCounter += 1;
  369. return `footnote-${anonymousFootnoteCounter}`;
  370. }
  371. function escapeHtmlAttribute(value) {
  372. return String(value)
  373. .replace(/&/g, "&amp;")
  374. .replace(/"/g, "&quot;")
  375. .replace(/'/g, "&#39;")
  376. .replace(/</g, "&lt;")
  377. .replace(/>/g, "&gt;");
  378. }
  379. function sanitizePreviewHtml(html) {
  380. if (typeof DOMPurify === "undefined") {
  381. throw new ReferenceError("DOMPurify is not defined. Secure rendering aborted.");
  382. }
  383. return DOMPurify.sanitize(html, PREVIEW_SANITIZE_OPTIONS);
  384. }
  385. function getLoadedScriptUrl(needle, fallbackUrl) {
  386. const scripts = document.getElementsByTagName("script");
  387. for (let i = 0; i < scripts.length; i += 1) {
  388. const src = scripts[i].getAttribute("src") || "";
  389. if (src.includes(needle)) {
  390. try {
  391. return new URL(src, window.location.href).toString();
  392. } catch (e) {
  393. return src;
  394. }
  395. }
  396. }
  397. return fallbackUrl;
  398. }
  399. function getPreviewWorkerUrl() {
  400. const scripts = document.getElementsByTagName("script");
  401. let scriptUrl = "";
  402. for (let i = scripts.length - 1; i >= 0; i -= 1) {
  403. const src = scripts[i].getAttribute("src") || "";
  404. if (src.includes("script.js")) {
  405. scriptUrl = src;
  406. break;
  407. }
  408. }
  409. try {
  410. return new URL("preview-worker.js", scriptUrl ? new URL(scriptUrl, window.location.href) : window.location.href).toString();
  411. } catch (e) {
  412. return "preview-worker.js";
  413. }
  414. }
  415. function getPreviewWorkerLibraryUrls() {
  416. return {
  417. marked: getLoadedScriptUrl("marked", "https://cdnjs.cloudflare.com/ajax/libs/marked/9.1.6/marked.min.js"),
  418. highlight: getLoadedScriptUrl("highlight", "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"),
  419. };
  420. }
  421. function isSegmentedPreviewSafe(markdown) {
  422. if (!markdown || markdown.length < PREVIEW_WORKER_THRESHOLD) return false;
  423. if (/^\s*---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/.test(markdown)) return false;
  424. if (/^\[[^\]\n]+\]:\s+\S+/m.test(markdown)) return false;
  425. if (/\[\^[^\]\n]+\]/.test(markdown)) return false;
  426. if (/\n:[ \t]+/.test(markdown)) return false;
  427. if (/^\s{0,3}<\/?[a-zA-Z][\w:-]*(?:\s|>|\/>)/m.test(markdown)) return false;
  428. return true;
  429. }
  430. function shouldUsePreviewWorker(rawVal, context) {
  431. if (!PREVIEW_ENGINE_V2_ENABLED || previewWorkerUnavailable || context.disableWorker) return false;
  432. if (typeof Worker === "undefined" || typeof URL === "undefined") return false;
  433. return isSegmentedPreviewSafe(rawVal);
  434. }
  435. function resetPreviewSegmentCache(previewDocumentId) {
  436. if (previewSegmentCacheTabId !== previewDocumentId) {
  437. previewSegmentHtmlCache.clear();
  438. previewSegmentCacheTabId = previewDocumentId;
  439. }
  440. }
  441. function trimPreviewSegmentCache() {
  442. while (previewSegmentHtmlCache.size > PREVIEW_BLOCK_REUSE_LIMIT) {
  443. const firstKey = previewSegmentHtmlCache.keys().next().value;
  444. previewSegmentHtmlCache.delete(firstKey);
  445. }
  446. }
  447. function buildSegmentedPreviewHtml(blocks, previewDocumentId) {
  448. resetPreviewSegmentCache(previewDocumentId);
  449. const htmlParts = [];
  450. blocks.forEach(function(block, index) {
  451. const hash = String(block.hash || "");
  452. const cacheKey = `${hash}:${block.sourceLength || 0}:${block.htmlLength || (block.html ? block.html.length : 0)}`;
  453. let sanitizedBlock = previewSegmentHtmlCache.get(cacheKey);
  454. if (sanitizedBlock === undefined) {
  455. sanitizedBlock = sanitizePreviewHtml(block.html || "");
  456. previewSegmentHtmlCache.set(cacheKey, sanitizedBlock);
  457. }
  458. const blockId = block.id || `preview-block-${index}`;
  459. htmlParts.push(
  460. `<section class="preview-render-block" style="content-visibility: auto; contain-intrinsic-size: auto 220px;" data-preview-block-id="${escapeHtmlAttribute(blockId)}" data-preview-block-hash="${escapeHtmlAttribute(cacheKey)}">${sanitizedBlock}</section>`
  461. );
  462. });
  463. trimPreviewSegmentCache();
  464. return htmlParts.join("");
  465. }
  466. function markPreviewWorkerFailure(error) {
  467. previewWorkerFailureCount += 1;
  468. if (previewWorkerFailureCount >= 2) {
  469. previewWorkerUnavailable = true;
  470. }
  471. if (previewWorker) {
  472. try {
  473. previewWorker.terminate();
  474. } catch (e) {
  475. // Ignore worker shutdown failures; fallback rendering will continue on main.
  476. }
  477. previewWorker = null;
  478. }
  479. previewWorkerRequests.forEach(function(pending) {
  480. clearTimeout(pending.timeoutId);
  481. pending.reject(error || new Error("Preview worker unavailable."));
  482. });
  483. previewWorkerRequests.clear();
  484. }
  485. function recordPreviewWorkerRenderFailure() {
  486. previewWorkerFailureCount += 1;
  487. if (previewWorkerFailureCount < 2) return;
  488. previewWorkerUnavailable = true;
  489. if (previewWorker) {
  490. try {
  491. previewWorker.terminate();
  492. } catch (e) {
  493. // Ignore worker shutdown failures; fallback rendering will continue on main.
  494. }
  495. previewWorker = null;
  496. }
  497. }
  498. function getPreviewWorker() {
  499. if (previewWorkerUnavailable) return null;
  500. if (previewWorker) return previewWorker;
  501. try {
  502. previewWorker = new Worker(getPreviewWorkerUrl());
  503. previewWorker.onmessage = function(event) {
  504. const data = event.data || {};
  505. const pending = previewWorkerRequests.get(data.requestId);
  506. if (!pending) return;
  507. clearTimeout(pending.timeoutId);
  508. previewWorkerRequests.delete(data.requestId);
  509. if (data.type === "render-result") {
  510. previewWorkerFailureCount = 0;
  511. pending.resolve(data.result);
  512. } else {
  513. recordPreviewWorkerRenderFailure();
  514. pending.reject(new Error(data.error || "Preview worker render failed."));
  515. }
  516. };
  517. previewWorker.onerror = function(event) {
  518. markPreviewWorkerFailure(event && event.message ? new Error(event.message) : new Error("Preview worker failed."));
  519. };
  520. } catch (e) {
  521. markPreviewWorkerFailure(e);
  522. return null;
  523. }
  524. return previewWorker;
  525. }
  526. function requestPreviewWorkerRender(rawVal, context) {
  527. const worker = getPreviewWorker();
  528. if (!worker) {
  529. return Promise.reject(new Error("Preview worker unavailable."));
  530. }
  531. const requestId = ++previewWorkerRequestCounter;
  532. return new Promise(function(resolve, reject) {
  533. const timeoutId = setTimeout(function() {
  534. previewWorkerRequests.delete(requestId);
  535. recordPreviewWorkerRenderFailure();
  536. reject(new Error("Preview worker timed out."));
  537. }, PREVIEW_WORKER_TIMEOUT);
  538. previewWorkerRequests.set(requestId, { resolve, reject, timeoutId });
  539. worker.postMessage({
  540. type: "render",
  541. requestId,
  542. markdown: rawVal,
  543. options: {
  544. minimumBlocks: PREVIEW_SEGMENT_MIN_BLOCKS,
  545. libraryUrls: getPreviewWorkerLibraryUrls(),
  546. renderId: context.renderId,
  547. },
  548. });
  549. });
  550. }
  551. function parseInlineWithoutFootnotes(text) {
  552. suppressFootnotePreprocess = true;
  553. try {
  554. return marked.parseInline(text);
  555. } finally {
  556. suppressFootnotePreprocess = false;
  557. }
  558. }
  559. function renderDefinitionContent(content, options = {}) {
  560. const { appendHtml = "" } = options;
  561. const paragraphs = String(content || "")
  562. .split(/\n(?:[ \t]*\n)+/)
  563. .map((paragraph) => paragraph.trim())
  564. .filter(Boolean);
  565. if (appendHtml) {
  566. if (paragraphs.length === 0) {
  567. paragraphs.push(appendHtml);
  568. } else {
  569. paragraphs[paragraphs.length - 1] = `${paragraphs[paragraphs.length - 1]} ${appendHtml}`;
  570. }
  571. }
  572. return paragraphs
  573. .map((paragraph) => {
  574. const renderedParagraph = parseInlineWithoutFootnotes(paragraph);
  575. if (typeof DOMPurify === "undefined") {
  576. throw new ReferenceError("DOMPurify is not defined. Secure rendering aborted.");
  577. }
  578. const safeParagraph = DOMPurify.sanitize(renderedParagraph);
  579. return `<p>${safeParagraph}</p>`;
  580. })
  581. .join("");
  582. }
  583. function extractFootnoteDefinitions(markdown) {
  584. const lines = markdown.split("\n");
  585. const preservedLines = [];
  586. let index = 0;
  587. while (index < lines.length) {
  588. const match = /^([ \t]{0,3})\[\^([^\]\n]+)\]:[ \t]*(.*)$/.exec(lines[index]);
  589. if (!match) {
  590. preservedLines.push(lines[index]);
  591. index += 1;
  592. continue;
  593. }
  594. const baseIndent = match[1] || "";
  595. const id = match[2].trim();
  596. const definitionLines = [match[3] || ""];
  597. index += 1;
  598. while (index < lines.length) {
  599. const line = lines[index];
  600. if (!line.startsWith(baseIndent)) {
  601. break;
  602. }
  603. const lineAfterBase = line.slice(baseIndent.length);
  604. const indentedMatch = /^(?: {2,}|\t)(.*)$/.exec(lineAfterBase);
  605. if (indentedMatch) {
  606. definitionLines.push(indentedMatch[1]);
  607. index += 1;
  608. continue;
  609. }
  610. if (lineAfterBase.trim() === "") {
  611. const nextLine = lines[index + 1] || "";
  612. const nextAfterBase = nextLine.startsWith(baseIndent)
  613. ? nextLine.slice(baseIndent.length)
  614. : "";
  615. if (/^(?: {2,}|\t)/.test(nextAfterBase)) {
  616. definitionLines.push("");
  617. index += 1;
  618. continue;
  619. }
  620. }
  621. break;
  622. }
  623. footnoteDefinitions.set(id, definitionLines.join("\n").trim());
  624. }
  625. return preservedLines.join("\n");
  626. }
  627. function applyFootnotes(markdown) {
  628. const markdownWithReferences = markdown.replace(/\[\^([^\]\n]+)\]/g, function(match, idText) {
  629. const id = idText.trim();
  630. if (!id) {
  631. return match;
  632. }
  633. if (!footnoteOrder.includes(id)) {
  634. footnoteOrder.push(id);
  635. }
  636. const refCount = (footnoteRefCounts.get(id) || 0) + 1;
  637. footnoteRefCounts.set(id, refCount);
  638. const normalizedId = normalizeFootnoteId(id);
  639. const refId = `fnref-${normalizedId}${refCount > 1 ? `-${refCount}` : ""}`;
  640. if (!footnoteFirstRefId.has(id)) {
  641. footnoteFirstRefId.set(id, refId);
  642. }
  643. const noteNumber = footnoteOrder.indexOf(id) + 1;
  644. const safeRefId = escapeHtmlAttribute(refId);
  645. const safeNormalizedId = escapeHtmlAttribute(normalizedId);
  646. return `<sup id="${safeRefId}" class="footnote-ref"><a href="#fn-${safeNormalizedId}" aria-label="Footnote ${noteNumber}">[${noteNumber}]</a></sup>`;
  647. });
  648. const footnotesHtml = footnoteOrder
  649. .filter((id) => footnoteDefinitions.has(id))
  650. .map((id) => {
  651. const normalizedId = normalizeFootnoteId(id);
  652. const backRefId = footnoteFirstRefId.get(id) || `fnref-${normalizedId}`;
  653. const safeNormalizedId = escapeHtmlAttribute(normalizedId);
  654. const safeBackRefId = escapeHtmlAttribute(backRefId);
  655. const backRefHtml = `<a href="#${safeBackRefId}" class="footnote-backref" aria-label="Back to content">←</a>`;
  656. const noteHtml = renderDefinitionContent(
  657. footnoteDefinitions.get(id) || "",
  658. { appendHtml: backRefHtml }
  659. );
  660. return `<li id="fn-${safeNormalizedId}">${noteHtml}</li>`;
  661. })
  662. .join("");
  663. if (!footnotesHtml) {
  664. return markdownWithReferences;
  665. }
  666. return `${markdownWithReferences}\n\n<section class="footnotes"><hr><ol>${footnotesHtml}</ol></section>`;
  667. }
  668. const blockMathExtension = {
  669. name: 'blockMath',
  670. level: 'block',
  671. start(src) {
  672. const match = src.match(BLOCK_MATH_MARKER_PATTERN);
  673. if (!match) {
  674. return undefined;
  675. }
  676. return match.index;
  677. },
  678. tokenizer(src) {
  679. const match = BLOCK_MATH_PATTERN.exec(src);
  680. if (!match) {
  681. return undefined;
  682. }
  683. return {
  684. type: 'blockMath',
  685. raw: match[0],
  686. text: match[1],
  687. };
  688. },
  689. renderer(token) {
  690. return `<div class="math-block">$$\n${token.text}\n$$</div>\n`;
  691. }
  692. };
  693. const definitionListExtension = {
  694. name: "definitionList",
  695. level: "block",
  696. start(src) {
  697. const match = src.match(/\n:[ \t]+/);
  698. if (!match) {
  699. return undefined;
  700. }
  701. return match.index + 1;
  702. },
  703. tokenizer(src) {
  704. const lines = src.split("\n");
  705. if (lines.length < 2) {
  706. return undefined;
  707. }
  708. const term = lines[0];
  709. if (EMPTY_LINE_PATTERN.test(term) || MARKDOWN_LIST_MARKER_PATTERN.test(term)) {
  710. return undefined;
  711. }
  712. if (!DEFINITION_LIST_ITEM_PATTERN.test(lines[1])) {
  713. return undefined;
  714. }
  715. const definitions = [];
  716. const rawLines = [term];
  717. let index = 1;
  718. while (index < lines.length) {
  719. const itemMatch = DEFINITION_LIST_ITEM_PATTERN.exec(lines[index]);
  720. if (!itemMatch) {
  721. break;
  722. }
  723. rawLines.push(lines[index]);
  724. const definitionLines = [itemMatch[1]];
  725. index += 1;
  726. while (index < lines.length) {
  727. const line = lines[index];
  728. if (DEFINITION_LIST_ITEM_PATTERN.test(line)) {
  729. break;
  730. }
  731. if (EMPTY_LINE_PATTERN.test(line)) {
  732. const nextLine = lines[index + 1] || "";
  733. if (/^(?: {2,}|\t)/.test(nextLine)) {
  734. rawLines.push(line);
  735. definitionLines.push("");
  736. index += 1;
  737. continue;
  738. }
  739. break;
  740. }
  741. const continuationMatch = /^(?: {2,}|\t)(.*)$/.exec(line);
  742. if (!continuationMatch) {
  743. break;
  744. }
  745. rawLines.push(line);
  746. definitionLines.push(continuationMatch[1]);
  747. index += 1;
  748. }
  749. definitions.push(definitionLines.join("\n").trim());
  750. }
  751. if (definitions.length === 0) {
  752. return undefined;
  753. }
  754. let raw = rawLines.join("\n");
  755. if (src.startsWith(raw + "\n")) {
  756. raw += "\n";
  757. }
  758. return {
  759. type: "definitionList",
  760. raw: raw,
  761. term: term.trim(),
  762. definitions: definitions,
  763. };
  764. },
  765. renderer(token) {
  766. const termHtml = parseInlineWithoutFootnotes(token.term);
  767. const definitionHtml = token.definitions
  768. .map((definition) => `<dd>${renderDefinitionContent(definition)}</dd>`)
  769. .join("");
  770. return `<dl><dt>${termHtml}</dt>${definitionHtml}</dl>\n`;
  771. },
  772. };
  773. const superscriptExtension = {
  774. name: "superscript",
  775. level: "inline",
  776. start(src) {
  777. const index = src.indexOf("^");
  778. return index >= 0 ? index : undefined;
  779. },
  780. tokenizer(src) {
  781. const match = SUPERSCRIPT_PATTERN.exec(src);
  782. if (!match) {
  783. return undefined;
  784. }
  785. return {
  786. type: "superscript",
  787. raw: match[0],
  788. text: match[1],
  789. };
  790. },
  791. renderer(token) {
  792. return `<sup>${marked.parseInline(token.text)}</sup>`;
  793. },
  794. };
  795. const subscriptExtension = {
  796. name: "subscript",
  797. level: "inline",
  798. start(src) {
  799. const index = src.indexOf("~");
  800. return index >= 0 ? index : undefined;
  801. },
  802. tokenizer(src) {
  803. const match = SUBSCRIPT_PATTERN.exec(src);
  804. if (!match) {
  805. return undefined;
  806. }
  807. return {
  808. type: "subscript",
  809. raw: match[0],
  810. text: match[1],
  811. };
  812. },
  813. renderer(token) {
  814. return `<sub>${marked.parseInline(token.text)}</sub>`;
  815. },
  816. };
  817. const highlightExtension = {
  818. name: "highlight",
  819. level: "inline",
  820. start(src) {
  821. const index = src.indexOf("==");
  822. return index >= 0 ? index : undefined;
  823. },
  824. tokenizer(src) {
  825. const match = HIGHLIGHT_PATTERN.exec(src);
  826. if (!match) {
  827. return undefined;
  828. }
  829. return {
  830. type: "highlight",
  831. raw: match[0],
  832. text: match[1],
  833. };
  834. },
  835. renderer(token) {
  836. return `<mark>${marked.parseInline(token.text)}</mark>`;
  837. },
  838. };
  839. renderer.code = function (code, language) {
  840. if (language === 'mermaid') {
  841. const uniqueId = 'mermaid-diagram-' + Math.random().toString(36).substr(2, 9);
  842. const escapedCode = code
  843. .replace(/&/g, "&amp;")
  844. .replace(/</g, "&lt;")
  845. .replace(/>/g, "&gt;");
  846. return `<div class="mermaid-container is-loading"><div class="mermaid" id="${uniqueId}" data-original-code="${encodeURIComponent(code)}">${escapedCode}</div></div>`;
  847. }
  848. const validLanguage = hljs.getLanguage(language) ? language : "plaintext";
  849. const highlightedCode = hljs.highlight(code, {
  850. language: validLanguage,
  851. }).value;
  852. return `<pre><code class="hljs ${validLanguage}">${highlightedCode}</code></pre>`;
  853. };
  854. renderer.heading = function (text, level, raw) {
  855. let id = raw
  856. .toLowerCase()
  857. .trim()
  858. .replace(/<[^>]*>/g, '')
  859. .replace(/\s+/g, '-')
  860. .replace(/[^\w-]/g, '')
  861. .replace(/-+/g, '-');
  862. if (!id) {
  863. id = 'heading-' + Math.random().toString(36).substr(2, 9);
  864. }
  865. return `<h${level} id="${id}">${text}</h${level}>`;
  866. };
  867. marked.use({
  868. extensions: [
  869. blockMathExtension,
  870. definitionListExtension,
  871. superscriptExtension,
  872. subscriptExtension,
  873. highlightExtension,
  874. ],
  875. hooks: {
  876. preprocess(markdown) {
  877. if (suppressFootnotePreprocess) {
  878. return markdown;
  879. }
  880. resetExtendedMarkdownState();
  881. // ✅ Replace escaped dollar signs before marked.js strips the backslash.
  882. // This prevents MathJax from treating lone $ as a math delimiter.
  883. const protectedMarkdown = markdown.replace(/\\\$/g, '&#36;');
  884. return applyFootnotes(extractFootnoteDefinitions(protectedMarkdown));
  885. },
  886. },
  887. });
  888. marked.setOptions({
  889. ...markedOptions,
  890. renderer: renderer,
  891. });
  892. const GITHUB_ALERT_META = {
  893. note: {
  894. label: "Note",
  895. viewBox: "0 0 512 512",
  896. path: "M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336l24 0 0-64-24 0c-13.3 0-24-10.7-24-24s10.7-24 24-24l48 0c13.3 0 24 10.7 24 24l0 88 8 0c13.3 0 24 10.7 24 24s-10.7 24-24 24l-80 0c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z",
  897. },
  898. tip: {
  899. label: "Tip",
  900. viewBox: "0 0 384 512",
  901. path: "M297.2 248.9C311.6 228.3 320 203.2 320 176c0-70.7-57.3-128-128-128S64 105.3 64 176c0 27.2 8.4 52.3 22.8 72.9c3.7 5.3 8.1 11.3 12.8 17.7c0 0 0 0 0 0c12.9 17.7 28.3 38.9 39.8 59.8c10.4 19 15.7 38.8 18.3 57.5L109 384c-2.2-12-5.9-23.7-11.8-34.5c-9.9-18-22.2-34.9-34.5-51.8c0 0 0 0 0 0s0 0 0 0c-5.2-7.1-10.4-14.2-15.4-21.4C27.6 247.9 16 213.3 16 176C16 78.8 94.8 0 192 0s176 78.8 176 176c0 37.3-11.6 71.9-31.4 100.3c-5 7.2-10.2 14.3-15.4 21.4c0 0 0 0 0 0s0 0 0 0c-12.3 16.8-24.6 33.7-34.5 51.8c-5.9 10.8-9.6 22.5-11.8 34.5l-48.6 0c2.6-18.7 7.9-38.6 18.3-57.5c11.5-20.9 26.9-42.1 39.8-59.8c0 0 0 0 0 0s0 0 0 0s0 0 0 0c4.7-6.4 9-12.4 12.7-17.7zM192 128c-26.5 0-48 21.5-48 48c0 8.8-7.2 16-16 16s-16-7.2-16-16c0-44.2 35.8-80 80-80c8.8 0 16 7.2 16 16s-7.2 16-16 16zm0 384c-44.2 0-80-35.8-80-80l0-16 160 0 0 16c0 44.2-35.8 80-80 80z",
  902. },
  903. important: {
  904. label: "Important",
  905. viewBox: "0 0 512 512",
  906. path: "M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zm0-384c13.3 0 24 10.7 24 24l0 112c0 13.3-10.7 24-24 24s-24-10.7-24-24l0-112c0-13.3 10.7-24 24-24zM224 352a32 32 0 1 1 64 0 32 32 0 1 1 -64 0z",
  907. },
  908. warning: {
  909. label: "Warning",
  910. viewBox: "0 0 512 512",
  911. path: "M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480L40 480c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24l0 112c0 13.3 10.7 24 24 24s24-10.7 24-24l0-112c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z",
  912. },
  913. caution: {
  914. label: "Caution",
  915. viewBox: "0 0 512 512",
  916. path: "M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM175 175c9.4-9.4 24.6-9.4 33.9 0l47 47 47-47c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9l-47 47 47 47c9.4 9.4 9.4 24.6 0 33.9s-24.6 9.4-33.9 0l-47-47-47 47c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9l47-47-47-47c-9.4-9.4-9.4-24.6 0-33.9z",
  917. },
  918. };
  919. const GITHUB_ALERT_MARKER_REGEX = /^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](?:(?:\s|&nbsp;|<br\s*\/?>)+|$)/i;
  920. function enhanceGitHubAlerts(container) {
  921. if (!container) return;
  922. const blockquotes = container.querySelectorAll("blockquote");
  923. blockquotes.forEach((blockquote) => {
  924. let firstParagraph = null;
  925. for (const child of blockquote.children) {
  926. if (child.tagName === "P") {
  927. firstParagraph = child;
  928. break;
  929. }
  930. }
  931. if (!firstParagraph) return;
  932. const firstParagraphHtml = firstParagraph.innerHTML.trim();
  933. const markerMatch = firstParagraphHtml.match(GITHUB_ALERT_MARKER_REGEX);
  934. if (!markerMatch) return;
  935. const alertType = markerMatch[1].toLowerCase();
  936. blockquote.classList.add("markdown-alert", `markdown-alert-${alertType}`);
  937. const title = document.createElement("p");
  938. title.className = "markdown-alert-title";
  939. const alertMeta = GITHUB_ALERT_META[alertType] || { label: markerMatch[1], path: "" };
  940. const icon = document.createElement("span");
  941. icon.className = "markdown-alert-icon";
  942. icon.setAttribute("aria-hidden", "true");
  943. if (alertMeta.path) {
  944. const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  945. svg.setAttribute("viewBox", alertMeta.viewBox || "0 0 512 512");
  946. const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
  947. path.setAttribute("d", alertMeta.path);
  948. svg.appendChild(path);
  949. icon.appendChild(svg);
  950. }
  951. const label = document.createElement("span");
  952. label.textContent = alertMeta.label;
  953. title.appendChild(icon);
  954. title.appendChild(label);
  955. blockquote.insertBefore(title, blockquote.firstChild);
  956. const remainingHtml = firstParagraphHtml
  957. .replace(GITHUB_ALERT_MARKER_REGEX, "")
  958. .trim();
  959. if (remainingHtml) {
  960. firstParagraph.innerHTML = remainingHtml;
  961. } else {
  962. firstParagraph.remove();
  963. }
  964. });
  965. }
  966. function parseFrontmatter(markdown) {
  967. const match = markdown.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/);
  968. if (!match) return { frontmatter: null, body: markdown };
  969. try {
  970. const data = jsyaml.load(match[1]) || {};
  971. return { frontmatter: data, body: markdown.slice(match[0].length) };
  972. } catch (e) {
  973. console.warn('Frontmatter YAML parse error:', e);
  974. return { frontmatter: null, body: markdown };
  975. }
  976. }
  977. function renderFrontmatterValue(value) {
  978. if (value === null || value === undefined) return '';
  979. if (value instanceof Date) {
  980. const y = value.getUTCFullYear();
  981. const m = String(value.getUTCMonth() + 1).padStart(2, '0');
  982. const d = String(value.getUTCDate()).padStart(2, '0');
  983. return `${y}-${m}-${d}`;
  984. }
  985. if (Array.isArray(value)) {
  986. const allPrimitive = value.every(v => v === null || typeof v !== 'object');
  987. if (allPrimitive) {
  988. return value
  989. .map(v => `<span class="fm-tag">${escapeHtml(String(v ?? ''))}</span>`)
  990. .join('');
  991. }
  992. return `<pre class="fm-complex">${escapeHtml(jsyaml.dump(value).trimEnd())}</pre>`;
  993. }
  994. if (typeof value === 'object') {
  995. return `<pre class="fm-complex">${escapeHtml(jsyaml.dump(value).trimEnd())}</pre>`;
  996. }
  997. return escapeHtml(String(value));
  998. }
  999. function renderFrontmatterTable(data) {
  1000. const rows = Object.entries(data).map(([key, value]) =>
  1001. `<tr><th>${escapeHtml(key)}</th><td>${renderFrontmatterValue(value)}</td></tr>`
  1002. );
  1003. return `<table class="frontmatter-table"><tbody>${rows.join('')}</tbody></table>`;
  1004. }
  1005. function escapeHtml(str) {
  1006. return str
  1007. .replace(/&/g, '&amp;')
  1008. .replace(/</g, '&lt;')
  1009. .replace(/>/g, '&gt;')
  1010. .replace(/"/g, '&quot;');
  1011. }
  1012. // PERF-012: Inlined default template to eliminate network request, FOUC, and layout shifts
  1013. const defaultMarkdownTemplate = document.getElementById('default-markdown');
  1014. let templateText = '';
  1015. if (defaultMarkdownTemplate) {
  1016. if (defaultMarkdownTemplate.content && typeof defaultMarkdownTemplate.content.textContent === 'string') {
  1017. templateText = defaultMarkdownTemplate.content.textContent.trim();
  1018. } else {
  1019. templateText = defaultMarkdownTemplate.textContent ? defaultMarkdownTemplate.textContent.trim() : '';
  1020. }
  1021. }
  1022. const sampleMarkdown = templateText || '# Welcome to Markdown Viewer\n\nStart typing your markdown here...';
  1023. if (!markdownEditor.value) {
  1024. markdownEditor.value = sampleMarkdown;
  1025. }
  1026. // ========================================
  1027. // DOCUMENT TABS & SESSION MANAGEMENT
  1028. // ========================================
  1029. const STORAGE_KEY = 'markdownViewerTabs';
  1030. const ACTIVE_TAB_KEY = 'markdownViewerActiveTab';
  1031. const UNTITLED_COUNTER_KEY = 'markdownViewerUntitledCounter';
  1032. let tabs = [];
  1033. let activeTabId = null;
  1034. let draggedTabId = null;
  1035. let saveTabStateTimeout = null;
  1036. let untitledCounter = 0;
  1037. function loadTabsFromStorage() {
  1038. try {
  1039. return JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];
  1040. } catch (e) {
  1041. return [];
  1042. }
  1043. }
  1044. function saveTabsToStorage(tabsArr) {
  1045. // PERF-008: Debounce tab saves to reduce main thread blocking from JSON.stringify
  1046. // on large document arrays. Immediate flush happens on visibilitychange/beforeunload.
  1047. clearTimeout(saveTabStateTimeout);
  1048. saveTabStateTimeout = setTimeout(function() {
  1049. _flushTabsToStorage(tabsArr);
  1050. }, 500);
  1051. }
  1052. function _flushTabsToStorage(tabsArr) {
  1053. clearTimeout(saveTabStateTimeout);
  1054. try {
  1055. localStorage.setItem(STORAGE_KEY, JSON.stringify(tabsArr || tabs));
  1056. } catch (e) {
  1057. console.warn('Failed to save tabs to localStorage:', e);
  1058. }
  1059. }
  1060. // Ensure tabs are persisted before page close (PERF-008)
  1061. window.addEventListener('beforeunload', function() { _flushTabsToStorage(tabs); });
  1062. document.addEventListener('visibilitychange', function() {
  1063. if (document.visibilityState === 'hidden') _flushTabsToStorage(tabs);
  1064. });
  1065. function loadActiveTabId() {
  1066. return localStorage.getItem(ACTIVE_TAB_KEY);
  1067. }
  1068. function saveActiveTabId(id) {
  1069. localStorage.setItem(ACTIVE_TAB_KEY, id);
  1070. }
  1071. function loadUntitledCounter() {
  1072. return parseInt(localStorage.getItem(UNTITLED_COUNTER_KEY) || '0', 10);
  1073. }
  1074. function saveUntitledCounter(val) {
  1075. localStorage.setItem(UNTITLED_COUNTER_KEY, String(val));
  1076. }
  1077. function nextUntitledTitle() {
  1078. untitledCounter += 1;
  1079. saveUntitledCounter(untitledCounter);
  1080. return 'Untitled ' + untitledCounter;
  1081. }
  1082. function createTab(content, title, viewMode) {
  1083. if (content === undefined) content = '';
  1084. if (title === undefined) title = null;
  1085. if (viewMode === undefined) viewMode = 'split';
  1086. return {
  1087. id: 'tab_' + Date.now() + '_' + Math.random().toString(36).substring(2, 8),
  1088. title: title || 'Untitled',
  1089. content: content,
  1090. scrollPos: 0,
  1091. viewMode: viewMode,
  1092. createdAt: Date.now()
  1093. };
  1094. }
  1095. function closeTabMenus() {
  1096. document.querySelectorAll('.tab-menu-btn.open').forEach(function(btn) {
  1097. btn.classList.remove('open');
  1098. btn.setAttribute('aria-expanded', 'false');
  1099. });
  1100. document.querySelectorAll('.tab-menu-dropdown.open').forEach(function(dropdown) {
  1101. dropdown.classList.remove('open');
  1102. });
  1103. }
  1104. function removeTabMenuDropdowns() {
  1105. document.querySelectorAll('.tab-menu-dropdown[data-tab-menu-dropdown="true"]').forEach(function(dropdown) {
  1106. dropdown.remove();
  1107. });
  1108. }
  1109. function positionTabMenu(menuBtn, dropdown) {
  1110. const rect = menuBtn.getBoundingClientRect();
  1111. const margin = 8;
  1112. const dropdownWidth = dropdown.offsetWidth || 130;
  1113. const dropdownHeight = dropdown.offsetHeight || 110;
  1114. let left = rect.right - dropdownWidth;
  1115. let top = rect.bottom + 4;
  1116. left = Math.max(margin, Math.min(left, window.innerWidth - dropdownWidth - margin));
  1117. if (top + dropdownHeight > window.innerHeight - margin) {
  1118. top = Math.max(margin, rect.top - dropdownHeight - 4);
  1119. }
  1120. dropdown.style.top = top + 'px';
  1121. dropdown.style.left = left + 'px';
  1122. dropdown.style.right = 'auto';
  1123. }
  1124. function runTabMenuAction(tabId, action, isMobileMenu) {
  1125. if (action === 'rename') {
  1126. if (isMobileMenu) closeMobileMenu();
  1127. renameTab(tabId);
  1128. } else if (action === 'duplicate') {
  1129. duplicateTab(tabId);
  1130. if (isMobileMenu) closeMobileMenu();
  1131. } else if (action === 'delete') {
  1132. deleteTab(tabId);
  1133. }
  1134. }
  1135. function createTabActionMenu(tab, options) {
  1136. const isMobileMenu = options && options.isMobileMenu;
  1137. const menuIdPrefix = options && options.menuIdPrefix ? options.menuIdPrefix : 'tab-menu';
  1138. const menuId = menuIdPrefix + '-' + tab.id;
  1139. const menuBtn = document.createElement('button');
  1140. menuBtn.type = 'button';
  1141. menuBtn.className = 'tab-menu-btn';
  1142. menuBtn.setAttribute('aria-label', 'File options for ' + (tab.title || 'Untitled'));
  1143. menuBtn.setAttribute('aria-haspopup', 'menu');
  1144. menuBtn.setAttribute('aria-expanded', 'false');
  1145. menuBtn.setAttribute('aria-controls', menuId);
  1146. menuBtn.setAttribute('draggable', 'false');
  1147. menuBtn.title = 'File options';
  1148. // PERF-007: Replace HTML entity with plain unicode character set via textContent
  1149. menuBtn.textContent = '⋯';
  1150. const dropdown = document.createElement('div');
  1151. dropdown.id = menuId;
  1152. dropdown.className = 'tab-menu-dropdown';
  1153. dropdown.setAttribute('data-tab-menu-dropdown', 'true');
  1154. dropdown.setAttribute('role', 'menu');
  1155. dropdown.innerHTML =
  1156. '<button type="button" class="tab-menu-item" role="menuitem" data-action="rename"><i class="bi bi-pencil"></i> Rename</button>' +
  1157. '<button type="button" class="tab-menu-item" role="menuitem" data-action="duplicate"><i class="bi bi-files"></i> Duplicate</button>' +
  1158. '<button type="button" class="tab-menu-item tab-menu-item-danger" role="menuitem" data-action="delete"><i class="bi bi-trash"></i> Delete</button>';
  1159. menuBtn.addEventListener('click', function(e) {
  1160. e.preventDefault();
  1161. e.stopPropagation();
  1162. const shouldOpen = !menuBtn.classList.contains('open');
  1163. closeTabMenus();
  1164. if (shouldOpen) {
  1165. menuBtn.classList.add('open');
  1166. menuBtn.setAttribute('aria-expanded', 'true');
  1167. dropdown.classList.add('open');
  1168. positionTabMenu(menuBtn, dropdown);
  1169. }
  1170. });
  1171. menuBtn.addEventListener('mousedown', function(e) {
  1172. e.stopPropagation();
  1173. });
  1174. menuBtn.addEventListener('dragstart', function(e) {
  1175. e.preventDefault();
  1176. e.stopPropagation();
  1177. });
  1178. dropdown.addEventListener('click', function(e) {
  1179. e.stopPropagation();
  1180. });
  1181. dropdown.querySelectorAll('.tab-menu-item').forEach(function(actionBtn) {
  1182. actionBtn.addEventListener('click', function(e) {
  1183. e.preventDefault();
  1184. e.stopPropagation();
  1185. const action = actionBtn.getAttribute('data-action');
  1186. closeTabMenus();
  1187. runTabMenuAction(tab.id, action, isMobileMenu);
  1188. });
  1189. });
  1190. document.body.appendChild(dropdown);
  1191. return { button: menuBtn, dropdown: dropdown };
  1192. }
  1193. function renderTabBar(tabsArr, currentActiveTabId) {
  1194. const tabList = document.getElementById('tab-list');
  1195. if (!tabList) return;
  1196. closeTabMenus();
  1197. removeTabMenuDropdowns();
  1198. // PERF-007: Use textContent instead of innerHTML to clear elements faster
  1199. tabList.textContent = '';
  1200. tabsArr.forEach(function(tab) {
  1201. const item = document.createElement('div');
  1202. item.className = 'tab-item' + (tab.id === currentActiveTabId ? ' active' : '');
  1203. item.setAttribute('data-tab-id', tab.id);
  1204. item.setAttribute('role', 'tab');
  1205. item.setAttribute('aria-selected', tab.id === currentActiveTabId ? 'true' : 'false');
  1206. item.setAttribute('draggable', 'true');
  1207. item.setAttribute('tabindex', tab.id === currentActiveTabId ? '0' : '-1');
  1208. const titleSpan = document.createElement('span');
  1209. titleSpan.className = 'tab-title';
  1210. titleSpan.textContent = tab.title || 'Untitled';
  1211. titleSpan.title = tab.title || 'Untitled';
  1212. const tabMenu = createTabActionMenu(tab, { menuIdPrefix: 'desktop-tab-menu' });
  1213. item.appendChild(titleSpan);
  1214. item.appendChild(tabMenu.button);
  1215. item.addEventListener('dragstart', function() {
  1216. draggedTabId = tab.id;
  1217. setTimeout(function() { item.classList.add('dragging'); }, 0);
  1218. });
  1219. item.addEventListener('dragend', function() {
  1220. item.classList.remove('dragging');
  1221. draggedTabId = null;
  1222. });
  1223. item.addEventListener('dragover', function(e) {
  1224. e.preventDefault();
  1225. item.classList.add('drag-over');
  1226. });
  1227. item.addEventListener('dragleave', function() {
  1228. item.classList.remove('drag-over');
  1229. });
  1230. item.addEventListener('drop', function(e) {
  1231. e.preventDefault();
  1232. item.classList.remove('drag-over');
  1233. if (!draggedTabId || draggedTabId === tab.id) return;
  1234. const fromIdx = tabs.findIndex(function(t) { return t.id === draggedTabId; });
  1235. const toIdx = tabs.findIndex(function(t) { return t.id === tab.id; });
  1236. if (fromIdx === -1 || toIdx === -1) return;
  1237. const moved = tabs.splice(fromIdx, 1)[0];
  1238. tabs.splice(toIdx, 0, moved);
  1239. saveTabsToStorage(tabs);
  1240. renderTabBar(tabs, activeTabId);
  1241. });
  1242. tabList.appendChild(item);
  1243. });
  1244. // PERF-006: Event delegation — single click handler for all tabs
  1245. tabList.onclick = function(e) {
  1246. const tabItem = e.target.closest('.tab-item');
  1247. if (!tabItem) return;
  1248. // Don't switch tab if clicking the menu button
  1249. if (e.target.closest('.tab-menu-btn')) return;
  1250. const tabId = tabItem.getAttribute('data-tab-id');
  1251. if (tabId) switchTab(tabId);
  1252. };
  1253. // Auto-scroll active tab into view (paint-aligned to prevent forced reflows)
  1254. const activeItem = tabList.querySelector('.tab-item.active');
  1255. if (activeItem) {
  1256. requestAnimationFrame(function() {
  1257. activeItem.scrollIntoView({ block: 'nearest', inline: 'nearest' });
  1258. });
  1259. }
  1260. // Arrow-key keyboard navigation inside tabList (WAI-ARIA compliance with manual selection)
  1261. tabList.onkeydown = function(e) {
  1262. const items = Array.from(tabList.querySelectorAll('.tab-item'));
  1263. if (items.length === 0) return;
  1264. const focusedItem = document.activeElement.closest('.tab-item');
  1265. if (!focusedItem) return;
  1266. const activeIdx = items.indexOf(focusedItem);
  1267. if (activeIdx === -1) return;
  1268. let targetIdx = -1;
  1269. if (e.key === 'ArrowRight') {
  1270. targetIdx = (activeIdx + 1) % items.length;
  1271. } else if (e.key === 'ArrowLeft') {
  1272. targetIdx = (activeIdx - 1 + items.length) % items.length;
  1273. } else if (e.key === 'Home') {
  1274. targetIdx = 0;
  1275. } else if (e.key === 'End') {
  1276. targetIdx = items.length - 1;
  1277. } else if (e.key === 'Enter' || e.key === ' ') {
  1278. e.preventDefault();
  1279. const tabId = focusedItem.getAttribute('data-tab-id');
  1280. switchTab(tabId);
  1281. // After switch tab, focus the active item in the newly rendered tab bar
  1282. requestAnimationFrame(function() {
  1283. const newActive = tabList.querySelector(`.tab-item[data-tab-id="${tabId}"]`);
  1284. if (newActive) newActive.focus();
  1285. });
  1286. return;
  1287. }
  1288. if (targetIdx !== -1) {
  1289. e.preventDefault();
  1290. // Update roving tabindex focus without triggering heavy re-renders
  1291. items.forEach(function(item, idx) {
  1292. if (idx === targetIdx) {
  1293. item.setAttribute('tabindex', '0');
  1294. item.focus();
  1295. } else {
  1296. item.setAttribute('tabindex', '-1');
  1297. }
  1298. });
  1299. }
  1300. };
  1301. renderMobileTabList(tabsArr, currentActiveTabId);
  1302. if (typeof tabList.dispatchEvent === 'function') {
  1303. tabList.dispatchEvent(new Event('scroll'));
  1304. }
  1305. }
  1306. // ========================================
  1307. // TAB OVERFLOW — Scroll Buttons, Wheel, Indicators
  1308. // ========================================
  1309. var _tabOverflowInitialized = false;
  1310. function setupTabOverflow() {
  1311. if (_tabOverflowInitialized) return;
  1312. _tabOverflowInitialized = true;
  1313. var tabBar = document.getElementById('tab-bar');
  1314. var tabList = document.getElementById('tab-list');
  1315. if (!tabBar || !tabList) return;
  1316. // --- Create scroll arrow buttons ---
  1317. var scrollLeftBtn = document.createElement('button');
  1318. scrollLeftBtn.className = 'tab-scroll-btn tab-scroll-left';
  1319. scrollLeftBtn.setAttribute('aria-label', 'Scroll tabs left');
  1320. scrollLeftBtn.title = 'Scroll left';
  1321. scrollLeftBtn.innerHTML = '<i class="bi bi-chevron-left"></i>';
  1322. scrollLeftBtn.addEventListener('click', function() {
  1323. tabList.scrollBy({ left: -200, behavior: 'smooth' });
  1324. });
  1325. var scrollRightBtn = document.createElement('button');
  1326. scrollRightBtn.className = 'tab-scroll-btn tab-scroll-right';
  1327. scrollRightBtn.setAttribute('aria-label', 'Scroll tabs right');
  1328. scrollRightBtn.title = 'Scroll right';
  1329. scrollRightBtn.innerHTML = '<i class="bi bi-chevron-right"></i>';
  1330. scrollRightBtn.addEventListener('click', function() {
  1331. tabList.scrollBy({ left: 200, behavior: 'smooth' });
  1332. });
  1333. // Insert scroll buttons flanking the tab-list
  1334. tabBar.insertBefore(scrollLeftBtn, tabList);
  1335. var newBtn = document.getElementById('tab-new-btn');
  1336. if (newBtn) {
  1337. tabBar.insertBefore(scrollRightBtn, newBtn);
  1338. } else {
  1339. var resetBtn = document.getElementById('tab-reset-btn');
  1340. if (resetBtn) {
  1341. tabBar.insertBefore(scrollRightBtn, resetBtn);
  1342. } else {
  1343. tabBar.appendChild(scrollRightBtn);
  1344. }
  1345. }
  1346. // --- Overflow detection ---
  1347. var _overflowRafId = null;
  1348. function updateOverflowState() {
  1349. if (_overflowRafId) return;
  1350. _overflowRafId = requestAnimationFrame(function() {
  1351. _overflowRafId = null;
  1352. var hasLeft = tabList.scrollLeft > 1;
  1353. var hasRight = tabList.scrollLeft < (tabList.scrollWidth - tabList.clientWidth - 1);
  1354. tabBar.classList.toggle('has-overflow-left', hasLeft);
  1355. tabBar.classList.toggle('has-overflow-right', hasRight);
  1356. });
  1357. }
  1358. tabList.addEventListener('scroll', updateOverflowState);
  1359. // Use ResizeObserver to detect when overflow state changes due to window resize
  1360. if (typeof ResizeObserver !== 'undefined') {
  1361. var resizeObs = new ResizeObserver(updateOverflowState);
  1362. resizeObs.observe(tabList);
  1363. }
  1364. // Initial check
  1365. updateOverflowState();
  1366. // --- Mouse wheel scroll: vertical wheel → horizontal scroll ---
  1367. tabList.addEventListener('wheel', function(e) {
  1368. // Only intercept vertical wheel (don't fight native horizontal wheel/trackpad)
  1369. if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
  1370. e.preventDefault();
  1371. tabList.scrollLeft += e.deltaY;
  1372. updateOverflowState();
  1373. }
  1374. }, { passive: false });
  1375. }
  1376. function renderMobileTabList(tabsArr, currentActiveTabId) {
  1377. const mobileTabList = document.getElementById('mobile-tab-list');
  1378. if (!mobileTabList) return;
  1379. // PERF-007: Clear element content using textContent instead of innerHTML
  1380. mobileTabList.textContent = '';
  1381. tabsArr.forEach(function(tab) {
  1382. const item = document.createElement('div');
  1383. item.className = 'mobile-tab-item' + (tab.id === currentActiveTabId ? ' active' : '');
  1384. item.setAttribute('role', 'tab');
  1385. item.setAttribute('aria-selected', tab.id === currentActiveTabId ? 'true' : 'false');
  1386. item.setAttribute('data-tab-id', tab.id);
  1387. const titleSpan = document.createElement('span');
  1388. titleSpan.className = 'mobile-tab-title';
  1389. titleSpan.textContent = tab.title || 'Untitled';
  1390. titleSpan.title = tab.title || 'Untitled';
  1391. const tabMenu = createTabActionMenu(tab, {
  1392. isMobileMenu: true,
  1393. menuIdPrefix: 'mobile-tab-menu'
  1394. });
  1395. item.appendChild(titleSpan);
  1396. item.appendChild(tabMenu.button);
  1397. item.addEventListener('click', function() {
  1398. switchTab(tab.id);
  1399. closeMobileMenu();
  1400. });
  1401. mobileTabList.appendChild(item);
  1402. });
  1403. }
  1404. // Close any open tab dropdown when clicking elsewhere in the document
  1405. document.addEventListener('click', function() {
  1406. closeTabMenus();
  1407. });
  1408. function saveCurrentTabState() {
  1409. const tab = tabs.find(function(t) { return t.id === activeTabId; });
  1410. if (!tab) return;
  1411. tab.content = markdownEditor.value;
  1412. tab.scrollPos = markdownEditor.scrollTop;
  1413. tab.viewMode = currentViewMode || 'split';
  1414. saveTabsToStorage(tabs);
  1415. }
  1416. function restoreViewMode(mode) {
  1417. currentViewMode = null;
  1418. setViewMode(mode || 'split');
  1419. }
  1420. function switchTab(tabId) {
  1421. if (tabId === activeTabId) return;
  1422. saveCurrentTabState();
  1423. // Clear typing timeout and reset tracking for the new tab
  1424. if (typingTimeout) {
  1425. clearTimeout(typingTimeout);
  1426. typingTimeout = null;
  1427. }
  1428. lastInputType = null;
  1429. pendingState = null;
  1430. activeTabId = tabId;
  1431. saveActiveTabId(activeTabId);
  1432. const tab = tabs.find(function(t) { return t.id === tabId; });
  1433. if (!tab) return;
  1434. markdownEditor.value = tab.content;
  1435. initTabHistory(tabId, tab.content);
  1436. lastPushedValue = tab.content;
  1437. currentHistoryTabId = tabId;
  1438. updateUndoRedoButtons();
  1439. restoreViewMode(tab.viewMode);
  1440. renderMarkdown();
  1441. requestAnimationFrame(function() {
  1442. markdownEditor.scrollTop = tab.scrollPos || 0;
  1443. });
  1444. renderTabBar(tabs, activeTabId);
  1445. }
  1446. function newTab(content, title) {
  1447. if (content === undefined) content = '';
  1448. if (tabs.length >= 20) {
  1449. alert('Maximum of 20 tabs reached. Please close an existing tab to open a new one.');
  1450. return;
  1451. }
  1452. if (!title) title = nextUntitledTitle();
  1453. const tab = createTab(content, title);
  1454. tabs.push(tab);
  1455. switchTab(tab.id);
  1456. markdownEditor.focus();
  1457. }
  1458. function closeTab(tabId) {
  1459. const idx = tabs.findIndex(function(t) { return t.id === tabId; });
  1460. if (idx === -1) return;
  1461. // Clean up history of the closed tab
  1462. if (tabHistories[tabId]) {
  1463. delete tabHistories[tabId];
  1464. }
  1465. tabs.splice(idx, 1);
  1466. if (tabs.length === 0) {
  1467. // Auto-create new "Untitled" when last tab is deleted
  1468. const newT = createTab('', nextUntitledTitle());
  1469. tabs.push(newT);
  1470. activeTabId = newT.id;
  1471. saveActiveTabId(activeTabId);
  1472. markdownEditor.value = '';
  1473. restoreViewMode('split');
  1474. renderMarkdown();
  1475. } else if (activeTabId === tabId) {
  1476. const newIdx = Math.max(0, idx - 1);
  1477. activeTabId = tabs[newIdx].id;
  1478. saveActiveTabId(activeTabId);
  1479. const newActiveTab = tabs[newIdx];
  1480. markdownEditor.value = newActiveTab.content;
  1481. restoreViewMode(newActiveTab.viewMode);
  1482. renderMarkdown();
  1483. requestAnimationFrame(function() {
  1484. markdownEditor.scrollTop = newActiveTab.scrollPos || 0;
  1485. });
  1486. }
  1487. saveTabsToStorage(tabs);
  1488. renderTabBar(tabs, activeTabId);
  1489. }
  1490. function deleteTab(tabId) {
  1491. closeTab(tabId);
  1492. }
  1493. function renameTab(tabId) {
  1494. const tab = tabs.find(function(t) { return t.id === tabId; });
  1495. if (!tab) return;
  1496. const modal = document.getElementById('rename-modal');
  1497. const input = document.getElementById('rename-modal-input');
  1498. const confirmBtn = document.getElementById('rename-modal-confirm');
  1499. const cancelBtn = document.getElementById('rename-modal-cancel');
  1500. if (!modal || !input) return;
  1501. input.value = tab.title;
  1502. function doRename() {
  1503. const newName = input.value.trim();
  1504. if (newName) {
  1505. tab.title = newName;
  1506. saveTabsToStorage(tabs);
  1507. renderTabBar(tabs, activeTabId);
  1508. }
  1509. closeAppModal(modal);
  1510. cleanup();
  1511. }
  1512. function doCancel() {
  1513. closeAppModal(modal);
  1514. cleanup();
  1515. }
  1516. function onKey(e) {
  1517. if (e.key === 'Enter') doRename();
  1518. }
  1519. function cleanup() {
  1520. confirmBtn.removeEventListener('click', doRename);
  1521. cancelBtn.removeEventListener('click', doCancel);
  1522. input.removeEventListener('keydown', onKey);
  1523. }
  1524. confirmBtn.addEventListener('click', doRename);
  1525. cancelBtn.addEventListener('click', doCancel);
  1526. input.addEventListener('keydown', onKey);
  1527. openAppModal(modal, {
  1528. focusTarget: input,
  1529. onClose: doCancel
  1530. });
  1531. input.select();
  1532. }
  1533. function duplicateTab(tabId) {
  1534. const tab = tabs.find(function(t) { return t.id === tabId; });
  1535. if (!tab) return;
  1536. if (tabs.length >= 20) {
  1537. alert('Maximum of 20 tabs reached. Please close an existing tab to open a new one.');
  1538. return;
  1539. }
  1540. const shouldSwitchToDuplicate = tabId === activeTabId;
  1541. saveCurrentTabState();
  1542. const dupTitle = tab.title + ' (copy)';
  1543. const dup = createTab(tab.content, dupTitle, tab.viewMode);
  1544. const idx = tabs.findIndex(function(t) { return t.id === tabId; });
  1545. tabs.splice(idx + 1, 0, dup);
  1546. if (shouldSwitchToDuplicate) {
  1547. switchTab(dup.id);
  1548. } else {
  1549. saveTabsToStorage(tabs);
  1550. renderTabBar(tabs, activeTabId);
  1551. }
  1552. }
  1553. function resetAllTabs() {
  1554. const modal = document.getElementById('reset-confirm-modal');
  1555. const confirmBtn = document.getElementById('reset-modal-confirm');
  1556. const cancelBtn = document.getElementById('reset-modal-cancel');
  1557. if (!modal) return;
  1558. function doReset() {
  1559. closeAppModal(modal);
  1560. cleanup();
  1561. tabs = [];
  1562. untitledCounter = 0;
  1563. saveUntitledCounter(0);
  1564. const welcome = createTab(sampleMarkdown, 'Welcome to Markdown');
  1565. tabs.push(welcome);
  1566. activeTabId = welcome.id;
  1567. saveActiveTabId(activeTabId);
  1568. saveTabsToStorage(tabs);
  1569. markdownEditor.value = sampleMarkdown;
  1570. restoreViewMode('split');
  1571. renderMarkdown();
  1572. renderTabBar(tabs, activeTabId);
  1573. }
  1574. function doCancel() {
  1575. closeAppModal(modal);
  1576. cleanup();
  1577. }
  1578. function cleanup() {
  1579. confirmBtn.removeEventListener('click', doReset);
  1580. cancelBtn.removeEventListener('click', doCancel);
  1581. }
  1582. confirmBtn.addEventListener('click', doReset);
  1583. cancelBtn.addEventListener('click', doCancel);
  1584. openAppModal(modal, {
  1585. focusTarget: confirmBtn,
  1586. onClose: doCancel
  1587. });
  1588. }
  1589. function initTabs() {
  1590. untitledCounter = loadUntitledCounter();
  1591. tabs = loadTabsFromStorage();
  1592. activeTabId = loadActiveTabId();
  1593. // Check if Neutralino passed an initial file via command line (early load)
  1594. if (window.NL_INITIAL_FILE_CONTENT) {
  1595. const initialFile = window.NL_INITIAL_FILE_CONTENT;
  1596. const tab = createTab(initialFile.content, initialFile.name);
  1597. tabs.push(tab);
  1598. activeTabId = tab.id;
  1599. saveTabsToStorage(tabs);
  1600. saveActiveTabId(activeTabId);
  1601. delete window.NL_INITIAL_FILE_CONTENT;
  1602. } else if (tabs.length === 0) {
  1603. const tab = createTab(sampleMarkdown, 'Welcome to Markdown');
  1604. tabs.push(tab);
  1605. activeTabId = tab.id;
  1606. saveTabsToStorage(tabs);
  1607. saveActiveTabId(activeTabId);
  1608. } else if (!tabs.find(function(t) { return t.id === activeTabId; })) {
  1609. activeTabId = tabs[0].id;
  1610. saveActiveTabId(activeTabId);
  1611. }
  1612. const activeTab = tabs.find(function(t) { return t.id === activeTabId; });
  1613. markdownEditor.value = activeTab.content;
  1614. initTabHistory(activeTabId, activeTab.content);
  1615. updateUndoRedoButtons();
  1616. restoreViewMode(activeTab.viewMode);
  1617. renderMarkdown();
  1618. const editorPane = document.querySelector('.editor-pane');
  1619. if (editorPane) {
  1620. editorPane.classList.remove('is-loading');
  1621. }
  1622. requestAnimationFrame(function() {
  1623. markdownEditor.scrollTop = activeTab.scrollPos || 0;
  1624. });
  1625. renderTabBar(tabs, activeTabId);
  1626. setupTabOverflow();
  1627. const staticNewBtn = document.getElementById('tab-new-btn');
  1628. if (staticNewBtn) {
  1629. staticNewBtn.onclick = function() {
  1630. newTab();
  1631. };
  1632. }
  1633. }
  1634. // Late-load callback hook for Neutralino command-line files
  1635. window.NL_IMPORT_EXTERNAL_FILE = function(content, name) {
  1636. if (typeof tabs === 'undefined') return;
  1637. const existing = tabs.find(function(t) { return t.title === name && t.content === content; });
  1638. if (existing) {
  1639. switchTab(existing.id);
  1640. return;
  1641. }
  1642. newTab(content, name);
  1643. };
  1644. function showPreviewSkeleton() {
  1645. if (markdownPreview && !markdownPreview.querySelector('#markdown-preview-skeleton')) {
  1646. markdownPreview.setAttribute('aria-busy', 'true');
  1647. markdownPreview.dataset.renderState = 'loading';
  1648. markdownPreview.innerHTML = `
  1649. <div class="skeleton-preview-container" id="markdown-preview-skeleton" aria-hidden="true">
  1650. <div class="skeleton-placeholder skeleton-title"></div>
  1651. <div class="skeleton-placeholder skeleton-line skeleton-w90"></div>
  1652. <div class="skeleton-placeholder skeleton-line skeleton-w85"></div>
  1653. <div class="skeleton-placeholder skeleton-line skeleton-w60"></div>
  1654. <div class="skeleton-placeholder skeleton-subtitle"></div>
  1655. <div class="skeleton-placeholder skeleton-line skeleton-w88"></div>
  1656. <div class="skeleton-placeholder skeleton-line skeleton-w92"></div>
  1657. <div class="skeleton-placeholder skeleton-line skeleton-w45"></div>
  1658. </div>
  1659. `;
  1660. }
  1661. }
  1662. function previewContainsSkeleton() {
  1663. return Boolean(markdownPreview && markdownPreview.querySelector('#markdown-preview-skeleton'));
  1664. }
  1665. function getActivePreviewDocumentId() {
  1666. return activeTabId || '__single-document__';
  1667. }
  1668. function clearPendingPreviewWork() {
  1669. if (pendingPreviewRenderCancel) {
  1670. pendingPreviewRenderCancel();
  1671. pendingPreviewRenderCancel = null;
  1672. }
  1673. }
  1674. function getPreviewRenderDelay(markdown) {
  1675. const length = markdown.length;
  1676. if (length >= HUGE_DOCUMENT_THRESHOLD) return HUGE_RENDER_DELAY;
  1677. if (length >= LARGE_DOCUMENT_THRESHOLD) return LARGE_RENDER_DELAY;
  1678. return RENDER_DELAY;
  1679. }
  1680. function getEditorWorkDelay(markdown) {
  1681. const length = markdown.length;
  1682. if (length >= HUGE_DOCUMENT_THRESHOLD) return HUGE_EDITOR_WORK_DELAY;
  1683. if (length >= LARGE_DOCUMENT_THRESHOLD) return LARGE_EDITOR_WORK_DELAY;
  1684. return 0;
  1685. }
  1686. function isEditorVisible() {
  1687. return currentViewMode === 'editor' || currentViewMode === 'split';
  1688. }
  1689. function deferPreviewWork(callback, rawLength) {
  1690. let cancelled = false;
  1691. let rafId = null;
  1692. let idleId = null;
  1693. let timeoutId = null;
  1694. rafId = requestAnimationFrame(function() {
  1695. rafId = null;
  1696. if (cancelled) return;
  1697. if ('requestIdleCallback' in window) {
  1698. idleId = window.requestIdleCallback(function() {
  1699. idleId = null;
  1700. if (!cancelled) callback();
  1701. }, { timeout: rawLength >= HUGE_DOCUMENT_THRESHOLD ? 700 : 350 });
  1702. } else {
  1703. timeoutId = setTimeout(function() {
  1704. timeoutId = null;
  1705. if (!cancelled) callback();
  1706. }, 0);
  1707. }
  1708. });
  1709. return function cancelDeferredPreviewWork() {
  1710. cancelled = true;
  1711. if (rafId !== null) cancelAnimationFrame(rafId);
  1712. if (idleId !== null && 'cancelIdleCallback' in window) window.cancelIdleCallback(idleId);
  1713. if (timeoutId !== null) clearTimeout(timeoutId);
  1714. };
  1715. }
  1716. function capturePreviewScroll() {
  1717. if (!previewPane) return null;
  1718. return {
  1719. top: previewPane.scrollTop,
  1720. left: previewPane.scrollLeft,
  1721. };
  1722. }
  1723. function restorePreviewScroll(snapshot) {
  1724. if (!snapshot || !previewPane) return;
  1725. requestAnimationFrame(function() {
  1726. const maxTop = Math.max(0, previewPane.scrollHeight - previewPane.clientHeight);
  1727. previewPane.scrollTop = Math.min(maxTop, snapshot.top);
  1728. previewPane.scrollLeft = snapshot.left;
  1729. });
  1730. }
  1731. function canReusePreviewNode(currentNode, nextNode, options) {
  1732. if (!currentNode || !nextNode || currentNode.nodeType !== nextNode.nodeType) return false;
  1733. if (currentNode.nodeType === Node.TEXT_NODE) {
  1734. if (currentNode.nodeValue !== nextNode.nodeValue) {
  1735. currentNode.nodeValue = nextNode.nodeValue;
  1736. }
  1737. return true;
  1738. }
  1739. if (currentNode.nodeType !== Node.ELEMENT_NODE) {
  1740. return currentNode.nodeValue === nextNode.nodeValue;
  1741. }
  1742. if (currentNode.nodeName !== nextNode.nodeName) return false;
  1743. const currentEl = currentNode;
  1744. const nextEl = nextNode;
  1745. if ((currentEl.id || nextEl.id) && currentEl.id !== nextEl.id) return false;
  1746. if (
  1747. options &&
  1748. options.reusePreviewBlocks &&
  1749. currentEl.dataset &&
  1750. nextEl.dataset &&
  1751. currentEl.dataset.previewBlockHash &&
  1752. currentEl.dataset.previewBlockHash === nextEl.dataset.previewBlockHash
  1753. ) {
  1754. return true;
  1755. }
  1756. if (currentEl.outerHTML === nextEl.outerHTML) return true;
  1757. if (currentEl.tagName === 'DETAILS' && nextEl.tagName === 'DETAILS' && currentEl.hasAttribute('open')) {
  1758. nextEl.setAttribute('open', '');
  1759. }
  1760. return false;
  1761. }
  1762. function patchPreviewDom(container, html, options) {
  1763. const result = {
  1764. fullReplace: false,
  1765. updatedNodes: [],
  1766. };
  1767. if (!previewHasCommittedRender || previewContainsSkeleton()) {
  1768. container.innerHTML = html;
  1769. result.fullReplace = true;
  1770. result.updatedNodes = [container];
  1771. return result;
  1772. }
  1773. const template = document.createElement('template');
  1774. template.innerHTML = html;
  1775. const nextNodes = Array.from(template.content.childNodes);
  1776. const currentNodeCount = container.childNodes.length;
  1777. if (nextNodes.length > 6000 || currentNodeCount > 6000) {
  1778. container.replaceChildren(...nextNodes);
  1779. result.fullReplace = true;
  1780. result.updatedNodes = [container];
  1781. return result;
  1782. }
  1783. let index = 0;
  1784. while (index < nextNodes.length || index < container.childNodes.length) {
  1785. const currentNode = container.childNodes[index];
  1786. const nextNode = nextNodes[index];
  1787. if (!nextNode) {
  1788. currentNode.remove();
  1789. continue;
  1790. }
  1791. if (!currentNode) {
  1792. container.appendChild(nextNode);
  1793. result.updatedNodes.push(nextNode);
  1794. index += 1;
  1795. continue;
  1796. }
  1797. if (canReusePreviewNode(currentNode, nextNode, options)) {
  1798. index += 1;
  1799. continue;
  1800. }
  1801. result.updatedNodes.push(nextNode);
  1802. currentNode.replaceWith(nextNode);
  1803. index += 1;
  1804. }
  1805. return result;
  1806. }
  1807. function commitPreviewHtml(sanitizedHtml, referenceData, rawVal, context) {
  1808. const shouldRestoreScroll = previewHasCommittedRender && !previewContainsSkeleton();
  1809. const scrollSnapshot = shouldRestoreScroll ? capturePreviewScroll() : null;
  1810. const patchResult = patchPreviewDom(markdownPreview, sanitizedHtml, {
  1811. reusePreviewBlocks: context.previewEngineMode === 'segmented' && !context.force,
  1812. });
  1813. applyReferencePreviewLinks(markdownPreview, referenceData.definitions);
  1814. enhanceGitHubAlerts(markdownPreview);
  1815. _lastRenderedContent = rawVal;
  1816. previewHasCommittedRender = true;
  1817. previewLastRenderedTabId = context.previewDocumentId;
  1818. markdownPreview.removeAttribute('aria-busy');
  1819. markdownPreview.dataset.renderState = 'ready';
  1820. restorePreviewScroll(scrollSnapshot);
  1821. return patchResult;
  1822. }
  1823. function getPreviewPostProcessRoots(patchResult) {
  1824. if (!patchResult || patchResult.fullReplace || !patchResult.updatedNodes || patchResult.updatedNodes.length === 0) {
  1825. return [markdownPreview];
  1826. }
  1827. const roots = [];
  1828. const seen = new Set();
  1829. patchResult.updatedNodes.forEach(function(node) {
  1830. const root = node && node.nodeType === Node.ELEMENT_NODE ? node : (node && node.parentElement);
  1831. if (root && !seen.has(root)) {
  1832. seen.add(root);
  1833. roots.push(root);
  1834. }
  1835. });
  1836. return roots.length ? roots : [markdownPreview];
  1837. }
  1838. function queryPreviewRoots(roots, selector) {
  1839. const matches = [];
  1840. const seen = new Set();
  1841. roots.forEach(function(root) {
  1842. if (!root || root.nodeType !== Node.ELEMENT_NODE) return;
  1843. if (root.matches && root.matches(selector) && !seen.has(root)) {
  1844. seen.add(root);
  1845. matches.push(root);
  1846. }
  1847. root.querySelectorAll(selector).forEach(function(node) {
  1848. if (!seen.has(node)) {
  1849. seen.add(node);
  1850. matches.push(node);
  1851. }
  1852. });
  1853. });
  1854. return matches;
  1855. }
  1856. function markPreviewRootsReady(roots) {
  1857. queryPreviewRoots(roots, '.mermaid-container.is-loading').forEach(function(container) {
  1858. container.classList.remove('is-loading');
  1859. });
  1860. }
  1861. function postProcessPreview(rawVal, context, patchResult) {
  1862. const roots = getPreviewPostProcessRoots(patchResult);
  1863. roots.forEach(function(root) {
  1864. processEmojis(root);
  1865. });
  1866. queryPreviewRoots(roots, 'input[type="checkbox"]').forEach(function(input) {
  1867. if (!input.hasAttribute('aria-label')) {
  1868. const parentText = input.parentElement ? input.parentElement.textContent.trim() : '';
  1869. input.setAttribute('aria-label', parentText || 'Task item');
  1870. }
  1871. });
  1872. try {
  1873. const mermaidNodes = queryPreviewRoots(roots, '.mermaid');
  1874. if (mermaidNodes.length > 0) {
  1875. const renderMermaidNodes = function() {
  1876. if (context.renderId !== previewRenderGeneration) return;
  1877. initMermaid(false);
  1878. Promise.resolve(mermaid.init(undefined, mermaidNodes))
  1879. .then(() => {
  1880. if (context.renderId !== previewRenderGeneration) return;
  1881. markPreviewRootsReady(roots);
  1882. addMermaidToolbars();
  1883. })
  1884. .catch((e) => {
  1885. if (context.renderId !== previewRenderGeneration) return;
  1886. console.warn("Mermaid rendering failed:", e);
  1887. markPreviewRootsReady(roots);
  1888. addMermaidToolbars();
  1889. });
  1890. };
  1891. if (typeof mermaid === 'undefined') {
  1892. loadScript(CDN.mermaid).then(function() {
  1893. if (context.renderId !== previewRenderGeneration) return;
  1894. initMermaid(true);
  1895. renderMermaidNodes();
  1896. }).catch(function(e) { console.warn('Failed to load mermaid:', e); });
  1897. } else {
  1898. renderMermaidNodes();
  1899. }
  1900. }
  1901. } catch (e) {
  1902. console.warn("Mermaid rendering failed:", e);
  1903. }
  1904. const hasMath = /\$\$|\$[^$]|\\\(|\\\[/.test(rawVal || '');
  1905. if (hasMath) {
  1906. const typesetTargets = roots.filter(function(root) {
  1907. return root && root.nodeType === Node.ELEMENT_NODE && /\$\$|\$[^$]|\\\(|\\\[/.test(root.textContent || '');
  1908. });
  1909. const mathTargets = typesetTargets.length ? typesetTargets : roots;
  1910. if (window.MathJax) {
  1911. try {
  1912. MathJax.typesetPromise(mathTargets).then(function() {
  1913. if (context.renderId !== previewRenderGeneration) return;
  1914. queryPreviewRoots(mathTargets, 'mjx-container[tabindex="0"]').forEach(function(mjx) {
  1915. mjx.removeAttribute('tabindex');
  1916. });
  1917. }).catch(function(err) {
  1918. console.warn('MathJax typesetting failed:', err);
  1919. });
  1920. } catch (e) {
  1921. console.warn("MathJax rendering failed:", e);
  1922. }
  1923. } else {
  1924. window.MathJax = {
  1925. loader: { load: ['[tex]/ams', '[tex]/boldsymbol'] },
  1926. options: {
  1927. a11y: { inTabOrder: false }
  1928. },
  1929. tex: {
  1930. inlineMath: [['$', '$'], ['\\(', '\\)']],
  1931. displayMath: [['$$', '$$'], ['\\[', '\\]']],
  1932. processEscapes: true,
  1933. packages: { '[+]': ['ams', 'boldsymbol'] }
  1934. }
  1935. };
  1936. loadScript(CDN.mathjax).then(function() {
  1937. if (context.renderId !== previewRenderGeneration) return;
  1938. try {
  1939. MathJax.typesetPromise(mathTargets).then(function() {
  1940. if (context.renderId !== previewRenderGeneration) return;
  1941. queryPreviewRoots(mathTargets, 'mjx-container[tabindex="0"]').forEach(function(mjx) {
  1942. mjx.removeAttribute('tabindex');
  1943. });
  1944. }).catch(function(err) {
  1945. console.warn('MathJax typesetting failed:', err);
  1946. });
  1947. } catch (e) {
  1948. console.warn('MathJax rendering failed:', e);
  1949. }
  1950. }).catch(function(e) { console.warn('Failed to load MathJax:', e); });
  1951. }
  1952. }
  1953. updateDocumentStats();
  1954. updateFindHighlights();
  1955. cleanupImageObjectUrls();
  1956. scheduleLineNumberUpdate();
  1957. }
  1958. function executeMainThreadRender(rawVal, context) {
  1959. const { frontmatter, body } = parseFrontmatter(rawVal);
  1960. const tableHtml = frontmatter ? renderFrontmatterTable(frontmatter) : '';
  1961. const referenceData = extractReferenceDefinitions(body);
  1962. const html = tableHtml + marked.parse(referenceData.cleanedMarkdown);
  1963. const sanitizedHtml = sanitizePreviewHtml(html);
  1964. if (context.renderId !== previewRenderGeneration || markdownEditor.value !== rawVal) return;
  1965. previewSegmentHtmlCache.clear();
  1966. const patchResult = commitPreviewHtml(sanitizedHtml, referenceData, rawVal, context);
  1967. postProcessPreview(rawVal, context, patchResult);
  1968. }
  1969. function executeWorkerRender(rawVal, context) {
  1970. requestPreviewWorkerRender(rawVal, context)
  1971. .then(function(result) {
  1972. if (context.renderId !== previewRenderGeneration || markdownEditor.value !== rawVal) return;
  1973. if (!result || result.mode !== 'segmented' || !Array.isArray(result.blocks) || result.blocks.length < PREVIEW_SEGMENT_MIN_BLOCKS) {
  1974. executeMainThreadRender(rawVal, Object.assign({}, context, { disableWorker: true }));
  1975. return;
  1976. }
  1977. const segmentedHtml = buildSegmentedPreviewHtml(result.blocks, context.previewDocumentId);
  1978. if (context.renderId !== previewRenderGeneration || markdownEditor.value !== rawVal) return;
  1979. const patchResult = commitPreviewHtml(segmentedHtml, { definitions: new Map() }, rawVal, Object.assign({}, context, {
  1980. previewEngineMode: 'segmented',
  1981. }));
  1982. postProcessPreview(rawVal, context, patchResult);
  1983. })
  1984. .catch(function(error) {
  1985. if (context.renderId !== previewRenderGeneration || markdownEditor.value !== rawVal) return;
  1986. console.warn('Preview worker unavailable; falling back to main-thread renderer:', error);
  1987. executeMainThreadRender(rawVal, Object.assign({}, context, { disableWorker: true }));
  1988. });
  1989. }
  1990. function renderMarkdown(options) {
  1991. options = options || {};
  1992. const rawVal = markdownEditor.value;
  1993. const force = options.force === true;
  1994. const previewDocumentId = getActivePreviewDocumentId();
  1995. const hasCurrentPreview =
  1996. previewHasCommittedRender &&
  1997. previewLastRenderedTabId === previewDocumentId &&
  1998. _lastRenderedContent === rawVal &&
  1999. !previewContainsSkeleton();
  2000. if (hasCurrentPreview && !force) return;
  2001. clearPendingPreviewWork();
  2002. const renderId = ++previewRenderGeneration;
  2003. const isLargeDocument = rawVal.length >= LARGE_DOCUMENT_THRESHOLD;
  2004. const isDocumentSwap = previewHasCommittedRender && previewLastRenderedTabId !== previewDocumentId;
  2005. const needsInitialPreview = !previewHasCommittedRender || previewContainsSkeleton();
  2006. const shouldShowSkeleton =
  2007. isLargeDocument &&
  2008. (options.showSkeleton === true || needsInitialPreview || isDocumentSwap);
  2009. if (shouldShowSkeleton) {
  2010. showPreviewSkeleton();
  2011. } else if (markdownPreview) {
  2012. markdownPreview.setAttribute('aria-busy', 'true');
  2013. markdownPreview.dataset.renderState = 'refreshing';
  2014. }
  2015. const runRender = function() {
  2016. pendingPreviewRenderCancel = null;
  2017. if (renderId !== previewRenderGeneration || markdownEditor.value !== rawVal) return;
  2018. executeRender(rawVal, {
  2019. force,
  2020. renderId,
  2021. previewDocumentId,
  2022. reason: options.reason || 'direct',
  2023. });
  2024. };
  2025. if (isLargeDocument) {
  2026. pendingPreviewRenderCancel = deferPreviewWork(runRender, rawVal.length);
  2027. } else {
  2028. runRender();
  2029. }
  2030. }
  2031. function executeRender(rawVal, context) {
  2032. context = context || {};
  2033. // PERF-003: Skip render if content hasn't changed
  2034. if (
  2035. !context.force &&
  2036. rawVal === _lastRenderedContent &&
  2037. previewLastRenderedTabId === context.previewDocumentId &&
  2038. previewHasCommittedRender &&
  2039. !previewContainsSkeleton()
  2040. ) {
  2041. markdownPreview.removeAttribute('aria-busy');
  2042. markdownPreview.dataset.renderState = 'ready';
  2043. return;
  2044. }
  2045. try {
  2046. if (shouldUsePreviewWorker(rawVal, context)) {
  2047. executeWorkerRender(rawVal, context);
  2048. } else {
  2049. executeMainThreadRender(rawVal, context);
  2050. }
  2051. } catch (e) {
  2052. console.error("Markdown rendering failed:", e);
  2053. const safeMessage = escapeHtml(e && e.message ? e.message : 'Unknown error');
  2054. const safeMarkdown = escapeHtml(rawVal);
  2055. markdownPreview.removeAttribute('aria-busy');
  2056. markdownPreview.dataset.renderState = 'error';
  2057. if (!previewHasCommittedRender || previewContainsSkeleton()) {
  2058. markdownPreview.innerHTML = `<div class="alert alert-danger">
  2059. <strong>Error rendering markdown:</strong> ${safeMessage}
  2060. </div>
  2061. <pre>${safeMarkdown}</pre>`;
  2062. }
  2063. }
  2064. }
  2065. function importMarkdownFile(file) {
  2066. if (file.size > 10 * 1024 * 1024) {
  2067. alert('File is too large (maximum 10MB supported).');
  2068. return;
  2069. }
  2070. const reader = new FileReader();
  2071. reader.onload = function(e) {
  2072. const text = e.target.result || '';
  2073. // Simple binary check: look for null bytes in the first 8KB
  2074. const checkLength = Math.min(text.length, 8000);
  2075. for (let i = 0; i < checkLength; i++) {
  2076. if (text.charCodeAt(i) === 0) {
  2077. alert('Cannot import: The selected file appears to be a binary file.');
  2078. return;
  2079. }
  2080. }
  2081. newTab(text, file.name.replace(/\.md$/i, ''));
  2082. };
  2083. reader.onerror = function() {
  2084. alert('Failed to read the file. Please check permissions and try again.');
  2085. };
  2086. reader.readAsText(file);
  2087. }
  2088. function isMarkdownPath(path) {
  2089. return /\.(md|markdown)$/i.test(path || "");
  2090. }
  2091. const MAX_GITHUB_FILES_SHOWN = 30;
  2092. const GITHUB_IMPORT_MIN_REQUEST_INTERVAL_MS = 800;
  2093. let lastGitHubImportRequestAt = 0;
  2094. const selectedGitHubImportPaths = new Set();
  2095. let availableGitHubImportPaths = [];
  2096. function getFileName(path) {
  2097. return (path || "").split("/").pop() || "document.md";
  2098. }
  2099. function buildRawGitHubUrl(owner, repo, ref, filePath) {
  2100. const encodedPath = filePath
  2101. .split("/")
  2102. .map((part) => encodeURIComponent(part))
  2103. .join("/");
  2104. return `https://raw.githubusercontent.com/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${encodeURIComponent(ref)}/${encodedPath}`;
  2105. }
  2106. async function fetchGitHubJson(url) {
  2107. const now = Date.now();
  2108. const waitTime = GITHUB_IMPORT_MIN_REQUEST_INTERVAL_MS - (now - lastGitHubImportRequestAt);
  2109. if (waitTime > 0) {
  2110. await new Promise((resolve) => setTimeout(resolve, waitTime));
  2111. }
  2112. lastGitHubImportRequestAt = Date.now();
  2113. const response = await fetch(url, {
  2114. headers: {
  2115. Accept: "application/vnd.github+json"
  2116. }
  2117. });
  2118. if (!response.ok) {
  2119. throw new Error(`GitHub API request failed (${response.status})`);
  2120. }
  2121. return response.json();
  2122. }
  2123. async function fetchTextContent(url) {
  2124. const response = await fetch(url);
  2125. if (!response.ok) {
  2126. throw new Error(`Failed to fetch file (${response.status})`);
  2127. }
  2128. return response.text();
  2129. }
  2130. function parseGitHubImportUrl(input) {
  2131. let parsedUrl;
  2132. try {
  2133. parsedUrl = new URL((input || "").trim());
  2134. } catch (_) {
  2135. return null;
  2136. }
  2137. const host = parsedUrl.hostname.replace(/^www\./, "");
  2138. const segments = parsedUrl.pathname.split("/").filter(Boolean);
  2139. if (host === "raw.githubusercontent.com") {
  2140. if (segments.length < 4) return null;
  2141. const [owner, repo, ref, ...rest] = segments;
  2142. const filePath = rest.join("/");
  2143. return { owner, repo, ref, type: "file", filePath };
  2144. }
  2145. if (host !== "github.com" || segments.length < 2) return null;
  2146. const owner = segments[0];
  2147. const repo = segments[1].replace(/\.git$/i, "");
  2148. if (segments.length === 2) {
  2149. return { owner, repo, type: "repo" };
  2150. }
  2151. const mode = segments[2];
  2152. if (mode === "blob" && segments.length >= 5) {
  2153. return {
  2154. owner,
  2155. repo,
  2156. type: "file",
  2157. ref: segments[3],
  2158. filePath: segments.slice(4).join("/")
  2159. };
  2160. }
  2161. if (mode === "tree" && segments.length >= 4) {
  2162. return {
  2163. owner,
  2164. repo,
  2165. type: "tree",
  2166. ref: segments[3],
  2167. basePath: segments.slice(4).join("/")
  2168. };
  2169. }
  2170. return { owner, repo, type: "repo" };
  2171. }
  2172. async function getDefaultBranch(owner, repo) {
  2173. const repoInfo = await fetchGitHubJson(`https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`);
  2174. return repoInfo.default_branch;
  2175. }
  2176. async function listMarkdownFiles(owner, repo, ref, basePath) {
  2177. const treeResponse = await fetchGitHubJson(`https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/git/trees/${encodeURIComponent(ref)}?recursive=1`);
  2178. const normalizedBasePath = (basePath || "").replace(/^\/+|\/+$/g, "");
  2179. return (treeResponse.tree || [])
  2180. .filter((entry) => entry.type === "blob" && isMarkdownPath(entry.path))
  2181. .filter((entry) => !normalizedBasePath || entry.path === normalizedBasePath || entry.path.startsWith(normalizedBasePath + "/"))
  2182. .map((entry) => entry.path)
  2183. .sort((a, b) => a.localeCompare(b));
  2184. }
  2185. function buildMarkdownFileTree(paths) {
  2186. const root = { folders: {}, files: [] };
  2187. (paths || []).forEach((path) => {
  2188. const segments = (path || "").split("/").filter(Boolean);
  2189. if (!segments.length) return;
  2190. const fileName = segments.pop();
  2191. let node = root;
  2192. segments.forEach((segment) => {
  2193. if (!node.folders[segment]) {
  2194. node.folders[segment] = { folders: {}, files: [] };
  2195. }
  2196. node = node.folders[segment];
  2197. });
  2198. node.files.push({ name: fileName, path });
  2199. });
  2200. return root;
  2201. }
  2202. function updateGitHubImportSelectedCount() {
  2203. if (!githubImportSelectedCount) return;
  2204. const count = selectedGitHubImportPaths.size;
  2205. githubImportSelectedCount.textContent = `${count} selected`;
  2206. }
  2207. function updateGitHubSelectAllButtonLabel() {
  2208. if (!githubImportSelectAllBtn) return;
  2209. const total = availableGitHubImportPaths.length;
  2210. const allSelected = total > 0 && selectedGitHubImportPaths.size === total;
  2211. githubImportSelectAllBtn.textContent = allSelected ? "Clear All" : "Select All";
  2212. }
  2213. function syncGitHubSelectionToButtons() {
  2214. if (!githubImportTree) return;
  2215. Array.from(githubImportTree.querySelectorAll(".github-tree-file-btn")).forEach((btn) => {
  2216. const isSelected = selectedGitHubImportPaths.has(btn.dataset.path);
  2217. btn.classList.toggle("is-selected", isSelected);
  2218. btn.setAttribute("aria-pressed", isSelected ? "true" : "false");
  2219. });
  2220. }
  2221. function setGitHubSelectedPaths(paths) {
  2222. selectedGitHubImportPaths.clear();
  2223. (paths || []).forEach((path) => selectedGitHubImportPaths.add(path));
  2224. updateGitHubImportSelectedCount();
  2225. syncGitHubSelectionToButtons();
  2226. updateGitHubSelectAllButtonLabel();
  2227. }
  2228. function toggleGitHubSelectedPath(path) {
  2229. if (!path) return;
  2230. if (selectedGitHubImportPaths.has(path)) {
  2231. selectedGitHubImportPaths.delete(path);
  2232. } else {
  2233. selectedGitHubImportPaths.add(path);
  2234. }
  2235. updateGitHubImportSelectedCount();
  2236. syncGitHubSelectionToButtons();
  2237. updateGitHubSelectAllButtonLabel();
  2238. }
  2239. function renderGitHubImportTree(paths) {
  2240. if (!githubImportTree || !githubImportFileSelect) return;
  2241. githubImportTree.innerHTML = "";
  2242. const tree = buildMarkdownFileTree(paths);
  2243. const createTreeBranch = function(node, parentPath) {
  2244. const list = document.createElement("ul");
  2245. const folderNames = Object.keys(node.folders).sort((a, b) => a.localeCompare(b));
  2246. folderNames.forEach((folderName) => {
  2247. const folderPath = parentPath ? `${parentPath}/${folderName}` : folderName;
  2248. const item = document.createElement("li");
  2249. const folderLabel = document.createElement("span");
  2250. folderLabel.className = "github-tree-folder-label";
  2251. folderLabel.textContent = `📁 ${folderName}`;
  2252. item.appendChild(folderLabel);
  2253. item.appendChild(createTreeBranch(node.folders[folderName], folderPath));
  2254. list.appendChild(item);
  2255. });
  2256. node.files
  2257. .sort((a, b) => a.path.localeCompare(b.path))
  2258. .forEach((file) => {
  2259. const fileItem = document.createElement("li");
  2260. const fileButton = document.createElement("button");
  2261. fileButton.type = "button";
  2262. fileButton.className = "github-tree-file-btn";
  2263. fileButton.dataset.path = file.path;
  2264. fileButton.setAttribute("aria-pressed", "false");
  2265. fileButton.textContent = `📄 ${file.name}`;
  2266. fileButton.addEventListener("click", function() {
  2267. toggleGitHubSelectedPath(file.path);
  2268. });
  2269. fileItem.appendChild(fileButton);
  2270. list.appendChild(fileItem);
  2271. });
  2272. return list;
  2273. };
  2274. githubImportTree.appendChild(createTreeBranch(tree, ""));
  2275. syncGitHubSelectionToButtons();
  2276. }
  2277. function setGitHubImportLoading(isLoading) {
  2278. if (!githubImportSubmitBtn) return;
  2279. if (isLoading) {
  2280. githubImportSubmitBtn.dataset.loadingText = githubImportSubmitBtn.textContent;
  2281. githubImportSubmitBtn.textContent = "Importing...";
  2282. } else if (githubImportSubmitBtn.dataset.loadingText) {
  2283. githubImportSubmitBtn.textContent = githubImportSubmitBtn.dataset.loadingText;
  2284. delete githubImportSubmitBtn.dataset.loadingText;
  2285. }
  2286. }
  2287. function setGitHubImportMessage(message, options = {}) {
  2288. if (!githubImportError) return;
  2289. const { isError = true } = options;
  2290. githubImportError.classList.toggle("is-info", !isError);
  2291. if (!message) {
  2292. githubImportError.textContent = "";
  2293. githubImportError.style.display = "none";
  2294. return;
  2295. }
  2296. githubImportError.textContent = message;
  2297. githubImportError.style.display = "block";
  2298. }
  2299. function resetGitHubImportModal() {
  2300. if (!githubImportUrlInput || !githubImportFileSelect || !githubImportSubmitBtn) return;
  2301. if (githubImportTitle) {
  2302. githubImportTitle.textContent = "Import Markdown from GitHub";
  2303. }
  2304. githubImportUrlInput.value = "";
  2305. githubImportUrlInput.style.display = "block";
  2306. githubImportUrlInput.disabled = false;
  2307. githubImportFileSelect.innerHTML = "";
  2308. githubImportFileSelect.style.display = "none";
  2309. githubImportFileSelect.disabled = false;
  2310. if (githubImportSelectionToolbar) {
  2311. githubImportSelectionToolbar.style.display = "none";
  2312. }
  2313. availableGitHubImportPaths = [];
  2314. setGitHubSelectedPaths([]);
  2315. if (githubImportTree) {
  2316. githubImportTree.innerHTML = "";
  2317. githubImportTree.style.display = "none";
  2318. }
  2319. githubImportSubmitBtn.dataset.step = "url";
  2320. delete githubImportSubmitBtn.dataset.owner;
  2321. delete githubImportSubmitBtn.dataset.repo;
  2322. delete githubImportSubmitBtn.dataset.ref;
  2323. githubImportSubmitBtn.textContent = "Import";
  2324. setGitHubImportMessage("");
  2325. }
  2326. function openGitHubImportModal() {
  2327. if (!githubImportModal || !githubImportUrlInput || !githubImportSubmitBtn) return;
  2328. resetGitHubImportModal();
  2329. openAppModal(githubImportModal, {
  2330. focusTarget: githubImportUrlInput,
  2331. onClose: closeGitHubImportModal
  2332. });
  2333. }
  2334. function closeGitHubImportModal() {
  2335. if (!githubImportModal) return;
  2336. closeAppModal(githubImportModal);
  2337. resetGitHubImportModal();
  2338. }
  2339. async function handleGitHubImportSubmit() {
  2340. if (!githubImportSubmitBtn || !githubImportUrlInput || !githubImportFileSelect) return;
  2341. const setGitHubImportDialogDisabled = (disabled) => {
  2342. githubImportSubmitBtn.disabled = disabled;
  2343. if (githubImportCancelBtn) {
  2344. githubImportCancelBtn.disabled = disabled;
  2345. }
  2346. if (githubImportSelectAllBtn) {
  2347. githubImportSelectAllBtn.disabled = disabled;
  2348. }
  2349. };
  2350. const step = githubImportSubmitBtn.dataset.step || "url";
  2351. if (step === "select") {
  2352. const selectedPaths = Array.from(selectedGitHubImportPaths);
  2353. const owner = githubImportSubmitBtn.dataset.owner;
  2354. const repo = githubImportSubmitBtn.dataset.repo;
  2355. const ref = githubImportSubmitBtn.dataset.ref;
  2356. if (!owner || !repo || !ref || !selectedPaths.length) {
  2357. setGitHubImportMessage("Please select at least one file to import.");
  2358. return;
  2359. }
  2360. setGitHubImportLoading(true);
  2361. setGitHubImportDialogDisabled(true);
  2362. announceToScreenReader("Importing selected files from GitHub...");
  2363. try {
  2364. for (const selectedPath of selectedPaths) {
  2365. const markdown = await fetchTextContent(buildRawGitHubUrl(owner, repo, ref, selectedPath));
  2366. newTab(markdown, getFileName(selectedPath).replace(/\.(md|markdown)$/i, ""));
  2367. }
  2368. closeGitHubImportModal();
  2369. announceToScreenReader("Files imported successfully.");
  2370. } catch (error) {
  2371. console.error("GitHub import failed:", error);
  2372. setGitHubImportMessage("GitHub import failed: " + error.message);
  2373. announceToScreenReader("GitHub import failed.");
  2374. } finally {
  2375. setGitHubImportDialogDisabled(false);
  2376. setGitHubImportLoading(false);
  2377. }
  2378. return;
  2379. }
  2380. const urlInput = githubImportUrlInput.value.trim();
  2381. if (!urlInput) {
  2382. setGitHubImportMessage("Please enter a GitHub URL.");
  2383. return;
  2384. }
  2385. const parsed = parseGitHubImportUrl(urlInput);
  2386. if (!parsed || !parsed.owner || !parsed.repo) {
  2387. setGitHubImportMessage("Please enter a valid GitHub URL.");
  2388. return;
  2389. }
  2390. setGitHubImportMessage("");
  2391. setGitHubImportLoading(true);
  2392. setGitHubImportDialogDisabled(true);
  2393. try {
  2394. if (parsed.type === "file") {
  2395. if (!isMarkdownPath(parsed.filePath)) {
  2396. throw new Error("The provided URL does not point to a Markdown file.");
  2397. }
  2398. announceToScreenReader("Fetching file from GitHub...");
  2399. const markdown = await fetchTextContent(buildRawGitHubUrl(parsed.owner, parsed.repo, parsed.ref, parsed.filePath));
  2400. newTab(markdown, getFileName(parsed.filePath).replace(/\.(md|markdown)$/i, ""));
  2401. closeGitHubImportModal();
  2402. announceToScreenReader("File imported successfully.");
  2403. return;
  2404. }
  2405. // Accessibility dynamic live announcer
  2406. const fetchingText = I18N_DICTS[activeLang].loadingFiles || "Fetching file tree...";
  2407. announceToScreenReader(fetchingText);
  2408. // Render hierarchical visual skeleton tree while the list is loading
  2409. if (githubImportTree) {
  2410. renderGitHubImportTreeSkeleton();
  2411. githubImportTree.style.display = "block";
  2412. }
  2413. const ref = parsed.ref || await getDefaultBranch(parsed.owner, parsed.repo);
  2414. const files = await listMarkdownFiles(parsed.owner, parsed.repo, ref, parsed.basePath || "");
  2415. if (!files.length) {
  2416. if (githubImportTree) {
  2417. githubImportTree.innerHTML = "";
  2418. githubImportTree.style.display = "none";
  2419. }
  2420. setGitHubImportMessage("No Markdown files were found at that GitHub location.");
  2421. announceToScreenReader("Failed to locate Markdown files.");
  2422. return;
  2423. }
  2424. const shownFiles = files.slice(0, MAX_GITHUB_FILES_SHOWN);
  2425. if (files.length === 1) {
  2426. const targetPath = files[0];
  2427. announceToScreenReader("Fetching file content...");
  2428. const markdown = await fetchTextContent(buildRawGitHubUrl(parsed.owner, parsed.repo, ref, targetPath));
  2429. newTab(markdown, getFileName(targetPath).replace(/\.(md|markdown)$/i, ""));
  2430. closeGitHubImportModal();
  2431. announceToScreenReader("File imported successfully.");
  2432. return;
  2433. }
  2434. githubImportFileSelect.innerHTML = "";
  2435. githubImportUrlInput.style.display = "none";
  2436. githubImportFileSelect.style.display = "none";
  2437. if (githubImportSelectionToolbar) {
  2438. githubImportSelectionToolbar.style.display = "flex";
  2439. }
  2440. if (githubImportTree) {
  2441. githubImportTree.style.display = "block";
  2442. }
  2443. shownFiles.forEach((filePath) => {
  2444. const option = document.createElement("option");
  2445. option.value = filePath;
  2446. option.textContent = filePath;
  2447. githubImportFileSelect.appendChild(option);
  2448. });
  2449. availableGitHubImportPaths = shownFiles.slice();
  2450. setGitHubSelectedPaths(shownFiles[0] ? [shownFiles[0]] : []);
  2451. renderGitHubImportTree(shownFiles);
  2452. // Announce load complete
  2453. announceToScreenReader("GitHub files loaded. " + files.length + " files available in the tree.");
  2454. if (files.length > MAX_GITHUB_FILES_SHOWN) {
  2455. setGitHubImportMessage(`Showing first ${MAX_GITHUB_FILES_SHOWN} of ${files.length} Markdown files.`, { isError: false });
  2456. } else {
  2457. setGitHubImportMessage("");
  2458. }
  2459. if (githubImportTitle) {
  2460. githubImportTitle.textContent = "Select Markdown file(s) to import";
  2461. }
  2462. githubImportSubmitBtn.dataset.step = "select";
  2463. githubImportSubmitBtn.dataset.owner = parsed.owner;
  2464. githubImportSubmitBtn.dataset.repo = parsed.repo;
  2465. githubImportSubmitBtn.dataset.ref = ref;
  2466. githubImportSubmitBtn.textContent = "Import Selected";
  2467. } catch (error) {
  2468. console.error("GitHub import failed:", error);
  2469. setGitHubImportMessage("GitHub import failed: " + error.message);
  2470. announceToScreenReader("GitHub import failed.");
  2471. if (githubImportTree) {
  2472. githubImportTree.innerHTML = "";
  2473. githubImportTree.style.display = "none";
  2474. }
  2475. } finally {
  2476. setGitHubImportDialogDisabled(false);
  2477. setGitHubImportLoading(false);
  2478. }
  2479. }
  2480. function scheduleEmojiLookupRefresh() {
  2481. if (emojiLookupLoaded || emojiRenderScheduled) return;
  2482. emojiRenderScheduled = true;
  2483. loadEmojiEntries()
  2484. .then(() => {
  2485. if (emojiUrlMap.size) {
  2486. renderMarkdown({ force: true, reason: 'emoji-refresh' });
  2487. }
  2488. })
  2489. .finally(() => {
  2490. emojiRenderScheduled = false;
  2491. });
  2492. }
  2493. function processEmojis(element) {
  2494. // Early exit if the raw text content has no colon characters (PERF-013)
  2495. // This avoids the expensive TreeWalker DOM walk for documents without emoji shortcodes
  2496. if (!element.textContent || !element.textContent.includes(':')) return;
  2497. // PERF-002: Lazy-load JoyPixels on first use
  2498. if (typeof joypixels === 'undefined') {
  2499. Promise.all([
  2500. loadScript(CDN.joypixels),
  2501. loadStyle(CDN.joypixels_css)
  2502. ]).then(function() { processEmojis(element); });
  2503. return;
  2504. }
  2505. const walker = document.createTreeWalker(
  2506. element,
  2507. NodeFilter.SHOW_TEXT,
  2508. null,
  2509. false
  2510. );
  2511. const textNodes = [];
  2512. let node;
  2513. while ((node = walker.nextNode())) {
  2514. let parent = node.parentNode;
  2515. let isInCode = false;
  2516. while (parent && parent !== element) {
  2517. if (parent.tagName === 'PRE' || parent.tagName === 'CODE') {
  2518. isInCode = true;
  2519. break;
  2520. }
  2521. parent = parent.parentNode;
  2522. }
  2523. if (!isInCode && node.nodeValue.includes(':')) {
  2524. textNodes.push(node);
  2525. }
  2526. }
  2527. let needsEmojiLookup = false;
  2528. textNodes.forEach(textNode => {
  2529. const text = textNode.nodeValue;
  2530. const emojiRegex = /:([\w+-]+):/g;
  2531. let match;
  2532. let lastIndex = 0;
  2533. let hasEmoji = false;
  2534. const fragment = document.createDocumentFragment();
  2535. while ((match = emojiRegex.exec(text)) !== null) {
  2536. const shortcode = match[1];
  2537. const emoji = joypixels.shortnameToUnicode(`:${shortcode}:`);
  2538. if (emoji !== `:${shortcode}:`) { // If conversion was successful
  2539. hasEmoji = true;
  2540. if (match.index > lastIndex) {
  2541. fragment.appendChild(document.createTextNode(text.substring(lastIndex, match.index)));
  2542. }
  2543. fragment.appendChild(document.createTextNode(emoji));
  2544. lastIndex = emojiRegex.lastIndex;
  2545. } else {
  2546. const emojiUrl = emojiUrlMap.get(shortcode);
  2547. if (emojiUrl) {
  2548. hasEmoji = true;
  2549. if (match.index > lastIndex) {
  2550. fragment.appendChild(document.createTextNode(text.substring(lastIndex, match.index)));
  2551. }
  2552. const image = document.createElement('img');
  2553. image.className = 'emoji-inline';
  2554. image.src = emojiUrl;
  2555. image.alt = `:${shortcode}:`;
  2556. image.loading = 'lazy';
  2557. image.setAttribute('aria-label', `:${shortcode}:`);
  2558. fragment.appendChild(image);
  2559. lastIndex = emojiRegex.lastIndex;
  2560. } else if (!emojiLookupLoaded) {
  2561. needsEmojiLookup = true;
  2562. }
  2563. }
  2564. }
  2565. if (hasEmoji) {
  2566. if (lastIndex < text.length) {
  2567. fragment.appendChild(document.createTextNode(text.substring(lastIndex)));
  2568. }
  2569. textNode.parentNode.replaceChild(fragment, textNode);
  2570. }
  2571. });
  2572. if (needsEmojiLookup) {
  2573. scheduleEmojiLookupRefresh();
  2574. }
  2575. }
  2576. function debouncedRender() {
  2577. clearTimeout(markdownRenderTimeout);
  2578. const delay = getPreviewRenderDelay(markdownEditor.value);
  2579. markdownRenderTimeout = setTimeout(function() {
  2580. renderMarkdown({ reason: 'edit' });
  2581. }, delay);
  2582. }
  2583. function countWordsFast(text) {
  2584. let count = 0;
  2585. let inWord = false;
  2586. for (let i = 0; i < text.length; i += 1) {
  2587. const code = text.charCodeAt(i);
  2588. if (
  2589. code === 32 ||
  2590. code === 9 ||
  2591. code === 10 ||
  2592. code === 13 ||
  2593. code === 12 ||
  2594. code === 11 ||
  2595. code === 160
  2596. ) {
  2597. inWord = false;
  2598. } else if (!inWord) {
  2599. count += 1;
  2600. inWord = true;
  2601. }
  2602. }
  2603. return count;
  2604. }
  2605. function updateDocumentStats() {
  2606. const text = markdownEditor.value;
  2607. const charCount = text.length;
  2608. charCountElement.textContent = charCount.toLocaleString();
  2609. const wordCount = countWordsFast(text);
  2610. wordCountElement.textContent = wordCount.toLocaleString();
  2611. const readingTimeMinutes = Math.ceil(wordCount / 200);
  2612. readingTimeElement.textContent = readingTimeMinutes;
  2613. }
  2614. function syncEditorToPreview() {
  2615. if (!syncScrollingEnabled || isPreviewScrolling || isProgrammaticScrolling) return;
  2616. isEditorScrolling = true;
  2617. if (scrollSyncTimeout) cancelAnimationFrame(scrollSyncTimeout);
  2618. scrollSyncTimeout = requestAnimationFrame(function() {
  2619. const editorScrollRange = markdownEditor.scrollHeight - markdownEditor.clientHeight;
  2620. const editorScrollRatio =
  2621. editorScrollRange > 0 ? markdownEditor.scrollTop / editorScrollRange : 0;
  2622. const previewScrollPosition =
  2623. (previewPane.scrollHeight - previewPane.clientHeight) *
  2624. editorScrollRatio;
  2625. if (!isNaN(previewScrollPosition) && isFinite(previewScrollPosition)) {
  2626. previewPane.scrollTop = previewScrollPosition;
  2627. }
  2628. setTimeout(function() {
  2629. isEditorScrolling = false;
  2630. }, 50);
  2631. });
  2632. }
  2633. function syncPreviewToEditor() {
  2634. if (!syncScrollingEnabled || isEditorScrolling || isProgrammaticScrolling) return;
  2635. isPreviewScrolling = true;
  2636. if (scrollSyncTimeout) cancelAnimationFrame(scrollSyncTimeout);
  2637. scrollSyncTimeout = requestAnimationFrame(function() {
  2638. const previewScrollRange = previewPane.scrollHeight - previewPane.clientHeight;
  2639. const previewScrollRatio =
  2640. previewScrollRange > 0 ? previewPane.scrollTop / previewScrollRange : 0;
  2641. const editorScrollPosition =
  2642. (markdownEditor.scrollHeight - markdownEditor.clientHeight) *
  2643. previewScrollRatio;
  2644. if (!isNaN(editorScrollPosition) && isFinite(editorScrollPosition)) {
  2645. markdownEditor.scrollTop = editorScrollPosition;
  2646. syncEditorScrollOverlays();
  2647. }
  2648. setTimeout(function() {
  2649. isPreviewScrolling = false;
  2650. }, 50);
  2651. });
  2652. }
  2653. function toggleSyncScrolling() {
  2654. syncScrollingEnabled = !syncScrollingEnabled;
  2655. if (syncScrollingEnabled) {
  2656. toggleSyncButton.innerHTML = '<i class="bi bi-link-45deg"></i> <span class="btn-text">Sync Off</span>';
  2657. toggleSyncButton.classList.add("sync-disabled");
  2658. toggleSyncButton.classList.remove("sync-enabled");
  2659. toggleSyncButton.classList.add("sync-active");
  2660. } else {
  2661. toggleSyncButton.innerHTML = '<i class="bi bi-link"></i> <span class="btn-text">Sync On</span>';
  2662. toggleSyncButton.classList.add("sync-enabled");
  2663. toggleSyncButton.classList.remove("sync-disabled");
  2664. toggleSyncButton.classList.remove("sync-active");
  2665. }
  2666. saveGlobalState({ syncScrollingEnabled });
  2667. }
  2668. // View Mode Functions - Story 1.1 & 1.2
  2669. function setViewMode(mode) {
  2670. if (mode === currentViewMode) return;
  2671. const previousMode = currentViewMode;
  2672. currentViewMode = mode;
  2673. // Update content container class
  2674. contentContainer.classList.remove('view-editor-only', 'view-preview-only', 'view-split');
  2675. contentContainer.classList.add('view-' + (mode === 'editor' ? 'editor-only' : mode === 'preview' ? 'preview-only' : 'split'));
  2676. // Update button active states (desktop)
  2677. viewModeButtons.forEach(btn => {
  2678. const btnMode = btn.getAttribute('data-view-mode');
  2679. if (btnMode === mode) {
  2680. btn.classList.add('is-active');
  2681. btn.setAttribute('aria-pressed', 'true');
  2682. } else {
  2683. btn.classList.remove('is-active');
  2684. btn.setAttribute('aria-pressed', 'false');
  2685. }
  2686. });
  2687. // Story 1.4: Update mobile button active states
  2688. mobileViewModeButtons.forEach(btn => {
  2689. const btnMode = btn.getAttribute('data-mode');
  2690. if (btnMode === mode) {
  2691. btn.classList.add('active');
  2692. btn.setAttribute('aria-pressed', 'true');
  2693. } else {
  2694. btn.classList.remove('active');
  2695. btn.setAttribute('aria-pressed', 'false');
  2696. }
  2697. });
  2698. // Story 1.2: Show/hide sync toggle based on view mode
  2699. updateSyncToggleVisibility(mode);
  2700. // Story 1.3: Handle pane widths when switching modes
  2701. if (mode === 'split') {
  2702. // Restore preserved pane widths when entering split mode
  2703. applyPaneWidths();
  2704. } else {
  2705. // Reset inline pane widths when not in split mode
  2706. resetPaneWidths();
  2707. }
  2708. // Re-render markdown when switching to a view that includes preview
  2709. if (mode === 'split' || mode === 'preview') {
  2710. renderMarkdown({ reason: 'view-switch' });
  2711. }
  2712. if (mode === 'split' || mode === 'editor') {
  2713. refreshEditorWidth();
  2714. scheduleLineNumberUpdate({ force: true });
  2715. updateFindHighlights();
  2716. scheduleEditorOverlayScrollSync();
  2717. }
  2718. }
  2719. function resolveViewToggleMode(mode) {
  2720. if ((mode === 'editor' || mode === 'preview') && currentViewMode === mode) {
  2721. return 'split';
  2722. }
  2723. return mode;
  2724. }
  2725. // Story 1.2: Update sync toggle visibility
  2726. function updateSyncToggleVisibility(mode) {
  2727. const isSplitView = mode === 'split';
  2728. // Desktop sync toggle
  2729. if (toggleSyncButton) {
  2730. toggleSyncButton.style.display = '';
  2731. toggleSyncButton.disabled = !isSplitView;
  2732. toggleSyncButton.setAttribute('aria-disabled', String(!isSplitView));
  2733. toggleSyncButton.removeAttribute('aria-hidden');
  2734. }
  2735. // Mobile sync toggle
  2736. if (mobileToggleSync) {
  2737. mobileToggleSync.style.display = '';
  2738. mobileToggleSync.disabled = !isSplitView;
  2739. mobileToggleSync.setAttribute('aria-disabled', String(!isSplitView));
  2740. mobileToggleSync.removeAttribute('aria-hidden');
  2741. }
  2742. }
  2743. function replaceEditorRange(start, end, replacement, selectStart, selectEnd) {
  2744. pushProgrammaticHistoryState();
  2745. markdownEditor.focus();
  2746. markdownEditor.setRangeText(replacement, start, end, 'end');
  2747. const nextStart = typeof selectStart === 'number' ? selectStart : start + replacement.length;
  2748. const nextEnd = typeof selectEnd === 'number' ? selectEnd : nextStart;
  2749. markdownEditor.setSelectionRange(nextStart, nextEnd);
  2750. markdownEditor.dispatchEvent(new Event('input', { bubbles: true }));
  2751. lastPushedValue = markdownEditor.value;
  2752. lastInputType = 'programmatic';
  2753. }
  2754. function wrapEditorSelection(prefix, suffix, placeholder) {
  2755. const start = markdownEditor.selectionStart;
  2756. const end = markdownEditor.selectionEnd;
  2757. const selected = markdownEditor.value.slice(start, end) || placeholder;
  2758. const replacement = prefix + selected + suffix;
  2759. const selectionStart = start + prefix.length;
  2760. const selectionEnd = selectionStart + selected.length;
  2761. replaceEditorRange(start, end, replacement, selectionStart, selectionEnd);
  2762. }
  2763. function getCurrentLineRange() {
  2764. const value = markdownEditor.value;
  2765. const start = markdownEditor.selectionStart;
  2766. const lineStart = value.lastIndexOf('\n', Math.max(0, start - 1)) + 1;
  2767. let lineEnd = value.indexOf('\n', start);
  2768. if (lineEnd === -1) lineEnd = value.length;
  2769. return { start: lineStart, end: lineEnd, text: value.slice(lineStart, lineEnd) };
  2770. }
  2771. function getSelectedLineRange() {
  2772. const value = markdownEditor.value;
  2773. const start = markdownEditor.selectionStart;
  2774. const end = markdownEditor.selectionEnd;
  2775. const lineStart = value.lastIndexOf('\n', Math.max(0, start - 1)) + 1;
  2776. let lineEnd = value.indexOf('\n', end);
  2777. if (lineEnd === -1) lineEnd = value.length;
  2778. return { start: lineStart, end: lineEnd, text: value.slice(lineStart, lineEnd) };
  2779. }
  2780. function transformEditorLines(transformer) {
  2781. const range = getSelectedLineRange();
  2782. const replacement = range.text.split('\n').map(transformer).join('\n');
  2783. replaceEditorRange(range.start, range.end, replacement, range.start, range.start + replacement.length);
  2784. }
  2785. function getListLineRange() {
  2786. const value = markdownEditor.value;
  2787. const start = markdownEditor.selectionStart;
  2788. const end = markdownEditor.selectionEnd;
  2789. const effectiveEnd = end > start && value[end - 1] === '\n' ? end - 1 : end;
  2790. const lineStart = value.lastIndexOf('\n', Math.max(0, start - 1)) + 1;
  2791. let lineEnd = value.indexOf('\n', effectiveEnd);
  2792. if (lineEnd === -1) lineEnd = value.length;
  2793. return { start: lineStart, end: lineEnd, text: value.slice(lineStart, lineEnd) };
  2794. }
  2795. function parseMarkdownListItem(line) {
  2796. const match = line.match(/^(\s*)((\d+)\.|[-*+])(?:\s+|$)(.*)$/);
  2797. if (!match) return null;
  2798. const isOrdered = typeof match[3] !== 'undefined';
  2799. return {
  2800. type: isOrdered ? 'ordered' : 'unordered',
  2801. indent: match[1],
  2802. marker: match[2],
  2803. number: isOrdered ? parseInt(match[3], 10) : null,
  2804. bullet: isOrdered ? null : match[2],
  2805. body: match[4] || '',
  2806. prefix: match[1] + match[2] + ' '
  2807. };
  2808. }
  2809. function stripListMarkerForApply(line) {
  2810. const parsed = parseMarkdownListItem(line);
  2811. if (parsed) {
  2812. return { indent: parsed.indent, body: parsed.body };
  2813. }
  2814. const match = line.match(/^(\s*)(.*)$/);
  2815. return { indent: match ? match[1] : '', body: match ? match[2] : line };
  2816. }
  2817. function getPreviousLineInfo(lineStart) {
  2818. if (lineStart <= 0) return null;
  2819. const value = markdownEditor.value;
  2820. const previousEnd = lineStart - 1;
  2821. const previousStart = previousEnd > 0 ? value.lastIndexOf('\n', previousEnd - 1) + 1 : 0;
  2822. return { start: previousStart, text: value.slice(previousStart, previousEnd) };
  2823. }
  2824. function getOrderedListStartNumber(lineStart) {
  2825. const previousLine = getPreviousLineInfo(lineStart);
  2826. if (!previousLine || !previousLine.text.trim()) return 1;
  2827. const parsed = parseMarkdownListItem(previousLine.text);
  2828. return parsed && parsed.type === 'ordered' ? parsed.number + 1 : 1;
  2829. }
  2830. function applyMarkdownList(type) {
  2831. const range = getListLineRange();
  2832. const hadSelection = markdownEditor.selectionStart !== markdownEditor.selectionEnd;
  2833. const lines = range.text.split('\n');
  2834. let nextNumber = type === 'ordered' ? getOrderedListStartNumber(range.start) : 1;
  2835. let firstPrefixLength = null;
  2836. const replacement = lines.map(function(line) {
  2837. const stripped = stripListMarkerForApply(line);
  2838. const prefix = type === 'ordered'
  2839. ? stripped.indent + (nextNumber++) + '. '
  2840. : stripped.indent + '- ';
  2841. if (firstPrefixLength === null) firstPrefixLength = prefix.length;
  2842. return prefix + stripped.body;
  2843. }).join('\n');
  2844. const isSingleLine = lines.length === 1;
  2845. const caret = (!hadSelection || isSingleLine)
  2846. ? range.start + (firstPrefixLength || 0)
  2847. : range.start + replacement.length;
  2848. replaceEditorRange(range.start, range.end, replacement, caret, caret);
  2849. }
  2850. function renumberOrderedListAfterPosition(position, nextNumber) {
  2851. let value = markdownEditor.value;
  2852. let lineStart = value.indexOf('\n', position);
  2853. if (lineStart === -1) return;
  2854. lineStart += 1;
  2855. let changed = false;
  2856. while (lineStart < value.length) {
  2857. let lineEnd = value.indexOf('\n', lineStart);
  2858. const hasNewline = lineEnd !== -1;
  2859. if (!hasNewline) lineEnd = value.length;
  2860. const line = value.slice(lineStart, lineEnd);
  2861. if (!line.trim()) break;
  2862. const parsed = parseMarkdownListItem(line);
  2863. if (!parsed || parsed.type !== 'ordered') break;
  2864. const replacement = parsed.indent + nextNumber + '. ' + parsed.body;
  2865. if (replacement !== line) {
  2866. value = value.slice(0, lineStart) + replacement + value.slice(lineEnd);
  2867. changed = true;
  2868. }
  2869. lineStart += replacement.length + (hasNewline ? 1 : 0);
  2870. nextNumber += 1;
  2871. }
  2872. if (changed) {
  2873. const selectionStart = markdownEditor.selectionStart;
  2874. const selectionEnd = markdownEditor.selectionEnd;
  2875. markdownEditor.value = value;
  2876. markdownEditor.setSelectionRange(selectionStart, selectionEnd);
  2877. markdownEditor.dispatchEvent(new Event('input', { bubbles: true }));
  2878. }
  2879. }
  2880. function handleListEnter(e) {
  2881. if (e.key !== 'Enter' || e.shiftKey || markdownEditor.selectionStart !== markdownEditor.selectionEnd) {
  2882. return false;
  2883. }
  2884. const range = getCurrentLineRange();
  2885. const parsed = parseMarkdownListItem(range.text);
  2886. if (!parsed) return false;
  2887. e.preventDefault();
  2888. if (!parsed.body.trim()) {
  2889. const caret = range.start + parsed.indent.length;
  2890. replaceEditorRange(range.start, range.end, parsed.indent, caret, caret);
  2891. return true;
  2892. }
  2893. const nextPrefix = parsed.type === 'ordered'
  2894. ? parsed.indent + (parsed.number + 1) + '. '
  2895. : parsed.indent + parsed.bullet + ' ';
  2896. const insertAt = markdownEditor.selectionStart;
  2897. const caret = insertAt + 1 + nextPrefix.length;
  2898. replaceEditorRange(insertAt, insertAt, '\n' + nextPrefix, caret, caret);
  2899. if (parsed.type === 'ordered') {
  2900. renumberOrderedListAfterPosition(caret, parsed.number + 2);
  2901. }
  2902. return true;
  2903. }
  2904. function transformSelectionOrCurrentLine(transformer) {
  2905. let start = markdownEditor.selectionStart;
  2906. let end = markdownEditor.selectionEnd;
  2907. if (start === end) {
  2908. const range = getCurrentLineRange();
  2909. start = range.start;
  2910. end = range.end;
  2911. }
  2912. const replacement = transformer(markdownEditor.value.slice(start, end));
  2913. replaceEditorRange(start, end, replacement, start, start + replacement.length);
  2914. }
  2915. function stripBasicMarkdown(text) {
  2916. return text
  2917. .replace(/^#{1,6}\s+/gm, '')
  2918. .replace(/^>\s?/gm, '')
  2919. .replace(/^(\s*)([-*+]|\d+\.)\s+/gm, '$1')
  2920. .replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1')
  2921. .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
  2922. .replace(/(\*\*|__)(.*?)\1/g, '$2')
  2923. .replace(/(\*|_)(.*?)\1/g, '$2')
  2924. .replace(/~~(.*?)~~/g, '$1')
  2925. .replace(/`([^`]+)`/g, '$1');
  2926. }
  2927. function getOrCreateTabHistory(tabId) {
  2928. if (!tabId) return { undoStack: [], redoStack: [] };
  2929. if (!tabHistories[tabId]) {
  2930. tabHistories[tabId] = {
  2931. undoStack: [],
  2932. redoStack: []
  2933. };
  2934. }
  2935. return tabHistories[tabId];
  2936. }
  2937. function initTabHistory(tabId, initialValue) {
  2938. const hist = getOrCreateTabHistory(tabId);
  2939. if (hist.undoStack.length === 0) {
  2940. hist.undoStack.push({
  2941. value: initialValue || '',
  2942. selectionStart: 0,
  2943. selectionEnd: 0
  2944. });
  2945. lastPushedValue = initialValue || '';
  2946. currentHistoryTabId = tabId;
  2947. pendingState = null;
  2948. }
  2949. }
  2950. function pushProgrammaticHistoryState() {
  2951. if (typingTimeout) {
  2952. clearTimeout(typingTimeout);
  2953. typingTimeout = null;
  2954. }
  2955. const tabId = activeTabId;
  2956. const hist = getOrCreateTabHistory(tabId);
  2957. const currentValue = markdownEditor.value;
  2958. if (pendingState) {
  2959. hist.undoStack.push(pendingState);
  2960. if (hist.undoStack.length > 200) {
  2961. hist.undoStack.shift();
  2962. }
  2963. hist.redoStack.length = 0;
  2964. pendingState = null;
  2965. lastPushedValue = currentValue;
  2966. } else if (currentValue !== lastPushedValue) {
  2967. hist.undoStack.push({
  2968. value: currentValue,
  2969. selectionStart: markdownEditor.selectionStart,
  2970. selectionEnd: markdownEditor.selectionEnd
  2971. });
  2972. if (hist.undoStack.length > 200) {
  2973. hist.undoStack.shift();
  2974. }
  2975. hist.redoStack.length = 0;
  2976. lastPushedValue = currentValue;
  2977. }
  2978. updateUndoRedoButtons();
  2979. }
  2980. function commitPendingState() {
  2981. if (typingTimeout) {
  2982. clearTimeout(typingTimeout);
  2983. typingTimeout = null;
  2984. }
  2985. if (!pendingState) return;
  2986. const tabId = activeTabId;
  2987. const hist = getOrCreateTabHistory(tabId);
  2988. hist.undoStack.push(pendingState);
  2989. if (hist.undoStack.length > 200) {
  2990. hist.undoStack.shift();
  2991. }
  2992. hist.redoStack.length = 0;
  2993. lastPushedValue = markdownEditor.value;
  2994. pendingState = null;
  2995. updateUndoRedoButtons();
  2996. }
  2997. function handleKeystrokeHistory(e) {
  2998. const currentValue = markdownEditor.value;
  2999. if (currentValue === lastPushedValue) return;
  3000. const inputType = e && typeof e.inputType === 'string' ? e.inputType : '';
  3001. if (!pendingState) {
  3002. pendingState = {
  3003. value: lastPushedValue,
  3004. selectionStart: lastCursorStart,
  3005. selectionEnd: lastCursorEnd
  3006. };
  3007. }
  3008. let shouldCommit = false;
  3009. if (inputType === 'insertLineBreak' || inputType === 'insertParagraph' || inputType === 'insertFromPaste' || lastInputType === 'programmatic') {
  3010. shouldCommit = true;
  3011. } else if (e && e.data === ' ') {
  3012. shouldCommit = true;
  3013. } else {
  3014. const isDelete = inputType.startsWith('delete');
  3015. const wasDelete = lastInputType === 'delete';
  3016. const isInsert = inputType.startsWith('insert');
  3017. const wasInsert = lastInputType === 'insert';
  3018. if ((isDelete && wasInsert) || (isInsert && wasDelete)) {
  3019. shouldCommit = true;
  3020. }
  3021. }
  3022. if (shouldCommit) {
  3023. commitPendingState();
  3024. }
  3025. if (typingTimeout) {
  3026. clearTimeout(typingTimeout);
  3027. }
  3028. typingTimeout = setTimeout(function() {
  3029. commitPendingState();
  3030. }, 1000);
  3031. if (inputType.startsWith('delete')) {
  3032. lastInputType = 'delete';
  3033. } else if (inputType.startsWith('insert')) {
  3034. lastInputType = 'insert';
  3035. } else {
  3036. lastInputType = 'other';
  3037. }
  3038. }
  3039. function updateLastCursor() {
  3040. if (markdownEditor) {
  3041. lastCursorStart = markdownEditor.selectionStart;
  3042. lastCursorEnd = markdownEditor.selectionEnd;
  3043. }
  3044. }
  3045. function updateUndoRedoButtons() {
  3046. const undoBtn = document.querySelector('[data-md-action="undo"]');
  3047. const redoBtn = document.querySelector('[data-md-action="redo"]');
  3048. if (!undoBtn || !redoBtn) return;
  3049. const tabId = activeTabId;
  3050. const hist = getOrCreateTabHistory(tabId);
  3051. const canUndo = hist.undoStack.length > 0 || pendingState !== null;
  3052. const canRedo = hist.redoStack.length > 0;
  3053. undoBtn.disabled = !canUndo;
  3054. undoBtn.classList.toggle('disabled', !canUndo);
  3055. redoBtn.disabled = !canRedo;
  3056. redoBtn.classList.toggle('disabled', !canRedo);
  3057. }
  3058. function executeUndo() {
  3059. if (typingTimeout) {
  3060. clearTimeout(typingTimeout);
  3061. typingTimeout = null;
  3062. }
  3063. const tabId = activeTabId;
  3064. const hist = getOrCreateTabHistory(tabId);
  3065. const currentValue = markdownEditor.value;
  3066. let stateToRestore = null;
  3067. if (pendingState) {
  3068. stateToRestore = pendingState;
  3069. pendingState = null;
  3070. hist.redoStack.push({
  3071. value: currentValue,
  3072. selectionStart: markdownEditor.selectionStart,
  3073. selectionEnd: markdownEditor.selectionEnd
  3074. });
  3075. if (hist.redoStack.length > 200) {
  3076. hist.redoStack.shift();
  3077. }
  3078. } else if (hist.undoStack.length > 0) {
  3079. const topState = hist.undoStack.pop();
  3080. if (topState) {
  3081. stateToRestore = topState;
  3082. hist.redoStack.push({
  3083. value: currentValue,
  3084. selectionStart: markdownEditor.selectionStart,
  3085. selectionEnd: markdownEditor.selectionEnd
  3086. });
  3087. if (hist.redoStack.length > 200) {
  3088. hist.redoStack.shift();
  3089. }
  3090. }
  3091. }
  3092. if (stateToRestore) {
  3093. markdownEditor.value = stateToRestore.value;
  3094. markdownEditor.setSelectionRange(stateToRestore.selectionStart, stateToRestore.selectionEnd);
  3095. lastPushedValue = stateToRestore.value;
  3096. lastInputType = null;
  3097. markdownEditor.dispatchEvent(new Event('input', { bubbles: true }));
  3098. saveCurrentTabState();
  3099. }
  3100. updateUndoRedoButtons();
  3101. }
  3102. function executeRedo() {
  3103. if (typingTimeout) {
  3104. clearTimeout(typingTimeout);
  3105. typingTimeout = null;
  3106. }
  3107. const tabId = activeTabId;
  3108. const hist = getOrCreateTabHistory(tabId);
  3109. const currentValue = markdownEditor.value;
  3110. if (hist.redoStack.length > 0) {
  3111. const stateToRestore = hist.redoStack.pop();
  3112. hist.undoStack.push({
  3113. value: currentValue,
  3114. selectionStart: markdownEditor.selectionStart,
  3115. selectionEnd: markdownEditor.selectionEnd
  3116. });
  3117. if (hist.undoStack.length > 200) {
  3118. hist.undoStack.shift();
  3119. }
  3120. markdownEditor.value = stateToRestore.value;
  3121. markdownEditor.setSelectionRange(stateToRestore.selectionStart, stateToRestore.selectionEnd);
  3122. lastPushedValue = stateToRestore.value;
  3123. lastInputType = null;
  3124. pendingState = null;
  3125. markdownEditor.dispatchEvent(new Event('input', { bubbles: true }));
  3126. saveCurrentTabState();
  3127. }
  3128. updateUndoRedoButtons();
  3129. }
  3130. function stripMarkdownFormatting(text) {
  3131. if (!text) return '';
  3132. return text
  3133. // Remove fenced code block syntax
  3134. .replace(/^```[a-zA-Z0-9-]*\r?\n?/gm, '')
  3135. .replace(/```\r?$/gm, '')
  3136. // Remove reference link definitions (e.g., [id]: url "title")
  3137. .replace(/^\[[^\]]+\]:\s*\S+(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*$/gm, '')
  3138. // Strip basic markdown constructs (headers, blockquotes, lists, bold, italic, strikethrough, code)
  3139. .replace(/^#{1,6}\s+/gm, '')
  3140. .replace(/^>\s?/gm, '')
  3141. .replace(/^(\s*)([-*+]|\d+\.)\s+/gm, '$1')
  3142. .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
  3143. .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
  3144. // HTML alignment tags or custom tags (strip the tags, keep inner text)
  3145. .replace(/<[^>]+>/g, '')
  3146. // Bold, Italic, Strikethrough, Inline code
  3147. .replace(/(\*\*|__)(.*?)\1/g, '$2')
  3148. .replace(/(\*|_)(.*?)\1/g, '$2')
  3149. .replace(/~~(.*?)~~/g, '$1')
  3150. .replace(/`([^`]+)`/g, '$1')
  3151. // Remove horizontal rules
  3152. .replace(/^\s*[-*_]{3,}\s*$/gm, '');
  3153. }
  3154. function applyClearFormatting() {
  3155. const fullText = markdownEditor.value;
  3156. pushProgrammaticHistoryState();
  3157. replaceEditorRange(0, fullText.length, '', 0, 0);
  3158. // Force immediate visual rendering and gutter update
  3159. renderMarkdown();
  3160. updateLineNumbers();
  3161. updateFindHighlights();
  3162. saveCurrentTabState();
  3163. }
  3164. function toTitleCase(text) {
  3165. return text.toLowerCase().replace(/\b\w/g, function(letter) {
  3166. return letter.toUpperCase();
  3167. });
  3168. }
  3169. function toSlug(text) {
  3170. const slug = text.toLowerCase().trim()
  3171. .replace(/[^a-z0-9\s-]/g, '')
  3172. .replace(/\s+/g, '-')
  3173. .replace(/-+/g, '-');
  3174. return slug || 'section';
  3175. }
  3176. function getUsedReferenceNumbers(text) {
  3177. const used = new Set();
  3178. const regex = /^\[(\d+)\]:/gm;
  3179. let match = regex.exec(text);
  3180. while (match) {
  3181. const num = parseInt(match[1], 10);
  3182. if (!Number.isNaN(num)) used.add(num);
  3183. match = regex.exec(text);
  3184. }
  3185. return used;
  3186. }
  3187. function extractReferenceDefinitions(markdown) {
  3188. const definitions = new Map();
  3189. // Matches reference definitions: [1]: <url> "title", [1]: url 'title', or [1]: url (title)
  3190. const definitionRegex = /^\[(\d+)\]:\s*(?:<([^>\s]+)>|(\S+))(?:\s+(?:"([^"]*)"|'([^']*)'|\(([^)]+)\)))?\s*$/gm;
  3191. const cleanedMarkdown = markdown.replace(
  3192. definitionRegex,
  3193. function(match, numberText, angleUrl, plainUrl, titleDouble, titleSingle, titleParen) {
  3194. const number = parseInt(numberText, 10);
  3195. if (Number.isNaN(number)) return match;
  3196. const url = (angleUrl || plainUrl || '').trim();
  3197. if (!url) return match;
  3198. const title = titleDouble || titleSingle || titleParen || '';
  3199. definitions.set(number, { url: url, title: title });
  3200. return '';
  3201. }
  3202. );
  3203. return { definitions, cleanedMarkdown };
  3204. }
  3205. function getNextAvailableReferenceNumber(used, startNumber) {
  3206. let next = Math.max(1, startNumber || 1);
  3207. while (used.has(next)) next += 1;
  3208. return next;
  3209. }
  3210. function sanitizeMarkdownTitle(title) {
  3211. return title
  3212. .replace(/\\/g, '\\\\')
  3213. .replace(/"/g, '\\"');
  3214. }
  3215. function isSafeReferenceUrl(url) {
  3216. if (!url) return false;
  3217. try {
  3218. const parsed = new URL(url, window.location.href);
  3219. return ['http:', 'https:', 'mailto:', 'tel:', 'blob:'].includes(parsed.protocol);
  3220. } catch (e) {
  3221. return false;
  3222. }
  3223. }
  3224. function applyReferencePreviewLinks(container, referenceDefinitions) {
  3225. if (!container || !referenceDefinitions || referenceDefinitions.size === 0) return;
  3226. function applyReferenceStyle(link, number) {
  3227. const definition = referenceDefinitions.get(number);
  3228. if (definition && definition.url && isSafeReferenceUrl(definition.url)) {
  3229. link.setAttribute('href', definition.url);
  3230. if (definition.title) {
  3231. link.setAttribute('title', definition.title);
  3232. } else {
  3233. link.removeAttribute('title');
  3234. }
  3235. } else {
  3236. link.removeAttribute('href');
  3237. }
  3238. link.textContent = '[' + number + ']';
  3239. link.classList.add('reference-link');
  3240. }
  3241. const links = container.querySelectorAll('a');
  3242. links.forEach(function(link) {
  3243. const text = link.textContent.trim();
  3244. let number = null;
  3245. if (/^\d+$/.test(text)) {
  3246. number = parseInt(text, 10);
  3247. } else {
  3248. const match = text.match(/^\[(\d+)\]$/);
  3249. if (match) number = parseInt(match[1], 10);
  3250. }
  3251. if (number && referenceDefinitions.has(number)) {
  3252. applyReferenceStyle(link, number);
  3253. }
  3254. });
  3255. const referenceRegex = /\[(\d+)\](?!\s*:)/g;
  3256. const nodesToProcess = [];
  3257. const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT, null);
  3258. while (walker.nextNode()) {
  3259. const node = walker.currentNode;
  3260. const parent = node.parentElement;
  3261. if (!parent || !node.nodeValue) continue;
  3262. if (parent.closest('a, code, pre, script, style, mjx-container')) continue;
  3263. referenceRegex.lastIndex = 0;
  3264. if (referenceRegex.test(node.nodeValue)) {
  3265. nodesToProcess.push(node);
  3266. }
  3267. }
  3268. nodesToProcess.forEach(function(node) {
  3269. const text = node.nodeValue;
  3270. referenceRegex.lastIndex = 0;
  3271. let match;
  3272. let lastIndex = 0;
  3273. const fragment = document.createDocumentFragment();
  3274. while ((match = referenceRegex.exec(text)) !== null) {
  3275. const before = text.slice(lastIndex, match.index);
  3276. if (before) fragment.appendChild(document.createTextNode(before));
  3277. const number = parseInt(match[1], 10);
  3278. const definition = referenceDefinitions.get(number);
  3279. if (definition && definition.url && isSafeReferenceUrl(definition.url)) {
  3280. const link = document.createElement('a');
  3281. link.href = definition.url;
  3282. if (definition.title) link.title = definition.title;
  3283. link.textContent = '[' + number + ']';
  3284. link.classList.add('reference-link');
  3285. fragment.appendChild(link);
  3286. } else {
  3287. fragment.appendChild(document.createTextNode(match[0]));
  3288. }
  3289. lastIndex = match.index + match[0].length;
  3290. }
  3291. const after = text.slice(lastIndex);
  3292. if (after) fragment.appendChild(document.createTextNode(after));
  3293. node.parentNode.replaceChild(fragment, node);
  3294. });
  3295. }
  3296. function cleanupImageObjectUrls() {
  3297. if (imageObjectUrls.size === 0) return;
  3298. const contents = [markdownEditor.value];
  3299. if (Array.isArray(tabs)) {
  3300. tabs.forEach(function(tab) {
  3301. if (tab && typeof tab.content === 'string' && tab.content) {
  3302. contents.push(tab.content);
  3303. }
  3304. });
  3305. }
  3306. const snapshot = contents.join('\n');
  3307. Array.from(imageObjectUrls).forEach(function(url) {
  3308. if (!snapshot.includes(url)) {
  3309. URL.revokeObjectURL(url);
  3310. imageObjectUrls.delete(url);
  3311. }
  3312. });
  3313. }
  3314. function insertAlignmentBlock(align) {
  3315. const allowedAlignments = new Set(['left', 'center', 'right']);
  3316. const isAllowed = allowedAlignments.has(align);
  3317. if (!isAllowed) {
  3318. console.warn('Unsupported alignment:', align);
  3319. return;
  3320. }
  3321. const safeAlign = align;
  3322. const value = markdownEditor.value;
  3323. const start = markdownEditor.selectionStart;
  3324. const end = markdownEditor.selectionEnd;
  3325. const selected = value.slice(start, end);
  3326. const hasSelection = start !== end;
  3327. const blockStart = `<div align="${safeAlign}">\n`;
  3328. const blockEnd = `\n</div>`;
  3329. const block = `${blockStart}${hasSelection ? selected : ''}${blockEnd}`;
  3330. const needsLeadingBreak = start > 0 && value[start - 1] !== '\n';
  3331. const needsTrailingBreak = end < value.length && value[end] !== '\n';
  3332. const replacement = (needsLeadingBreak ? '\n' : '') + block + (needsTrailingBreak ? '\n' : '');
  3333. const contentStart = start + (needsLeadingBreak ? 1 : 0) + blockStart.length;
  3334. const contentEnd = contentStart + (hasSelection ? selected.length : 0);
  3335. replaceEditorRange(start, end, replacement, contentStart, hasSelection ? contentEnd : contentStart);
  3336. }
  3337. function insertMarkdownBlock(block, startOverride, endOverride) {
  3338. const value = markdownEditor.value;
  3339. const start = typeof startOverride === 'number' ? startOverride : markdownEditor.selectionStart;
  3340. const end = typeof endOverride === 'number' ? endOverride : markdownEditor.selectionEnd;
  3341. const needsLeadingBreak = start > 0 && value[start - 1] !== '\n';
  3342. const needsTrailingBreak = end < value.length && value[end] !== '\n';
  3343. const replacement = (needsLeadingBreak ? '\n' : '') + block + (needsTrailingBreak ? '\n' : '');
  3344. const caret = start + replacement.length;
  3345. replaceEditorRange(start, end, replacement, caret, caret);
  3346. }
  3347. function clampNumber(value, min, max, fallback) {
  3348. const parsed = parseInt(value, 10);
  3349. if (Number.isNaN(parsed)) return fallback;
  3350. return Math.max(min, Math.min(max, parsed));
  3351. }
  3352. function buildMarkdownTable(columns, rows) {
  3353. const header = Array.from({ length: columns }, (_, index) => `Column ${index + 1}`).join(' | ');
  3354. const divider = Array.from({ length: columns }, () => '---').join(' | ');
  3355. const bodyRows = Array.from({ length: rows }, () => `| ${Array.from({ length: columns }, () => 'Value').join(' | ')} |`);
  3356. return `| ${header} |\n| ${divider} |\n${bodyRows.join('\n')}\n`;
  3357. }
  3358. function loadEmojiEntries() {
  3359. if (emojiLoadPromise) return emojiLoadPromise;
  3360. emojiLoadPromise = fetch(EMOJI_API_URL)
  3361. .then((response) => {
  3362. if (!response.ok) throw new Error(`Emoji request failed (${response.status})`);
  3363. return response.json();
  3364. })
  3365. .then((data) => {
  3366. emojiEntries = Object.keys(data)
  3367. .sort((a, b) => a.localeCompare(b))
  3368. .map((name) => ({
  3369. name,
  3370. url: data[name],
  3371. shortcode: `:${name}:`,
  3372. search: `${name} :${name}:`.toLowerCase(),
  3373. }));
  3374. emojiUrlMap = new Map(emojiEntries.map((entry) => [entry.name, entry.url]));
  3375. emojiLookupLoaded = true;
  3376. return emojiEntries;
  3377. })
  3378. .catch((error) => {
  3379. console.error('Failed to load GitHub emojis:', error);
  3380. emojiEntries = [];
  3381. emojiUrlMap = new Map();
  3382. emojiLookupLoaded = true;
  3383. return emojiEntries;
  3384. });
  3385. return emojiLoadPromise;
  3386. }
  3387. function createAlertPreview(type, meta) {
  3388. const wrapper = document.createElement('div');
  3389. wrapper.className = `markdown-alert markdown-alert-${type}`;
  3390. const title = document.createElement('p');
  3391. title.className = 'markdown-alert-title';
  3392. const icon = document.createElement('span');
  3393. icon.className = 'markdown-alert-icon';
  3394. icon.setAttribute('aria-hidden', 'true');
  3395. if (meta.path) {
  3396. const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  3397. svg.setAttribute('viewBox', meta.viewBox || '0 0 512 512');
  3398. const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  3399. path.setAttribute('d', meta.path);
  3400. svg.appendChild(path);
  3401. icon.appendChild(svg);
  3402. }
  3403. const label = document.createElement('span');
  3404. label.textContent = meta.label;
  3405. title.appendChild(icon);
  3406. title.appendChild(label);
  3407. const body = document.createElement('p');
  3408. body.textContent = `${meta.label} details go here.`;
  3409. wrapper.appendChild(title);
  3410. wrapper.appendChild(body);
  3411. return wrapper;
  3412. }
  3413. function flashCopyButton(button) {
  3414. const icon = button.querySelector('i');
  3415. if (!icon) return;
  3416. icon.className = 'bi bi-check-lg';
  3417. button.classList.add('is-copied');
  3418. clearTimeout(button.copyTimeout);
  3419. button.copyTimeout = setTimeout(() => {
  3420. icon.className = 'bi bi-clipboard';
  3421. button.classList.remove('is-copied');
  3422. }, 1200);
  3423. }
  3424. function openTableModal() {
  3425. const modal = document.getElementById('table-modal');
  3426. const columnInput = document.getElementById('table-modal-columns');
  3427. const rowInput = document.getElementById('table-modal-rows');
  3428. const confirmBtn = document.getElementById('table-modal-insert');
  3429. const cancelBtn = document.getElementById('table-modal-cancel');
  3430. if (!modal || !columnInput || !rowInput || !confirmBtn || !cancelBtn) return;
  3431. const start = markdownEditor.selectionStart;
  3432. const end = markdownEditor.selectionEnd;
  3433. columnInput.value = '3';
  3434. rowInput.value = '1';
  3435. modal.style.display = 'flex';
  3436. function insertTable() {
  3437. const columns = clampNumber(columnInput.value, 1, 20, 3);
  3438. const rows = clampNumber(rowInput.value, 1, 20, 1);
  3439. const table = buildMarkdownTable(columns, rows);
  3440. modal.style.display = 'none';
  3441. cleanup();
  3442. insertMarkdownBlock(table, start, end);
  3443. }
  3444. function closeModal() {
  3445. modal.style.display = 'none';
  3446. cleanup();
  3447. }
  3448. function onKey(e) {
  3449. if (e.key === 'Enter') {
  3450. e.preventDefault();
  3451. insertTable();
  3452. } else if (e.key === 'Escape') {
  3453. e.preventDefault();
  3454. closeModal();
  3455. }
  3456. }
  3457. function cleanup() {
  3458. confirmBtn.removeEventListener('click', insertTable);
  3459. cancelBtn.removeEventListener('click', closeModal);
  3460. columnInput.removeEventListener('keydown', onKey);
  3461. rowInput.removeEventListener('keydown', onKey);
  3462. }
  3463. confirmBtn.addEventListener('click', insertTable);
  3464. cancelBtn.addEventListener('click', closeModal);
  3465. columnInput.addEventListener('keydown', onKey);
  3466. rowInput.addEventListener('keydown', onKey);
  3467. requestAnimationFrame(() => {
  3468. columnInput.focus();
  3469. columnInput.select();
  3470. });
  3471. }
  3472. function openEmojiModal() {
  3473. const modal = document.getElementById('emoji-modal');
  3474. const grid = document.getElementById('emoji-modal-grid');
  3475. const emptyMessage = document.getElementById('emoji-modal-empty');
  3476. const searchInput = document.getElementById('emoji-modal-search');
  3477. const confirmBtn = document.getElementById('emoji-modal-insert');
  3478. const cancelBtn = document.getElementById('emoji-modal-cancel');
  3479. if (!modal || !grid || !emptyMessage || !searchInput || !confirmBtn || !cancelBtn) return;
  3480. const start = markdownEditor.selectionStart;
  3481. const end = markdownEditor.selectionEnd;
  3482. modal.style.display = 'flex';
  3483. confirmBtn.disabled = true;
  3484. // Localized and accessible announcements for loading
  3485. const loadingText = I18N_DICTS[activeLang].loadingEmojis || "Loading emojis...";
  3486. emptyMessage.textContent = loadingText;
  3487. emptyMessage.style.display = 'block';
  3488. announceToScreenReader(loadingText);
  3489. searchInput.value = '';
  3490. emojiSelection.clear();
  3491. // PERF-007: Clear elements using textContent
  3492. grid.textContent = '';
  3493. grid.scrollTop = 0;
  3494. emojiItems = [];
  3495. // Render visual placeholders during active requests
  3496. if (!emojiLookupLoaded) {
  3497. renderEmojiSkeletons();
  3498. }
  3499. let currentFilteredEntries = [];
  3500. let renderedCount = 0;
  3501. const CHUNK_SIZE = 120;
  3502. function updateInsertState() {
  3503. confirmBtn.disabled = emojiSelection.size === 0;
  3504. }
  3505. function toggleSelection(shortcode, element) {
  3506. if (emojiSelection.has(shortcode)) {
  3507. emojiSelection.delete(shortcode);
  3508. element.classList.remove('is-selected');
  3509. } else {
  3510. emojiSelection.add(shortcode);
  3511. element.classList.add('is-selected');
  3512. }
  3513. element.setAttribute('aria-pressed', emojiSelection.has(shortcode).toString());
  3514. updateInsertState();
  3515. }
  3516. function renderEmojiChunk(clear = false) {
  3517. if (clear) {
  3518. // PERF-007: Clear elements using textContent
  3519. grid.textContent = '';
  3520. emojiItems = [];
  3521. renderedCount = 0;
  3522. }
  3523. const nextBatch = currentFilteredEntries.slice(renderedCount, renderedCount + CHUNK_SIZE);
  3524. if (nextBatch.length === 0) {
  3525. emptyMessage.style.display = emojiItems.length ? 'none' : 'block';
  3526. return;
  3527. }
  3528. const fragment = document.createDocumentFragment();
  3529. const newItems = nextBatch.map((entry) => {
  3530. const item = document.createElement('button');
  3531. item.type = 'button';
  3532. item.className = 'emoji-item';
  3533. const isSelected = emojiSelection.has(entry.shortcode);
  3534. if (isSelected) {
  3535. item.classList.add('is-selected');
  3536. }
  3537. item.setAttribute('aria-pressed', isSelected ? 'true' : 'false');
  3538. item.dataset.search = entry.search;
  3539. item.dataset.shortcode = entry.shortcode;
  3540. const preview = document.createElement('span');
  3541. preview.className = 'emoji-preview';
  3542. const image = document.createElement('img');
  3543. image.src = entry.url;
  3544. image.alt = entry.shortcode;
  3545. image.loading = 'lazy';
  3546. preview.appendChild(image);
  3547. const shortcodeRow = document.createElement('div');
  3548. shortcodeRow.className = 'emoji-shortcode';
  3549. const code = document.createElement('span');
  3550. code.textContent = entry.shortcode;
  3551. const copyBtn = document.createElement('button');
  3552. copyBtn.type = 'button';
  3553. copyBtn.className = 'emoji-copy-btn';
  3554. copyBtn.setAttribute('aria-label', `Copy ${entry.shortcode}`);
  3555. copyBtn.innerHTML = '<i class="bi bi-clipboard"></i>';
  3556. copyBtn.addEventListener('click', (event) => {
  3557. event.stopPropagation();
  3558. copyTextToClipboard(entry.shortcode)
  3559. .then(() => flashCopyButton(copyBtn))
  3560. .catch((error) => console.error('Copy failed:', error));
  3561. });
  3562. shortcodeRow.appendChild(code);
  3563. shortcodeRow.appendChild(copyBtn);
  3564. item.appendChild(preview);
  3565. item.appendChild(shortcodeRow);
  3566. item.addEventListener('click', () => toggleSelection(entry.shortcode, item));
  3567. fragment.appendChild(item);
  3568. return { element: item, search: entry.search, shortcode: entry.shortcode };
  3569. });
  3570. emojiItems = emojiItems.concat(newItems);
  3571. grid.appendChild(fragment);
  3572. renderedCount += nextBatch.length;
  3573. emptyMessage.style.display = emojiItems.length ? 'none' : 'block';
  3574. }
  3575. function applyFilter() {
  3576. const query = searchInput.value.trim().toLowerCase();
  3577. currentFilteredEntries = emojiEntries.filter(entry => !query || entry.search.includes(query));
  3578. renderEmojiChunk(true);
  3579. }
  3580. function handleScroll() {
  3581. if (grid.scrollTop + grid.clientHeight >= grid.scrollHeight - 60) {
  3582. renderEmojiChunk(false);
  3583. }
  3584. }
  3585. function insertEmojis() {
  3586. if (!emojiSelection.size) return;
  3587. // Retain the modal's visual/definition order of emojis, consistent with the Symbols modal
  3588. const ordered = emojiItems
  3589. .filter(item => emojiSelection.has(item.shortcode))
  3590. .map(item => item.shortcode);
  3591. const insertion = ordered.join(' ');
  3592. modal.style.display = 'none';
  3593. cleanup();
  3594. replaceEditorRange(start, end, insertion, start + insertion.length, start + insertion.length);
  3595. }
  3596. function closeModal() {
  3597. modal.style.display = 'none';
  3598. cleanup();
  3599. }
  3600. function onKey(e) {
  3601. if (e.key === 'Escape') {
  3602. e.preventDefault();
  3603. closeModal();
  3604. }
  3605. }
  3606. function cleanup() {
  3607. confirmBtn.removeEventListener('click', insertEmojis);
  3608. cancelBtn.removeEventListener('click', closeModal);
  3609. searchInput.removeEventListener('input', applyFilter);
  3610. searchInput.removeEventListener('keydown', onKey);
  3611. grid.removeEventListener('scroll', handleScroll);
  3612. }
  3613. loadEmojiEntries().then((entries) => {
  3614. if (!entries.length) {
  3615. emptyMessage.textContent = 'Unable to load emojis.';
  3616. emptyMessage.style.display = 'block';
  3617. // PERF-007: Clear elements using textContent
  3618. grid.textContent = '';
  3619. emojiItems = [];
  3620. announceToScreenReader("Failed to load emojis.");
  3621. return;
  3622. }
  3623. currentFilteredEntries = entries;
  3624. renderEmojiChunk(true);
  3625. emptyMessage.textContent = 'No emojis found.';
  3626. announceToScreenReader("Emojis loaded. " + entries.length + " items available.");
  3627. updateInsertState();
  3628. });
  3629. confirmBtn.addEventListener('click', insertEmojis);
  3630. cancelBtn.addEventListener('click', closeModal);
  3631. searchInput.addEventListener('input', applyFilter);
  3632. searchInput.addEventListener('keydown', onKey);
  3633. grid.addEventListener('scroll', handleScroll);
  3634. requestAnimationFrame(() => searchInput.focus());
  3635. }
  3636. function openSymbolsModal() {
  3637. const modal = document.getElementById('symbols-modal');
  3638. const grid = document.getElementById('symbols-modal-grid');
  3639. const emptyMessage = document.getElementById('symbols-modal-empty');
  3640. const searchInput = document.getElementById('symbols-modal-search');
  3641. const confirmBtn = document.getElementById('symbols-modal-insert');
  3642. const cancelBtn = document.getElementById('symbols-modal-cancel');
  3643. if (!modal || !grid || !emptyMessage || !searchInput || !confirmBtn || !cancelBtn) return;
  3644. const start = markdownEditor.selectionStart;
  3645. const end = markdownEditor.selectionEnd;
  3646. modal.style.display = 'flex';
  3647. confirmBtn.disabled = true;
  3648. searchInput.value = '';
  3649. symbolSelection.clear();
  3650. // PERF-007: Clear elements using textContent
  3651. grid.textContent = '';
  3652. const sectionEntries = [];
  3653. SYMBOL_SECTIONS.forEach((section) => {
  3654. const sectionWrapper = document.createElement('div');
  3655. sectionWrapper.className = 'symbol-section';
  3656. const title = document.createElement('p');
  3657. title.className = 'symbol-section-title';
  3658. title.textContent = section.title;
  3659. const sectionGrid = document.createElement('div');
  3660. sectionGrid.className = 'symbol-section-grid';
  3661. const sectionItems = section.items.map((entry) => {
  3662. const item = document.createElement('button');
  3663. item.type = 'button';
  3664. item.className = 'symbol-item';
  3665. item.setAttribute('aria-pressed', 'false');
  3666. const preview = document.createElement('span');
  3667. preview.className = 'symbol-preview';
  3668. preview.textContent = entry.symbol;
  3669. const codeRow = document.createElement('div');
  3670. codeRow.className = 'symbol-code';
  3671. const code = document.createElement('span');
  3672. code.textContent = entry.entity;
  3673. const copyBtn = document.createElement('button');
  3674. copyBtn.type = 'button';
  3675. copyBtn.className = 'symbol-copy-btn';
  3676. copyBtn.setAttribute('aria-label', `Copy ${entry.entity}`);
  3677. copyBtn.innerHTML = '<i class="bi bi-clipboard"></i>';
  3678. copyBtn.addEventListener('click', (event) => {
  3679. event.stopPropagation();
  3680. copyTextToClipboard(entry.entity)
  3681. .then(() => flashCopyButton(copyBtn))
  3682. .catch((error) => console.error('Copy failed:', error));
  3683. });
  3684. codeRow.appendChild(code);
  3685. codeRow.appendChild(copyBtn);
  3686. item.appendChild(preview);
  3687. item.appendChild(codeRow);
  3688. item.dataset.search = `${entry.symbol} ${entry.entity} ${entry.name}`.toLowerCase();
  3689. item.dataset.entity = entry.entity;
  3690. item.addEventListener('click', () => {
  3691. if (symbolSelection.has(entry.entity)) {
  3692. symbolSelection.delete(entry.entity);
  3693. item.classList.remove('is-selected');
  3694. } else {
  3695. symbolSelection.add(entry.entity);
  3696. item.classList.add('is-selected');
  3697. }
  3698. item.setAttribute('aria-pressed', symbolSelection.has(entry.entity).toString());
  3699. confirmBtn.disabled = symbolSelection.size === 0;
  3700. });
  3701. sectionGrid.appendChild(item);
  3702. return { element: item, search: item.dataset.search, entity: entry.entity };
  3703. });
  3704. sectionWrapper.appendChild(title);
  3705. sectionWrapper.appendChild(sectionGrid);
  3706. grid.appendChild(sectionWrapper);
  3707. sectionEntries.push({ wrapper: sectionWrapper, items: sectionItems });
  3708. });
  3709. symbolItems = sectionEntries.flatMap((section) => section.items);
  3710. function applyFilter() {
  3711. const query = searchInput.value.trim().toLowerCase();
  3712. let visibleCount = 0;
  3713. sectionEntries.forEach((section) => {
  3714. let sectionVisible = 0;
  3715. section.items.forEach((item) => {
  3716. const match = !query || item.search.includes(query);
  3717. item.element.style.display = match ? '' : 'none';
  3718. if (match) {
  3719. visibleCount += 1;
  3720. sectionVisible += 1;
  3721. }
  3722. });
  3723. section.wrapper.style.display = sectionVisible ? '' : 'none';
  3724. });
  3725. emptyMessage.style.display = visibleCount ? 'none' : 'block';
  3726. }
  3727. function insertSymbols() {
  3728. if (!symbolSelection.size) return;
  3729. const ordered = symbolItems
  3730. .filter((item) => symbolSelection.has(item.entity))
  3731. .map((item) => item.entity);
  3732. const insertion = ordered.join(' ');
  3733. modal.style.display = 'none';
  3734. cleanup();
  3735. replaceEditorRange(start, end, insertion, start + insertion.length, start + insertion.length);
  3736. }
  3737. function closeModal() {
  3738. modal.style.display = 'none';
  3739. cleanup();
  3740. }
  3741. function onKey(e) {
  3742. if (e.key === 'Escape') {
  3743. e.preventDefault();
  3744. closeModal();
  3745. }
  3746. }
  3747. function cleanup() {
  3748. confirmBtn.removeEventListener('click', insertSymbols);
  3749. cancelBtn.removeEventListener('click', closeModal);
  3750. searchInput.removeEventListener('input', applyFilter);
  3751. searchInput.removeEventListener('keydown', onKey);
  3752. }
  3753. emptyMessage.textContent = 'No symbols found.';
  3754. applyFilter();
  3755. confirmBtn.addEventListener('click', insertSymbols);
  3756. cancelBtn.addEventListener('click', closeModal);
  3757. searchInput.addEventListener('input', applyFilter);
  3758. searchInput.addEventListener('keydown', onKey);
  3759. requestAnimationFrame(() => searchInput.focus());
  3760. }
  3761. function openAlertModal() {
  3762. const modal = document.getElementById('alert-modal');
  3763. const grid = document.getElementById('alert-modal-grid');
  3764. const confirmBtn = document.getElementById('alert-modal-insert');
  3765. const cancelBtn = document.getElementById('alert-modal-cancel');
  3766. if (!modal || !grid || !confirmBtn || !cancelBtn) return;
  3767. const start = markdownEditor.selectionStart;
  3768. const end = markdownEditor.selectionEnd;
  3769. modal.style.display = 'flex';
  3770. // PERF-007: Clear elements using textContent
  3771. grid.textContent = '';
  3772. const alertTypes = ['note', 'tip', 'important', 'warning', 'caution'];
  3773. let selectedType = alertTypes[0];
  3774. const options = [];
  3775. alertTypes.forEach((type) => {
  3776. const meta = GITHUB_ALERT_META[type] || { label: type };
  3777. const option = document.createElement('button');
  3778. option.type = 'button';
  3779. option.className = 'alert-option';
  3780. option.dataset.alertType = type;
  3781. option.setAttribute('aria-pressed', (type === selectedType).toString());
  3782. const preview = document.createElement('div');
  3783. preview.className = 'alert-preview';
  3784. preview.appendChild(createAlertPreview(type, meta));
  3785. option.appendChild(preview);
  3786. if (type === selectedType) option.classList.add('is-selected');
  3787. option.addEventListener('click', () => {
  3788. selectedType = type;
  3789. options.forEach((item) => {
  3790. const isSelected = item === option;
  3791. item.classList.toggle('is-selected', isSelected);
  3792. item.setAttribute('aria-pressed', isSelected.toString());
  3793. });
  3794. });
  3795. options.push(option);
  3796. grid.appendChild(option);
  3797. });
  3798. function insertAlert() {
  3799. const type = selectedType.toUpperCase();
  3800. const meta = GITHUB_ALERT_META[selectedType] || { label: selectedType };
  3801. const body = `${meta.label} details go here.`;
  3802. const block = `> [!${type}]\n> ${body}\n`;
  3803. modal.style.display = 'none';
  3804. cleanup();
  3805. insertMarkdownBlock(block, start, end);
  3806. }
  3807. function closeModal() {
  3808. modal.style.display = 'none';
  3809. cleanup();
  3810. }
  3811. function onKey(e) {
  3812. if (e.key === 'Escape') {
  3813. e.preventDefault();
  3814. closeModal();
  3815. }
  3816. }
  3817. function cleanup() {
  3818. confirmBtn.removeEventListener('click', insertAlert);
  3819. cancelBtn.removeEventListener('click', closeModal);
  3820. modal.removeEventListener('keydown', onKey);
  3821. }
  3822. confirmBtn.addEventListener('click', insertAlert);
  3823. cancelBtn.addEventListener('click', closeModal);
  3824. modal.addEventListener('keydown', onKey);
  3825. }
  3826. function insertMarkdownLink() {
  3827. const modal = document.getElementById('link-modal');
  3828. const urlInput = document.getElementById('link-modal-url');
  3829. const textInput = document.getElementById('link-modal-text');
  3830. const confirmBtn = document.getElementById('link-modal-apply');
  3831. const cancelBtn = document.getElementById('link-modal-cancel');
  3832. if (!modal || !urlInput || !textInput || !confirmBtn || !cancelBtn) return;
  3833. const start = markdownEditor.selectionStart;
  3834. const end = markdownEditor.selectionEnd;
  3835. const selected = markdownEditor.value.slice(start, end);
  3836. urlInput.value = 'https://';
  3837. textInput.value = selected || '';
  3838. modal.style.display = 'flex';
  3839. function applyLink() {
  3840. const url = urlInput.value.trim() || 'https://';
  3841. const linkText = textInput.value.trim() || selected || 'link text';
  3842. const replacement = '[' + linkText + '](' + url + ')';
  3843. modal.style.display = 'none';
  3844. cleanup();
  3845. replaceEditorRange(start, end, replacement, start + replacement.length, start + replacement.length);
  3846. }
  3847. function closeModal() {
  3848. modal.style.display = 'none';
  3849. cleanup();
  3850. }
  3851. function onKey(e) {
  3852. if (e.key === 'Enter') {
  3853. e.preventDefault();
  3854. applyLink();
  3855. } else if (e.key === 'Escape') {
  3856. e.preventDefault();
  3857. closeModal();
  3858. }
  3859. }
  3860. function cleanup() {
  3861. confirmBtn.removeEventListener('click', applyLink);
  3862. cancelBtn.removeEventListener('click', closeModal);
  3863. urlInput.removeEventListener('keydown', onKey);
  3864. textInput.removeEventListener('keydown', onKey);
  3865. }
  3866. confirmBtn.addEventListener('click', applyLink);
  3867. cancelBtn.addEventListener('click', closeModal);
  3868. urlInput.addEventListener('keydown', onKey);
  3869. textInput.addEventListener('keydown', onKey);
  3870. requestAnimationFrame(function() {
  3871. urlInput.focus();
  3872. urlInput.select();
  3873. });
  3874. }
  3875. function insertMarkdownImage() {
  3876. const modal = document.getElementById('image-modal');
  3877. const uploadOption = document.getElementById('image-source-upload');
  3878. const urlOption = document.getElementById('image-source-url');
  3879. const uploadFields = document.getElementById('image-upload-fields');
  3880. const urlFields = document.getElementById('image-url-fields');
  3881. const fileInput = document.getElementById('image-modal-file');
  3882. const urlInput = document.getElementById('image-modal-url');
  3883. const altInput = document.getElementById('image-modal-alt');
  3884. const confirmBtn = document.getElementById('image-modal-insert');
  3885. const cancelBtn = document.getElementById('image-modal-cancel');
  3886. if (!modal || !uploadOption || !urlOption || !uploadFields || !urlFields || !fileInput || !urlInput || !altInput || !confirmBtn || !cancelBtn) return;
  3887. const start = markdownEditor.selectionStart;
  3888. const end = markdownEditor.selectionEnd;
  3889. const selected = markdownEditor.value.slice(start, end);
  3890. urlInput.value = 'https://';
  3891. altInput.value = selected || '';
  3892. fileInput.value = '';
  3893. urlOption.checked = true;
  3894. uploadOption.checked = false;
  3895. modal.style.display = 'flex';
  3896. function buildImageMarkdown(url) {
  3897. const titleText = altInput.value.trim();
  3898. const altText = titleText || 'alt text';
  3899. const safeTitle = sanitizeMarkdownTitle(titleText);
  3900. const titlePart = safeTitle ? ' "' + safeTitle + '"' : '';
  3901. return '![' + altText + '](' + url + titlePart + ')';
  3902. }
  3903. function insertImage(url) {
  3904. const safeUrl = url.trim() || 'https://';
  3905. const replacement = buildImageMarkdown(safeUrl);
  3906. modal.style.display = 'none';
  3907. cleanup();
  3908. replaceEditorRange(start, end, replacement, start + replacement.length, start + replacement.length);
  3909. }
  3910. function insertFromFile(file) {
  3911. const objectUrl = URL.createObjectURL(file);
  3912. imageObjectUrls.add(objectUrl);
  3913. insertImage(objectUrl);
  3914. }
  3915. function updateMode(shouldFocus) {
  3916. const isUpload = uploadOption.checked;
  3917. uploadFields.style.display = isUpload ? 'flex' : 'none';
  3918. urlFields.style.display = isUpload ? 'none' : 'flex';
  3919. if (shouldFocus) {
  3920. requestAnimationFrame(function() {
  3921. if (isUpload) {
  3922. fileInput.focus();
  3923. } else {
  3924. urlInput.focus();
  3925. urlInput.select();
  3926. }
  3927. });
  3928. }
  3929. }
  3930. function onModeChange() {
  3931. updateMode(true);
  3932. }
  3933. function onFileChange() {
  3934. const file = fileInput.files && fileInput.files[0];
  3935. if (file) {
  3936. insertFromFile(file);
  3937. }
  3938. }
  3939. function onKey(e) {
  3940. if (e.key === 'Enter') {
  3941. e.preventDefault();
  3942. if (uploadOption.checked) {
  3943. const file = fileInput.files && fileInput.files[0];
  3944. if (file) insertFromFile(file);
  3945. else fileInput.click();
  3946. } else {
  3947. insertImage(urlInput.value);
  3948. }
  3949. } else if (e.key === 'Escape') {
  3950. e.preventDefault();
  3951. closeModal();
  3952. }
  3953. }
  3954. function closeModal() {
  3955. modal.style.display = 'none';
  3956. cleanup();
  3957. }
  3958. function cleanup() {
  3959. confirmBtn.removeEventListener('click', onConfirm);
  3960. cancelBtn.removeEventListener('click', closeModal);
  3961. uploadOption.removeEventListener('change', onModeChange);
  3962. urlOption.removeEventListener('change', onModeChange);
  3963. fileInput.removeEventListener('change', onFileChange);
  3964. fileInput.removeEventListener('keydown', onKey);
  3965. urlInput.removeEventListener('keydown', onKey);
  3966. altInput.removeEventListener('keydown', onKey);
  3967. }
  3968. function onConfirm() {
  3969. if (uploadOption.checked) {
  3970. const file = fileInput.files && fileInput.files[0];
  3971. if (file) insertFromFile(file);
  3972. else fileInput.click();
  3973. } else {
  3974. insertImage(urlInput.value);
  3975. }
  3976. }
  3977. confirmBtn.addEventListener('click', onConfirm);
  3978. cancelBtn.addEventListener('click', closeModal);
  3979. uploadOption.addEventListener('change', onModeChange);
  3980. urlOption.addEventListener('change', onModeChange);
  3981. fileInput.addEventListener('change', onFileChange);
  3982. fileInput.addEventListener('keydown', onKey);
  3983. urlInput.addEventListener('keydown', onKey);
  3984. altInput.addEventListener('keydown', onKey);
  3985. updateMode(true);
  3986. }
  3987. function insertMarkdownReference() {
  3988. const modal = document.getElementById('reference-modal');
  3989. const numberInput = document.getElementById('reference-modal-number');
  3990. const urlInput = document.getElementById('reference-modal-url');
  3991. const titleInput = document.getElementById('reference-modal-title-input');
  3992. const confirmBtn = document.getElementById('reference-modal-apply');
  3993. const cancelBtn = document.getElementById('reference-modal-cancel');
  3994. if (!modal || !numberInput || !urlInput || !titleInput || !confirmBtn || !cancelBtn) return;
  3995. const start = markdownEditor.selectionStart;
  3996. const end = markdownEditor.selectionEnd;
  3997. const currentValue = markdownEditor.value;
  3998. const used = getUsedReferenceNumbers(currentValue);
  3999. const maxUsed = used.size ? Math.max(...used) : 0;
  4000. referenceCounter = Math.max(1, maxUsed + 1);
  4001. const suggestedNumber = getNextAvailableReferenceNumber(used, referenceCounter);
  4002. numberInput.value = '[' + suggestedNumber + ']';
  4003. urlInput.value = 'https://';
  4004. titleInput.value = '';
  4005. modal.style.display = 'flex';
  4006. function insertReference() {
  4007. const latestValue = markdownEditor.value;
  4008. const usedNumbers = getUsedReferenceNumbers(latestValue);
  4009. const parsed = parseInt(numberInput.value.replace(/[^\d]/g, ''), 10);
  4010. const baseNumber = Number.isNaN(parsed) ? suggestedNumber : parsed;
  4011. const finalNumber = getNextAvailableReferenceNumber(usedNumbers, baseNumber);
  4012. const url = urlInput.value.trim() || 'https://';
  4013. const title = titleInput.value.trim();
  4014. const safeTitle = sanitizeMarkdownTitle(title);
  4015. const definition = '[' + finalNumber + ']: ' + url + (safeTitle ? ' "' + safeTitle + '"' : '');
  4016. const selected = latestValue.slice(start, end);
  4017. const inlineReference = selected + '[' + finalNumber + ']';
  4018. const baseValue = latestValue.slice(0, start) + inlineReference + latestValue.slice(end);
  4019. let separator = '';
  4020. if (baseValue.length && !baseValue.endsWith('\n')) {
  4021. separator = '\n';
  4022. }
  4023. const updatedValue = baseValue + separator + definition;
  4024. markdownEditor.value = updatedValue;
  4025. markdownEditor.focus();
  4026. const caret = start + inlineReference.length;
  4027. markdownEditor.setSelectionRange(caret, caret);
  4028. markdownEditor.dispatchEvent(new Event('input', { bubbles: true }));
  4029. referenceCounter = Math.max(referenceCounter, finalNumber + 1);
  4030. modal.style.display = 'none';
  4031. cleanup();
  4032. }
  4033. function closeModal() {
  4034. modal.style.display = 'none';
  4035. cleanup();
  4036. }
  4037. function onKey(e) {
  4038. if (e.key === 'Enter') {
  4039. e.preventDefault();
  4040. insertReference();
  4041. } else if (e.key === 'Escape') {
  4042. e.preventDefault();
  4043. closeModal();
  4044. }
  4045. }
  4046. function cleanup() {
  4047. confirmBtn.removeEventListener('click', insertReference);
  4048. cancelBtn.removeEventListener('click', closeModal);
  4049. numberInput.removeEventListener('keydown', onKey);
  4050. urlInput.removeEventListener('keydown', onKey);
  4051. titleInput.removeEventListener('keydown', onKey);
  4052. }
  4053. confirmBtn.addEventListener('click', insertReference);
  4054. cancelBtn.addEventListener('click', closeModal);
  4055. numberInput.addEventListener('keydown', onKey);
  4056. urlInput.addEventListener('keydown', onKey);
  4057. titleInput.addEventListener('keydown', onKey);
  4058. requestAnimationFrame(function() {
  4059. numberInput.focus();
  4060. numberInput.select();
  4061. });
  4062. }
  4063. function escapeRegExp(text) {
  4064. return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  4065. }
  4066. function getFocusableElements(container) {
  4067. return Array.from(container.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'))
  4068. .filter(element => !element.disabled && element.offsetParent !== null);
  4069. }
  4070. function trapFocusInModal(modal, event) {
  4071. const focusable = getFocusableElements(modal);
  4072. if (!focusable.length) {
  4073. event.preventDefault();
  4074. return;
  4075. }
  4076. const first = focusable[0];
  4077. const last = focusable[focusable.length - 1];
  4078. if (event.shiftKey && document.activeElement === first) {
  4079. event.preventDefault();
  4080. last.focus();
  4081. } else if (!event.shiftKey && document.activeElement === last) {
  4082. event.preventDefault();
  4083. first.focus();
  4084. }
  4085. }
  4086. function openAppModal(modal, options = {}) {
  4087. if (!modal) return;
  4088. if (activeModal && activeModal !== modal) {
  4089. closeAppModal(activeModal);
  4090. }
  4091. lastFocusedElement = document.activeElement;
  4092. modal.style.display = 'flex';
  4093. requestAnimationFrame(function() {
  4094. modal.classList.add('is-visible');
  4095. });
  4096. modal.setAttribute('aria-hidden', 'false');
  4097. activeModal = modal;
  4098. const focusTarget = options.focusTarget || getFocusableElements(modal)[0];
  4099. if (focusTarget) {
  4100. focusTarget.focus();
  4101. }
  4102. const handleKeydown = function(event) {
  4103. if (event.key === 'Escape') {
  4104. event.preventDefault();
  4105. if (options.onClose) {
  4106. options.onClose();
  4107. } else {
  4108. closeAppModal(modal);
  4109. }
  4110. } else if (event.key === 'Tab') {
  4111. trapFocusInModal(modal, event);
  4112. }
  4113. };
  4114. const handlePointerDown = function(event) {
  4115. if (event.target === modal) {
  4116. if (options.onClose) {
  4117. options.onClose();
  4118. } else {
  4119. closeAppModal(modal);
  4120. }
  4121. }
  4122. };
  4123. modal.addEventListener('keydown', handleKeydown);
  4124. modal.addEventListener('mousedown', handlePointerDown);
  4125. modal._modalHandlers = { handleKeydown, handlePointerDown };
  4126. }
  4127. function closeAppModal(modal) {
  4128. if (!modal) return;
  4129. modal.classList.remove('is-visible');
  4130. modal.setAttribute('aria-hidden', 'true');
  4131. const handlers = modal._modalHandlers || {};
  4132. if (handlers.handleKeydown) modal.removeEventListener('keydown', handlers.handleKeydown);
  4133. if (handlers.handlePointerDown) modal.removeEventListener('mousedown', handlers.handlePointerDown);
  4134. if (activeModal === modal) activeModal = null;
  4135. window.setTimeout(function() {
  4136. if (!modal.classList.contains('is-visible')) {
  4137. modal.style.display = 'none';
  4138. }
  4139. }, 200);
  4140. if (lastFocusedElement && typeof lastFocusedElement.focus === 'function') {
  4141. lastFocusedElement.focus();
  4142. }
  4143. }
  4144. function updateFindHighlights() {
  4145. updatePreviewFindHighlights();
  4146. if (!editorHighlightLayer) return;
  4147. if (!isEditorVisible()) return;
  4148. if (!isFindModalOpen || !findReplaceInput || !findReplaceInput.value || !findMatches.length) {
  4149. if (editorHighlightLayer.textContent !== '') {
  4150. editorHighlightLayer.textContent = '';
  4151. }
  4152. return;
  4153. }
  4154. const text = markdownEditor.value || '';
  4155. const scrollTop = cachedScrollTop;
  4156. const scrollLeft = cachedScrollLeft;
  4157. const fragment = document.createDocumentFragment();
  4158. let lastIndex = 0;
  4159. findMatches.forEach(function(match, index) {
  4160. fragment.appendChild(document.createTextNode(text.slice(lastIndex, match.start)));
  4161. const mark = document.createElement('mark');
  4162. mark.className = 'find-highlight' + (index === activeFindIndex ? ' active' : '');
  4163. mark.textContent = text.slice(match.start, match.end);
  4164. fragment.appendChild(mark);
  4165. lastIndex = match.end;
  4166. });
  4167. fragment.appendChild(document.createTextNode(text.slice(lastIndex)));
  4168. editorHighlightLayer.textContent = '';
  4169. editorHighlightLayer.appendChild(fragment);
  4170. editorHighlightLayer.scrollTop = scrollTop;
  4171. editorHighlightLayer.scrollLeft = scrollLeft;
  4172. }
  4173. let previewHighlights = [];
  4174. let activePreviewHighlightIndex = -1;
  4175. function isPreviewVisible() {
  4176. return currentViewMode === 'preview' || currentViewMode === 'split';
  4177. }
  4178. function clearPreviewFindHighlights() {
  4179. if (!markdownPreview) return;
  4180. const highlights = markdownPreview.querySelectorAll('.preview-find-highlight');
  4181. highlights.forEach(function(el) {
  4182. const parent = el.parentNode;
  4183. if (parent) {
  4184. parent.replaceChild(document.createTextNode(el.textContent), el);
  4185. }
  4186. });
  4187. markdownPreview.normalize();
  4188. }
  4189. function highlightPreviewText(node, regex) {
  4190. if (!node) return;
  4191. if (node.nodeType === Node.TEXT_NODE) {
  4192. const val = node.nodeValue;
  4193. if (!val) return;
  4194. regex.lastIndex = 0;
  4195. let match;
  4196. const matches = [];
  4197. while ((match = regex.exec(val)) !== null) {
  4198. if (match[0].length === 0) {
  4199. regex.lastIndex++;
  4200. continue;
  4201. }
  4202. matches.push({
  4203. start: match.index,
  4204. end: match.index + match[0].length,
  4205. text: match[0]
  4206. });
  4207. }
  4208. if (matches.length > 0) {
  4209. const parent = node.parentNode;
  4210. if (!parent) return;
  4211. const fragment = document.createDocumentFragment();
  4212. let lastIdx = 0;
  4213. matches.forEach(function(m) {
  4214. if (m.start > lastIdx) {
  4215. fragment.appendChild(document.createTextNode(val.slice(lastIdx, m.start)));
  4216. }
  4217. const mark = document.createElement('mark');
  4218. mark.className = 'preview-find-highlight';
  4219. mark.textContent = m.text;
  4220. fragment.appendChild(mark);
  4221. lastIdx = m.end;
  4222. });
  4223. if (lastIdx < val.length) {
  4224. fragment.appendChild(document.createTextNode(val.slice(lastIdx)));
  4225. }
  4226. parent.replaceChild(fragment, node);
  4227. }
  4228. } else if (node.nodeType === Node.ELEMENT_NODE) {
  4229. const tagName = node.tagName.toLowerCase();
  4230. if (tagName === 'script' || tagName === 'style' || tagName === 'textarea' || tagName === 'noscript' || tagName === 'svg') {
  4231. return;
  4232. }
  4233. if (node.classList.contains('mermaid') || node.classList.contains('mjx-container') || node.closest('.mermaid') || node.closest('.mjx-container')) {
  4234. return;
  4235. }
  4236. const children = Array.from(node.childNodes);
  4237. children.forEach(function(child) {
  4238. highlightPreviewText(child, regex);
  4239. });
  4240. }
  4241. }
  4242. function updatePreviewFindHighlights() {
  4243. clearPreviewFindHighlights();
  4244. previewHighlights = [];
  4245. if (!isFindModalOpen || !findReplaceInput || !findReplaceInput.value || !isPreviewVisible()) {
  4246. return;
  4247. }
  4248. const query = findReplaceInput.value;
  4249. const isRegex = document.getElementById('find-regex').classList.contains('active');
  4250. const isCaseSensitive = document.getElementById('find-case').classList.contains('active');
  4251. const isWholeWord = document.getElementById('find-word').classList.contains('active');
  4252. let regex;
  4253. try {
  4254. let pattern = isRegex ? query : query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  4255. if (isWholeWord) {
  4256. pattern = `\\b${pattern}\\b`;
  4257. }
  4258. const flags = isCaseSensitive ? 'g' : 'gi';
  4259. regex = new RegExp(pattern, flags);
  4260. } catch (e) {
  4261. return;
  4262. }
  4263. highlightPreviewText(markdownPreview, regex);
  4264. previewHighlights = Array.from(markdownPreview.querySelectorAll('.preview-find-highlight'));
  4265. updateActivePreviewHighlight();
  4266. }
  4267. function updateActivePreviewHighlight() {
  4268. previewHighlights.forEach(function(el) {
  4269. el.classList.remove('active');
  4270. });
  4271. if (!previewHighlights.length) {
  4272. activePreviewHighlightIndex = -1;
  4273. return;
  4274. }
  4275. if (findMatches.length > 0 && activeFindIndex >= 0) {
  4276. const ratio = activeFindIndex / findMatches.length;
  4277. activePreviewHighlightIndex = Math.min(
  4278. previewHighlights.length - 1,
  4279. Math.floor(ratio * previewHighlights.length)
  4280. );
  4281. } else {
  4282. activePreviewHighlightIndex = 0;
  4283. }
  4284. if (activePreviewHighlightIndex >= 0 && activePreviewHighlightIndex < previewHighlights.length) {
  4285. const activeEl = previewHighlights[activePreviewHighlightIndex];
  4286. activeEl.classList.add('active');
  4287. scrollPreviewHighlightIntoView(activeEl);
  4288. }
  4289. }
  4290. function scrollPreviewHighlightIntoView(element) {
  4291. if (!element || !previewPane) return;
  4292. const paneRect = previewPane.getBoundingClientRect();
  4293. const elemRect = element.getBoundingClientRect();
  4294. const isVisible = (
  4295. elemRect.top >= paneRect.top + 40 &&
  4296. elemRect.bottom <= paneRect.bottom - 40
  4297. );
  4298. if (!isVisible) {
  4299. const scrollTop = previewPane.scrollTop + (elemRect.top - paneRect.top) - (paneRect.height / 2) + (elemRect.height / 2);
  4300. previewPane.scrollTop = scrollTop;
  4301. }
  4302. }
  4303. function syncHighlightScroll() {
  4304. if (!editorHighlightLayer) return;
  4305. editorHighlightLayer.scrollTop = cachedScrollTop;
  4306. editorHighlightLayer.scrollLeft = cachedScrollLeft;
  4307. }
  4308. function scheduleEditorOverlayScrollSync() {
  4309. if (editorOverlayScrollFrame) return;
  4310. editorOverlayScrollFrame = requestAnimationFrame(function() {
  4311. editorOverlayScrollFrame = null;
  4312. syncHighlightScroll();
  4313. syncLineNumberScroll();
  4314. });
  4315. }
  4316. function updateLineNumberGutter(lineCount) {
  4317. if (!editorPaneElement) return;
  4318. const digits = String(Math.max(1, lineCount)).length;
  4319. const gutterSize = `${Math.max(LINE_NUMBER_GUTTER_MIN_CH, digits + LINE_NUMBER_GUTTER_PADDING_CH)}ch`;
  4320. editorPaneElement.style.setProperty('--line-number-gutter', gutterSize);
  4321. }
  4322. function getLineHeight(styles) {
  4323. const computed = parseFloat(styles.lineHeight);
  4324. if (!Number.isNaN(computed)) return computed;
  4325. const fontSize = parseFloat(styles.fontSize) || 14;
  4326. return fontSize * 1.5;
  4327. }
  4328. function getWrappedLineCountMonospace(lineText, maxCharsPerLine) {
  4329. if (!lineText) return 1;
  4330. const words = lineText.replace(/\t/g, ' ').split(' ');
  4331. let linesCount = 1;
  4332. let currentLineLength = 0;
  4333. for (let i = 0; i < words.length; i++) {
  4334. const word = words[i];
  4335. const wordLength = word.length;
  4336. if (wordLength === 0) {
  4337. if (currentLineLength + 1 > maxCharsPerLine) {
  4338. linesCount++;
  4339. currentLineLength = 1;
  4340. } else {
  4341. currentLineLength++;
  4342. }
  4343. continue;
  4344. }
  4345. if (wordLength > maxCharsPerLine) {
  4346. const remainingSpace = maxCharsPerLine - currentLineLength;
  4347. if (remainingSpace > 0 && currentLineLength > 0) {
  4348. const firstPart = wordLength - remainingSpace;
  4349. linesCount += 1 + Math.floor(firstPart / maxCharsPerLine);
  4350. currentLineLength = firstPart % maxCharsPerLine;
  4351. } else {
  4352. linesCount += Math.floor(wordLength / maxCharsPerLine);
  4353. currentLineLength = wordLength % maxCharsPerLine;
  4354. }
  4355. continue;
  4356. }
  4357. const spaceRequired = currentLineLength === 0 ? 0 : 1;
  4358. if (currentLineLength + spaceRequired + wordLength > maxCharsPerLine) {
  4359. linesCount++;
  4360. currentLineLength = wordLength;
  4361. } else {
  4362. currentLineLength += spaceRequired + wordLength;
  4363. }
  4364. }
  4365. return Math.max(1, linesCount);
  4366. }
  4367. const lineCache = new Map();
  4368. let cachedPaddingLeft = 10;
  4369. let cachedPaddingRight = 10;
  4370. let cachedCharWidth = 0;
  4371. let cachedLineHeight = 21;
  4372. let cachedEditorWidth = 0;
  4373. let cachedMaxCharsPerLine = 80;
  4374. let cachedScrollTop = 0;
  4375. let cachedScrollLeft = 0;
  4376. let isGeometryInitialized = false;
  4377. let lastLineNumberLineCount = 0;
  4378. let lastLineNumberDocumentLength = 0;
  4379. function countLinesFast(text) {
  4380. if (!text) return 1;
  4381. let count = 1;
  4382. for (let i = 0; i < text.length; i += 1) {
  4383. if (text.charCodeAt(i) === 10) count += 1;
  4384. }
  4385. return count;
  4386. }
  4387. function countLinesBeforeIndex(text, endIndex) {
  4388. let count = 0;
  4389. const max = Math.max(0, Math.min(text.length, endIndex));
  4390. for (let i = 0; i < max; i += 1) {
  4391. if (text.charCodeAt(i) === 10) count += 1;
  4392. }
  4393. return count;
  4394. }
  4395. function initEditorGeometry() {
  4396. if (!markdownEditor) return;
  4397. const styles = window.getComputedStyle(markdownEditor);
  4398. cachedPaddingLeft = parseFloat(styles.paddingLeft) || 10;
  4399. cachedPaddingRight = parseFloat(styles.paddingRight) || 10;
  4400. // Measure character width
  4401. const testSpan = document.createElement('span');
  4402. testSpan.style.fontFamily = styles.fontFamily;
  4403. testSpan.style.fontSize = styles.fontSize;
  4404. testSpan.style.visibility = 'hidden';
  4405. testSpan.style.position = 'absolute';
  4406. testSpan.style.whiteSpace = 'pre';
  4407. testSpan.textContent = 'a'.repeat(100);
  4408. document.body.appendChild(testSpan);
  4409. cachedCharWidth = testSpan.getBoundingClientRect().width / 100;
  4410. document.body.removeChild(testSpan);
  4411. // Calculate line height
  4412. const computed = parseFloat(styles.lineHeight);
  4413. if (!Number.isNaN(computed)) {
  4414. cachedLineHeight = computed;
  4415. } else {
  4416. const fontSize = parseFloat(styles.fontSize) || 14;
  4417. cachedLineHeight = fontSize * 1.5;
  4418. }
  4419. isGeometryInitialized = true;
  4420. lineCache.clear();
  4421. }
  4422. function refreshEditorWidth() {
  4423. if (!markdownEditor) return;
  4424. if (!isGeometryInitialized) {
  4425. initEditorGeometry();
  4426. }
  4427. cachedEditorWidth = markdownEditor.clientWidth;
  4428. const availableWidth = cachedEditorWidth - cachedPaddingLeft - cachedPaddingRight;
  4429. const nextMaxCharsPerLine = Math.max(1, Math.floor(availableWidth / cachedCharWidth));
  4430. if (nextMaxCharsPerLine !== cachedMaxCharsPerLine) {
  4431. cachedMaxCharsPerLine = nextMaxCharsPerLine;
  4432. lineCache.clear();
  4433. }
  4434. cachedScrollTop = markdownEditor.scrollTop;
  4435. cachedScrollLeft = markdownEditor.scrollLeft;
  4436. }
  4437. function updateLineNumberItem(item, index, lineText, lineHeight) {
  4438. if (!item) return;
  4439. let wrapHeight = lineCache.get(lineText);
  4440. if (wrapHeight === undefined) {
  4441. const wrapCount = getWrappedLineCountMonospace(lineText, cachedMaxCharsPerLine);
  4442. wrapHeight = wrapCount * lineHeight;
  4443. if (lineCache.size >= LINE_CACHE_MAX_ENTRIES) {
  4444. lineCache.clear();
  4445. }
  4446. lineCache.set(lineText, wrapHeight);
  4447. }
  4448. const targetText = String(index + 1);
  4449. if (item.textContent !== targetText) {
  4450. item.textContent = targetText;
  4451. }
  4452. const targetHeight = `${wrapHeight}px`;
  4453. if (item.style.height !== targetHeight) {
  4454. item.style.height = targetHeight;
  4455. }
  4456. }
  4457. function updateActiveLineNumberHeight(text, lineCount, lineHeight) {
  4458. const caret = markdownEditor.selectionStart || 0;
  4459. const lineIndex = Math.min(lineCount - 1, countLinesBeforeIndex(text, caret));
  4460. const lineStart = text.lastIndexOf('\n', Math.max(0, caret - 1)) + 1;
  4461. const lineEndIndex = text.indexOf('\n', caret);
  4462. const lineEnd = lineEndIndex === -1 ? text.length : lineEndIndex;
  4463. updateLineNumberItem(lineNumbers.children[lineIndex], lineIndex, text.slice(lineStart, lineEnd), lineHeight);
  4464. }
  4465. function updateLineNumbers(options) {
  4466. const opts = options || {};
  4467. if (!lineNumbers || !markdownEditor) return;
  4468. if (!isEditorVisible()) return;
  4469. const text = markdownEditor.value || '';
  4470. const lineCount = countLinesFast(text);
  4471. if (cachedEditorWidth === 0) {
  4472. refreshEditorWidth();
  4473. }
  4474. updateLineNumberGutter(lineCount);
  4475. const lineHeight = cachedLineHeight;
  4476. const existingItems = lineNumbers.children;
  4477. const existingCount = existingItems.length;
  4478. const isLargeEditorDocument = text.length >= LARGE_DOCUMENT_THRESHOLD;
  4479. const canUseActiveLineFastPath =
  4480. isLargeEditorDocument &&
  4481. !opts.force &&
  4482. lineCount === lastLineNumberLineCount &&
  4483. existingCount === lineCount;
  4484. if (canUseActiveLineFastPath) {
  4485. updateActiveLineNumberHeight(text, lineCount, lineHeight);
  4486. lastLineNumberDocumentLength = text.length;
  4487. syncLineNumberScroll();
  4488. return;
  4489. }
  4490. const lines = text.split('\n');
  4491. // Adjust the number of DOM elements in-place to avoid complete tear-down
  4492. if (existingCount < lineCount) {
  4493. const fragment = document.createDocumentFragment();
  4494. for (let i = existingCount; i < lineCount; i += 1) {
  4495. const lineNumber = document.createElement('div');
  4496. lineNumber.className = 'line-number';
  4497. fragment.appendChild(lineNumber);
  4498. }
  4499. lineNumbers.appendChild(fragment);
  4500. } else if (existingCount > lineCount) {
  4501. while (lineNumbers.children.length > lineCount) {
  4502. lineNumbers.removeChild(lineNumbers.lastChild);
  4503. }
  4504. }
  4505. // Update only the heights and numbers that changed, using monospace simulator to avoid forced reflows
  4506. for (let i = 0; i < lineCount; i += 1) {
  4507. updateLineNumberItem(existingItems[i], i, lines[i], lineHeight);
  4508. }
  4509. lastLineNumberLineCount = lineCount;
  4510. lastLineNumberDocumentLength = text.length;
  4511. syncLineNumberScroll();
  4512. }
  4513. function scheduleLineNumberUpdate(options) {
  4514. const opts = options || {};
  4515. if (!lineNumbers) return;
  4516. if (!isEditorVisible()) return;
  4517. if (opts.force) {
  4518. if (lineNumberUpdateTimeout) {
  4519. clearTimeout(lineNumberUpdateTimeout);
  4520. lineNumberUpdateTimeout = null;
  4521. }
  4522. if (lineNumberUpdateFrame) {
  4523. cancelAnimationFrame(lineNumberUpdateFrame);
  4524. lineNumberUpdateFrame = null;
  4525. }
  4526. } else if (lineNumberUpdateFrame || lineNumberUpdateTimeout) {
  4527. return;
  4528. }
  4529. const text = markdownEditor ? markdownEditor.value || '' : '';
  4530. const delay = opts.delay !== undefined
  4531. ? opts.delay
  4532. : (opts.inputType === 'insertFromPaste' || text.length >= LARGE_DOCUMENT_THRESHOLD ? getEditorWorkDelay(text) : 0);
  4533. const runUpdate = function() {
  4534. lineNumberUpdateFrame = window.requestAnimationFrame(function() {
  4535. lineNumberUpdateFrame = null;
  4536. updateLineNumbers(opts);
  4537. });
  4538. };
  4539. if (delay > 0) {
  4540. lineNumberUpdateTimeout = setTimeout(function() {
  4541. lineNumberUpdateTimeout = null;
  4542. runUpdate();
  4543. }, delay);
  4544. } else {
  4545. runUpdate();
  4546. }
  4547. }
  4548. function syncLineNumberScroll() {
  4549. if (!lineNumbers) return;
  4550. lineNumbers.scrollTop = cachedScrollTop;
  4551. }
  4552. function syncEditorScrollOverlays() {
  4553. cachedScrollTop = markdownEditor.scrollTop;
  4554. cachedScrollLeft = markdownEditor.scrollLeft;
  4555. syncHighlightScroll();
  4556. syncLineNumberScroll();
  4557. }
  4558. function clampEditorScrollTop(scrollTop) {
  4559. const maxScrollTop = Math.max(0, markdownEditor.scrollHeight - markdownEditor.clientHeight);
  4560. return Math.min(maxScrollTop, Math.max(0, scrollTop));
  4561. }
  4562. function estimateEditorOffsetForIndex(index) {
  4563. if (!isGeometryInitialized || cachedEditorWidth !== markdownEditor.clientWidth) {
  4564. refreshEditorWidth();
  4565. }
  4566. const styles = window.getComputedStyle(markdownEditor);
  4567. const paddingTop = parseFloat(styles.paddingTop) || 10;
  4568. const textBefore = (markdownEditor.value || '').slice(0, Math.max(0, index));
  4569. const lines = textBefore.split('\n');
  4570. let visualRows = 0;
  4571. for (let i = 0; i < lines.length - 1; i += 1) {
  4572. visualRows += getWrappedLineCountMonospace(lines[i], cachedMaxCharsPerLine);
  4573. }
  4574. const currentLinePrefix = lines[lines.length - 1] || '';
  4575. visualRows += Math.max(0, getWrappedLineCountMonospace(currentLinePrefix, cachedMaxCharsPerLine) - 1);
  4576. return paddingTop + (visualRows * cachedLineHeight);
  4577. }
  4578. function getActiveFindHighlight() {
  4579. if (!editorHighlightLayer) return null;
  4580. return editorHighlightLayer.querySelector('.find-highlight.active');
  4581. }
  4582. function scrollActiveMatchIntoView(match) {
  4583. let matchTop = null;
  4584. let matchHeight = cachedLineHeight;
  4585. let activeHighlight = getActiveFindHighlight();
  4586. if (!activeHighlight) {
  4587. updateFindHighlights();
  4588. activeHighlight = getActiveFindHighlight();
  4589. }
  4590. if (activeHighlight) {
  4591. matchTop = activeHighlight.offsetTop;
  4592. matchHeight = activeHighlight.offsetHeight || matchHeight;
  4593. } else {
  4594. matchTop = estimateEditorOffsetForIndex(match.start);
  4595. }
  4596. const targetScrollTop = clampEditorScrollTop(
  4597. matchTop - (markdownEditor.clientHeight / 2) + (matchHeight / 2)
  4598. );
  4599. markdownEditor.scrollTop = targetScrollTop;
  4600. syncEditorScrollOverlays();
  4601. }
  4602. // Class encapsulating Search & Replace Engine
  4603. class FindReplaceEngine {
  4604. constructor(editor) {
  4605. this.editor = editor;
  4606. this.history = { find: [], replace: [] };
  4607. this.activeMatches = [];
  4608. this.currentMatchIndex = -1;
  4609. this._cachedScopeText = null;
  4610. this._cachedScopeMap = null;
  4611. }
  4612. buildASTScopeMap(text) {
  4613. // PERF-026: Cache scope map to avoid re-lexing on every search keystroke
  4614. if (text === this._cachedScopeText && this._cachedScopeMap) {
  4615. return this._cachedScopeMap;
  4616. }
  4617. if (typeof marked === 'undefined' || !marked.lexer) return [];
  4618. try {
  4619. const tokens = marked.lexer(text);
  4620. const scopeMap = [];
  4621. let currentIndex = 0;
  4622. const traverse = (tokenList) => {
  4623. for (const token of tokenList) {
  4624. const start = text.indexOf(token.raw, currentIndex);
  4625. if (start === -1) continue;
  4626. const end = start + token.raw.length;
  4627. currentIndex = end;
  4628. let scope = 'plain';
  4629. if (token.type === 'heading') scope = 'heading';
  4630. else if (token.type === 'code') {
  4631. if (token.lang === 'mermaid') scope = 'mermaid';
  4632. else scope = 'code';
  4633. } else if (token.type === 'paragraph' && token.raw.startsWith('$$') && token.raw.endsWith('$$')) {
  4634. scope = 'latex';
  4635. }
  4636. scopeMap.push({ start, end, scope, type: token.type });
  4637. if (token.tokens) traverse(token.tokens);
  4638. }
  4639. };
  4640. traverse(tokens);
  4641. this._cachedScopeText = text;
  4642. this._cachedScopeMap = scopeMap;
  4643. return scopeMap;
  4644. } catch (e) {
  4645. console.warn("AST scope parsing failed:", e);
  4646. return [];
  4647. }
  4648. }
  4649. compileRegExp(query, isRegex, isCaseSensitive, isWholeWord) {
  4650. if (!query) return null;
  4651. let pattern = isRegex ? query : query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  4652. if (isWholeWord) {
  4653. pattern = `\\b${pattern}\\b`;
  4654. }
  4655. const flags = isCaseSensitive ? 'gd' : 'gid';
  4656. return new RegExp(pattern, flags);
  4657. }
  4658. executeSearch(options) {
  4659. const { query, isRegex, isCaseSensitive, isWholeWord, scopeFilter, findInSelection } = options;
  4660. const fullText = this.editor.value || '';
  4661. let searchRange = { start: 0, end: fullText.length };
  4662. if (findInSelection) {
  4663. searchRange.start = this.editor.selectionStart;
  4664. searchRange.end = this.editor.selectionEnd;
  4665. }
  4666. let regex;
  4667. try {
  4668. regex = this.compileRegExp(query, isRegex, isCaseSensitive, isWholeWord);
  4669. } catch (err) {
  4670. throw new Error(err.message);
  4671. }
  4672. if (!regex) {
  4673. this.activeMatches = [];
  4674. this.currentMatchIndex = -1;
  4675. return this.activeMatches;
  4676. }
  4677. const rawMatches = [];
  4678. let match;
  4679. while ((match = regex.exec(fullText)) !== null) {
  4680. if (match.index >= searchRange.end) break;
  4681. if (match.index >= searchRange.start) {
  4682. rawMatches.push({
  4683. start: match.index,
  4684. end: match.index + match[0].length,
  4685. value: match[0],
  4686. groups: match.groups || null,
  4687. matchArray: match
  4688. });
  4689. }
  4690. if (regex.lastIndex === match.index) {
  4691. regex.lastIndex++;
  4692. }
  4693. }
  4694. if (scopeFilter && scopeFilter !== 'entire') {
  4695. const scopeMap = this.buildASTScopeMap(fullText);
  4696. this.activeMatches = rawMatches.filter(m => {
  4697. const matchingScope = scopeMap.find(s => m.start >= s.start && m.end <= s.end);
  4698. return matchingScope && matchingScope.scope === scopeFilter;
  4699. });
  4700. } else {
  4701. this.activeMatches = rawMatches;
  4702. }
  4703. this.currentMatchIndex = this.activeMatches.length > 0 ? 0 : -1;
  4704. this.addHistory('find', query);
  4705. return this.activeMatches;
  4706. }
  4707. preserveCase(source, replacement) {
  4708. if (source === source.toUpperCase()) {
  4709. return replacement.toUpperCase();
  4710. }
  4711. if (source === source.toLowerCase()) {
  4712. return replacement.toLowerCase();
  4713. }
  4714. if (source[0] === source[0].toUpperCase() && source.slice(1) === source.slice(1).toLowerCase()) {
  4715. return replacement[0].toUpperCase() + replacement.slice(1).toLowerCase();
  4716. }
  4717. return replacement;
  4718. }
  4719. applyCaptureGroups(match, replacementTemplate) {
  4720. if (!match.matchArray) return replacementTemplate;
  4721. let result = replacementTemplate;
  4722. result = result.replace(/\$(\d+)/g, (m, number) => {
  4723. const idx = parseInt(number, 10);
  4724. return match.matchArray[idx] !== undefined ? match.matchArray[idx] : m;
  4725. });
  4726. if (match.groups) {
  4727. result = result.replace(/\$<([^>]+)>/g, (m, name) => {
  4728. return match.groups[name] !== undefined ? match.groups[name] : m;
  4729. });
  4730. }
  4731. return result;
  4732. }
  4733. executeReplace(match, replacementTemplate, options) {
  4734. const { preserveCase, isRegex } = options;
  4735. const text = this.editor.value;
  4736. let finalReplacement = replacementTemplate;
  4737. if (isRegex) {
  4738. finalReplacement = this.applyCaptureGroups(match, finalReplacement);
  4739. }
  4740. if (preserveCase) {
  4741. finalReplacement = this.preserveCase(match.value, finalReplacement);
  4742. }
  4743. const before = text.slice(0, match.start);
  4744. const after = text.slice(match.end);
  4745. this.editor.value = before + finalReplacement + after;
  4746. this.editor.dispatchEvent(new Event('input', { bubbles: true }));
  4747. this.addHistory('replace', replacementTemplate);
  4748. return finalReplacement.length - match.value.length;
  4749. }
  4750. addHistory(type, query) {
  4751. if (!query) return;
  4752. const list = this.history[type];
  4753. const index = list.indexOf(query);
  4754. if (index !== -1) {
  4755. list.splice(index, 1);
  4756. }
  4757. list.unshift(query);
  4758. if (list.length > 10) {
  4759. list.pop();
  4760. }
  4761. }
  4762. }
  4763. // Verification helper for rich text blocks
  4764. function validateBlockSyntax(originalBlockText, newBlockText, scope) {
  4765. if (scope === 'latex') {
  4766. const origDisplay = (originalBlockText.match(/\$\$/g) || []).length;
  4767. const newDisplay = (newBlockText.match(/\$\$/g) || []).length;
  4768. const origInline = (originalBlockText.match(/[^\$]\$[^\$]/g) || []).length;
  4769. const newInline = (newBlockText.match(/[^\$]\$[^\$]/g) || []).length;
  4770. if (origDisplay !== newDisplay || origInline !== newInline) {
  4771. return { valid: false, reason: "LaTeX math block delimiters are unbalanced." };
  4772. }
  4773. }
  4774. if (scope === 'mermaid') {
  4775. const diagramTypePattern = /^(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram-v2|erDiagram|gantt|pie|quadrantChart|c4Context|mindmap|timeline|zenuml)/i;
  4776. if (!diagramTypePattern.test(newBlockText.trim())) {
  4777. return { valid: false, reason: "Missing diagram type definition (e.g. flowchart TD)." };
  4778. }
  4779. }
  4780. return { valid: true };
  4781. }
  4782. // Global Engine Instance
  4783. let frEngine = null;
  4784. let isFrDocked = false;
  4785. let dragOffset = { x: 0, y: 0 };
  4786. let isPanelDragging = false;
  4787. let lastFloatingLeft = null;
  4788. let lastFloatingTop = null;
  4789. let lastFloatingRight = null;
  4790. function initFindReplacePanelDrag() {
  4791. const handle = document.getElementById('find-replace-drag-handle');
  4792. const panel = document.getElementById('find-replace-modal');
  4793. if (!handle || !panel) return;
  4794. const startDrag = (clientX, clientY) => {
  4795. isPanelDragging = true;
  4796. dragOffset.x = clientX - panel.offsetLeft;
  4797. dragOffset.y = clientY - panel.offsetTop;
  4798. document.body.classList.add('resizing');
  4799. };
  4800. const moveDrag = (clientX, clientY) => {
  4801. const x = clientX - dragOffset.x;
  4802. const y = clientY - dragOffset.y;
  4803. // Keep panel inside viewport boundaries
  4804. const maxX = window.innerWidth - panel.offsetWidth;
  4805. const maxY = window.innerHeight - panel.offsetHeight;
  4806. const newLeft = `${Math.max(0, Math.min(maxX, x))}px`;
  4807. const newTop = `${Math.max(0, Math.min(maxY, y))}px`;
  4808. panel.style.left = newLeft;
  4809. panel.style.top = newTop;
  4810. panel.style.right = 'auto';
  4811. lastFloatingLeft = newLeft;
  4812. lastFloatingTop = newTop;
  4813. lastFloatingRight = 'auto';
  4814. };
  4815. const stopDrag = () => {
  4816. if (isPanelDragging) {
  4817. isPanelDragging = false;
  4818. document.body.classList.remove('resizing');
  4819. }
  4820. };
  4821. // Mouse events
  4822. handle.addEventListener('mousedown', (e) => {
  4823. if (isFrDocked) return;
  4824. if (window.innerWidth < 768) return; // Do NOT allow dragging on mobile layouts
  4825. if (e.target.closest('.find-replace-header-actions')) return;
  4826. startDrag(e.clientX, e.clientY);
  4827. });
  4828. document.addEventListener('mousemove', (e) => {
  4829. if (!isPanelDragging || isFrDocked) return;
  4830. moveDrag(e.clientX, e.clientY);
  4831. });
  4832. document.addEventListener('mouseup', stopDrag);
  4833. // Touch events for tablets
  4834. handle.addEventListener('touchstart', (e) => {
  4835. if (isFrDocked) return;
  4836. if (window.innerWidth < 768) return; // Do NOT allow dragging on mobile layouts
  4837. if (e.target.closest('.find-replace-header-actions')) return;
  4838. if (e.touches && e.touches[0]) {
  4839. startDrag(e.touches[0].clientX, e.touches[0].clientY);
  4840. }
  4841. }, { passive: true });
  4842. document.addEventListener('touchmove', (e) => {
  4843. if (!isPanelDragging || isFrDocked) return;
  4844. if (e.touches && e.touches[0]) {
  4845. moveDrag(e.touches[0].clientX, e.touches[0].clientY);
  4846. }
  4847. }, { passive: true });
  4848. document.addEventListener('touchend', stopDrag);
  4849. }
  4850. let frPreferredDocked = false;
  4851. function toggleFrDockMode(forceFloat = false) {
  4852. // If forceFloat is an Event (e.g. from click listener directly), treat as false
  4853. if (forceFloat instanceof Event || (forceFloat && typeof forceFloat === 'object')) {
  4854. forceFloat = false;
  4855. }
  4856. const panel = document.getElementById('find-replace-modal');
  4857. const dockBtn = document.getElementById('find-replace-dock');
  4858. const contentCont = document.querySelector('.content-container');
  4859. if (!panel || !dockBtn || !contentCont) return;
  4860. // Save active element focus and selection before DOM movement
  4861. const activeEl = document.activeElement;
  4862. const activeId = activeEl ? activeEl.id : null;
  4863. const isInput = activeEl && (activeEl.tagName === 'INPUT' || activeEl.tagName === 'SELECT' || activeEl.tagName === 'TEXTAREA');
  4864. let selStart = 0;
  4865. let selEnd = 0;
  4866. if (isInput && typeof activeEl.selectionStart === 'number') {
  4867. selStart = activeEl.selectionStart;
  4868. selEnd = activeEl.selectionEnd;
  4869. }
  4870. if (window.innerWidth < 1080 || forceFloat) {
  4871. isFrDocked = false;
  4872. panel.classList.remove('docked');
  4873. if (panel.parentElement !== document.body) {
  4874. document.body.appendChild(panel);
  4875. }
  4876. contentCont.classList.remove('fr-docked');
  4877. contentCont.style.setProperty('--dock-width', '0px');
  4878. panel.style.left = lastFloatingLeft !== null ? lastFloatingLeft : '';
  4879. panel.style.top = lastFloatingTop !== null ? lastFloatingTop : '';
  4880. panel.style.right = lastFloatingRight !== null ? lastFloatingRight : '';
  4881. dockBtn.innerHTML = '<i class="bi bi-layout-sidebar-reverse"></i>';
  4882. dockBtn.title = "Toggle Dock Mode";
  4883. panel.style.display = 'flex';
  4884. applyPaneWidths();
  4885. // Restore focus and selection
  4886. if (activeId) {
  4887. const el = document.getElementById(activeId);
  4888. if (el) {
  4889. el.focus();
  4890. if (isInput && typeof el.selectionStart === 'number') {
  4891. el.setSelectionRange(selStart, selEnd);
  4892. }
  4893. }
  4894. }
  4895. return;
  4896. }
  4897. isFrDocked = !isFrDocked;
  4898. // Save preference to localStorage
  4899. frPreferredDocked = isFrDocked;
  4900. localStorage.setItem('find-replace-docked', frPreferredDocked ? 'true' : 'false');
  4901. if (isFrDocked) {
  4902. panel.classList.add('docked');
  4903. panel.style.left = 'auto';
  4904. panel.style.top = 'auto';
  4905. panel.style.right = 'auto';
  4906. // Append panel to dock container (.content-container)
  4907. contentCont.appendChild(panel);
  4908. contentCont.classList.add('fr-docked');
  4909. contentCont.style.setProperty('--dock-width', '340px');
  4910. dockBtn.innerHTML = '<i class="bi bi-window"></i>';
  4911. dockBtn.title = "Toggle Floating Mode";
  4912. } else {
  4913. panel.classList.remove('docked');
  4914. // Reset position and float on body
  4915. document.body.appendChild(panel);
  4916. contentCont.classList.remove('fr-docked');
  4917. contentCont.style.setProperty('--dock-width', '0px');
  4918. panel.style.left = lastFloatingLeft !== null ? lastFloatingLeft : '';
  4919. panel.style.top = lastFloatingTop !== null ? lastFloatingTop : '';
  4920. panel.style.right = lastFloatingRight !== null ? lastFloatingRight : '';
  4921. dockBtn.innerHTML = '<i class="bi bi-layout-sidebar-reverse"></i>';
  4922. dockBtn.title = "Toggle Dock Mode";
  4923. }
  4924. // Ensure display is flex and recalculate split panes
  4925. panel.style.display = 'flex';
  4926. applyPaneWidths();
  4927. // Restore focus and selection after layout change
  4928. if (activeId) {
  4929. const el = document.getElementById(activeId);
  4930. if (el) {
  4931. el.focus();
  4932. if (isInput && typeof el.selectionStart === 'number') {
  4933. el.setSelectionRange(selStart, selEnd);
  4934. }
  4935. }
  4936. }
  4937. }
  4938. function updateFindControls() {
  4939. const total = findMatches.length;
  4940. const current = total && activeFindIndex >= 0 ? activeFindIndex + 1 : 0;
  4941. const countSpan = document.getElementById('find-replace-count');
  4942. if (countSpan) {
  4943. countSpan.textContent = `${current} of ${total} matches`;
  4944. }
  4945. const prevBtn = document.getElementById('find-prev');
  4946. const nextBtn = document.getElementById('find-next');
  4947. const replaceCurrentBtn = document.getElementById('find-replace-current');
  4948. const replaceAllBtn = document.getElementById('find-replace-all');
  4949. const hasMatches = total > 0;
  4950. const hasQuery = !!(findReplaceInput && findReplaceInput.value);
  4951. if (prevBtn) prevBtn.disabled = !hasMatches;
  4952. if (nextBtn) nextBtn.disabled = !hasMatches;
  4953. if (replaceCurrentBtn) replaceCurrentBtn.disabled = !hasMatches;
  4954. if (replaceAllBtn) replaceAllBtn.disabled = !hasQuery || !hasMatches;
  4955. }
  4956. function refreshFindMatches(options) {
  4957. clearTimeout(findRefreshTimeout);
  4958. findRefreshTimeout = null;
  4959. const opts = options || {};
  4960. const query = findReplaceInput ? findReplaceInput.value : '';
  4961. const errorBox = document.getElementById('find-replace-error');
  4962. const errorMsg = document.getElementById('regex-error-msg');
  4963. if (errorBox) errorBox.style.display = 'none';
  4964. if (!isFindModalOpen || !query) {
  4965. findMatches = [];
  4966. activeFindIndex = -1;
  4967. updateFindControls();
  4968. updateFindHighlights();
  4969. return;
  4970. }
  4971. const isRegex = document.getElementById('find-regex').classList.contains('active');
  4972. const isCaseSensitive = document.getElementById('find-case').classList.contains('active');
  4973. const isWholeWord = document.getElementById('find-word').classList.contains('active');
  4974. const scopeFilter = document.getElementById('find-replace-scope').value;
  4975. const findInSelection = document.getElementById('find-sel').classList.contains('active');
  4976. try {
  4977. findMatches = frEngine.executeSearch({
  4978. query,
  4979. isRegex,
  4980. isCaseSensitive,
  4981. isWholeWord,
  4982. scopeFilter,
  4983. findInSelection
  4984. });
  4985. } catch (err) {
  4986. findMatches = [];
  4987. activeFindIndex = -1;
  4988. if (errorBox && errorMsg) {
  4989. errorMsg.textContent = err.message;
  4990. errorBox.style.display = 'block';
  4991. }
  4992. }
  4993. const shouldResetActiveIndex = opts.resetIndex || query !== lastFindQuery;
  4994. if (shouldResetActiveIndex) {
  4995. activeFindIndex = findMatches.length ? 0 : -1;
  4996. } else if (activeFindIndex >= findMatches.length) {
  4997. activeFindIndex = findMatches.length - 1;
  4998. }
  4999. lastFindQuery = query;
  5000. updateFindControls();
  5001. updateFindHighlights();
  5002. if (shouldResetActiveIndex && findMatches.length && activeFindIndex >= 0) {
  5003. scrollActiveMatchIntoView(findMatches[activeFindIndex]);
  5004. }
  5005. updateHistoryDropdowns();
  5006. }
  5007. function scheduleFindRefresh(options) {
  5008. clearTimeout(findRefreshTimeout);
  5009. const text = markdownEditor ? markdownEditor.value || '' : '';
  5010. const delay = text.length >= LARGE_DOCUMENT_THRESHOLD ? LARGE_FIND_REFRESH_DELAY : FIND_REFRESH_DELAY;
  5011. findRefreshTimeout = setTimeout(function() {
  5012. findRefreshTimeout = null;
  5013. refreshFindMatches(options);
  5014. }, delay);
  5015. }
  5016. function selectActiveMatch() {
  5017. if (!findMatches.length || activeFindIndex < 0) return;
  5018. const match = findMatches[activeFindIndex];
  5019. markdownEditor.focus();
  5020. markdownEditor.setSelectionRange(match.start, match.end);
  5021. try {
  5022. scrollActiveMatchIntoView(match);
  5023. } catch (e) {
  5024. console.warn("Viewport centering scroll failed:", e);
  5025. }
  5026. }
  5027. function cycleFindMatch(direction) {
  5028. const totalMatches = findMatches.length;
  5029. if (!totalMatches) return;
  5030. activeFindIndex = (activeFindIndex + direction + totalMatches) % totalMatches;
  5031. updateFindControls();
  5032. updateFindHighlights();
  5033. selectActiveMatch();
  5034. }
  5035. function openFindReplaceModal() {
  5036. if (!findReplaceModal || !findReplaceInput) return;
  5037. if (!frEngine) {
  5038. frEngine = new FindReplaceEngine(markdownEditor);
  5039. }
  5040. isFindModalOpen = true;
  5041. const selected = markdownEditor.value.slice(markdownEditor.selectionStart, markdownEditor.selectionEnd);
  5042. if (selected && selected.length < 100) {
  5043. findReplaceInput.value = selected;
  5044. }
  5045. // Restore docked/floating mode preference
  5046. let wasDockedPref = localStorage.getItem('find-replace-docked') === 'true';
  5047. // Force floating-only mode on mobile/tablet viewports
  5048. if (window.innerWidth < 1080) {
  5049. wasDockedPref = false;
  5050. }
  5051. if (wasDockedPref) {
  5052. isFrDocked = false; // Set false so toggleFrDockMode() turns it to true
  5053. toggleFrDockMode();
  5054. } else {
  5055. isFrDocked = true; // Set true so toggleFrDockMode() turns it to false
  5056. toggleFrDockMode();
  5057. }
  5058. findReplaceModal.style.display = 'flex';
  5059. requestAnimationFrame(function() {
  5060. findReplaceInput.focus();
  5061. findReplaceInput.select();
  5062. });
  5063. refreshFindMatches({ resetIndex: true });
  5064. if (findMatches.length) {
  5065. selectActiveMatch();
  5066. }
  5067. }
  5068. function closeFindReplaceModal() {
  5069. isFindModalOpen = false;
  5070. const panel = document.getElementById('find-replace-modal');
  5071. const contentCont = document.querySelector('.content-container');
  5072. if (panel) {
  5073. panel.style.display = 'none';
  5074. if (isFrDocked) {
  5075. // Reset split layout styles when closed
  5076. if (contentCont) {
  5077. contentCont.classList.remove('fr-docked');
  5078. contentCont.style.setProperty('--dock-width', '0px');
  5079. applyPaneWidths();
  5080. }
  5081. }
  5082. }
  5083. findMatches = [];
  5084. activeFindIndex = -1;
  5085. updateFindControls();
  5086. updateFindHighlights();
  5087. }
  5088. function replaceCurrentMatch() {
  5089. if (!findMatches.length || activeFindIndex < 0) return;
  5090. const replacement = findReplaceWith ? findReplaceWith.value : '';
  5091. const match = findMatches[activeFindIndex];
  5092. const preserveCase = document.getElementById('replace-preserve-case').classList.contains('active');
  5093. const isRegex = document.getElementById('find-regex').classList.contains('active');
  5094. // Syntax validation
  5095. const scopeFilter = document.getElementById('find-replace-scope').value;
  5096. if (scopeFilter === 'latex' || scopeFilter === 'mermaid') {
  5097. const check = validateBlockSyntax(match.value, replacement, scopeFilter);
  5098. if (!check.valid) {
  5099. alert(`Blocked replacement: ${check.reason}`);
  5100. return;
  5101. }
  5102. }
  5103. frEngine.executeReplace(match, replacement, { preserveCase, isRegex });
  5104. refreshFindMatches();
  5105. if (findMatches.length) {
  5106. activeFindIndex = Math.min(activeFindIndex, findMatches.length - 1);
  5107. selectActiveMatch();
  5108. }
  5109. }
  5110. function replaceAllMatches() {
  5111. if (!findMatches.length) return;
  5112. const query = findReplaceInput ? findReplaceInput.value : '';
  5113. const replacement = findReplaceWith ? findReplaceWith.value : '';
  5114. const showDiff = document.getElementById('find-replace-diff-toggle').checked;
  5115. if (showDiff) {
  5116. renderDiffPreview();
  5117. return;
  5118. }
  5119. executeBulkReplace();
  5120. }
  5121. function executeBulkReplace() {
  5122. const replacement = findReplaceWith ? findReplaceWith.value : '';
  5123. const preserveCase = document.getElementById('replace-preserve-case').classList.contains('active');
  5124. const isRegex = document.getElementById('find-regex').classList.contains('active');
  5125. // Reverse sorting to replace from bottom up
  5126. const matchesCopy = [...findMatches];
  5127. matchesCopy.sort((a, b) => b.start - a.start);
  5128. for (const match of matchesCopy) {
  5129. frEngine.executeReplace(match, replacement, { preserveCase, isRegex });
  5130. }
  5131. refreshFindMatches({ resetIndex: true });
  5132. if (findMatches.length) {
  5133. selectActiveMatch();
  5134. }
  5135. }
  5136. function renderDiffPreview() {
  5137. const container = document.getElementById('find-replace-diff-container');
  5138. const modal = document.getElementById('find-replace-diff-modal');
  5139. if (!container || !modal) return;
  5140. const replacement = findReplaceWith ? findReplaceWith.value : '';
  5141. const preserveCase = document.getElementById('replace-preserve-case').classList.contains('active');
  5142. const isRegex = document.getElementById('find-regex').classList.contains('active');
  5143. const lines = markdownEditor.value.split('\n');
  5144. const matchesCopy = [...findMatches];
  5145. matchesCopy.sort((a, b) => b.start - a.start);
  5146. // Draft the replaced value in memory
  5147. let draftValue = markdownEditor.value;
  5148. for (const match of matchesCopy) {
  5149. let finalRepl = replacement;
  5150. if (isRegex) {
  5151. finalRepl = frEngine.applyCaptureGroups(match, finalRepl);
  5152. }
  5153. if (preserveCase) {
  5154. finalRepl = frEngine.preserveCase(match.value, finalRepl);
  5155. }
  5156. draftValue = draftValue.slice(0, match.start) + finalRepl + draftValue.slice(match.end);
  5157. }
  5158. const draftLines = draftValue.split('\n');
  5159. // PERF-007: Clear elements using textContent
  5160. container.textContent = '';
  5161. const fragment = document.createDocumentFragment();
  5162. const maxLines = Math.max(lines.length, draftLines.length);
  5163. for (let i = 0; i < maxLines; i++) {
  5164. const origLine = lines[i] !== undefined ? lines[i] : null;
  5165. const newLine = draftLines[i] !== undefined ? draftLines[i] : null;
  5166. if (origLine !== newLine) {
  5167. if (origLine !== null) {
  5168. const delLine = document.createElement('div');
  5169. delLine.className = 'diff-line deletion';
  5170. delLine.innerHTML = `<span class="diff-line-num">${i + 1}</span><span class="diff-line-content">- ${escapeHtml(origLine)}</span>`;
  5171. fragment.appendChild(delLine);
  5172. }
  5173. if (newLine !== null) {
  5174. const addLine = document.createElement('div');
  5175. addLine.className = 'diff-line addition';
  5176. addLine.innerHTML = `<span class="diff-line-num">${i + 1}</span><span class="diff-line-content">+ ${escapeHtml(newLine)}</span>`;
  5177. fragment.appendChild(addLine);
  5178. }
  5179. } else if (origLine !== null) {
  5180. // Show context for matching lines to prevent giant blank diff spaces
  5181. // Show context only if it surrounds a modified line
  5182. const hasDiffNearby = Array.from({length: 5}, (_, idx) => i - 2 + idx)
  5183. .some(lineIdx => lines[lineIdx] !== undefined && draftLines[lineIdx] !== undefined && lines[lineIdx] !== draftLines[lineIdx]);
  5184. if (hasDiffNearby) {
  5185. const ctxLine = document.createElement('div');
  5186. ctxLine.className = 'diff-line context';
  5187. ctxLine.innerHTML = `<span class="diff-line-num">${i + 1}</span><span class="diff-line-content"> ${escapeHtml(origLine)}</span>`;
  5188. fragment.appendChild(ctxLine);
  5189. }
  5190. }
  5191. }
  5192. container.appendChild(fragment);
  5193. openAppModal(modal, {
  5194. focusTarget: document.getElementById('find-replace-diff-confirm'),
  5195. onClose: () => closeAppModal(modal)
  5196. });
  5197. }
  5198. function updateHistoryDropdowns() {
  5199. const select = document.getElementById('find-replace-history');
  5200. if (!select || !frEngine) return;
  5201. // Preserve the first option
  5202. select.innerHTML = '<option value="">Recent queries...</option>';
  5203. frEngine.history.find.forEach(q => {
  5204. const opt = document.createElement('option');
  5205. opt.value = q;
  5206. opt.textContent = q;
  5207. select.appendChild(opt);
  5208. });
  5209. }
  5210. function initFindReplaceModal() {
  5211. const modal = document.getElementById('find-replace-modal');
  5212. if (!modal) return;
  5213. initFindReplacePanelDrag();
  5214. // Toggle options
  5215. const toggleButtons = ['find-case', 'find-word', 'find-regex', 'find-sel', 'replace-preserve-case', 'find-wrap'];
  5216. toggleButtons.forEach(id => {
  5217. const btn = document.getElementById(id);
  5218. if (btn) {
  5219. btn.addEventListener('click', () => {
  5220. const isActive = btn.classList.contains('active');
  5221. if (isActive) {
  5222. btn.classList.remove('active');
  5223. btn.setAttribute('aria-pressed', 'false');
  5224. } else {
  5225. btn.classList.add('active');
  5226. btn.setAttribute('aria-pressed', 'true');
  5227. }
  5228. refreshFindMatches({ resetIndex: true });
  5229. });
  5230. }
  5231. });
  5232. // History select handler
  5233. const historySelect = document.getElementById('find-replace-history');
  5234. if (historySelect) {
  5235. historySelect.addEventListener('change', () => {
  5236. if (historySelect.value) {
  5237. findReplaceInput.value = historySelect.value;
  5238. refreshFindMatches({ resetIndex: true });
  5239. }
  5240. });
  5241. }
  5242. // Scope select handler
  5243. const scopeSelect = document.getElementById('find-replace-scope');
  5244. if (scopeSelect) {
  5245. scopeSelect.addEventListener('change', () => {
  5246. refreshFindMatches({ resetIndex: true });
  5247. });
  5248. }
  5249. // Reset position handler
  5250. const resetBtn = document.getElementById('find-replace-reset');
  5251. const resetFooterBtn = document.getElementById('find-replace-reset-footer');
  5252. const doResetPosition = () => {
  5253. lastFloatingLeft = null;
  5254. lastFloatingTop = null;
  5255. lastFloatingRight = null;
  5256. modal.style.left = '';
  5257. modal.style.top = '';
  5258. modal.style.right = '';
  5259. };
  5260. if (resetBtn) {
  5261. resetBtn.addEventListener('click', doResetPosition);
  5262. }
  5263. if (resetFooterBtn) {
  5264. resetFooterBtn.addEventListener('click', doResetPosition);
  5265. }
  5266. // Dock toggle handler
  5267. const dockBtn = document.getElementById('find-replace-dock');
  5268. if (dockBtn) {
  5269. dockBtn.addEventListener('click', () => toggleFrDockMode(false));
  5270. }
  5271. // Advanced Drawer Toggle
  5272. const drawerToggle = document.getElementById('fr-drawer-toggle');
  5273. const drawerContent = document.getElementById('fr-drawer-content');
  5274. if (drawerToggle && drawerContent) {
  5275. drawerToggle.addEventListener('click', () => {
  5276. const isOpen = drawerContent.style.display === 'flex';
  5277. if (isOpen) {
  5278. drawerContent.style.display = 'none';
  5279. drawerToggle.setAttribute('aria-expanded', 'false');
  5280. drawerToggle.innerHTML = '<i class="bi bi-chevron-right me-1"></i> Advanced Options';
  5281. } else {
  5282. drawerContent.style.display = 'flex';
  5283. drawerToggle.setAttribute('aria-expanded', 'true');
  5284. drawerToggle.innerHTML = '<i class="bi bi-chevron-down me-1"></i> Advanced Options';
  5285. }
  5286. });
  5287. }
  5288. // Inputs
  5289. if (findReplaceInput) {
  5290. findReplaceInput.addEventListener('input', function() {
  5291. refreshFindMatches({ resetIndex: true });
  5292. });
  5293. findReplaceInput.addEventListener('keydown', function(event) {
  5294. if (event.key === 'Enter') {
  5295. event.preventDefault();
  5296. cycleFindMatch(event.shiftKey ? -1 : 1);
  5297. }
  5298. });
  5299. }
  5300. if (findReplaceWith) {
  5301. findReplaceWith.addEventListener('input', updateFindControls);
  5302. }
  5303. // Navigation buttons
  5304. const prevBtn = document.getElementById('find-prev');
  5305. const nextBtn = document.getElementById('find-next');
  5306. if (prevBtn) prevBtn.addEventListener('click', () => cycleFindMatch(-1));
  5307. if (nextBtn) nextBtn.addEventListener('click', () => cycleFindMatch(1));
  5308. // Action buttons
  5309. const currentBtn = document.getElementById('find-replace-current');
  5310. const allBtn = document.getElementById('find-replace-all');
  5311. if (currentBtn) currentBtn.addEventListener('click', replaceCurrentMatch);
  5312. if (allBtn) allBtn.addEventListener('click', replaceAllMatches);
  5313. // Close buttons
  5314. const closeBtn = document.getElementById('find-replace-close');
  5315. const closeIcon = document.getElementById('find-replace-close-icon');
  5316. if (closeBtn) closeBtn.addEventListener('click', closeFindReplaceModal);
  5317. if (closeIcon) closeIcon.addEventListener('click', closeFindReplaceModal);
  5318. // Diff modal confirmation triggers
  5319. const diffConfirmBtn = document.getElementById('find-replace-diff-confirm');
  5320. const diffCancelBtn = document.getElementById('find-replace-diff-cancel');
  5321. const diffCloseIcon = document.getElementById('find-replace-diff-close-icon');
  5322. const diffModal = document.getElementById('find-replace-diff-modal');
  5323. if (diffConfirmBtn) {
  5324. diffConfirmBtn.addEventListener('click', () => {
  5325. executeBulkReplace();
  5326. closeAppModal(diffModal);
  5327. });
  5328. }
  5329. if (diffCancelBtn) diffCancelBtn.addEventListener('click', () => closeAppModal(diffModal));
  5330. if (diffCloseIcon) diffCloseIcon.addEventListener('click', () => closeAppModal(diffModal));
  5331. }
  5332. function initAppModals() {
  5333. if (clearFormattingConfirm) {
  5334. clearFormattingConfirm.addEventListener('click', function() {
  5335. applyClearFormatting();
  5336. closeAppModal(clearFormattingModal);
  5337. });
  5338. }
  5339. if (clearFormattingCancel) {
  5340. clearFormattingCancel.addEventListener('click', function() { closeAppModal(clearFormattingModal); });
  5341. }
  5342. if (clearFormattingClose) {
  5343. clearFormattingClose.addEventListener('click', function() { closeAppModal(clearFormattingModal); });
  5344. }
  5345. if (helpModalClose) {
  5346. helpModalClose.addEventListener('click', function() { closeAppModal(helpModal); });
  5347. }
  5348. if (helpModalCloseIcon) {
  5349. helpModalCloseIcon.addEventListener('click', function() { closeAppModal(helpModal); });
  5350. }
  5351. if (aboutModalClose) {
  5352. aboutModalClose.addEventListener('click', function() { closeAppModal(aboutModal); });
  5353. }
  5354. if (aboutModalCloseIcon) {
  5355. aboutModalCloseIcon.addEventListener('click', function() { closeAppModal(aboutModal); });
  5356. }
  5357. }
  5358. function openHelpModal() {
  5359. if (helpModal) {
  5360. openAppModal(helpModal);
  5361. }
  5362. }
  5363. function openAboutModal() {
  5364. if (aboutModal) {
  5365. const aboutVersion = document.getElementById("about-version");
  5366. if (aboutVersion) {
  5367. aboutVersion.textContent = APP_VERSION;
  5368. }
  5369. openAppModal(aboutModal);
  5370. }
  5371. }
  5372. function openClearFormattingModal() {
  5373. if (clearFormattingModal) {
  5374. openAppModal(clearFormattingModal);
  5375. }
  5376. }
  5377. function runMarkdownTool(action, button) {
  5378. if (action === 'undo') {
  5379. executeUndo();
  5380. return;
  5381. }
  5382. if (action === 'redo') {
  5383. executeRedo();
  5384. return;
  5385. }
  5386. if (action === 'bold') wrapEditorSelection('**', '**', 'bold text');
  5387. else if (action === 'strike') wrapEditorSelection('~~', '~~', 'struck text');
  5388. else if (action === 'italic') wrapEditorSelection('*', '*', 'italic text');
  5389. else if (action === 'quote') transformEditorLines(function(line) { return line ? '> ' + line.replace(/^>\s?/, '') : '>'; });
  5390. else if (action === 'align-left') insertAlignmentBlock('left');
  5391. else if (action === 'align-center') insertAlignmentBlock('center');
  5392. else if (action === 'align-right') insertAlignmentBlock('right');
  5393. else if (action === 'title-case') transformSelectionOrCurrentLine(toTitleCase);
  5394. else if (action === 'uppercase') transformSelectionOrCurrentLine(function(text) { return text.toUpperCase(); });
  5395. else if (action === 'lowercase') transformSelectionOrCurrentLine(function(text) { return text.toLowerCase(); });
  5396. else if (action === 'heading') {
  5397. const level = parseInt(button.getAttribute('data-md-level') || '1', 10);
  5398. const marker = '#'.repeat(Math.max(1, Math.min(6, level))) + ' ';
  5399. transformEditorLines(function(line) { return marker + line.replace(/^#{1,6}\s+/, ''); });
  5400. } else if (action === 'unordered-list') {
  5401. applyMarkdownList('unordered');
  5402. } else if (action === 'ordered-list') {
  5403. applyMarkdownList('ordered');
  5404. } else if (action === 'horizontal-rule') insertMarkdownBlock('---\n');
  5405. else if (action === 'link') insertMarkdownLink();
  5406. else if (action === 'reference') insertMarkdownReference();
  5407. else if (action === 'image') insertMarkdownImage();
  5408. else if (action === 'inline-code') wrapEditorSelection('`', '`', 'code');
  5409. else if (action === 'code-block') insertMarkdownBlock('```js\n' + (markdownEditor.value.slice(markdownEditor.selectionStart, markdownEditor.selectionEnd) || 'console.log("Hello, Markdown!");') + '\n```\n');
  5410. else if (action === 'table') openTableModal();
  5411. else if (action === 'date-time') {
  5412. const now = new Date();
  5413. const datePart = now.toLocaleDateString('en-CA');
  5414. const timePart = now.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
  5415. const dayName = now.toLocaleDateString('en-US', { weekday: 'long' });
  5416. const timestamp = `${datePart} ${timePart} ${dayName}`;
  5417. replaceEditorRange(markdownEditor.selectionStart, markdownEditor.selectionEnd, timestamp, markdownEditor.selectionStart + timestamp.length, markdownEditor.selectionStart + timestamp.length);
  5418. } else if (action === 'emoji') {
  5419. openEmojiModal();
  5420. }
  5421. else if (action === 'symbols') openSymbolsModal();
  5422. else if (action === 'alert') openAlertModal();
  5423. else if (action === 'terminal-block') insertMarkdownBlock('```bash\nnpm run dev\n```\n');
  5424. else if (action === 'fullscreen') {
  5425. if (document.fullscreenElement && document.exitFullscreen) document.exitFullscreen();
  5426. else if (document.documentElement.requestFullscreen) document.documentElement.requestFullscreen();
  5427. } else if (action === 'clear-formatting') openClearFormattingModal();
  5428. else if (action === 'find') openFindReplaceModal();
  5429. else if (action === 'help') openHelpModal();
  5430. else if (action === 'info') openAboutModal();
  5431. }
  5432. function initMarkdownFormatToolbar() {
  5433. if (!markdownFormatToolbar) return;
  5434. markdownFormatToolbar.addEventListener('mousedown', function(e) {
  5435. if (e.target.closest('[data-md-action]')) e.preventDefault();
  5436. });
  5437. markdownFormatToolbar.addEventListener('click', function(e) {
  5438. const button = e.target.closest('[data-md-action]');
  5439. if (!button) return;
  5440. e.preventDefault();
  5441. runMarkdownTool(button.getAttribute('data-md-action'), button);
  5442. });
  5443. }
  5444. // Story 1.3: Resize Divider Functions
  5445. function initResizer() {
  5446. if (!resizeDivider) return;
  5447. // Set up WAI-ARIA accessibility tags
  5448. resizeDivider.setAttribute('role', 'separator');
  5449. resizeDivider.setAttribute('aria-orientation', 'vertical');
  5450. resizeDivider.setAttribute('tabindex', '0');
  5451. resizeDivider.setAttribute('aria-valuemin', MIN_PANE_PERCENT.toString());
  5452. resizeDivider.setAttribute('aria-valuemax', (100 - MIN_PANE_PERCENT).toString());
  5453. updateResizerAria();
  5454. resizeDivider.addEventListener('mousedown', startResize);
  5455. document.addEventListener('mousemove', handleResize);
  5456. document.addEventListener('mouseup', stopResize);
  5457. // Touch support for tablets (though disabled via CSS, keeping for future)
  5458. resizeDivider.addEventListener('touchstart', startResizeTouch);
  5459. document.addEventListener('touchmove', handleResizeTouch);
  5460. document.addEventListener('touchend', stopResize);
  5461. resizeDivider.addEventListener('keydown', handleResizerKeydown);
  5462. function handleResizerKeydown(e) {
  5463. if (currentViewMode !== 'split') return;
  5464. let delta = 0;
  5465. if (e.key === 'ArrowLeft') {
  5466. delta = -5; // Shift left by 5%
  5467. } else if (e.key === 'ArrowRight') {
  5468. delta = 5; // Shift right by 5%
  5469. } else {
  5470. return;
  5471. }
  5472. e.preventDefault();
  5473. editorWidthPercent = Math.max(MIN_PANE_PERCENT, Math.min(100 - MIN_PANE_PERCENT, editorWidthPercent + delta));
  5474. applyPaneWidths();
  5475. updateResizerAria();
  5476. }
  5477. function updateResizerAria() {
  5478. resizeDivider.setAttribute('aria-valuenow', Math.round(editorWidthPercent));
  5479. }
  5480. }
  5481. function startResize(e) {
  5482. if (window.innerWidth < 1080) return;
  5483. if (currentViewMode !== 'split') return;
  5484. e.preventDefault();
  5485. isResizing = true;
  5486. resizeDivider.classList.add('dragging');
  5487. document.body.classList.add('resizing');
  5488. }
  5489. function startResizeTouch(e) {
  5490. if (window.innerWidth < 1080) return;
  5491. if (currentViewMode !== 'split') return;
  5492. e.preventDefault();
  5493. isResizing = true;
  5494. resizeDivider.classList.add('dragging');
  5495. document.body.classList.add('resizing');
  5496. }
  5497. function handleResize(e) {
  5498. if (!isResizing) return;
  5499. const containerRect = contentContainer.getBoundingClientRect();
  5500. const containerWidth = containerRect.width;
  5501. const mouseX = e.clientX - containerRect.left;
  5502. // Calculate percentage
  5503. let newEditorPercent = (mouseX / containerWidth) * 100;
  5504. // Enforce minimum pane widths
  5505. newEditorPercent = Math.max(MIN_PANE_PERCENT, Math.min(100 - MIN_PANE_PERCENT, newEditorPercent));
  5506. editorWidthPercent = newEditorPercent;
  5507. applyPaneWidths();
  5508. }
  5509. function handleResizeTouch(e) {
  5510. if (!isResizing || !e.touches[0]) return;
  5511. const containerRect = contentContainer.getBoundingClientRect();
  5512. const containerWidth = containerRect.width;
  5513. const touchX = e.touches[0].clientX - containerRect.left;
  5514. let newEditorPercent = (touchX / containerWidth) * 100;
  5515. newEditorPercent = Math.max(MIN_PANE_PERCENT, Math.min(100 - MIN_PANE_PERCENT, newEditorPercent));
  5516. editorWidthPercent = newEditorPercent;
  5517. applyPaneWidths();
  5518. }
  5519. function stopResize() {
  5520. if (!isResizing) return;
  5521. isResizing = false;
  5522. resizeDivider.classList.remove('dragging');
  5523. document.body.classList.remove('resizing');
  5524. }
  5525. function applyPaneWidths() {
  5526. if (window.innerWidth < 1080) {
  5527. resetPaneWidths();
  5528. return;
  5529. }
  5530. if (currentViewMode !== 'split') return;
  5531. const previewPercent = 100 - editorWidthPercent;
  5532. editorPaneElement.style.flex = `0 0 calc((100% - var(--dock-width, 0px)) * ${editorWidthPercent / 100} - 4px)`;
  5533. previewPaneElement.style.flex = `0 0 calc((100% - var(--dock-width, 0px)) * ${previewPercent / 100} - 4px)`;
  5534. refreshEditorWidth();
  5535. scheduleLineNumberUpdate();
  5536. }
  5537. function resetPaneWidths() {
  5538. editorPaneElement.style.flex = '';
  5539. previewPaneElement.style.flex = '';
  5540. refreshEditorWidth();
  5541. }
  5542. function openMobileMenu() {
  5543. mobileMenuPanel.classList.add("active");
  5544. mobileMenuOverlay.classList.add("active");
  5545. }
  5546. function closeMobileMenu() {
  5547. mobileMenuPanel.classList.remove("active");
  5548. mobileMenuOverlay.classList.remove("active");
  5549. }
  5550. mobileMenuToggle.addEventListener("click", openMobileMenu);
  5551. mobileCloseMenu.addEventListener("click", closeMobileMenu);
  5552. mobileMenuOverlay.addEventListener("click", closeMobileMenu);
  5553. function updateMobileStats() {
  5554. mobileCharCount.textContent = charCountElement.textContent;
  5555. mobileWordCount.textContent = wordCountElement.textContent;
  5556. mobileReadingTime.textContent = readingTimeElement.textContent;
  5557. }
  5558. const origUpdateStats = updateDocumentStats;
  5559. updateDocumentStats = function() {
  5560. origUpdateStats();
  5561. updateMobileStats();
  5562. };
  5563. mobileToggleSync.addEventListener("click", () => {
  5564. toggleSyncScrolling();
  5565. if (syncScrollingEnabled) {
  5566. mobileToggleSync.innerHTML = '<i class="bi bi-link-45deg me-2"></i> Sync Off';
  5567. mobileToggleSync.classList.add("sync-disabled");
  5568. mobileToggleSync.classList.remove("sync-enabled");
  5569. mobileToggleSync.classList.add("sync-active");
  5570. } else {
  5571. mobileToggleSync.innerHTML = '<i class="bi bi-link me-2"></i> Sync On';
  5572. mobileToggleSync.classList.add("sync-enabled");
  5573. mobileToggleSync.classList.remove("sync-disabled");
  5574. mobileToggleSync.classList.remove("sync-active");
  5575. }
  5576. });
  5577. mobileImportBtn.addEventListener("click", () => {
  5578. if (typeof Neutralino !== 'undefined') {
  5579. nativeImportMarkdown();
  5580. } else {
  5581. fileInput.click();
  5582. }
  5583. });
  5584. mobileImportGithubBtn.addEventListener("click", () => {
  5585. closeMobileMenu();
  5586. openGitHubImportModal();
  5587. });
  5588. mobileExportMd.addEventListener("click", () => exportMd.click());
  5589. mobileExportHtml.addEventListener("click", () => exportHtml.click());
  5590. mobileExportPdf.addEventListener("click", () => exportPdf.click());
  5591. mobileCopyMarkdown.addEventListener("click", () => copyMarkdownButton.click());
  5592. mobileThemeToggle.addEventListener("click", () => {
  5593. themeToggle.click();
  5594. mobileThemeToggle.innerHTML = themeToggle.innerHTML + " Toggle Dark Mode";
  5595. });
  5596. const mobileNewTabBtn = document.getElementById("mobile-new-tab-btn");
  5597. if (mobileNewTabBtn) {
  5598. mobileNewTabBtn.addEventListener("click", function() {
  5599. newTab();
  5600. closeMobileMenu();
  5601. });
  5602. }
  5603. const mobileTabResetBtn = document.getElementById("mobile-tab-reset-btn");
  5604. if (mobileTabResetBtn) {
  5605. mobileTabResetBtn.addEventListener("click", function() {
  5606. closeMobileMenu();
  5607. resetAllTabs();
  5608. });
  5609. }
  5610. initTabs();
  5611. if (loadGlobalState().syncScrollingEnabled === false) toggleSyncScrolling();
  5612. updateMobileStats();
  5613. updateFindHighlights();
  5614. syncHighlightScroll();
  5615. // Defer DOM geometry measurement until after FCP/LCP critical paint path
  5616. setTimeout(function() {
  5617. initEditorGeometry();
  5618. refreshEditorWidth();
  5619. scheduleLineNumberUpdate();
  5620. }, 100);
  5621. // Initialize resizer - Story 1.3
  5622. initResizer();
  5623. function constrainFloatingPanelPosition() {
  5624. const panel = document.getElementById('find-replace-modal');
  5625. if (!panel || isFrDocked || panel.style.display === 'none') return;
  5626. if (window.innerWidth < 768) return; // Mobile layout forces fixed responsive positioning via CSS
  5627. // Only adjust if the inline style has custom dragged coordinates
  5628. if (!panel.style.left || panel.style.left === 'auto') return;
  5629. const leftVal = parseFloat(panel.style.left) || 0;
  5630. const topVal = parseFloat(panel.style.top) || 0;
  5631. const maxX = window.innerWidth - panel.offsetWidth;
  5632. const maxY = window.innerHeight - panel.offsetHeight;
  5633. const constrainedLeft = `${Math.max(0, Math.min(maxX, leftVal))}px`;
  5634. const constrainedTop = `${Math.max(0, Math.min(maxY, topVal))}px`;
  5635. panel.style.left = constrainedLeft;
  5636. panel.style.top = constrainedTop;
  5637. lastFloatingLeft = constrainedLeft;
  5638. lastFloatingTop = constrainedTop;
  5639. }
  5640. let resizeLayoutTimeout = null;
  5641. window.addEventListener('resize', () => {
  5642. clearTimeout(resizeLayoutTimeout);
  5643. resizeLayoutTimeout = setTimeout(function() {
  5644. initEditorGeometry();
  5645. refreshEditorWidth();
  5646. scheduleLineNumberUpdate();
  5647. if (window.innerWidth < 1080 && isFrDocked && isFindModalOpen) {
  5648. toggleFrDockMode(true);
  5649. }
  5650. constrainFloatingPanelPosition();
  5651. }, 100);
  5652. });
  5653. // View Mode Button Event Listeners - Story 1.1
  5654. viewModeButtons.forEach(btn => {
  5655. btn.addEventListener('click', function() {
  5656. const mode = this.getAttribute('data-view-mode');
  5657. setViewMode(resolveViewToggleMode(mode));
  5658. saveCurrentTabState();
  5659. });
  5660. });
  5661. // Story 1.4: Mobile View Mode Button Event Listeners
  5662. mobileViewModeButtons.forEach(btn => {
  5663. btn.addEventListener('click', function() {
  5664. const mode = this.getAttribute('data-mode');
  5665. setViewMode(mode);
  5666. saveCurrentTabState();
  5667. closeMobileMenu();
  5668. });
  5669. });
  5670. markdownEditor.addEventListener("input", function(e) {
  5671. handleKeystrokeHistory(e);
  5672. debouncedRender();
  5673. clearTimeout(saveTabStateTimeout);
  5674. saveTabStateTimeout = setTimeout(saveCurrentTabState, 500);
  5675. if (isFindModalOpen) {
  5676. scheduleFindRefresh();
  5677. } else {
  5678. updateFindHighlights();
  5679. }
  5680. scheduleLineNumberUpdate({
  5681. inputType: e && typeof e.inputType === 'string' ? e.inputType : '',
  5682. });
  5683. });
  5684. markdownEditor.addEventListener('keydown', updateLastCursor);
  5685. markdownEditor.addEventListener('keyup', updateLastCursor);
  5686. markdownEditor.addEventListener('mousedown', updateLastCursor);
  5687. markdownEditor.addEventListener('mouseup', updateLastCursor);
  5688. markdownEditor.addEventListener('focus', updateLastCursor);
  5689. initMarkdownFormatToolbar();
  5690. initFindReplaceModal();
  5691. initAppModals();
  5692. // Editor key handlers for list continuation and indentation
  5693. markdownEditor.addEventListener("keydown", function(e) {
  5694. if (handleListEnter(e)) {
  5695. return;
  5696. }
  5697. if (e.key === 'Tab') {
  5698. e.preventDefault();
  5699. const start = this.selectionStart;
  5700. const end = this.selectionEnd;
  5701. const value = this.value;
  5702. // Insert 2 spaces
  5703. const indent = ' '; // 2 spaces
  5704. // Update textarea value
  5705. this.value = value.substring(0, start) + indent + value.substring(end);
  5706. // Update cursor position
  5707. this.selectionStart = this.selectionEnd = start + indent.length;
  5708. // Trigger input event to update preview
  5709. this.dispatchEvent(new Event('input'));
  5710. }
  5711. });
  5712. markdownEditor.addEventListener("scroll", function() {
  5713. cachedScrollTop = this.scrollTop;
  5714. cachedScrollLeft = this.scrollLeft;
  5715. syncEditorToPreview();
  5716. scheduleEditorOverlayScrollSync();
  5717. });
  5718. previewPane.addEventListener("scroll", syncPreviewToEditor);
  5719. toggleSyncButton.addEventListener("click", toggleSyncScrolling);
  5720. if (directionToggle) {
  5721. directionToggle.addEventListener("click", function () {
  5722. const currentDir = markdownEditor ? markdownEditor.getAttribute("dir") : "ltr";
  5723. const direction = currentDir === "rtl" ? "ltr" : "rtl";
  5724. applyDirectionToContent(direction);
  5725. saveGlobalState({ direction });
  5726. updateDirectionToggleUI(direction);
  5727. });
  5728. }
  5729. themeToggle.addEventListener("click", function () {
  5730. _lastRenderedContent = null;
  5731. const theme =
  5732. document.documentElement.getAttribute("data-theme") === "dark"
  5733. ? "light"
  5734. : "dark";
  5735. document.documentElement.setAttribute("data-theme", theme);
  5736. saveGlobalState({ theme });
  5737. if (theme === "dark") {
  5738. themeToggle.innerHTML = '<i class="bi bi-sun"></i>';
  5739. } else {
  5740. themeToggle.innerHTML = '<i class="bi bi-moon"></i>';
  5741. }
  5742. // PERF-004: Only re-render Mermaid diagrams on theme change instead of full renderMarkdown()
  5743. // CSS custom properties handle all other theme transitions automatically.
  5744. // PERF-002: Guard mermaid re-render — skip if not loaded yet
  5745. if (typeof mermaid !== 'undefined') {
  5746. initMermaid(true); // Force re-init with new theme
  5747. try {
  5748. const mermaidNodes = markdownPreview.querySelectorAll('.mermaid');
  5749. if (mermaidNodes.length > 0) {
  5750. // Clear existing rendered Mermaid SVGs and re-render with new theme
  5751. mermaidNodes.forEach(function(node) {
  5752. // Restore original diagram code to prevent parsing already-rendered SVG as source
  5753. const originalCode = node.getAttribute('data-original-code');
  5754. if (originalCode) {
  5755. const decodedCode = decodeURIComponent(originalCode);
  5756. const escapedCode = decodedCode
  5757. .replace(/&/g, "&amp;")
  5758. .replace(/</g, "&lt;")
  5759. .replace(/>/g, "&gt;");
  5760. node.innerHTML = escapedCode;
  5761. }
  5762. node.removeAttribute('data-processed');
  5763. const container = node.closest('.mermaid-container');
  5764. if (container) {
  5765. container.classList.add('is-loading');
  5766. const oldToolbar = container.querySelector('.mermaid-toolbar');
  5767. if (oldToolbar) oldToolbar.remove();
  5768. }
  5769. });
  5770. Promise.resolve(mermaid.init(undefined, mermaidNodes))
  5771. .then(function() {
  5772. markdownPreview.querySelectorAll('.mermaid-container.is-loading').forEach(function(c) {
  5773. c.classList.remove('is-loading');
  5774. });
  5775. addMermaidToolbars();
  5776. })
  5777. .catch(function(e) {
  5778. console.warn('Mermaid theme re-render failed:', e);
  5779. markdownPreview.querySelectorAll('.mermaid-container.is-loading').forEach(function(c) {
  5780. c.classList.remove('is-loading');
  5781. });
  5782. });
  5783. }
  5784. } catch (e) {
  5785. console.warn('Mermaid theme re-render failed:', e);
  5786. }
  5787. }
  5788. });
  5789. async function nativeSaveMarkdown() {
  5790. try {
  5791. const content = markdownEditor.value;
  5792. const result = await Neutralino.os.showSaveDialog("Save Markdown File", {
  5793. filters: [
  5794. { name: "Markdown files (*.md)", extensions: ["md", "markdown"] },
  5795. { name: "All files (*.*)", extensions: ["*"] }
  5796. ]
  5797. });
  5798. if (result) {
  5799. await Neutralino.filesystem.writeFile(result, content);
  5800. const fileName = result.split(/[/\\]/).pop().replace(/\.(md|markdown)$/i, "");
  5801. const activeTab = tabs.find(function(t) { return t.id === activeTabId; });
  5802. if (activeTab) {
  5803. activeTab.title = fileName;
  5804. activeTab.content = content;
  5805. saveTabsToStorage(tabs);
  5806. renderTabBar(tabs, activeTabId);
  5807. }
  5808. }
  5809. } catch (e) {
  5810. console.error("Native save failed:", e);
  5811. alert("Native save failed: " + e.message);
  5812. }
  5813. }
  5814. async function nativeSaveHtml(htmlContent) {
  5815. try {
  5816. const result = await Neutralino.os.showSaveDialog("Save HTML document", {
  5817. filters: [
  5818. { name: "HTML documents (*.html)", extensions: ["html", "htm"] }
  5819. ]
  5820. });
  5821. if (result) {
  5822. await Neutralino.filesystem.writeFile(result, htmlContent);
  5823. }
  5824. } catch (e) {
  5825. console.error("Native HTML save failed:", e);
  5826. alert("Native HTML save failed: " + e.message);
  5827. }
  5828. }
  5829. async function nativeImportMarkdown() {
  5830. try {
  5831. const result = await Neutralino.os.showOpenDialog("Open Markdown file", {
  5832. filters: [
  5833. { name: "Markdown files (*.md)", extensions: ["md", "markdown"] },
  5834. { name: "All files (*.*)", extensions: ["*"] }
  5835. ],
  5836. multiSelections: true
  5837. });
  5838. if (result && result.length > 0) {
  5839. for (const filePath of result) {
  5840. const content = await Neutralino.filesystem.readFile(filePath);
  5841. const fileName = filePath.split(/[/\\]/).pop().replace(/\.(md|markdown)$/i, "");
  5842. newTab(content, fileName);
  5843. }
  5844. }
  5845. } catch (e) {
  5846. console.error("Native import failed:", e);
  5847. alert("Native import failed: " + e.message);
  5848. }
  5849. }
  5850. if (importFromFileButton) {
  5851. importFromFileButton.addEventListener("click", function (e) {
  5852. e.preventDefault();
  5853. if (typeof Neutralino !== 'undefined') {
  5854. nativeImportMarkdown();
  5855. } else {
  5856. fileInput.click();
  5857. }
  5858. });
  5859. }
  5860. if (importFromGithubButton) {
  5861. importFromGithubButton.addEventListener("click", function (e) {
  5862. e.preventDefault();
  5863. openGitHubImportModal();
  5864. });
  5865. }
  5866. if (githubImportSubmitBtn) {
  5867. githubImportSubmitBtn.addEventListener("click", handleGitHubImportSubmit);
  5868. }
  5869. if (githubImportCancelBtn) {
  5870. githubImportCancelBtn.addEventListener("click", closeGitHubImportModal);
  5871. }
  5872. const handleGitHubImportInputKeydown = function(e) {
  5873. if (e.key === "Enter") {
  5874. e.preventDefault();
  5875. handleGitHubImportSubmit();
  5876. } else if (e.key === "Escape") {
  5877. closeGitHubImportModal();
  5878. }
  5879. };
  5880. if (githubImportUrlInput) {
  5881. githubImportUrlInput.addEventListener("keydown", handleGitHubImportInputKeydown);
  5882. }
  5883. if (githubImportFileSelect) {
  5884. githubImportFileSelect.addEventListener("keydown", handleGitHubImportInputKeydown);
  5885. }
  5886. if (githubImportSelectAllBtn) {
  5887. githubImportSelectAllBtn.addEventListener("click", function() {
  5888. const allPaths = availableGitHubImportPaths.slice();
  5889. const shouldSelectAll = selectedGitHubImportPaths.size !== allPaths.length;
  5890. setGitHubSelectedPaths(shouldSelectAll ? allPaths : []);
  5891. });
  5892. }
  5893. fileInput.addEventListener("change", function (e) {
  5894. const file = e.target.files[0];
  5895. if (file) {
  5896. importMarkdownFile(file);
  5897. }
  5898. this.value = "";
  5899. });
  5900. exportMd.addEventListener("click", function () {
  5901. if (typeof Neutralino !== 'undefined') {
  5902. nativeSaveMarkdown();
  5903. return;
  5904. }
  5905. try {
  5906. const blob = new Blob([markdownEditor.value], {
  5907. type: "text/markdown;charset=utf-8",
  5908. });
  5909. saveAs(blob, "document.md");
  5910. } catch (e) {
  5911. console.error("Export failed:", e);
  5912. alert("Export failed: " + e.message);
  5913. }
  5914. });
  5915. exportHtml.addEventListener("click", function () {
  5916. try {
  5917. const { frontmatter, body } = parseFrontmatter(markdownEditor.value);
  5918. const tableHtml = frontmatter ? renderFrontmatterTable(frontmatter) : '';
  5919. const referenceData = extractReferenceDefinitions(body);
  5920. const html = tableHtml + marked.parse(referenceData.cleanedMarkdown);
  5921. const sanitizedHtml = DOMPurify.sanitize(html, {
  5922. ADD_TAGS: ['mjx-container', 'input'],
  5923. ADD_ATTR: ['id', 'class', 'style', 'align', 'type', 'checked', 'disabled', 'data-original-code'],
  5924. ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel|blob):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
  5925. });
  5926. const tempContainer = document.createElement("div");
  5927. tempContainer.innerHTML = sanitizedHtml;
  5928. applyReferencePreviewLinks(tempContainer, referenceData.definitions);
  5929. enhanceGitHubAlerts(tempContainer);
  5930. const enhancedHtml = tempContainer.innerHTML;
  5931. const isDarkTheme =
  5932. document.documentElement.getAttribute("data-theme") === "dark";
  5933. const cssTheme = isDarkTheme
  5934. ? "https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.3.0/github-markdown-dark.min.css"
  5935. : "https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.3.0/github-markdown.min.css";
  5936. const fullHtml = `<!DOCTYPE html>
  5937. <html lang="en">
  5938. <head>
  5939. <meta charset="UTF-8">
  5940. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5941. <title>Markdown Export</title>
  5942. <link rel="stylesheet" href="${cssTheme}">
  5943. <script>
  5944. window.MathJax = {
  5945. loader: { load: ['[tex]/ams', '[tex]/boldsymbol'] },
  5946. tex: {
  5947. inlineMath: [['$', '$'], ['\\\\(', '\\\\)']],
  5948. displayMath: [['$$', '$$'], ['\\\\[', '\\\\]']],
  5949. processEscapes: true,
  5950. packages: { '[+]': ['ams', 'boldsymbol'] }
  5951. }
  5952. };
  5953. </script>
  5954. <script defer src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.min.js"></script>
  5955. <script src="https://cdn.jsdelivr.net/npm/mermaid@11.6.0/dist/mermaid.min.js"></script>
  5956. <style>
  5957. html {
  5958. background-color: ${isDarkTheme ? "#0d1117" : "#ffffff"};
  5959. }
  5960. body {
  5961. margin: 0;
  5962. background-color: ${isDarkTheme ? "#0d1117" : "#ffffff"};
  5963. color: ${isDarkTheme ? "#c9d1d9" : "#24292e"};
  5964. }
  5965. .markdown-body {
  5966. box-sizing: border-box;
  5967. min-width: 200px;
  5968. max-width: 100%;
  5969. width: fit-content;
  5970. margin: 0 auto;
  5971. padding: 45px;
  5972. background-color: ${isDarkTheme ? "#0d1117" : "#ffffff"};
  5973. color: ${isDarkTheme ? "#c9d1d9" : "#24292e"};
  5974. }
  5975. .markdown-body > p,
  5976. .markdown-body > ul,
  5977. .markdown-body > ol,
  5978. .markdown-body > blockquote,
  5979. .markdown-body > h1,
  5980. .markdown-body > h2,
  5981. .markdown-body > h3,
  5982. .markdown-body > h4,
  5983. .markdown-body > h5,
  5984. .markdown-body > h6,
  5985. .markdown-body > pre,
  5986. .markdown-body > table,
  5987. .markdown-body > details,
  5988. .markdown-body > dl,
  5989. .markdown-body > hr {
  5990. max-width: 980px;
  5991. margin-left: auto !important;
  5992. margin-right: auto !important;
  5993. }
  5994. /* Syntax Highlighting */
  5995. .hljs-doctag, .hljs-keyword, .hljs-template-tag, .hljs-template-variable, .hljs-type, .hljs-variable.language_ { color: ${isDarkTheme ? "#ff7b72" : "#d73a49"}; }
  5996. .hljs-title, .hljs-title.class_, .hljs-title.class_.inherited__, .hljs-title.function_ { color: ${isDarkTheme ? "#d2a8ff" : "#6f42c1"}; }
  5997. .hljs-attr, .hljs-attribute, .hljs-literal, .hljs-meta, .hljs-number, .hljs-operator, .hljs-variable, .hljs-selector-attr, .hljs-selector-class, .hljs-selector-id { color: ${isDarkTheme ? "#79c0ff" : "#005cc5"}; }
  5998. .hljs-regexp, .hljs-string, .hljs-meta .hljs-string { color: ${isDarkTheme ? "#a5d6ff" : "#032f62"}; }
  5999. .hljs-built_in, .hljs-symbol { color: ${isDarkTheme ? "#ffa657" : "#e36209"}; }
  6000. .hljs-comment, .hljs-code, .hljs-formula { color: ${isDarkTheme ? "#8b949e" : "#6a737d"}; }
  6001. .hljs-name, .hljs-quote, .hljs-selector-tag, .hljs-selector-pseudo { color: ${isDarkTheme ? "#7ee787" : "#22863a"}; }
  6002. .hljs-subst { color: ${isDarkTheme ? "#c9d1d9" : "#24292e"}; }
  6003. .hljs-section { color: ${isDarkTheme ? "#1f6feb" : "#005cc5"}; font-weight: bold; }
  6004. .hljs-bullet { color: ${isDarkTheme ? "#79c0ff" : "#005cc5"}; }
  6005. .hljs-emphasis { font-style: italic; }
  6006. .hljs-strong { font-weight: bold; }
  6007. .hljs-addition { color: ${isDarkTheme ? "#aff5b4" : "#22863a"}; background-color: ${isDarkTheme ? "#033a16" : "#f0fff4"}; }
  6008. .hljs-deletion { color: ${isDarkTheme ? "#ffdcd7" : "#b31d28"}; background-color: ${isDarkTheme ? "#67060c" : "#ffeef0"}; }
  6009. .markdown-alert {
  6010. padding: 0.5rem 1rem;
  6011. margin-bottom: 16px;
  6012. border-left: 0.25em solid;
  6013. border-radius: 0.375rem;
  6014. }
  6015. .markdown-alert > :last-child {
  6016. margin-bottom: 0;
  6017. }
  6018. .markdown-alert-title {
  6019. margin: 0 0 8px;
  6020. font-weight: 600;
  6021. line-height: 1.25;
  6022. display: flex;
  6023. align-items: center;
  6024. gap: 8px;
  6025. }
  6026. .markdown-alert-icon {
  6027. display: inline-flex;
  6028. width: 16px;
  6029. height: 16px;
  6030. }
  6031. .markdown-alert-icon svg {
  6032. width: 16px;
  6033. height: 16px;
  6034. fill: currentColor;
  6035. }
  6036. .markdown-alert-note { color: ${isDarkTheme ? "#4493f8" : "#0969da"}; border-left-color: ${isDarkTheme ? "#4493f8" : "#0969da"}; background-color: ${isDarkTheme ? "rgba(31, 111, 235, 0.15)" : "#ddf4ff"}; }
  6037. .markdown-alert-tip { color: ${isDarkTheme ? "#3fb950" : "#1a7f37"}; border-left-color: ${isDarkTheme ? "#3fb950" : "#1a7f37"}; background-color: ${isDarkTheme ? "rgba(35, 134, 54, 0.15)" : "#dafbe1"}; }
  6038. .markdown-alert-important { color: ${isDarkTheme ? "#ab7df8" : "#8250df"}; border-left-color: ${isDarkTheme ? "#ab7df8" : "#8250df"}; background-color: ${isDarkTheme ? "rgba(137, 87, 229, 0.15)" : "#fbefff"}; }
  6039. .markdown-alert-warning { color: ${isDarkTheme ? "#d29922" : "#9a6700"}; border-left-color: ${isDarkTheme ? "#d29922" : "#9a6700"}; background-color: ${isDarkTheme ? "rgba(210, 153, 34, 0.18)" : "#fff8c5"}; }
  6040. .markdown-alert-caution { color: ${isDarkTheme ? "#f85149" : "#cf222e"}; border-left-color: ${isDarkTheme ? "#f85149" : "#cf222e"}; background-color: ${isDarkTheme ? "rgba(248, 81, 73, 0.18)" : "#ffebe9"}; }
  6041. .markdown-alert > *:not(.markdown-alert-title) { color: ${isDarkTheme ? "#c9d1d9" : "#24292e"}; }
  6042. .frontmatter-table {
  6043. width: 100%;
  6044. border-collapse: collapse;
  6045. margin-bottom: 24px;
  6046. font-size: 14px;
  6047. }
  6048. .frontmatter-table th,
  6049. .frontmatter-table td {
  6050. border: 1px solid ${isDarkTheme ? "#30363d" : "#e1e4e8"};
  6051. padding: 8px 12px;
  6052. text-align: left;
  6053. }
  6054. .frontmatter-table th {
  6055. font-weight: 600;
  6056. background-color: ${isDarkTheme ? "#161b22" : "#f6f8fa"};
  6057. width: 150px;
  6058. }
  6059. /* Footnote styles */
  6060. .footnotes {
  6061. margin-top: 1.5rem;
  6062. font-size: 0.9em;
  6063. border-top: 1px solid ${isDarkTheme ? "#30363d" : "#eaecef"};
  6064. padding-top: 8px;
  6065. }
  6066. .footnotes ol {
  6067. padding-left: 1.5em;
  6068. }
  6069. .footnotes ol > li::marker {
  6070. content: "[" counter(list-item) "] ";
  6071. font-weight: 600;
  6072. }
  6073. .footnotes li > p {
  6074. margin: 0.2em 0;
  6075. }
  6076. .footnote-ref a,
  6077. .footnote-backref {
  6078. text-decoration: none;
  6079. }
  6080. .footnote-backref {
  6081. margin-left: 0.4em;
  6082. }
  6083. a.reference-link {
  6084. font-size: 0.75em;
  6085. letter-spacing: -0.02em;
  6086. line-height: 1;
  6087. vertical-align: super;
  6088. position: relative;
  6089. top: 0.08em;
  6090. }
  6091. /* Mermaid and Math styles */
  6092. .mermaid-container {
  6093. position: relative;
  6094. margin-bottom: 16px;
  6095. }
  6096. .math-block {
  6097. margin: 1em 0;
  6098. overflow-x: auto;
  6099. text-align: center;
  6100. }
  6101. @media (max-width: 767px) {
  6102. .markdown-body {
  6103. padding: 15px;
  6104. }
  6105. }
  6106. </style>
  6107. </head>
  6108. <body>
  6109. <article class="markdown-body">
  6110. ${enhancedHtml}
  6111. </article>
  6112. <script>
  6113. function fitMarkdownExportToContent() {
  6114. var article = document.querySelector('.markdown-body');
  6115. if (!article) return;
  6116. article.style.width = '';
  6117. article.style.maxWidth = '980px';
  6118. var overflow = article.scrollWidth - article.clientWidth;
  6119. if (overflow <= 1) return;
  6120. var styles = window.getComputedStyle(article);
  6121. var paddingLeft = parseFloat(styles.paddingLeft) || 0;
  6122. var paddingRight = parseFloat(styles.paddingRight) || 0;
  6123. var borderRight = parseFloat(styles.borderRightWidth) || 0;
  6124. var borderLeft = parseFloat(styles.borderLeftWidth) || 0;
  6125. var boxSizing = styles.boxSizing;
  6126. var requiredWidth = boxSizing === 'border-box'
  6127. ? Math.ceil(article.scrollWidth + borderLeft + borderRight)
  6128. : Math.ceil(article.scrollWidth - paddingLeft - paddingRight);
  6129. article.style.width = requiredWidth + 'px';
  6130. article.style.maxWidth = 'none';
  6131. }
  6132. function queueMarkdownExportFit() {
  6133. window.requestAnimationFrame(function () {
  6134. window.requestAnimationFrame(fitMarkdownExportToContent);
  6135. });
  6136. }
  6137. window.addEventListener('load', function () {
  6138. var mathReady = Promise.resolve();
  6139. var article = document.querySelector('.markdown-body');
  6140. if (article && window.MutationObserver) {
  6141. new MutationObserver(queueMarkdownExportFit).observe(article, {
  6142. childList: true,
  6143. subtree: true
  6144. });
  6145. }
  6146. if (window.MathJax && typeof window.MathJax.typesetPromise === 'function') {
  6147. mathReady = window.MathJax.typesetPromise().catch(function (err) {
  6148. console.warn('MathJax typeset failed:', err);
  6149. });
  6150. }
  6151. if (window.mermaid) {
  6152. try {
  6153. window.mermaid.initialize({ startOnLoad: true, theme: '${isDarkTheme ? "dark" : "default"}' });
  6154. } catch (e) {
  6155. console.warn('Mermaid initialization failed:', e);
  6156. }
  6157. }
  6158. mathReady.finally(queueMarkdownExportFit);
  6159. queueMarkdownExportFit();
  6160. });
  6161. window.addEventListener('resize', queueMarkdownExportFit);
  6162. </script>
  6163. </body>
  6164. </html>`;
  6165. const blob = new Blob([fullHtml], { type: "text/html;charset=utf-8" });
  6166. if (typeof Neutralino !== 'undefined') {
  6167. nativeSaveHtml(fullHtml);
  6168. } else {
  6169. saveAs(blob, "document.html");
  6170. }
  6171. } catch (e) {
  6172. console.error("HTML export failed:", e);
  6173. alert("HTML export failed: " + e.message);
  6174. }
  6175. });
  6176. // ============================================
  6177. // Page-Break Detection Functions (Story 1.1)
  6178. // ============================================
  6179. // Page configuration constants for A4 PDF export
  6180. const PAGE_CONFIG = {
  6181. a4Width: 210, // mm
  6182. a4Height: 297, // mm
  6183. margin: 15, // mm each side
  6184. contentWidth: 180, // 210 - 30 (margins)
  6185. contentHeight: 267, // 297 - 30 (margins)
  6186. windowWidth: 1000, // html2canvas config
  6187. scale: 2 // html2canvas scale factor
  6188. };
  6189. const PDF_EXPORT_DEBUG = true;
  6190. let activePdfExport = null;
  6191. class PdfExportCancelledError extends Error {
  6192. constructor() {
  6193. super("PDF generation cancelled.");
  6194. this.name = "PdfExportCancelledError";
  6195. }
  6196. }
  6197. function logPdfExportDebug(...args) {
  6198. if (PDF_EXPORT_DEBUG) console.log(...args);
  6199. }
  6200. function throwIfPdfExportAborted(signal) {
  6201. if (signal && signal.aborted) {
  6202. throw new PdfExportCancelledError();
  6203. }
  6204. }
  6205. function runPdfAbortable(state, promise) {
  6206. throwIfPdfExportAborted(state.signal);
  6207. return new Promise((resolve, reject) => {
  6208. const handleAbort = () => reject(new PdfExportCancelledError());
  6209. state.signal.addEventListener("abort", handleAbort, { once: true });
  6210. Promise.resolve(promise)
  6211. .then(resolve, reject)
  6212. .finally(() => {
  6213. state.signal.removeEventListener("abort", handleAbort);
  6214. });
  6215. });
  6216. }
  6217. function formatPdfExportEta(ms) {
  6218. if (!Number.isFinite(ms) || ms <= 0) return "Calculating...";
  6219. const seconds = Math.ceil(ms / 1000);
  6220. if (seconds < 60) return `${seconds}s`;
  6221. const minutes = Math.floor(seconds / 60);
  6222. const remainder = seconds % 60;
  6223. return remainder ? `${minutes}m ${remainder}s` : `${minutes}m`;
  6224. }
  6225. function createPdfProgressState() {
  6226. const abortController = new AbortController();
  6227. const overlay = document.createElement("div");
  6228. overlay.className = "pdf-progress-overlay";
  6229. overlay.setAttribute("role", "dialog");
  6230. overlay.setAttribute("aria-modal", "true");
  6231. overlay.setAttribute("aria-labelledby", "pdf-progress-title");
  6232. overlay.innerHTML = `
  6233. <div class="pdf-progress-modal">
  6234. <div class="pdf-progress-header">
  6235. <p class="pdf-progress-title" id="pdf-progress-title">Generating PDF</p>
  6236. <button type="button" class="modal-close-btn pdf-progress-cancel-icon" aria-label="Cancel PDF generation" title="Cancel PDF generation">
  6237. <i class="bi bi-x-lg"></i>
  6238. </button>
  6239. </div>
  6240. <div class="pdf-progress-percent">0%</div>
  6241. <div class="pdf-progress-track"
  6242. role="progressbar"
  6243. aria-label="PDF generation progress"
  6244. aria-valuemin="0"
  6245. aria-valuemax="100"
  6246. aria-valuenow="0">
  6247. <div class="pdf-progress-fill"></div>
  6248. </div>
  6249. <div class="pdf-progress-details">
  6250. <div class="pdf-progress-detail">
  6251. <span>Current Step</span>
  6252. <strong class="pdf-progress-step">Preparing</strong>
  6253. </div>
  6254. <div class="pdf-progress-detail">
  6255. <span>Estimated remaining</span>
  6256. <strong class="pdf-progress-eta">Calculating...</strong>
  6257. </div>
  6258. </div>
  6259. <div class="pdf-progress-actions">
  6260. <button type="button" class="reset-modal-btn reset-modal-cancel pdf-progress-cancel">Cancel</button>
  6261. </div>
  6262. </div>`;
  6263. const state = {
  6264. abortController,
  6265. signal: abortController.signal,
  6266. startedAt: performance.now(),
  6267. overlay,
  6268. fill: overlay.querySelector(".pdf-progress-fill"),
  6269. percentText: overlay.querySelector(".pdf-progress-percent"),
  6270. progressBar: overlay.querySelector(".pdf-progress-track"),
  6271. stepText: overlay.querySelector(".pdf-progress-step"),
  6272. etaText: overlay.querySelector(".pdf-progress-eta"),
  6273. cancelButtons: overlay.querySelectorAll(".pdf-progress-cancel, .pdf-progress-cancel-icon"),
  6274. triggerHtml: new Map(),
  6275. tempElement: null,
  6276. cleanedUp: false
  6277. };
  6278. state.cancelButtons.forEach(button => {
  6279. button.addEventListener("click", () => cancelPdfExport(state));
  6280. });
  6281. return state;
  6282. }
  6283. function updatePdfProgress(state, percent, step) {
  6284. if (!state || state.cleanedUp) return;
  6285. const nextPercent = Math.max(0, Math.min(100, Math.round(percent)));
  6286. state.fill.style.width = `${nextPercent}%`;
  6287. state.percentText.textContent = `${nextPercent}%`;
  6288. state.progressBar.setAttribute("aria-valuenow", String(nextPercent));
  6289. state.stepText.textContent = step;
  6290. const elapsed = performance.now() - state.startedAt;
  6291. const eta = nextPercent > 5 && nextPercent < 100
  6292. ? (elapsed / nextPercent) * (100 - nextPercent)
  6293. : 0;
  6294. state.etaText.textContent = nextPercent >= 100 ? "Complete" : formatPdfExportEta(eta);
  6295. }
  6296. function setPdfExportTriggersBusy(state, busy) {
  6297. const triggers = [exportPdf, mobileExportPdf].filter(Boolean);
  6298. triggers.forEach((trigger, index) => {
  6299. if (busy) {
  6300. state.triggerHtml.set(trigger, trigger.innerHTML);
  6301. trigger.innerHTML = index === 0
  6302. ? '<i class="bi bi-hourglass-split"></i> Generating...'
  6303. : '<i class="bi bi-hourglass-split me-2"></i> Generating PDF...';
  6304. trigger.classList.add("pdf-export-loading");
  6305. trigger.setAttribute("aria-disabled", "true");
  6306. trigger.disabled = true;
  6307. } else {
  6308. if (state.triggerHtml.has(trigger)) {
  6309. trigger.innerHTML = state.triggerHtml.get(trigger);
  6310. }
  6311. trigger.classList.remove("pdf-export-loading");
  6312. trigger.removeAttribute("aria-disabled");
  6313. trigger.disabled = false;
  6314. }
  6315. });
  6316. }
  6317. function cleanupPdfExport(state) {
  6318. if (!state || state.cleanedUp) return;
  6319. state.cleanedUp = true;
  6320. if (state.tempElement && state.tempElement.parentNode) {
  6321. if (window.keepTempElementForAudit) {
  6322. window.auditedTempElement = state.tempElement;
  6323. console.log("Skipped tempElement removal for audit");
  6324. } else {
  6325. state.tempElement.parentNode.removeChild(state.tempElement);
  6326. }
  6327. }
  6328. if (state.overlay && state.overlay.parentNode) {
  6329. state.overlay.parentNode.removeChild(state.overlay);
  6330. }
  6331. setPdfExportTriggersBusy(state, false);
  6332. if (activePdfExport === state) {
  6333. activePdfExport = null;
  6334. }
  6335. }
  6336. function cancelPdfExport(state) {
  6337. if (!state || state.signal.aborted) return;
  6338. state.abortController.abort();
  6339. cleanupPdfExport(state);
  6340. }
  6341. async function waitForPdfFrame(state) {
  6342. throwIfPdfExportAborted(state.signal);
  6343. await new Promise(resolve => requestAnimationFrame(resolve));
  6344. throwIfPdfExportAborted(state.signal);
  6345. }
  6346. function markdownLikelyContainsMath(markdown) {
  6347. return /(^|[^\\])\$\$|\\\[|\\\(|(^|[^\\])\$[^$\n]+\$/.test(markdown);
  6348. }
  6349. function choosePdfCanvasScale(element) {
  6350. const pixelArea = element.offsetWidth * element.scrollHeight;
  6351. if (pixelArea > 14000000) return 1.25;
  6352. if (pixelArea > 8000000) return 1.5;
  6353. return PAGE_CONFIG.scale;
  6354. }
  6355. function readPixelStyle(element, propertyName) {
  6356. const value = window.getComputedStyle(element).getPropertyValue(propertyName);
  6357. return parseFloat(value) || 0;
  6358. }
  6359. function fitExportElementToContent(element) {
  6360. if (!element) return false;
  6361. const overflow = element.scrollWidth - element.clientWidth;
  6362. if (overflow <= 1) return false;
  6363. const paddingLeft = readPixelStyle(element, 'padding-left');
  6364. const paddingRight = readPixelStyle(element, 'padding-right');
  6365. const borderLeft = readPixelStyle(element, 'border-left-width');
  6366. const borderRight = readPixelStyle(element, 'border-right-width');
  6367. const boxSizing = window.getComputedStyle(element).boxSizing;
  6368. const requiredWidth = boxSizing === 'border-box'
  6369. ? Math.ceil(element.scrollWidth + borderLeft + borderRight)
  6370. : Math.ceil(element.scrollWidth - paddingLeft - paddingRight);
  6371. element.style.width = `${requiredWidth}px`;
  6372. return true;
  6373. }
  6374. /**
  6375. * Task 1: Identifies all graphic elements that may need page-break handling
  6376. * @param {HTMLElement} container - The container element to search within
  6377. * @returns {Array} Array of {element, type} objects
  6378. */
  6379. function identifyGraphicElements(container) {
  6380. const graphics = [];
  6381. // Query all targeting elements in precise DOM layout flow order
  6382. container.querySelectorAll('img, svg, pre, table, p, li, h1, h2, h3, h4, h5, h6, blockquote, hr, .math-block, mjx-container[display="true"]').forEach(el => {
  6383. const tag = el.tagName.toLowerCase();
  6384. // Skip any elements nested inside blockquotes to treat blockquotes as atomic containers
  6385. if (el.parentElement && el.parentElement.closest('blockquote')) {
  6386. return;
  6387. }
  6388. // Skip any elements nested inside list items that contain block children (treat list items as atomic)
  6389. if (el.parentElement) {
  6390. const liAncestor = el.parentElement.closest('li');
  6391. if (liAncestor) {
  6392. const hasBlockChildren = liAncestor.querySelector('p, blockquote, pre, table, ul, ol') !== null;
  6393. if (hasBlockChildren) {
  6394. return;
  6395. }
  6396. }
  6397. }
  6398. let type = '';
  6399. if (tag === 'img') type = 'img';
  6400. else if (tag === 'svg') {
  6401. if (!el.closest('mjx-container, .math-block')) {
  6402. type = 'svg';
  6403. }
  6404. }
  6405. else if (tag === 'pre') type = 'pre';
  6406. else if (tag === 'table') type = 'table';
  6407. else if (tag === 'hr') type = 'hr';
  6408. else if (tag === 'blockquote') {
  6409. type = 'blockquote';
  6410. }
  6411. else if (['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)) {
  6412. type = 'text';
  6413. } else if (tag === 'li') {
  6414. // Treat list items with block children as atomic containers, otherwise treat as text
  6415. const hasBlockChildren = el.querySelector('p, blockquote, pre, table, ul, ol') !== null;
  6416. if (hasBlockChildren) {
  6417. type = 'li';
  6418. } else {
  6419. type = 'text';
  6420. }
  6421. } else if (el.classList.contains('math-block') || tag === 'mjx-container') {
  6422. type = 'math';
  6423. }
  6424. if (type) {
  6425. graphics.push({ element: el, type: type });
  6426. }
  6427. });
  6428. return graphics;
  6429. }
  6430. /**
  6431. * Calculates the computed line-height of a text element, defaulting based on tag if "normal"
  6432. * @param {HTMLElement} element
  6433. * @returns {number} The line-height in pixels
  6434. */
  6435. function getElementLineHeight(element) {
  6436. const style = window.getComputedStyle(element);
  6437. const fontSize = parseFloat(style.fontSize) || 14;
  6438. let lineHeight = parseFloat(style.lineHeight);
  6439. if (isNaN(lineHeight)) {
  6440. const tag = element.tagName.toLowerCase();
  6441. if (tag.startsWith('h')) {
  6442. lineHeight = fontSize * 1.25;
  6443. } else {
  6444. lineHeight = fontSize * 1.5;
  6445. }
  6446. } else if (lineHeight < 10) {
  6447. // Handle unitless line-height (e.g. "1.5")
  6448. lineHeight = lineHeight * fontSize;
  6449. }
  6450. return lineHeight;
  6451. }
  6452. /**
  6453. * Calculates the shift needed to align a split text element's lines with the page boundary
  6454. * @param {Object} item - The split element item
  6455. * @param {Array} pageBoundaries - Page break positions
  6456. * @returns {number} The shift in pixels
  6457. */
  6458. function calculateTextElementShift(item, pageBoundaries) {
  6459. const boundaryY = pageBoundaries[item.splitPageIndex];
  6460. if (boundaryY === undefined) return 0;
  6461. const element = item.element;
  6462. const style = window.getComputedStyle(element);
  6463. const tag = element.tagName.toLowerCase();
  6464. const isHeading = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag);
  6465. // Safety buffer (in pixels) to ensure text rendering, glyph ascenders,
  6466. // and sub-pixel anti-aliasing are pushed cleanly past the slicing boundary.
  6467. const SAFETY_BUFFER = 4;
  6468. // Headings should never be split. Push the entire heading to the next page.
  6469. if (isHeading) {
  6470. return (boundaryY - item.top) + SAFETY_BUFFER;
  6471. }
  6472. const paddingTop = parseFloat(style.paddingTop) || 0;
  6473. const borderTop = parseFloat(style.borderTopWidth) || 0;
  6474. const paddingBottom = parseFloat(style.paddingBottom) || 0;
  6475. const borderBottom = parseFloat(style.borderBottomWidth) || 0;
  6476. const lh = getElementLineHeight(element);
  6477. const contentTop = item.top + paddingTop + borderTop;
  6478. const contentHeight = item.height - paddingTop - paddingBottom - borderTop - borderBottom;
  6479. if (contentHeight <= 0) return 0;
  6480. const numLines = Math.max(1, Math.round(contentHeight / lh));
  6481. for (let i = 0; i < numLines; i++) {
  6482. const lineTop = contentTop + i * lh;
  6483. const lineBottom = contentTop + (i + 1) * lh;
  6484. // Check if this line is split by boundaryY (using a small tolerance to prevent float vibrations)
  6485. if (lineTop < boundaryY - 0.5 && lineBottom > boundaryY + 0.5) {
  6486. // Calculate shift to align the line's top with boundaryY, plus a safety buffer
  6487. return (boundaryY - lineTop) + SAFETY_BUFFER;
  6488. }
  6489. }
  6490. // Fallback: If a short paragraph/list item is split across pages but no single line is cut
  6491. // (e.g. boundary falls exactly in padding/margin), push the whole element.
  6492. if (item.height <= lh * 3) {
  6493. return (boundaryY - item.top) + SAFETY_BUFFER;
  6494. }
  6495. return 0;
  6496. }
  6497. /**
  6498. * Task 2: Calculates element positions relative to the container
  6499. * @param {Array} elements - Array of {element, type} objects
  6500. * @param {HTMLElement} container - The container element
  6501. * @returns {Array} Array with position data added
  6502. */
  6503. function calculateElementPositions(elements, container) {
  6504. const containerRect = container.getBoundingClientRect();
  6505. return elements.map(item => {
  6506. const rect = item.element.getBoundingClientRect();
  6507. const top = rect.top - containerRect.top;
  6508. const height = rect.height;
  6509. const bottom = top + height;
  6510. return {
  6511. element: item.element,
  6512. type: item.type,
  6513. top: top,
  6514. height: height,
  6515. bottom: bottom
  6516. };
  6517. });
  6518. }
  6519. /**
  6520. * Task 3: Calculates page boundary positions
  6521. * @param {number} totalHeight - Total height of content in pixels
  6522. * @param {number} elementWidth - Actual width of the rendered element in pixels
  6523. * @param {Object} pageConfig - Page configuration object
  6524. * @returns {Array} Array of y-coordinates where pages end
  6525. */
  6526. function calculatePageBoundaries(totalHeight, elementWidth, pageConfig) {
  6527. const aspectRatio = pageConfig.contentHeight / pageConfig.contentWidth;
  6528. const pageHeightPx = elementWidth * aspectRatio;
  6529. const boundaries = [];
  6530. let y = pageHeightPx;
  6531. while (y < totalHeight) {
  6532. boundaries.push(y);
  6533. y += pageHeightPx;
  6534. }
  6535. return { boundaries, pageHeightPx };
  6536. }
  6537. /**
  6538. * Task 4: Detects which elements would be split across page boundaries
  6539. * @param {Array} elements - Array of elements with position data
  6540. * @param {Array} pageBoundaries - Array of page break y-coordinates
  6541. * @returns {Array} Array of split elements with additional split info
  6542. */
  6543. function detectSplitElements(elements, pageBoundaries) {
  6544. if (!elements || elements.length === 0) return [];
  6545. if (!pageBoundaries || pageBoundaries.length === 0) return [];
  6546. const splitElements = [];
  6547. for (const item of elements) {
  6548. let startPage = 0;
  6549. for (let i = 0; i < pageBoundaries.length; i++) {
  6550. if (item.top >= pageBoundaries[i]) {
  6551. startPage = i + 1;
  6552. } else {
  6553. break;
  6554. }
  6555. }
  6556. let endPage = 0;
  6557. for (let i = 0; i < pageBoundaries.length; i++) {
  6558. if (item.bottom > pageBoundaries[i]) {
  6559. endPage = i + 1;
  6560. } else {
  6561. break;
  6562. }
  6563. }
  6564. if (endPage > startPage) {
  6565. const boundaryY = pageBoundaries[startPage] || pageBoundaries[0];
  6566. const overflowAmount = item.bottom - boundaryY;
  6567. splitElements.push({
  6568. element: item.element,
  6569. type: item.type,
  6570. top: item.top,
  6571. height: item.height,
  6572. splitPageIndex: startPage,
  6573. overflowAmount: overflowAmount
  6574. });
  6575. }
  6576. }
  6577. return splitElements;
  6578. }
  6579. /**
  6580. * Task 5: Main entry point for analyzing graphics for page breaks
  6581. * @param {HTMLElement} tempElement - The rendered content container
  6582. * @returns {Object} Analysis result with totalElements, splitElements, pageCount
  6583. */
  6584. function analyzeGraphicsForPageBreaks(tempElement, signal) {
  6585. try {
  6586. throwIfPdfExportAborted(signal);
  6587. const graphics = identifyGraphicElements(tempElement);
  6588. const elementsWithPositions = calculateElementPositions(graphics, tempElement);
  6589. throwIfPdfExportAborted(signal);
  6590. const totalHeight = Math.ceil(tempElement.getBoundingClientRect().height);
  6591. const elementWidth = tempElement.offsetWidth;
  6592. const { boundaries: pageBoundaries, pageHeightPx } = calculatePageBoundaries(
  6593. totalHeight,
  6594. elementWidth,
  6595. PAGE_CONFIG
  6596. );
  6597. const splitElements = detectSplitElements(elementsWithPositions, pageBoundaries);
  6598. const pageCount = pageBoundaries.length + 1;
  6599. return {
  6600. totalElements: graphics.length,
  6601. splitElements: splitElements,
  6602. pageCount: pageCount,
  6603. pageBoundaries: pageBoundaries,
  6604. pageHeightPx: pageHeightPx
  6605. };
  6606. } catch (error) {
  6607. if (error instanceof PdfExportCancelledError) throw error;
  6608. console.error('Page-break analysis failed:', error);
  6609. return {
  6610. totalElements: 0,
  6611. splitElements: [],
  6612. pageCount: 1,
  6613. pageBoundaries: [],
  6614. pageHeightPx: 0
  6615. };
  6616. }
  6617. }
  6618. // ============================================
  6619. // End Page-Break Detection Functions
  6620. // ============================================
  6621. // ============================================
  6622. // Page-Break Insertion Functions (Story 1.2)
  6623. // ============================================
  6624. /**
  6625. * Resets temporary styles applied to graphics elements back to their original state.
  6626. * This is called at the start of each layout iteration in the cascade loop.
  6627. * @param {HTMLElement} container - The container element to process
  6628. */
  6629. function resetGraphicsStyles(container) {
  6630. // Remove all dynamically inserted page-break spacers
  6631. container.querySelectorAll('.pdf-page-break-spacer').forEach(el => el.remove());
  6632. container.querySelectorAll('[data-pdf-original-margin-top]').forEach(el => {
  6633. el.style.marginTop = el.dataset.pdfOriginalMarginTop;
  6634. el.removeAttribute('data-pdf-original-margin-top');
  6635. });
  6636. container.querySelectorAll('[data-pdf-original-margin-bottom]').forEach(el => {
  6637. el.style.marginBottom = el.dataset.pdfOriginalMarginBottom;
  6638. el.removeAttribute('data-pdf-original-margin-bottom');
  6639. });
  6640. container.querySelectorAll('[data-pdf-original-transform]').forEach(el => {
  6641. el.style.transform = el.dataset.pdfOriginalTransform;
  6642. el.style.transformOrigin = '';
  6643. el.removeAttribute('data-pdf-original-transform');
  6644. });
  6645. container.querySelectorAll('[data-pdf-original-width]').forEach(el => {
  6646. el.style.width = el.dataset.pdfOriginalWidth;
  6647. el.removeAttribute('data-pdf-original-width');
  6648. });
  6649. container.querySelectorAll('[data-pdf-original-height]').forEach(el => {
  6650. el.style.height = el.dataset.pdfOriginalHeight;
  6651. el.removeAttribute('data-pdf-original-height');
  6652. });
  6653. container.querySelectorAll('[data-pdf-original-max-width]').forEach(el => {
  6654. el.style.maxWidth = el.dataset.pdfOriginalMaxWidth;
  6655. el.removeAttribute('data-pdf-original-max-width');
  6656. });
  6657. container.querySelectorAll('[data-pdf-original-font-size]').forEach(el => {
  6658. el.style.fontSize = el.dataset.pdfOriginalFontSize;
  6659. el.removeAttribute('data-pdf-original-font-size');
  6660. });
  6661. container.querySelectorAll('[data-pdf-original-overflow]').forEach(el => {
  6662. el.style.overflow = el.dataset.pdfOriginalOverflow;
  6663. el.removeAttribute('data-pdf-original-overflow');
  6664. });
  6665. }
  6666. function mergeSplitTables(container) {
  6667. const groupIds = new Set();
  6668. container.querySelectorAll('table[data-split-group-id]').forEach(t => {
  6669. if (t.dataset.splitGroupId) {
  6670. groupIds.add(t.dataset.splitGroupId);
  6671. }
  6672. });
  6673. for (const groupId of groupIds) {
  6674. const originalTable = container.querySelector(`table[data-split-group-id="${groupId}"]:not([data-split-part="true"])`);
  6675. if (!originalTable) continue;
  6676. const parts = Array.from(container.querySelectorAll(`table[data-split-group-id="${groupId}"][data-split-part="true"]`));
  6677. const tbody = originalTable.tBodies[0] || originalTable.querySelector('tbody') || originalTable;
  6678. for (const part of parts) {
  6679. const partTbody = part.tBodies[0] || part.querySelector('tbody') || part;
  6680. const rows = Array.from(partTbody.children).filter(child => child.tagName.toLowerCase() === 'tr');
  6681. for (const row of rows) {
  6682. tbody.appendChild(row);
  6683. }
  6684. part.remove();
  6685. }
  6686. const spacers = Array.from(container.querySelectorAll(`div[data-split-group-id="${groupId}"][data-split-spacer="true"]`));
  6687. for (const spacer of spacers) {
  6688. spacer.remove();
  6689. }
  6690. originalTable.removeAttribute('data-split-group-id');
  6691. }
  6692. }
  6693. function splitTables(container, pageHeightPx) {
  6694. mergeSplitTables(container);
  6695. const tables = Array.from(container.querySelectorAll('table'));
  6696. let groupCounter = 0;
  6697. for (const table of tables) {
  6698. if (table.dataset.splitPart === "true") continue;
  6699. const tableRect = table.getBoundingClientRect();
  6700. if (tableRect.height <= pageHeightPx) continue;
  6701. const tbody = table.tBodies[0] || table.querySelector('tbody');
  6702. if (!tbody) continue;
  6703. const rows = Array.from(tbody.children).filter(child => child.tagName.toLowerCase() === 'tr');
  6704. if (rows.length === 0) continue;
  6705. const groupId = `table-group-${groupCounter++}`;
  6706. table.dataset.splitGroupId = groupId;
  6707. const containerRect = container.getBoundingClientRect();
  6708. const rowPositions = rows.map(row => {
  6709. const rect = row.getBoundingClientRect();
  6710. return {
  6711. row: row,
  6712. top: rect.top - containerRect.top,
  6713. bottom: rect.bottom - containerRect.top,
  6714. height: rect.height
  6715. };
  6716. });
  6717. let currentTable = table;
  6718. let currentTbody = tbody;
  6719. let accumulatedShift = 0;
  6720. for (let i = 0; i < rowPositions.length; i++) {
  6721. const pos = rowPositions[i];
  6722. const shiftedTop = pos.top + accumulatedShift;
  6723. const shiftedBottom = pos.bottom + accumulatedShift;
  6724. const currentPageIndex = Math.floor(shiftedTop / pageHeightPx);
  6725. const nextPageBoundary = (currentPageIndex + 1) * pageHeightPx;
  6726. if (shiftedBottom > nextPageBoundary) {
  6727. const spacerHeight = nextPageBoundary - shiftedTop;
  6728. const originalThead = table.querySelector('thead');
  6729. const theadHeight = originalThead ? originalThead.getBoundingClientRect().height : 0;
  6730. accumulatedShift += spacerHeight + theadHeight;
  6731. const nextTable = table.cloneNode(false);
  6732. nextTable.removeAttribute('id');
  6733. nextTable.dataset.splitGroupId = groupId;
  6734. nextTable.dataset.splitPart = "true";
  6735. if (originalThead) nextTable.appendChild(originalThead.cloneNode(true));
  6736. const nextTbody = document.createElement('tbody');
  6737. nextTable.appendChild(nextTbody);
  6738. const spacer = document.createElement('div');
  6739. spacer.className = 'table-page-break-spacer';
  6740. spacer.dataset.splitGroupId = groupId;
  6741. spacer.dataset.splitSpacer = "true";
  6742. spacer.style.height = `${spacerHeight}px`;
  6743. spacer.style.margin = '0';
  6744. spacer.style.padding = '0';
  6745. spacer.style.border = 'none';
  6746. currentTable.parentNode.insertBefore(spacer, currentTable.nextSibling);
  6747. spacer.parentNode.insertBefore(nextTable, spacer.nextSibling);
  6748. currentTable = nextTable;
  6749. currentTbody = nextTbody;
  6750. }
  6751. if (currentTable !== table) currentTbody.appendChild(pos.row);
  6752. }
  6753. }
  6754. }
  6755. function applyPageBreaksWithCascade(tempElement, pageConfig, maxIterations = 10, signal) {
  6756. let iteration = 0;
  6757. let analysis;
  6758. const elementWidth = tempElement.offsetWidth;
  6759. const aspectRatio = pageConfig.contentHeight / pageConfig.contentWidth;
  6760. const pageHeightPx = elementWidth * aspectRatio;
  6761. const lastAdjustments = new Map(); // Store {margin, scale} for each element
  6762. do {
  6763. throwIfPdfExportAborted(signal);
  6764. // Reset graphics element styles applied in previous iterations
  6765. resetGraphicsStyles(tempElement);
  6766. // Split tables at page breaks dynamically using calculated pageHeightPx
  6767. splitTables(tempElement, pageHeightPx);
  6768. // We must get ALL target elements in document order
  6769. const graphics = identifyGraphicElements(tempElement);
  6770. const elementsWithPositions = calculateElementPositions(graphics, tempElement);
  6771. // Get page boundaries based on current height
  6772. const totalHeight = Math.ceil(tempElement.getBoundingClientRect().height);
  6773. const { boundaries: pageBoundaries, pageHeightPx: pageHeightPxFromAnalysis } = calculatePageBoundaries(
  6774. totalHeight,
  6775. elementWidth,
  6776. pageConfig
  6777. );
  6778. let adjustmentsMade = false;
  6779. let accumulatedShift = 0;
  6780. const currentIterationAdjustments = new Map();
  6781. for (const item of elementsWithPositions) {
  6782. throwIfPdfExportAborted(signal);
  6783. const currentTop = item.top + accumulatedShift;
  6784. const currentBottom = currentTop + item.height;
  6785. let targetMargin = 0;
  6786. let targetScale = 1.0;
  6787. // 1. Heading Keep-With-Next Rule (must run for all headings regardless of split)
  6788. const tag = item.element.tagName.toLowerCase();
  6789. const isHeading = item.type === 'text' && ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag);
  6790. if (isHeading) {
  6791. let nextBoundaryY = null;
  6792. for (const boundary of pageBoundaries) {
  6793. if (currentTop < boundary) {
  6794. nextBoundaryY = boundary;
  6795. break;
  6796. }
  6797. }
  6798. if (nextBoundaryY !== null) {
  6799. const distanceToBoundary = nextBoundaryY - currentTop;
  6800. if (distanceToBoundary < 70) {
  6801. targetMargin = distanceToBoundary + 4; // Push heading entirely to next page
  6802. }
  6803. }
  6804. }
  6805. // 2. If not already pushed by Keep-With-Next, perform standard page-split calculations
  6806. if (targetMargin === 0) {
  6807. // Check if this element crosses any page boundary or starts extremely close to it (sub-pixel safety)
  6808. let splitPageIndex = -1;
  6809. for (let i = 0; i < pageBoundaries.length; i++) {
  6810. if (currentTop < pageBoundaries[i] + 12 && currentBottom > pageBoundaries[i]) {
  6811. splitPageIndex = i;
  6812. break;
  6813. }
  6814. }
  6815. if (splitPageIndex !== -1) {
  6816. const boundaryY = pageBoundaries[splitPageIndex];
  6817. const remainingSpace = boundaryY - currentTop;
  6818. if (item.type === 'text') {
  6819. const shiftedItem = { ...item, top: currentTop, splitPageIndex: splitPageIndex };
  6820. const shift = calculateTextElementShift(shiftedItem, pageBoundaries);
  6821. if (shift > 0.5) {
  6822. targetMargin = shift;
  6823. }
  6824. } else {
  6825. // Graphic element splitting (with larger buffer to ensure complete clearance)
  6826. const buffer = 15;
  6827. const scaleNeeded = (remainingSpace - buffer) / item.height;
  6828. const remainingSpacePercent = remainingSpace / pageHeightPxFromAnalysis;
  6829. const isTextContainer = ['blockquote', 'li', 'table', 'pre', 'math'].includes(item.type);
  6830. // Fit on current page by scaling if it's an image/svg and space/scale are acceptable.
  6831. // Otherwise, always push text/block containers to next page to prevent transform-scaling bugs.
  6832. if (!isTextContainer && remainingSpacePercent >= 0.20 && scaleNeeded >= 0.6) {
  6833. targetScale = Math.min(1.0, scaleNeeded);
  6834. } else {
  6835. // Push to next page
  6836. const marginNeeded = boundaryY - currentTop + buffer;
  6837. targetMargin = marginNeeded;
  6838. // Check if it fits the next page height after being pushed (Rule 3 Case C)
  6839. const newTop = currentTop + marginNeeded;
  6840. const newBottom = newTop + item.height;
  6841. const nextBoundaryY = pageBoundaries[splitPageIndex + 1] || (boundaryY + pageHeightPxFromAnalysis);
  6842. if (newBottom > nextBoundaryY) {
  6843. const scaleToFitPage = (pageHeightPxFromAnalysis - 20) / item.height;
  6844. targetScale = Math.max(0.5, Math.min(1.0, scaleToFitPage));
  6845. }
  6846. }
  6847. }
  6848. } else {
  6849. // Element is not split. But graphic elements taller than a page must still scale to fit!
  6850. if (item.type !== 'text' && item.height > pageHeightPxFromAnalysis) {
  6851. const scaleToFitPage = (pageHeightPxFromAnalysis - 20) / item.height;
  6852. targetScale = Math.max(0.5, Math.min(1.0, scaleToFitPage));
  6853. }
  6854. }
  6855. }
  6856. // Check if this calculated adjustment is different from the previous iteration
  6857. const prevAdjustment = lastAdjustments.get(item.element) || { margin: 0, scale: 1.0 };
  6858. if (Math.abs(targetMargin - prevAdjustment.margin) > 0.1 || Math.abs(targetScale - prevAdjustment.scale) > 0.001) {
  6859. adjustmentsMade = true;
  6860. }
  6861. currentIterationAdjustments.set(item.element, { margin: targetMargin, scale: targetScale });
  6862. // Apply style adjustments to the DOM
  6863. if (targetMargin > 0) {
  6864. let targetElement = item.element;
  6865. // Redirect inline image or svg margins to their parent block element if nested
  6866. if (item.type === 'svg' && item.element.parentElement) {
  6867. const parent = item.element.parentElement;
  6868. if (['p', 'li', 'blockquote'].includes(parent.tagName.toLowerCase())) {
  6869. targetElement = parent;
  6870. } else {
  6871. targetElement = parent;
  6872. }
  6873. } else if (item.type === 'img' && item.element.parentElement) {
  6874. const parent = item.element.parentElement;
  6875. if (item.element.classList.contains('mermaid-img')) {
  6876. if (parent.parentElement && parent.parentElement.classList.contains('mermaid-container')) {
  6877. targetElement = parent.parentElement;
  6878. } else {
  6879. targetElement = parent;
  6880. }
  6881. } else if (['p', 'li', 'blockquote'].includes(parent.tagName.toLowerCase())) {
  6882. targetElement = parent;
  6883. }
  6884. }
  6885. // If target is a list item, apply marginTop directly to avoid invalid HTML / collapsed spacers
  6886. if (targetElement.tagName.toLowerCase() === 'li') {
  6887. if (!targetElement.dataset.hasOwnProperty('pdfOriginalMarginTop')) {
  6888. targetElement.dataset.pdfOriginalMarginTop = targetElement.style.marginTop || '';
  6889. }
  6890. targetElement.style.marginTop = `${targetMargin}px`;
  6891. } else {
  6892. // Create a physical spacer element to avoid margin collapse issues entirely
  6893. const spacer = document.createElement('div');
  6894. spacer.className = 'pdf-page-break-spacer';
  6895. spacer.style.height = `${targetMargin}px`;
  6896. spacer.style.margin = '0';
  6897. spacer.style.padding = '0';
  6898. spacer.style.border = 'none';
  6899. spacer.style.display = 'block';
  6900. targetElement.parentNode.insertBefore(spacer, targetElement);
  6901. }
  6902. accumulatedShift += targetMargin;
  6903. }
  6904. if (targetScale < 1.0) {
  6905. applyGraphicScaling(item.element, targetScale, item.type);
  6906. const heightSaved = item.height * (1.0 - targetScale);
  6907. accumulatedShift -= heightSaved;
  6908. }
  6909. }
  6910. // Copy current adjustments to lastAdjustments
  6911. lastAdjustments.clear();
  6912. for (const [el, adj] of currentIterationAdjustments) {
  6913. lastAdjustments.set(el, adj);
  6914. }
  6915. if (!adjustmentsMade) {
  6916. break;
  6917. }
  6918. iteration++;
  6919. } while (iteration < maxIterations);
  6920. if (iteration >= maxIterations) {
  6921. console.warn('Page-break stabilization reached max iterations:', maxIterations);
  6922. }
  6923. // Return the final page boundaries and height analysis for the export flow
  6924. analysis = analyzeGraphicsForPageBreaks(tempElement, signal);
  6925. logPdfExportDebug('Page-break cascade complete:', {
  6926. iterations: iteration,
  6927. finalSplitCount: analysis.splitElements.length
  6928. });
  6929. return analysis;
  6930. }
  6931. // ============================================
  6932. // End Page-Break Insertion Functions
  6933. // ============================================
  6934. // ============================================
  6935. // Oversized Graphics Scaling Functions (Story 1.3)
  6936. // ============================================
  6937. const MIN_SCALE_FACTOR = 0.5;
  6938. function calculateScaleFactor(elementHeight, availableHeight, buffer = 5) {
  6939. const targetHeight = availableHeight - buffer;
  6940. let scaleFactor = targetHeight / elementHeight;
  6941. let wasClampedToMin = false;
  6942. if (scaleFactor < MIN_SCALE_FACTOR) {
  6943. console.warn(
  6944. `Warning: Large graphic requires ${(scaleFactor * 100).toFixed(0)}% scaling. ` +
  6945. `Clamping to minimum ${MIN_SCALE_FACTOR * 100}%. Content may be cut off.`
  6946. );
  6947. scaleFactor = MIN_SCALE_FACTOR;
  6948. wasClampedToMin = true;
  6949. }
  6950. return { scaleFactor, wasClampedToMin };
  6951. }
  6952. function applyGraphicScaling(element, scaleFactor, elementType) {
  6953. if (!element.dataset.hasOwnProperty('pdfOriginalTransform')) {
  6954. element.dataset.pdfOriginalTransform = element.style.transform || '';
  6955. }
  6956. if (!element.dataset.hasOwnProperty('pdfOriginalMarginBottom')) {
  6957. element.dataset.pdfOriginalMarginBottom = element.style.marginBottom || '';
  6958. }
  6959. if (elementType === 'svg' || elementType === 'img') {
  6960. if (!element.dataset.hasOwnProperty('pdfOriginalWidth')) {
  6961. element.dataset.pdfOriginalWidth = element.style.width || '';
  6962. }
  6963. if (!element.dataset.hasOwnProperty('pdfOriginalHeight')) {
  6964. element.dataset.pdfOriginalHeight = element.style.height || '';
  6965. }
  6966. if (!element.dataset.hasOwnProperty('pdfOriginalMaxWidth')) {
  6967. element.dataset.pdfOriginalMaxWidth = element.style.maxWidth || '';
  6968. }
  6969. let origWidth = parseFloat(element.dataset.pdfOriginalClientWidth);
  6970. let origHeight = parseFloat(element.dataset.pdfOriginalClientHeight);
  6971. if (isNaN(origWidth) || isNaN(origHeight)) {
  6972. origWidth = element.clientWidth || element.getBoundingClientRect().width;
  6973. origHeight = element.clientHeight || element.getBoundingClientRect().height;
  6974. element.dataset.pdfOriginalClientWidth = String(origWidth);
  6975. element.dataset.pdfOriginalClientHeight = String(origHeight);
  6976. }
  6977. // Apply physical scale
  6978. element.style.width = `${origWidth * scaleFactor}px`;
  6979. element.style.height = `${origHeight * scaleFactor}px`;
  6980. if (elementType === 'svg') {
  6981. element.style.maxWidth = 'none';
  6982. }
  6983. } else {
  6984. // For pre, table, blockquote, math, li, etc.
  6985. // Use transform: scale combined with physical height and overflow hidden to guarantee no native splits
  6986. if (!element.dataset.hasOwnProperty('pdfOriginalHeight')) {
  6987. element.dataset.pdfOriginalHeight = element.style.height || '';
  6988. }
  6989. if (!element.dataset.hasOwnProperty('pdfOriginalOverflow')) {
  6990. element.dataset.pdfOriginalOverflow = element.style.overflow || '';
  6991. }
  6992. element.style.transform = `scale(${scaleFactor})`;
  6993. element.style.transformOrigin = 'top left';
  6994. let origHeight = parseFloat(element.dataset.pdfOriginalClientHeight);
  6995. if (isNaN(origHeight)) {
  6996. origHeight = element.offsetHeight || element.getBoundingClientRect().height;
  6997. element.dataset.pdfOriginalClientHeight = String(origHeight);
  6998. }
  6999. const scaledHeight = origHeight * scaleFactor;
  7000. element.style.height = `${scaledHeight}px`;
  7001. element.style.overflow = 'hidden';
  7002. }
  7003. }
  7004. function waitForAllImages(container) {
  7005. const imgs = Array.from(container.querySelectorAll('img'));
  7006. const promises = imgs.map(img => {
  7007. if (img.complete) return Promise.resolve();
  7008. return new Promise(resolve => {
  7009. img.addEventListener('load', resolve, { once: true });
  7010. img.addEventListener('error', resolve, { once: true });
  7011. });
  7012. });
  7013. return Promise.all(promises);
  7014. }
  7015. // ============================================
  7016. // End Oversized Graphics Scaling Functions
  7017. // ============================================
  7018. exportPdf.addEventListener("click", async function (event) {
  7019. event.preventDefault();
  7020. logPdfExportDebug("PDF export button clicked!");
  7021. if (activePdfExport) {
  7022. logPdfExportDebug("PDF export already active, ignoring click");
  7023. return;
  7024. }
  7025. const progressState = createPdfProgressState();
  7026. activePdfExport = progressState;
  7027. setPdfExportTriggersBusy(progressState, true);
  7028. document.body.appendChild(progressState.overlay);
  7029. updatePdfProgress(progressState, 3, "Starting");
  7030. progressState.overlay.querySelector(".pdf-progress-cancel")?.focus();
  7031. try {
  7032. logPdfExportDebug("PDF export try block entered. typeof jspdf:", typeof jspdf, "typeof html2canvas:", typeof html2canvas);
  7033. // PERF-002: Lazy-load PDF libraries on first export
  7034. if (typeof jspdf === 'undefined' || typeof html2canvas === 'undefined') {
  7035. logPdfExportDebug("Lazy loading PDF libraries started...");
  7036. updatePdfProgress(progressState, 8, "Loading PDF libraries");
  7037. await runPdfAbortable(progressState, Promise.all([
  7038. loadScript(CDN.jspdf).then(() => logPdfExportDebug("jspdf load callback fired")),
  7039. loadScript(CDN.html2canvas).then(() => logPdfExportDebug("html2canvas load callback fired"))
  7040. ]));
  7041. logPdfExportDebug("Lazy loading PDF libraries resolved.");
  7042. throwIfPdfExportAborted(progressState.signal);
  7043. }
  7044. logPdfExportDebug("Parsing markdown...");
  7045. updatePdfProgress(progressState, 15, "Parsing markdown");
  7046. await waitForPdfFrame(progressState);
  7047. const markdown = markdownEditor.value;
  7048. const html = marked.parse(markdown);
  7049. const sanitizedHtml = DOMPurify.sanitize(html, {
  7050. ADD_TAGS: ['mjx-container', 'svg', 'path', 'g', 'marker', 'defs', 'pattern', 'clipPath', 'input'],
  7051. ADD_ATTR: ['id', 'class', 'style', 'align', 'viewBox', 'd', 'fill', 'stroke', 'transform', 'marker-end', 'marker-start', 'type', 'checked', 'disabled', 'data-original-code'],
  7052. ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel|blob):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
  7053. });
  7054. throwIfPdfExportAborted(progressState.signal);
  7055. updatePdfProgress(progressState, 24, "Preparing document");
  7056. await waitForPdfFrame(progressState);
  7057. const tempElement = document.createElement("div");
  7058. progressState.tempElement = tempElement;
  7059. tempElement.className = "markdown-body pdf-export";
  7060. tempElement.innerHTML = sanitizedHtml;
  7061. enhanceGitHubAlerts(tempElement);
  7062. tempElement.style.padding = "0px";
  7063. tempElement.style.width = "210mm";
  7064. tempElement.style.margin = "0 auto";
  7065. tempElement.style.fontSize = "14px";
  7066. tempElement.style.position = "fixed";
  7067. tempElement.style.left = "-9999px";
  7068. tempElement.style.top = "0";
  7069. const currentTheme = document.documentElement.getAttribute("data-theme");
  7070. tempElement.style.backgroundColor = currentTheme === "dark" ? "#0d1117" : "#ffffff";
  7071. tempElement.style.color = currentTheme === "dark" ? "#c9d1d9" : "#24292e";
  7072. document.body.appendChild(tempElement);
  7073. await waitForPdfFrame(progressState);
  7074. const mermaidNodes = tempElement.querySelectorAll('.mermaid');
  7075. if (mermaidNodes.length > 0) {
  7076. updatePdfProgress(progressState, 34, "Rendering diagrams");
  7077. try {
  7078. if (typeof mermaid === 'undefined') {
  7079. await runPdfAbortable(progressState, loadScript(CDN.mermaid));
  7080. }
  7081. throwIfPdfExportAborted(progressState.signal);
  7082. initMermaid(true);
  7083. await runPdfAbortable(progressState, mermaid.init(undefined, mermaidNodes));
  7084. tempElement.querySelectorAll('.mermaid-container.is-loading').forEach(container => {
  7085. container.classList.remove('is-loading');
  7086. });
  7087. // Convert all rendered Mermaid SVGs inside tempElement to <img> tags with data URI sources
  7088. const compiledMermaids = tempElement.querySelectorAll('.mermaid-container');
  7089. compiledMermaids.forEach(container => {
  7090. const svgElement = container.querySelector('svg');
  7091. if (svgElement) {
  7092. const rect = svgElement.getBoundingClientRect();
  7093. const width = rect.width || svgElement.clientWidth || parseFloat(svgElement.getAttribute('width')) || 600;
  7094. const height = rect.height || svgElement.clientHeight || parseFloat(svgElement.getAttribute('height')) || 400;
  7095. const clonedSvg = svgElement.cloneNode(true);
  7096. clonedSvg.setAttribute('width', width);
  7097. clonedSvg.setAttribute('height', height);
  7098. if (!clonedSvg.getAttribute('viewBox')) {
  7099. clonedSvg.setAttribute('viewBox', `0 0 ${width} ${height}`);
  7100. }
  7101. clonedSvg.style.width = `${width}px`;
  7102. clonedSvg.style.height = `${height}px`;
  7103. const svgString = new XMLSerializer().serializeToString(clonedSvg);
  7104. const svgBase64 = btoa(unescape(encodeURIComponent(svgString)));
  7105. const img = document.createElement('img');
  7106. img.className = 'mermaid-img';
  7107. if (svgElement.id) img.id = svgElement.id + '-img';
  7108. img.src = 'data:image/svg+xml;base64,' + svgBase64;
  7109. img.style.width = `${width}px`;
  7110. img.style.height = `${height}px`;
  7111. img.style.maxWidth = '100%';
  7112. img.style.display = 'block';
  7113. img.style.margin = '0 auto';
  7114. img.dataset.originalWidth = String(width);
  7115. img.dataset.originalHeight = String(height);
  7116. container.innerHTML = '';
  7117. container.appendChild(img);
  7118. }
  7119. });
  7120. } catch (mermaidError) {
  7121. if (mermaidError instanceof PdfExportCancelledError) throw mermaidError;
  7122. console.warn("Mermaid rendering issue:", mermaidError);
  7123. tempElement.querySelectorAll('.mermaid-container.is-loading').forEach(container => {
  7124. container.classList.remove('is-loading');
  7125. });
  7126. }
  7127. throwIfPdfExportAborted(progressState.signal);
  7128. await waitForPdfFrame(progressState);
  7129. }
  7130. if (window.MathJax && markdownLikelyContainsMath(markdown)) {
  7131. updatePdfProgress(progressState, 44, "Rendering math");
  7132. try {
  7133. await runPdfAbortable(progressState, MathJax.typesetPromise([tempElement]));
  7134. } catch (mathJaxError) {
  7135. if (mathJaxError instanceof PdfExportCancelledError) throw mathJaxError;
  7136. console.warn("MathJax rendering issue:", mathJaxError);
  7137. }
  7138. throwIfPdfExportAborted(progressState.signal);
  7139. // Hide MathJax assistive elements that cause duplicate text in PDF
  7140. // These are screen reader elements that html2canvas captures as visible
  7141. // Use multiple CSS properties to ensure html2canvas doesn't render them
  7142. const assistiveElements = tempElement.querySelectorAll('mjx-assistive-mml');
  7143. assistiveElements.forEach(el => {
  7144. el.style.display = 'none';
  7145. el.style.visibility = 'hidden';
  7146. el.style.position = 'absolute';
  7147. el.style.width = '0';
  7148. el.style.height = '0';
  7149. el.style.overflow = 'hidden';
  7150. el.remove(); // Remove entirely from DOM
  7151. });
  7152. // Also hide any MathJax script elements that might contain source
  7153. const mathScripts = tempElement.querySelectorAll('script[type*="math"], script[type*="tex"]');
  7154. mathScripts.forEach(el => el.remove());
  7155. }
  7156. await waitForPdfFrame(progressState);
  7157. fitExportElementToContent(tempElement);
  7158. await waitForPdfFrame(progressState);
  7159. // Await loading of all images and fonts (including converted Mermaid base64 images) before cascade sizing runs
  7160. updatePdfProgress(progressState, 50, "Loading document assets");
  7161. await runPdfAbortable(progressState, Promise.all([
  7162. waitForAllImages(tempElement),
  7163. document.fonts ? document.fonts.ready : Promise.resolve()
  7164. ]));
  7165. throwIfPdfExportAborted(progressState.signal);
  7166. await waitForPdfFrame(progressState);
  7167. // Analyze and apply page-breaks for graphics (Story 1.1 + 1.2)
  7168. updatePdfProgress(progressState, 55, "Optimizing page breaks");
  7169. const pageBreakAnalysis = applyPageBreaksWithCascade(tempElement, PAGE_CONFIG, 10, progressState.signal);
  7170. throwIfPdfExportAborted(progressState.signal);
  7171. await waitForPdfFrame(progressState);
  7172. const pdfOptions = {
  7173. orientation: 'portrait',
  7174. unit: 'mm',
  7175. format: 'a4',
  7176. compress: true,
  7177. hotfixes: ["px_scaling"]
  7178. };
  7179. const pdf = new jspdf.jsPDF(pdfOptions);
  7180. const pageWidth = pdf.internal.pageSize.getWidth();
  7181. const pageHeight = pdf.internal.pageSize.getHeight();
  7182. const margin = 15;
  7183. const contentWidth = pageWidth - (margin * 2);
  7184. const captureScale = choosePdfCanvasScale(tempElement);
  7185. updatePdfProgress(progressState, 65, "Capturing document");
  7186. const canvas = await runPdfAbortable(progressState, html2canvas(tempElement, {
  7187. scale: captureScale,
  7188. useCORS: true,
  7189. allowTaint: false,
  7190. logging: false,
  7191. windowWidth: Math.max(PAGE_CONFIG.windowWidth, Math.ceil(tempElement.getBoundingClientRect().width)),
  7192. windowHeight: Math.ceil(tempElement.getBoundingClientRect().height)
  7193. }));
  7194. await waitForPdfFrame(progressState);
  7195. throwIfPdfExportAborted(progressState.signal);
  7196. console.log(`[PDF DEBUG] canvas.width = ${canvas.width}, canvas.height = ${canvas.height}`);
  7197. console.log(`[PDF DEBUG] tempElement.offsetWidth = ${tempElement.offsetWidth}, rect.width = ${tempElement.getBoundingClientRect().width}`);
  7198. const scaleFactor = canvas.width / contentWidth;
  7199. console.log(`[PDF DEBUG] scaleFactor = ${scaleFactor}, PAGE_CONFIG.scale = ${PAGE_CONFIG.scale}, captureScale = ${captureScale}`);
  7200. const imgHeight = canvas.height / scaleFactor;
  7201. console.log(`[PDF DEBUG] imgHeight = ${imgHeight}, contentHeight = ${pageHeight - margin * 2}`);
  7202. // Introduce a 0.5mm tolerance to prevent rounding errors from creating a trailing blank page
  7203. const pagesCount = Math.ceil((imgHeight - 0.5) / (pageHeight - margin * 2));
  7204. console.log(`[PDF DEBUG] pagesCount = ${pagesCount}`);
  7205. updatePdfProgress(progressState, 76, "Rendering pages");
  7206. for (let page = 0; page < pagesCount; page++) {
  7207. throwIfPdfExportAborted(progressState.signal);
  7208. const pageProgress = 76 + ((page + 1) / pagesCount) * 18;
  7209. updatePdfProgress(progressState, pageProgress, `Rendering page ${page + 1} of ${pagesCount}`);
  7210. if (page > 0) pdf.addPage();
  7211. const sourceY = page * (pageHeight - margin * 2) * scaleFactor;
  7212. const sourceHeight = Math.min(canvas.height - sourceY, (pageHeight - margin * 2) * scaleFactor);
  7213. const destHeight = sourceHeight / scaleFactor;
  7214. const pageCanvas = document.createElement('canvas');
  7215. pageCanvas.width = canvas.width;
  7216. pageCanvas.height = sourceHeight;
  7217. const ctx = pageCanvas.getContext('2d');
  7218. ctx.drawImage(canvas, 0, sourceY, canvas.width, sourceHeight, 0, 0, canvas.width, sourceHeight);
  7219. const imgData = pageCanvas.toDataURL('image/png');
  7220. pdf.addImage(imgData, 'PNG', margin, margin, contentWidth, destHeight);
  7221. await waitForPdfFrame(progressState);
  7222. }
  7223. throwIfPdfExportAborted(progressState.signal);
  7224. updatePdfProgress(progressState, 98, "Preparing download");
  7225. pdf.save("document.pdf");
  7226. updatePdfProgress(progressState, 100, "Complete");
  7227. } catch (error) {
  7228. if (error instanceof PdfExportCancelledError || progressState.signal.aborted) {
  7229. console.info("PDF export cancelled");
  7230. } else {
  7231. console.error("PDF export failed:", error);
  7232. alert("PDF export failed: " + error.message);
  7233. }
  7234. } finally {
  7235. cleanupPdfExport(progressState);
  7236. }
  7237. });
  7238. copyMarkdownButton.addEventListener("click", function () {
  7239. try {
  7240. const markdownText = markdownEditor.value;
  7241. copyToClipboard(markdownText);
  7242. } catch (e) {
  7243. console.error("Copy failed:", e);
  7244. alert("Failed to copy Markdown: " + e.message);
  7245. }
  7246. });
  7247. async function copyTextToClipboard(text) {
  7248. if (navigator.clipboard && window.isSecureContext) {
  7249. await navigator.clipboard.writeText(text);
  7250. return;
  7251. }
  7252. const textArea = document.createElement("textarea");
  7253. textArea.value = text;
  7254. textArea.style.position = "fixed";
  7255. textArea.style.opacity = "0";
  7256. document.body.appendChild(textArea);
  7257. textArea.focus();
  7258. textArea.select();
  7259. const successful = document.execCommand("copy");
  7260. document.body.removeChild(textArea);
  7261. if (!successful) {
  7262. throw new Error("Copy command was unsuccessful");
  7263. }
  7264. }
  7265. async function copyToClipboard(text) {
  7266. try {
  7267. await copyTextToClipboard(text);
  7268. showCopiedMessage();
  7269. } catch (err) {
  7270. console.error("Copy failed:", err);
  7271. alert("Failed to copy HTML: " + err.message);
  7272. }
  7273. }
  7274. function showCopiedMessage() {
  7275. const originalText = copyMarkdownButton.innerHTML;
  7276. copyMarkdownButton.innerHTML = '<i class="bi bi-check-lg"></i> Copied!';
  7277. setTimeout(() => {
  7278. copyMarkdownButton.innerHTML = originalText;
  7279. }, 2000);
  7280. }
  7281. // ============================================
  7282. // Share via URL (pako compression + base64url)
  7283. // ============================================
  7284. const MAX_SHARE_URL_LENGTH = 32000;
  7285. function encodeMarkdownForShare(text) {
  7286. if (typeof pako === 'undefined') throw new Error('pako not loaded');
  7287. const compressed = pako.deflate(new TextEncoder().encode(text));
  7288. const chunkSize = 0x8000;
  7289. let binary = '';
  7290. for (let i = 0; i < compressed.length; i += chunkSize) {
  7291. binary += String.fromCharCode.apply(null, compressed.subarray(i, i + chunkSize));
  7292. }
  7293. return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  7294. }
  7295. function decodeMarkdownFromShare(encoded) {
  7296. if (typeof pako === 'undefined') throw new Error('pako not loaded');
  7297. const base64 = encoded.replace(/-/g, '+').replace(/_/g, '/');
  7298. const binary = atob(base64);
  7299. const bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
  7300. return new TextDecoder().decode(pako.inflate(bytes));
  7301. }
  7302. // ============================================
  7303. // Share Modal
  7304. // ============================================
  7305. const shareModal = document.getElementById('share-modal');
  7306. const shareModalCloseX = document.getElementById('share-modal-close-icon');
  7307. const shareModalClose = document.getElementById('share-modal-close');
  7308. const shareUrlInput = document.getElementById('share-url-input');
  7309. const shareCopyBtn = document.getElementById('share-copy-btn');
  7310. const shareModeView = document.getElementById('share-mode-view');
  7311. const shareModeEdit = document.getElementById('share-mode-edit');
  7312. const shareCardView = document.getElementById('share-card-view');
  7313. const shareCardEdit = document.getElementById('share-card-edit');
  7314. function buildShareUrl(mode) {
  7315. const markdownText = markdownEditor.value;
  7316. let encoded;
  7317. try {
  7318. encoded = encodeMarkdownForShare(markdownText);
  7319. } catch (e) {
  7320. console.error('Share encoding failed:', e);
  7321. return null;
  7322. }
  7323. const isLocal = window.location.origin.includes('localhost') ||
  7324. window.location.origin.startsWith('file://') ||
  7325. typeof Neutralino !== 'undefined';
  7326. const baseUrl = isLocal
  7327. ? 'https://markdownviewer.pages.dev/'
  7328. : window.location.origin + window.location.pathname;
  7329. const base = baseUrl + '#share=' + encoded;
  7330. return mode === 'edit' ? base + '&edit=1' : base;
  7331. }
  7332. function updateShareUrlField() {
  7333. const mode = shareModeView.checked ? 'view' : 'edit';
  7334. const url = buildShareUrl(mode);
  7335. if (!url) {
  7336. shareUrlInput.value = 'Error generating link.';
  7337. shareCopyBtn.disabled = true;
  7338. return;
  7339. }
  7340. const tooLarge = url.length > MAX_SHARE_URL_LENGTH;
  7341. if (tooLarge) {
  7342. shareUrlInput.value = 'Document too large to share via URL.';
  7343. shareCopyBtn.disabled = true;
  7344. } else {
  7345. shareUrlInput.value = url;
  7346. shareCopyBtn.disabled = false;
  7347. }
  7348. }
  7349. function openShareModal() {
  7350. // PERF-002: Lazy-load pako on first share
  7351. if (typeof pako === 'undefined') {
  7352. loadScript(CDN.pako).then(function() {
  7353. openShareModal();
  7354. }).catch(function(e) {
  7355. console.error('Failed to load pako:', e);
  7356. alert('Failed to load sharing library. Please check your internet connection.');
  7357. });
  7358. return;
  7359. }
  7360. // Reset to view-only by default each time
  7361. shareModeView.checked = true;
  7362. syncShareCardStyles();
  7363. updateShareUrlField();
  7364. shareModal.style.display = '';
  7365. requestAnimationFrame(() => {
  7366. shareModal.classList.add('is-visible');
  7367. shareModal.setAttribute('aria-hidden', 'false');
  7368. });
  7369. }
  7370. function closeShareModal() {
  7371. shareModal.classList.remove('is-visible');
  7372. shareModal.setAttribute('aria-hidden', 'true');
  7373. shareModal.addEventListener('transitionend', function handler() {
  7374. shareModal.style.display = 'none';
  7375. shareModal.removeEventListener('transitionend', handler);
  7376. });
  7377. }
  7378. function syncShareCardStyles() {
  7379. if (shareModeView.checked) {
  7380. shareCardView.classList.add('is-selected');
  7381. shareCardEdit.classList.remove('is-selected');
  7382. } else {
  7383. shareCardEdit.classList.add('is-selected');
  7384. shareCardView.classList.remove('is-selected');
  7385. }
  7386. }
  7387. shareModeView.addEventListener('change', function () {
  7388. syncShareCardStyles();
  7389. updateShareUrlField();
  7390. });
  7391. shareModeEdit.addEventListener('change', function () {
  7392. syncShareCardStyles();
  7393. updateShareUrlField();
  7394. });
  7395. shareCopyBtn.addEventListener('click', function () {
  7396. const url = shareUrlInput.value;
  7397. if (!url || shareCopyBtn.disabled) return;
  7398. function onCopied() {
  7399. const orig = shareCopyBtn.innerHTML;
  7400. shareCopyBtn.innerHTML = '<i class="bi bi-check-lg"></i>';
  7401. setTimeout(() => { shareCopyBtn.innerHTML = orig; }, 2000);
  7402. }
  7403. if (navigator.clipboard && window.isSecureContext) {
  7404. navigator.clipboard.writeText(url).then(onCopied).catch(() => {});
  7405. } else {
  7406. try {
  7407. const tmp = document.createElement('textarea');
  7408. tmp.value = url;
  7409. document.body.appendChild(tmp);
  7410. tmp.select();
  7411. document.execCommand('copy');
  7412. document.body.removeChild(tmp);
  7413. onCopied();
  7414. } catch (_) {}
  7415. }
  7416. });
  7417. shareModalCloseX.addEventListener('click', closeShareModal);
  7418. shareModalClose.addEventListener('click', closeShareModal);
  7419. shareModal.addEventListener('click', function (e) {
  7420. if (e.target === shareModal) closeShareModal();
  7421. });
  7422. document.addEventListener('keydown', function (e) {
  7423. if (e.key === 'Escape' && shareModal.classList.contains('is-visible')) {
  7424. closeShareModal();
  7425. }
  7426. // Global Ctrl+F / Cmd+F interception
  7427. if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'f') {
  7428. e.preventDefault();
  7429. openFindReplaceModal();
  7430. const findInput = document.getElementById('find-replace-input');
  7431. if (findInput) {
  7432. findInput.focus();
  7433. findInput.select();
  7434. }
  7435. return;
  7436. }
  7437. // Global Ctrl+H / Cmd+H interception
  7438. if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'h') {
  7439. e.preventDefault();
  7440. openFindReplaceModal();
  7441. const replaceInput = document.getElementById('find-replace-with');
  7442. if (replaceInput) {
  7443. replaceInput.focus();
  7444. replaceInput.select();
  7445. }
  7446. return;
  7447. }
  7448. // Global Escape dismissal for find-replace panel
  7449. if (e.key === 'Escape' && isFindModalOpen) {
  7450. e.preventDefault();
  7451. closeFindReplaceModal();
  7452. return;
  7453. }
  7454. });
  7455. shareButton.addEventListener('click', openShareModal);
  7456. mobileShareButton.addEventListener('click', openShareModal);
  7457. function loadFromShareHash() {
  7458. // PERF-002: Lazy-load pako when loading shared URL content
  7459. if (typeof pako === 'undefined') {
  7460. const hash = window.location.hash;
  7461. if (!hash.startsWith('#share=')) return;
  7462. loadScript(CDN.pako).then(function() {
  7463. loadFromShareHash();
  7464. }).catch(function(e) {
  7465. console.error('Failed to load pako for shared URL:', e);
  7466. });
  7467. return;
  7468. }
  7469. const hash = window.location.hash;
  7470. if (!hash.startsWith('#share=')) return;
  7471. // Parse encoded content and optional &edit=1 flag.
  7472. // Hash format: #share=<encoded> or #share=<encoded>&edit=1
  7473. const rest = hash.slice('#share='.length);
  7474. const ampIdx = rest.indexOf('&');
  7475. const encoded = ampIdx === -1 ? rest : rest.slice(0, ampIdx);
  7476. const params = ampIdx === -1 ? '' : rest.slice(ampIdx + 1);
  7477. const isEdit = params.split('&').includes('edit=1');
  7478. if (!encoded) return;
  7479. try {
  7480. const decoded = decodeMarkdownFromShare(encoded);
  7481. markdownEditor.value = decoded;
  7482. renderMarkdown({ reason: 'document-load', showSkeleton: true });
  7483. saveCurrentTabState();
  7484. // Apply the correct view mode: edit=1 → split, default → preview only
  7485. setViewMode(isEdit ? 'split' : 'preview');
  7486. } catch (e) {
  7487. console.error("Failed to load shared content:", e);
  7488. alert("The shared URL could not be decoded. It may be corrupted or incomplete.");
  7489. }
  7490. }
  7491. loadFromShareHash();
  7492. // Full-window drag-and-drop: track nesting level for reliable enter/leave detection
  7493. let dragDepth = 0;
  7494. document.addEventListener("dragenter", function(e) {
  7495. if (e.dataTransfer && e.dataTransfer.types && e.dataTransfer.types.includes("Files")) {
  7496. e.preventDefault();
  7497. dragDepth++;
  7498. dragOverlay.classList.add("active");
  7499. dragOverlay.setAttribute("aria-hidden", "false");
  7500. }
  7501. }, false);
  7502. document.addEventListener("dragover", function(e) {
  7503. if (e.dataTransfer && e.dataTransfer.types && e.dataTransfer.types.includes("Files")) {
  7504. e.preventDefault();
  7505. }
  7506. }, false);
  7507. document.addEventListener("dragleave", function(e) {
  7508. if (e.dataTransfer && e.dataTransfer.types && e.dataTransfer.types.includes("Files")) {
  7509. dragDepth--;
  7510. if (dragDepth <= 0) {
  7511. dragDepth = 0;
  7512. dragOverlay.classList.remove("active");
  7513. dragOverlay.setAttribute("aria-hidden", "true");
  7514. }
  7515. }
  7516. }, false);
  7517. document.addEventListener("drop", function(e) {
  7518. e.preventDefault();
  7519. dragDepth = 0;
  7520. dragOverlay.classList.remove("active");
  7521. dragOverlay.setAttribute("aria-hidden", "true");
  7522. handleDrop(e);
  7523. }, false);
  7524. function handleDrop(e) {
  7525. const dt = e.dataTransfer;
  7526. const files = dt.files;
  7527. if (files.length) {
  7528. const file = files[0];
  7529. const isMarkdownFile =
  7530. file.type === "text/markdown" ||
  7531. /\.(md|markdown)$/i.test(file.name || "");
  7532. if (isMarkdownFile) {
  7533. importMarkdownFile(file);
  7534. } else {
  7535. alert("Please upload a Markdown file (.md or .markdown)");
  7536. }
  7537. }
  7538. }
  7539. document.addEventListener("keydown", function (e) {
  7540. if (document.activeElement === markdownEditor) {
  7541. const isCmdOrCtrl = e.ctrlKey || e.metaKey;
  7542. if (isCmdOrCtrl && !e.shiftKey && e.key.toLowerCase() === 'z') {
  7543. e.preventDefault();
  7544. executeUndo();
  7545. return;
  7546. } else if ((isCmdOrCtrl && e.shiftKey && e.key.toLowerCase() === 'z') || (isCmdOrCtrl && e.key.toLowerCase() === 'y')) {
  7547. e.preventDefault();
  7548. executeRedo();
  7549. return;
  7550. }
  7551. }
  7552. if ((e.ctrlKey || e.metaKey) && e.key === "s") {
  7553. e.preventDefault();
  7554. exportMd.click();
  7555. }
  7556. if ((e.ctrlKey || e.metaKey) && e.key === "c") {
  7557. const activeEl = document.activeElement;
  7558. const isTextControl = activeEl && (activeEl.tagName === "TEXTAREA" || activeEl.tagName === "INPUT");
  7559. const hasSelection = window.getSelection && window.getSelection().toString().trim().length > 0;
  7560. const editorHasSelection = markdownEditor.selectionStart !== markdownEditor.selectionEnd;
  7561. if (!isTextControl && !hasSelection && !editorHasSelection) {
  7562. e.preventDefault();
  7563. copyMarkdownButton.click();
  7564. }
  7565. }
  7566. // Story 1.2: Only allow sync toggle shortcut when in split view
  7567. if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === "s") {
  7568. e.preventDefault();
  7569. if (currentViewMode === 'split') {
  7570. toggleSyncScrolling();
  7571. }
  7572. }
  7573. const isDesktop = typeof Neutralino !== 'undefined';
  7574. // New tab (Ctrl+T on desktop, Alt+Shift+T on web/desktop)
  7575. if ((isDesktop && (e.ctrlKey || e.metaKey) && e.key === "t") || (e.altKey && e.shiftKey && e.key.toLowerCase() === "t")) {
  7576. e.preventDefault();
  7577. newTab();
  7578. }
  7579. // Close tab (Ctrl+W on desktop, Alt+Shift+W on web/desktop)
  7580. if ((isDesktop && (e.ctrlKey || e.metaKey) && e.key === "w") || (e.altKey && e.shiftKey && e.key.toLowerCase() === "w")) {
  7581. e.preventDefault();
  7582. closeTab(activeTabId);
  7583. }
  7584. // Close Mermaid zoom modal with Escape
  7585. if (e.key === "Escape") {
  7586. closeTabMenus();
  7587. closeMermaidModal();
  7588. }
  7589. });
  7590. document.getElementById('tab-reset-btn').addEventListener('click', function() {
  7591. resetAllTabs();
  7592. });
  7593. // ========================================
  7594. // MERMAID DIAGRAM TOOLBAR
  7595. // ========================================
  7596. /**
  7597. * Serialises an SVG element to a data URL suitable for use as an image source.
  7598. * Inline styles and dimensions are preserved so the PNG matches the rendered diagram.
  7599. */
  7600. function svgToDataUrl(svgEl) {
  7601. const clone = svgEl.cloneNode(true);
  7602. // Ensure explicit width/height so the canvas has the right dimensions
  7603. const bbox = svgEl.getBoundingClientRect();
  7604. if (!clone.getAttribute('width')) clone.setAttribute('width', Math.round(bbox.width));
  7605. if (!clone.getAttribute('height')) clone.setAttribute('height', Math.round(bbox.height));
  7606. const serialized = new XMLSerializer().serializeToString(clone);
  7607. return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(serialized);
  7608. }
  7609. /**
  7610. * Renders an SVG element onto a canvas and resolves with the canvas.
  7611. */
  7612. function svgToCanvas(svgEl) {
  7613. return new Promise((resolve, reject) => {
  7614. const bbox = svgEl.getBoundingClientRect();
  7615. const scale = window.devicePixelRatio || 1;
  7616. const width = Math.max(Math.round(bbox.width), 1);
  7617. const height = Math.max(Math.round(bbox.height), 1);
  7618. const canvas = document.createElement('canvas');
  7619. canvas.width = width * scale;
  7620. canvas.height = height * scale;
  7621. const ctx = canvas.getContext('2d');
  7622. ctx.scale(scale, scale);
  7623. // Fill background matching current theme using the CSS variable value
  7624. const bgColor = getComputedStyle(document.documentElement)
  7625. .getPropertyValue('--bg-color').trim() || '#ffffff';
  7626. ctx.fillStyle = bgColor;
  7627. ctx.fillRect(0, 0, width, height);
  7628. const img = new Image();
  7629. img.onload = () => { ctx.drawImage(img, 0, 0, width, height); resolve(canvas); };
  7630. img.onerror = reject;
  7631. img.src = svgToDataUrl(svgEl);
  7632. });
  7633. }
  7634. /** Downloads the diagram in the given container as a PNG file. */
  7635. async function downloadMermaidPng(container, btn) {
  7636. const svgEl = container.querySelector('svg');
  7637. if (!svgEl) return;
  7638. const original = btn.innerHTML;
  7639. btn.innerHTML = '<i class="bi bi-hourglass-split"></i>';
  7640. try {
  7641. const canvas = await svgToCanvas(svgEl);
  7642. canvas.toBlob(blob => {
  7643. const url = URL.createObjectURL(blob);
  7644. const a = document.createElement('a');
  7645. a.href = url;
  7646. a.download = `diagram-${Date.now()}.png`;
  7647. a.click();
  7648. URL.revokeObjectURL(url);
  7649. btn.innerHTML = '<i class="bi bi-check-lg"></i>';
  7650. setTimeout(() => { btn.innerHTML = original; }, 1500);
  7651. }, 'image/png');
  7652. } catch (e) {
  7653. console.error('Mermaid PNG export failed:', e);
  7654. btn.innerHTML = original;
  7655. }
  7656. }
  7657. /** Copies the diagram in the given container as a PNG image to the clipboard. */
  7658. async function copyMermaidImage(container, btn) {
  7659. const svgEl = container.querySelector('svg');
  7660. if (!svgEl) return;
  7661. const original = btn.innerHTML;
  7662. btn.innerHTML = '<i class="bi bi-hourglass-split"></i>';
  7663. try {
  7664. const canvas = await svgToCanvas(svgEl);
  7665. canvas.toBlob(async blob => {
  7666. try {
  7667. await navigator.clipboard.write([
  7668. new ClipboardItem({ 'image/png': blob })
  7669. ]);
  7670. btn.innerHTML = '<i class="bi bi-check-lg"></i> Copied!';
  7671. } catch (clipErr) {
  7672. console.error('Clipboard write failed:', clipErr);
  7673. btn.innerHTML = '<i class="bi bi-x-lg"></i>';
  7674. }
  7675. setTimeout(() => { btn.innerHTML = original; }, 1800);
  7676. }, 'image/png');
  7677. } catch (e) {
  7678. console.error('Mermaid copy failed:', e);
  7679. btn.innerHTML = original;
  7680. }
  7681. }
  7682. /** Downloads the SVG source of a diagram. */
  7683. function downloadMermaidSvg(container, btn) {
  7684. const svgEl = container.querySelector('svg');
  7685. if (!svgEl) return;
  7686. const clone = svgEl.cloneNode(true);
  7687. const serialized = new XMLSerializer().serializeToString(clone);
  7688. const blob = new Blob([serialized], { type: 'image/svg+xml' });
  7689. const url = URL.createObjectURL(blob);
  7690. const a = document.createElement('a');
  7691. a.href = url;
  7692. a.download = `diagram-${Date.now()}.svg`;
  7693. a.click();
  7694. URL.revokeObjectURL(url);
  7695. const original = btn.innerHTML;
  7696. btn.innerHTML = '<i class="bi bi-check-lg"></i>';
  7697. setTimeout(() => { btn.innerHTML = original; }, 1500);
  7698. }
  7699. // ---- Zoom modal state ----
  7700. let modalZoomScale = 1;
  7701. let modalPanX = 0;
  7702. let modalPanY = 0;
  7703. let modalIsDragging = false;
  7704. let modalDragStart = { x: 0, y: 0 };
  7705. let modalCurrentSvgEl = null;
  7706. const mermaidZoomModal = document.getElementById('mermaid-zoom-modal');
  7707. const mermaidModalDiagram = document.getElementById('mermaid-modal-diagram');
  7708. function applyModalTransform() {
  7709. if (modalCurrentSvgEl) {
  7710. modalCurrentSvgEl.style.transform =
  7711. `translate(${modalPanX}px, ${modalPanY}px) scale(${modalZoomScale})`;
  7712. }
  7713. }
  7714. function closeMermaidModal() {
  7715. if (!mermaidZoomModal.classList.contains('active')) return;
  7716. mermaidZoomModal.classList.remove('active');
  7717. // PERF-007: Clear elements using textContent
  7718. mermaidModalDiagram.textContent = '';
  7719. modalCurrentSvgEl = null;
  7720. modalZoomScale = 1;
  7721. modalPanX = 0;
  7722. modalPanY = 0;
  7723. }
  7724. /** Opens the zoom modal with the SVG from the given container. */
  7725. function openMermaidZoomModal(container) {
  7726. const svgEl = container.querySelector('svg');
  7727. if (!svgEl) return;
  7728. // PERF-007: Clear elements using textContent
  7729. mermaidModalDiagram.textContent = '';
  7730. modalZoomScale = 1;
  7731. modalPanX = 0;
  7732. modalPanY = 0;
  7733. const svgClone = svgEl.cloneNode(true);
  7734. // Remove fixed dimensions so it sizes naturally inside the modal
  7735. svgClone.removeAttribute('width');
  7736. svgClone.removeAttribute('height');
  7737. svgClone.style.width = 'auto';
  7738. svgClone.style.height = 'auto';
  7739. svgClone.style.maxWidth = '80vw';
  7740. svgClone.style.maxHeight = '60vh';
  7741. svgClone.style.transformOrigin = 'center';
  7742. mermaidModalDiagram.appendChild(svgClone);
  7743. modalCurrentSvgEl = svgClone;
  7744. mermaidZoomModal.classList.add('active');
  7745. }
  7746. // Modal close button
  7747. document.getElementById('mermaid-modal-close').addEventListener('click', closeMermaidModal);
  7748. // Click backdrop to close
  7749. mermaidZoomModal.addEventListener('click', function(e) {
  7750. if (e.target === mermaidZoomModal) closeMermaidModal();
  7751. });
  7752. // Zoom controls
  7753. document.getElementById('mermaid-modal-zoom-in').addEventListener('click', () => {
  7754. modalZoomScale = Math.min(modalZoomScale + 0.25, 10);
  7755. applyModalTransform();
  7756. });
  7757. document.getElementById('mermaid-modal-zoom-out').addEventListener('click', () => {
  7758. modalZoomScale = Math.max(modalZoomScale - 0.25, 0.1);
  7759. applyModalTransform();
  7760. });
  7761. document.getElementById('mermaid-modal-zoom-reset').addEventListener('click', () => {
  7762. modalZoomScale = 1; modalPanX = 0; modalPanY = 0;
  7763. applyModalTransform();
  7764. });
  7765. // Mouse-wheel zoom inside modal
  7766. mermaidModalDiagram.addEventListener('wheel', function(e) {
  7767. e.preventDefault();
  7768. const delta = e.deltaY < 0 ? 0.15 : -0.15;
  7769. modalZoomScale = Math.min(Math.max(modalZoomScale + delta, 0.1), 10);
  7770. applyModalTransform();
  7771. }, { passive: false });
  7772. // Drag to pan inside modal
  7773. mermaidModalDiagram.addEventListener('mousedown', function(e) {
  7774. modalIsDragging = true;
  7775. modalDragStart = { x: e.clientX - modalPanX, y: e.clientY - modalPanY };
  7776. mermaidModalDiagram.classList.add('dragging');
  7777. });
  7778. document.addEventListener('mousemove', function(e) {
  7779. if (!modalIsDragging) return;
  7780. modalPanX = e.clientX - modalDragStart.x;
  7781. modalPanY = e.clientY - modalDragStart.y;
  7782. applyModalTransform();
  7783. });
  7784. document.addEventListener('mouseup', function() {
  7785. if (modalIsDragging) {
  7786. modalIsDragging = false;
  7787. mermaidModalDiagram.classList.remove('dragging');
  7788. }
  7789. });
  7790. // Modal download buttons (operate on the currently displayed SVG)
  7791. document.getElementById('mermaid-modal-download-png').addEventListener('click', async function() {
  7792. if (!modalCurrentSvgEl) return;
  7793. const btn = this;
  7794. const original = btn.innerHTML;
  7795. btn.innerHTML = '<i class="bi bi-hourglass-split"></i>';
  7796. try {
  7797. // Use the original SVG (with dimensions) for proper PNG rendering
  7798. const canvas = await svgToCanvas(modalCurrentSvgEl);
  7799. canvas.toBlob(blob => {
  7800. const url = URL.createObjectURL(blob);
  7801. const a = document.createElement('a');
  7802. a.href = url; a.download = `diagram-${Date.now()}.png`; a.click();
  7803. URL.revokeObjectURL(url);
  7804. btn.innerHTML = '<i class="bi bi-check-lg"></i>';
  7805. setTimeout(() => { btn.innerHTML = original; }, 1500);
  7806. }, 'image/png');
  7807. } catch (e) {
  7808. console.error('Modal PNG export failed:', e);
  7809. btn.innerHTML = original;
  7810. }
  7811. });
  7812. document.getElementById('mermaid-modal-copy').addEventListener('click', async function() {
  7813. if (!modalCurrentSvgEl) return;
  7814. const btn = this;
  7815. const original = btn.innerHTML;
  7816. btn.innerHTML = '<i class="bi bi-hourglass-split"></i>';
  7817. try {
  7818. const canvas = await svgToCanvas(modalCurrentSvgEl);
  7819. canvas.toBlob(async blob => {
  7820. try {
  7821. await navigator.clipboard.write([
  7822. new ClipboardItem({ 'image/png': blob })
  7823. ]);
  7824. btn.innerHTML = '<i class="bi bi-check-lg"></i> Copied!';
  7825. } catch (clipErr) {
  7826. console.error('Clipboard write failed:', clipErr);
  7827. btn.innerHTML = '<i class="bi bi-x-lg"></i>';
  7828. }
  7829. setTimeout(() => { btn.innerHTML = original; }, 1800);
  7830. }, 'image/png');
  7831. } catch (e) {
  7832. console.error('Modal copy failed:', e);
  7833. btn.innerHTML = original;
  7834. }
  7835. });
  7836. document.getElementById('mermaid-modal-download-svg').addEventListener('click', function() {
  7837. if (!modalCurrentSvgEl) return;
  7838. const serialized = new XMLSerializer().serializeToString(modalCurrentSvgEl);
  7839. const blob = new Blob([serialized], { type: 'image/svg+xml' });
  7840. const url = URL.createObjectURL(blob);
  7841. const a = document.createElement('a');
  7842. a.href = url; a.download = `diagram-${Date.now()}.svg`; a.click();
  7843. URL.revokeObjectURL(url);
  7844. });
  7845. /**
  7846. * Adds the hover toolbar to every rendered Mermaid container.
  7847. * Safe to call multiple times – existing toolbars are not duplicated.
  7848. */
  7849. function addMermaidToolbars() {
  7850. markdownPreview.querySelectorAll('.mermaid-container').forEach(container => {
  7851. if (container.querySelector('.mermaid-toolbar')) return; // already added
  7852. const svgEl = container.querySelector('svg');
  7853. if (!svgEl) return; // diagram not yet rendered
  7854. const toolbar = document.createElement('div');
  7855. toolbar.className = 'mermaid-toolbar';
  7856. toolbar.setAttribute('aria-label', 'Diagram actions');
  7857. const btnZoom = document.createElement('button');
  7858. btnZoom.className = 'mermaid-toolbar-btn';
  7859. btnZoom.title = 'Zoom diagram';
  7860. btnZoom.setAttribute('aria-label', 'Zoom diagram');
  7861. btnZoom.innerHTML = '<i class="bi bi-arrows-fullscreen"></i>';
  7862. btnZoom.addEventListener('click', () => openMermaidZoomModal(container));
  7863. const btnPng = document.createElement('button');
  7864. btnPng.className = 'mermaid-toolbar-btn';
  7865. btnPng.title = 'Download PNG';
  7866. btnPng.setAttribute('aria-label', 'Download PNG');
  7867. btnPng.innerHTML = '<i class="bi bi-file-image"></i> PNG';
  7868. btnPng.addEventListener('click', () => downloadMermaidPng(container, btnPng));
  7869. const btnCopy = document.createElement('button');
  7870. btnCopy.className = 'mermaid-toolbar-btn';
  7871. btnCopy.title = 'Copy image to clipboard';
  7872. btnCopy.setAttribute('aria-label', 'Copy image to clipboard');
  7873. btnCopy.innerHTML = '<i class="bi bi-clipboard-image"></i> Copy';
  7874. btnCopy.addEventListener('click', () => copyMermaidImage(container, btnCopy));
  7875. const btnSvg = document.createElement('button');
  7876. btnSvg.className = 'mermaid-toolbar-btn';
  7877. btnSvg.title = 'Download SVG';
  7878. btnSvg.setAttribute('aria-label', 'Download SVG');
  7879. btnSvg.innerHTML = '<i class="bi bi-filetype-svg"></i> SVG';
  7880. btnSvg.addEventListener('click', () => downloadMermaidSvg(container, btnSvg));
  7881. toolbar.appendChild(btnZoom);
  7882. toolbar.appendChild(btnCopy);
  7883. toolbar.appendChild(btnPng);
  7884. toolbar.appendChild(btnSvg);
  7885. container.appendChild(toolbar);
  7886. });
  7887. }
  7888. // ==========================================================================
  7889. // Aegis SEO agency Multilingual & Internationalization (i18n) engine
  7890. // ==========================================================================
  7891. const I18N_DICTS = {
  7892. en: {
  7893. title: "Markdown Viewer",
  7894. syncOff: "Sync Off",
  7895. syncOn: "Sync On",
  7896. import: "Import",
  7897. importFile: "From files",
  7898. importGithub: "From GitHub",
  7899. export: "Export",
  7900. exportMd: "Markdown (.md)",
  7901. exportHtml: "HTML",
  7902. exportPdf: "PDF",
  7903. copy: "Copy",
  7904. copied: "Copied!",
  7905. share: "Share",
  7906. reset: "Reset",
  7907. editor: "Editor",
  7908. split: "Split",
  7909. preview: "Preview",
  7910. minRead: "Min Read",
  7911. words: "Words",
  7912. chars: "Chars",
  7913. switchRtl: "Switch to RTL",
  7914. switchLtr: "Switch to LTR",
  7915. darkMode: "Dark Mode",
  7916. lightMode: "Light Mode",
  7917. helpTitle: "Markdown Viewer Help",
  7918. aboutTitle: "About Markdown",
  7919. shareTitle: "Share Document",
  7920. renameTitle: "Rename file",
  7921. insertLink: "Insert link",
  7922. insertRef: "Insert reference",
  7923. insertImg: "Insert image",
  7924. insertTable: "Insert table",
  7925. findReplace: "Find & Replace",
  7926. placeholder: "Type your markdown here...",
  7927. loadingEmojis: "Loading emojis...",
  7928. loadingFiles: "Fetching file tree..."
  7929. },
  7930. zh: {
  7931. title: "Markdown 阅读器",
  7932. syncOff: "同步关闭",
  7933. syncOn: "同步开启",
  7934. import: "导入",
  7935. importFile: "本地文件导入",
  7936. importGithub: "从 GitHub 导入",
  7937. export: "导出",
  7938. exportMd: "导出 Markdown (.md)",
  7939. exportHtml: "导出 HTML",
  7940. exportPdf: "导出 PDF",
  7941. copy: "复制",
  7942. copied: "已复制!",
  7943. share: "分享",
  7944. reset: "重置",
  7945. editor: "编辑器",
  7946. split: "分栏预览",
  7947. preview: "纯预览",
  7948. minRead: "分钟阅读",
  7949. words: "字数",
  7950. chars: "字符数",
  7951. switchRtl: "切换为右至左布局",
  7952. switchLtr: "切换为左至右布局",
  7953. darkMode: "深色模式",
  7954. lightMode: "浅色模式",
  7955. helpTitle: "Markdown 阅读器帮助说明",
  7956. aboutTitle: "关于 Markdown 阅读器",
  7957. shareTitle: "分享当前文档",
  7958. renameTitle: "重命名文件",
  7959. insertLink: "插入超链接",
  7960. insertRef: "插入脚注引用",
  7961. insertImg: "插入图片",
  7962. insertTable: "插入表格",
  7963. findReplace: "查找与替换",
  7964. placeholder: "在此输入您的 Markdown 文本...",
  7965. loadingEmojis: "正在加载表情...",
  7966. loadingFiles: "正在获取文件树..."
  7967. },
  7968. ja: {
  7969. title: "Markdown ビューア",
  7970. syncOff: "同期オフ",
  7971. syncOn: "同期オン",
  7972. import: "インポート",
  7973. importFile: "ファイルから",
  7974. importGithub: "GitHub から",
  7975. export: "エクスポート",
  7976. exportMd: "Markdown (.md)",
  7977. exportHtml: "HTML",
  7978. exportPdf: "PDF",
  7979. copy: "コピー",
  7980. copied: "コピー完了!",
  7981. share: "共有",
  7982. reset: "リセット",
  7983. editor: "エディタ",
  7984. split: "分割表示",
  7985. preview: "プレビュー",
  7986. minRead: "分 読了",
  7987. words: "単語数",
  7988. chars: "文字数",
  7989. switchRtl: "RTL表示に切替",
  7990. switchLtr: "LTR表示に切替",
  7991. darkMode: "ダークモード",
  7992. lightMode: "ライトモード",
  7993. helpTitle: "Markdown ビューア ヘルプ",
  7994. aboutTitle: "Markdown について",
  7995. shareTitle: "ドキュメントの共有",
  7996. renameTitle: "ファイル名の変更",
  7997. insertLink: "リンクの挿入",
  7998. insertRef: "参照の挿入",
  7999. insertImg: "画像の挿入",
  8000. insertTable: "テーブルの挿入",
  8001. findReplace: "検索と置換",
  8002. placeholder: "ここにMarkdownを入力してください...",
  8003. loadingEmojis: "絵文字を読み込んでいます...",
  8004. loadingFiles: "ファイルツリーを取得しています..."
  8005. },
  8006. ko: {
  8007. title: "마크다운 뷰어",
  8008. syncOff: "동기화 끄기",
  8009. syncOn: "동기화 켜기",
  8010. import: "가져오기",
  8011. importFile: "로컬 파일에서",
  8012. importGithub: "GitHub에서",
  8013. export: "내보내기",
  8014. exportMd: "마크다운 (.md)",
  8015. exportHtml: "HTML로 내보내기",
  8016. exportPdf: "PDF로 내보내기",
  8017. copy: "복사",
  8018. copied: "복사됨!",
  8019. share: "공유",
  8020. reset: "초기화",
  8021. editor: "편집기",
  8022. split: "분할 보기",
  8023. preview: "미리보기",
  8024. minRead: "분 읽기",
  8025. words: "단어 수",
  8026. chars: "글자 수",
  8027. switchRtl: "우측 정렬로 전환",
  8028. switchLtr: "좌측 정렬로 전환",
  8029. darkMode: "다크 모드",
  8030. lightMode: "라이트 모드",
  8031. helpTitle: "마크다운 뷰어 도움말",
  8032. aboutTitle: "마크다운 정보",
  8033. shareTitle: "문서 공유",
  8034. renameTitle: "파일 이름 바꾸기",
  8035. insertLink: "링크 삽입",
  8036. insertRef: "참조 삽입",
  8037. insertImg: "이미지 삽입",
  8038. insertTable: "표 삽입",
  8039. findReplace: "찾기 및 바꾸기",
  8040. placeholder: "여기에 마크다운 내용을 입력하세요...",
  8041. loadingEmojis: "이모지 로딩 중...",
  8042. loadingFiles: "파일 트리 가져오는 중..."
  8043. },
  8044. pt: {
  8045. title: "Visualizador de Markdown",
  8046. syncOff: "Desativar Sincronia",
  8047. syncOn: "Ativar Sincronia",
  8048. import: "Importar",
  8049. importFile: "De arquivos",
  8050. importGithub: "Do GitHub",
  8051. export: "Exportar",
  8052. exportMd: "Markdown (.md)",
  8053. exportHtml: "HTML",
  8054. exportPdf: "PDF",
  8055. copy: "Copiar",
  8056. copied: "Copiado!",
  8057. share: "Compartilhar",
  8058. reset: "Redefinir",
  8059. editor: "Editor",
  8060. split: "Dividido",
  8061. preview: "Visualizar",
  8062. minRead: "Min de leitura",
  8063. words: "Palavras",
  8064. chars: "Caracteres",
  8065. switchRtl: "Mudar para RTL",
  8066. switchLtr: "Mudar para LTR",
  8067. darkMode: "Modo Escuro",
  8068. lightMode: "Modo Claro",
  8069. helpTitle: "Ajuda do Visualizador de Markdown",
  8070. aboutTitle: "Sobre o Markdown",
  8071. shareTitle: "Compartilhar Documento",
  8072. renameTitle: "Renomear arquivo",
  8073. insertLink: "Inserir link",
  8074. insertRef: "Inserir referência",
  8075. insertImg: "Inserir imagem",
  8076. insertTable: "Inserir tabela",
  8077. findReplace: "Localizar & Substituir",
  8078. placeholder: "Digite seu markdown aqui...",
  8079. loadingEmojis: "Carregando emojis...",
  8080. loadingFiles: "Buscando árvore de arquivos..."
  8081. },
  8082. es: {
  8083. title: "Visualizador de Markdown",
  8084. syncOff: "Sincronización desactivada",
  8085. syncOn: "Sincronización activada",
  8086. import: "Importar",
  8087. importFile: "Desde archivos",
  8088. importGithub: "Desde GitHub",
  8089. export: "Exportar",
  8090. exportMd: "Markdown (.md)",
  8091. exportHtml: "HTML",
  8092. exportPdf: "PDF",
  8093. copy: "Copiar",
  8094. copied: "¡Copiado!",
  8095. share: "Compartir",
  8096. reset: "Restablecer",
  8097. editor: "Editor",
  8098. split: "Dividido",
  8099. preview: "Previsualizar",
  8100. minRead: "Min de lectura",
  8101. words: "Palabras",
  8102. chars: "Caracteres",
  8103. switchRtl: "Cambiar a RTL",
  8104. switchLtr: "Cambiar a LTR",
  8105. darkMode: "Modo oscuro",
  8106. lightMode: "Modo claro",
  8107. helpTitle: "Ayuda del Visualizador de Markdown",
  8108. aboutTitle: "Acerca de Markdown",
  8109. shareTitle: "Compartir documento",
  8110. renameTitle: "Renombrar archivo",
  8111. insertLink: "Insertar enlace",
  8112. insertRef: "Insertar referencia",
  8113. insertImg: "Insertar imagen",
  8114. insertTable: "Insertar tabla",
  8115. findReplace: "Buscar y reemplazar",
  8116. placeholder: "Escribe tu markdown aquí...",
  8117. loadingEmojis: "Cargando emojis...",
  8118. loadingFiles: "Obteniendo árbol de archivos..."
  8119. },
  8120. fr: {
  8121. title: "Lecteur Markdown",
  8122. syncOff: "Désactiver la synchro",
  8123. syncOn: "Activer la synchro",
  8124. import: "Importer",
  8125. importFile: "Depuis des fichiers",
  8126. importGithub: "Depuis GitHub",
  8127. export: "Exporter",
  8128. exportMd: "Markdown (.md)",
  8129. exportHtml: "HTML",
  8130. exportPdf: "PDF",
  8131. copy: "Copier",
  8132. copied: "Copié !",
  8133. share: "Partager",
  8134. reset: "Réinitialiser",
  8135. editor: "Éditeur",
  8136. split: "Divisé",
  8137. preview: "Aperçu",
  8138. minRead: "Min de lecture",
  8139. words: "Mots",
  8140. chars: "Caractères",
  8141. switchRtl: "Passer à RTL",
  8142. switchLtr: "Passer à LTR",
  8143. darkMode: "Mode sombre",
  8144. lightMode: "Mode clair",
  8145. helpTitle: "Aide du Lecteur Markdown",
  8146. aboutTitle: "À propos de Markdown",
  8147. shareTitle: "Partager le document",
  8148. renameTitle: "Renommer le fichier",
  8149. insertLink: "Insérer un lien",
  8150. insertRef: "Insérer une référence",
  8151. insertImg: "Insérer une image",
  8152. insertTable: "Insérer un tableau",
  8153. findReplace: "Rechercher & remplacer",
  8154. placeholder: "Saisissez votre markdown ici...",
  8155. loadingEmojis: "Chargement des émojis...",
  8156. loadingFiles: "Récupération de l'arborescence des fichiers..."
  8157. },
  8158. de: {
  8159. title: "Markdown Viewer",
  8160. syncOff: "Synchronisierung aus",
  8161. syncOn: "Synchronisierung an",
  8162. import: "Importieren",
  8163. importFile: "Aus Dateien",
  8164. importGithub: "Aus GitHub",
  8165. export: "Exportieren",
  8166. exportMd: "Markdown (.md)",
  8167. exportHtml: "HTML",
  8168. exportPdf: "PDF",
  8169. copy: "Kopieren",
  8170. copied: "Kopiert!",
  8171. share: "Teilen",
  8172. reset: "Zurücksetzen",
  8173. editor: "Editor",
  8174. split: "Geteilt",
  8175. preview: "Vorschau",
  8176. minRead: "Min. Lesezeit",
  8177. words: "Wörter",
  8178. chars: "Zeichen",
  8179. switchRtl: "Zu RTL wechseln",
  8180. switchLtr: "Zu LTR wechseln",
  8181. darkMode: "Dunkelmodus",
  8182. lightMode: "Heller Modus",
  8183. helpTitle: "Markdown Viewer Hilfe",
  8184. aboutTitle: "Über Markdown",
  8185. shareTitle: "Dokument teilen",
  8186. renameTitle: "Datei umbenennen",
  8187. insertLink: "Link einfügen",
  8188. insertRef: "Referenz einfügen",
  8189. insertImg: "Bild einfügen",
  8190. insertTable: "Tabelle einfügen",
  8191. findReplace: "Suchen & Ersetzen",
  8192. placeholder: "Geben Sie hier Ihr Markdown ein...",
  8193. loadingEmojis: "Emojis werden geladen...",
  8194. loadingFiles: "Dateibaum wird abgerufen..."
  8195. },
  8196. ru: {
  8197. title: "Просмотрщик Markdown",
  8198. syncOff: "Синхронизация выкл",
  8199. syncOn: "Синхронизация вкл",
  8200. import: "Импорт",
  8201. importFile: "Из файлов",
  8202. importGithub: "Из GitHub",
  8203. export: "Экспорт",
  8204. exportMd: "Markdown (.md)",
  8205. exportHtml: "HTML",
  8206. exportPdf: "PDF",
  8207. copy: "Копировать",
  8208. copied: "Скопировано!",
  8209. share: "Поделиться",
  8210. reset: "Сбросить",
  8211. editor: "Редактор",
  8212. split: "Разделение",
  8213. preview: "Предпросмотр",
  8214. minRead: "Мин чтения",
  8215. words: "Слов",
  8216. chars: "Символов",
  8217. switchRtl: "Переключить на RTL",
  8218. switchLtr: "Переключить на LTR",
  8219. darkMode: "Темная тема",
  8220. lightMode: "Светлая тема",
  8221. helpTitle: "Справка Markdown Viewer",
  8222. aboutTitle: "О Markdown",
  8223. shareTitle: "Поделиться документом",
  8224. renameTitle: "Переименовать файл",
  8225. insertLink: "Вставить ссылку",
  8226. insertRef: "Вставить сноску",
  8227. insertImg: "Вставить изображение",
  8228. insertTable: "Вставить таблицу",
  8229. findReplace: "Найти и заменить",
  8230. placeholder: "Введите здесь ваш markdown...",
  8231. loadingEmojis: "Загрузка эмодзи...",
  8232. loadingFiles: "Получение списка файлов..."
  8233. },
  8234. it: {
  8235. title: "Visualizzatore Markdown",
  8236. syncOff: "Sincronia disattivata",
  8237. syncOn: "Sincronia attivata",
  8238. import: "Importa",
  8239. importFile: "Da file",
  8240. importGithub: "Da GitHub",
  8241. export: "Esporta",
  8242. exportMd: "Markdown (.md)",
  8243. exportHtml: "HTML",
  8244. exportPdf: "PDF",
  8245. copy: "Copia",
  8246. copied: "Copiato!",
  8247. share: "Condividi",
  8248. reset: "Ripristina",
  8249. editor: "Editor",
  8250. split: "Diviso",
  8251. preview: "Anteprima",
  8252. minRead: "Min di lettura",
  8253. words: "Parole",
  8254. chars: "Caratteri",
  8255. switchRtl: "Passa a RTL",
  8256. switchLtr: "Passa a LTR",
  8257. darkMode: "Tema scuro",
  8258. lightMode: "Tema chiaro",
  8259. helpTitle: "Aiuto di Visualizzatore Markdown",
  8260. aboutTitle: "Informazioni su Markdown",
  8261. shareTitle: "Condividi documento",
  8262. renameTitle: "Rinomina file",
  8263. insertLink: "Inserisci link",
  8264. insertRef: "Inserisci riferimento",
  8265. insertImg: "Inserisci immagine",
  8266. insertTable: "Inserisci tabella",
  8267. findReplace: "Trova e sostituisci",
  8268. placeholder: "Scrivi il tuo markdown qui...",
  8269. loadingEmojis: "Caricamento emoji...",
  8270. loadingFiles: "Recupero albero dei file..."
  8271. },
  8272. tr: {
  8273. title: "Markdown Görüntüleyici",
  8274. syncOff: "Senkronizasyonu Kapat",
  8275. syncOn: "Senkronizasyonu Aç",
  8276. import: "İçe Aktar",
  8277. importFile: "Dosyalardan",
  8278. importGithub: "GitHub'dan",
  8279. export: "Dışa Aktar",
  8280. exportMd: "Markdown (.md)",
  8281. exportHtml: "HTML",
  8282. exportPdf: "PDF",
  8283. copy: "Kopyala",
  8284. copied: "Kopyalandı!",
  8285. share: "Paylaş",
  8286. reset: "Sıfırla",
  8287. editor: "Editör",
  8288. split: "Bölünmüş",
  8289. preview: "Önizleme",
  8290. minRead: "Dk Okuma",
  8291. words: "Kelime",
  8292. chars: "Karakter",
  8293. switchRtl: "RTL'ye Geç",
  8294. switchLtr: "LTR'ye Geç",
  8295. darkMode: "Karanlık Mod",
  8296. lightMode: "Aydınlık Mod",
  8297. helpTitle: "Markdown Görüntüleyici Yardımı",
  8298. aboutTitle: "Markdown Hakkında",
  8299. shareTitle: "Belgeyi Paylaş",
  8300. renameTitle: "Dosyayı yeniden adlandır",
  8301. insertLink: "Bağlantı ekle",
  8302. insertRef: "Referans ekle",
  8303. insertImg: "Resim ekle",
  8304. insertTable: "Tablo ekle",
  8305. findReplace: "Bul ve Değiştir",
  8306. placeholder: "Markdown'ınızı buraya yazın...",
  8307. loadingEmojis: "Emoji'ler yükleniyor...",
  8308. loadingFiles: "Dosya ağacı alınıyor..."
  8309. },
  8310. pl: {
  8311. title: "Czytnik Markdown",
  8312. syncOff: "Wyłącz synchronizację",
  8313. syncOn: "Włącz synchronizację",
  8314. import: "Importuj",
  8315. importFile: "Z plików",
  8316. importGithub: "Z GitHub",
  8317. export: "Eksportuj",
  8318. exportMd: "Markdown (.md)",
  8319. exportHtml: "HTML",
  8320. exportPdf: "PDF",
  8321. copy: "Kopiuj",
  8322. copied: "Skopiowano!",
  8323. share: "Udostępnij",
  8324. reset: "Resetuj",
  8325. editor: "Edytor",
  8326. split: "Podzielony",
  8327. preview: "Podgląd",
  8328. minRead: "Min. czytania",
  8329. words: "Słowa",
  8330. chars: "Znaki",
  8331. switchRtl: "Przełącz na RTL",
  8332. switchLtr: "Przełącz na LTR",
  8333. darkMode: "Tryb ciemny",
  8334. lightMode: "Tryb jasny",
  8335. helpTitle: "Pomoc Czytnika Markdown",
  8336. aboutTitle: "O Markdown",
  8337. shareTitle: "Udostępnij dokument",
  8338. renameTitle: "Zmień nazwę pliku",
  8339. insertLink: "Wstaw link",
  8340. insertRef: "Wstaw odnośnik",
  8341. insertImg: "Wstaw obraz",
  8342. insertTable: "Wstaw tabelę",
  8343. findReplace: "Znajdź i zamień",
  8344. placeholder: "Wpisz tutaj swój markdown...",
  8345. loadingEmojis: "Ładowanie emoji...",
  8346. loadingFiles: "Pobieranie drzewa plików..."
  8347. },
  8348. tw: {
  8349. title: "Markdown 閱讀器",
  8350. syncOff: "同步關閉",
  8351. syncOn: "同步開啟",
  8352. import: "匯入",
  8353. importFile: "本地檔案匯入",
  8354. importGithub: "從 GitHub 匯入",
  8355. export: "匯出",
  8356. exportMd: "匯出 Markdown (.md)",
  8357. exportHtml: "匯出 HTML",
  8358. exportPdf: "匯出 PDF",
  8359. copy: "複製",
  8360. copied: "已複製!",
  8361. share: "分享",
  8362. reset: "重置",
  8363. editor: "編輯器",
  8364. split: "分欄預覽",
  8365. preview: "純預覽",
  8366. minRead: "分鐘閱讀",
  8367. words: "字數",
  8368. chars: "字元數",
  8369. switchRtl: "切換為右至左佈局",
  8370. switchLtr: "切換為左至右佈局",
  8371. darkMode: "深色模式",
  8372. lightMode: "淺色模式",
  8373. helpTitle: "Markdown 閱讀器說明",
  8374. aboutTitle: "關於 Markdown 閱讀器",
  8375. shareTitle: "分享當前文件",
  8376. renameTitle: "重新命名檔案",
  8377. insertLink: "插入超連結",
  8378. insertRef: "插入腳註引用",
  8379. insertImg: "插入圖片",
  8380. insertTable: "插入表格",
  8381. findReplace: "尋找與取代",
  8382. placeholder: "在此輸入您的 Markdown 文本...",
  8383. loadingEmojis: "正在載入表情...",
  8384. loadingFiles: "正在獲取檔案樹..."
  8385. },
  8386. uk: {
  8387. title: "Переглядач Markdown",
  8388. syncOff: "Вимкнути синхронізацію",
  8389. syncOn: "Увімкнути синхронізацію",
  8390. import: "Імпорт",
  8391. importFile: "З файлів",
  8392. importGithub: "З GitHub",
  8393. export: "Експорт",
  8394. exportMd: "Markdown (.md)",
  8395. exportHtml: "HTML",
  8396. exportPdf: "PDF",
  8397. copy: "Копіювати",
  8398. copied: "Скопійовано!",
  8399. share: "Поділитися",
  8400. reset: "Скинути",
  8401. editor: "Редактор",
  8402. split: "Розділений",
  8403. preview: "Перегляд",
  8404. minRead: "Хв читання",
  8405. words: "Слів",
  8406. chars: "Символів",
  8407. switchRtl: "Перемкнути на RTL",
  8408. switchLtr: "Перемкнути на LTR",
  8409. darkMode: "Темний режим",
  8410. lightMode: "Світлий режим",
  8411. helpTitle: "Довідка Markdown Viewer",
  8412. aboutTitle: "Про Markdown",
  8413. shareTitle: "Поділитися документом",
  8414. renameTitle: "Перейменувати файл",
  8415. insertLink: "Вставити посилання",
  8416. insertRef: "Вставити витяг",
  8417. insertImg: "Вставити зображення",
  8418. insertTable: "Вставити таблицю",
  8419. findReplace: "Знайти та замінити",
  8420. placeholder: "Введіть ваш markdown тут...",
  8421. loadingEmojis: "Завантаження емодзі...",
  8422. loadingFiles: "Отримання структури файлів..."
  8423. }
  8424. };
  8425. let activeLang = 'en';
  8426. function applyTranslations(lang) {
  8427. activeLang = lang;
  8428. document.documentElement.setAttribute('lang', lang === 'zh' ? 'zh-Hans' : (lang === 'tw' ? 'zh-Hant' : lang));
  8429. const dict = I18N_DICTS[lang] || I18N_DICTS.en;
  8430. // Update main logo and header elements
  8431. const logoEl = document.querySelector('.app-header h1');
  8432. if (logoEl) logoEl.textContent = dict.title;
  8433. // Update dynamic current language labels in drop menus
  8434. const labelEl = document.getElementById('current-lang-label');
  8435. if (labelEl) {
  8436. const flags = {
  8437. en: "🇺🇸 English",
  8438. zh: "🇨🇳 简体中文",
  8439. ja: "🇯🇵 日本語",
  8440. ko: "🇰🇷 한국어",
  8441. pt: "🇧🇷 Português (Brasil)",
  8442. es: "🇪🇸 Español",
  8443. fr: "🇫🇷 Français",
  8444. de: "🇩🇪 Deutsch",
  8445. ru: "🇷🇺 Русский",
  8446. it: "🇮🇹 Italiano",
  8447. tr: "🇹🇷 Türkçe",
  8448. pl: "🇵🇱 Polski",
  8449. tw: "🇹🇼 繁體中文",
  8450. uk: "🇺🇦 Українська"
  8451. };
  8452. labelEl.textContent = flags[lang];
  8453. }
  8454. const mobileLabelEl = document.getElementById('mobile-current-lang-label');
  8455. if (mobileLabelEl) {
  8456. const flags = {
  8457. en: "us English",
  8458. zh: "CN 简体中文",
  8459. ja: "JP 日本語",
  8460. ko: "KR 한국어",
  8461. pt: "BR Português (Brasil)",
  8462. es: "ES Español",
  8463. fr: "FR Français",
  8464. de: "DE Deutsch",
  8465. ru: "RU Русский",
  8466. it: "IT Italiano",
  8467. tr: "TR Türkçe",
  8468. pl: "PL Polski",
  8469. tw: "TW 繁體中文",
  8470. uk: "UK Українська"
  8471. };
  8472. mobileLabelEl.textContent = flags[lang];
  8473. }
  8474. // Translate buttons with text content
  8475. const toggleSyncEl = document.getElementById('toggle-sync');
  8476. if (toggleSyncEl) {
  8477. const isSyncActive = toggleSyncEl.classList.contains('sync-active');
  8478. const textSpan = toggleSyncEl.querySelector('.btn-text');
  8479. if (textSpan) textSpan.textContent = isSyncActive ? dict.syncOff : dict.syncOn;
  8480. }
  8481. const mobileToggleSyncEl = document.getElementById('mobile-toggle-sync');
  8482. if (mobileToggleSyncEl) {
  8483. const isSyncActive = mobileToggleSyncEl.classList.contains('sync-active');
  8484. mobileToggleSyncEl.innerHTML = `<i class="bi bi-link"></i> ${isSyncActive ? dict.syncOff : dict.syncOn}`;
  8485. }
  8486. // Import buttons
  8487. const importDropEl = document.getElementById('importDropdown');
  8488. if (importDropEl) {
  8489. const importText = importDropEl.querySelector('.btn-text');
  8490. if (importText) importText.textContent = dict.import;
  8491. }
  8492. const importFileEl = document.getElementById('import-from-file');
  8493. if (importFileEl) importFileEl.innerHTML = `<i class="bi bi-upload me-2"></i>${dict.importFile}`;
  8494. const importGithubEl = document.getElementById('import-from-github');
  8495. if (importGithubEl) importGithubEl.innerHTML = `<i class="bi bi-github me-2"></i>${dict.importGithub}`;
  8496. const mImportFileEl = document.getElementById('mobile-import-button');
  8497. if (mImportFileEl) mImportFileEl.innerHTML = `<i class="bi bi-upload me-2"></i>${dict.importFile}`;
  8498. const mImportGithubEl = document.getElementById('mobile-import-github-button');
  8499. if (mImportGithubEl) mImportGithubEl.innerHTML = `<i class="bi bi-github me-2"></i>${dict.importGithub}`;
  8500. // Export buttons
  8501. const exportDropEl = document.getElementById('exportDropdown');
  8502. if (exportDropEl) {
  8503. const exportText = exportDropEl.querySelector('.btn-text');
  8504. if (exportText) exportText.textContent = dict.export;
  8505. }
  8506. const exportMdEl = document.getElementById('export-md');
  8507. if (exportMdEl) exportMdEl.innerHTML = `<i class="bi bi-file-earmark-text me-2"></i>${dict.exportMd}`;
  8508. const exportHtmlEl = document.getElementById('export-html');
  8509. if (exportHtmlEl) exportHtmlEl.innerHTML = `<i class="bi bi-file-earmark-code me-2"></i>${dict.exportHtml}`;
  8510. const exportPdfEl = document.getElementById('export-pdf');
  8511. if (exportPdfEl) exportPdfEl.innerHTML = `<i class="bi bi-file-earmark-pdf me-2"></i>${dict.exportPdf}`;
  8512. const mExportMdEl = document.getElementById('mobile-export-md');
  8513. if (mExportMdEl) mExportMdEl.innerHTML = `<i class="bi bi-file-earmark-text me-2"></i>${dict.exportMd}`;
  8514. const mExportHtmlEl = document.getElementById('mobile-export-html');
  8515. if (mExportHtmlEl) mExportHtmlEl.innerHTML = `<i class="bi bi-file-earmark-code me-2"></i>${dict.exportHtml}`;
  8516. const mExportPdfEl = document.getElementById('mobile-export-pdf');
  8517. if (mExportPdfEl) mExportPdfEl.innerHTML = `<i class="bi bi-file-earmark-pdf me-2"></i>${dict.exportPdf}`;
  8518. // Copy / Share
  8519. if (copyMarkdownButton) {
  8520. const copyButtonText = copyMarkdownButton.querySelector('.btn-text');
  8521. if (copyButtonText) copyButtonText.textContent = dict.copy;
  8522. }
  8523. const mCopyBtn = document.getElementById('mobile-copy-markdown');
  8524. if (mCopyBtn) mCopyBtn.innerHTML = `<i class="bi bi-clipboard me-2"></i>${dict.copy}`;
  8525. if (shareButton) {
  8526. const shareButtonText = shareButton.querySelector('.btn-text');
  8527. if (shareButtonText) shareButtonText.textContent = dict.share;
  8528. }
  8529. const mShareBtn = document.getElementById('mobile-share-button');
  8530. if (mShareBtn) mShareBtn.innerHTML = `<i class="bi bi-share me-2"></i>${dict.share}`;
  8531. // Document Reset
  8532. const tabResetBtn = document.getElementById('tab-reset-btn');
  8533. if (tabResetBtn) tabResetBtn.innerHTML = `<i class="bi bi-arrow-counterclockwise"></i> ${dict.reset}`;
  8534. const mTabResetBtn = document.getElementById('mobile-tab-reset-btn');
  8535. if (mTabResetBtn) mTabResetBtn.innerHTML = `<i class="bi bi-arrow-counterclockwise"></i> ${dict.reset} all files`;
  8536. // View toggle buttons title tooltips
  8537. document.querySelectorAll('[data-view-mode="editor"]').forEach(b => b.title = dict.editor);
  8538. document.querySelectorAll('[data-view-mode="split"]').forEach(b => b.title = dict.split);
  8539. document.querySelectorAll('[data-view-mode="preview"]').forEach(b => b.title = dict.preview);
  8540. document.querySelectorAll('.mobile-view-mode-btn[data-mode="editor"] span').forEach(s => s.textContent = dict.editor);
  8541. document.querySelectorAll('.mobile-view-mode-btn[data-mode="split"] span').forEach(s => s.textContent = dict.split);
  8542. document.querySelectorAll('.mobile-view-mode-btn[data-mode="preview"] span').forEach(s => s.textContent = dict.preview);
  8543. // Direction Toggle
  8544. const dirToggle = document.getElementById('direction-toggle');
  8545. if (dirToggle) {
  8546. const isRtl = document.body.style.direction === 'rtl';
  8547. dirToggle.title = isRtl ? dict.switchLtr : dict.switchRtl;
  8548. }
  8549. // Modal Titles
  8550. const modalHelpTitle = document.getElementById('help-modal-title');
  8551. if (modalHelpTitle) modalHelpTitle.textContent = dict.helpTitle;
  8552. const modalAboutTitle = document.getElementById('about-modal-title');
  8553. if (modalAboutTitle) modalAboutTitle.textContent = dict.aboutTitle;
  8554. const modalShareTitle = document.getElementById('share-modal-title');
  8555. if (modalShareTitle) modalShareTitle.textContent = dict.shareTitle;
  8556. const modalRenameTitle = document.getElementById('rename-modal-title');
  8557. if (modalRenameTitle) modalRenameTitle.textContent = dict.renameTitle;
  8558. const modalLinkTitle = document.getElementById('link-modal-title');
  8559. if (modalLinkTitle) modalLinkTitle.textContent = dict.insertLink;
  8560. const modalRefTitle = document.getElementById('reference-modal-title');
  8561. if (modalRefTitle) modalRefTitle.textContent = dict.insertRef;
  8562. const modalImgTitle = document.getElementById('image-modal-title');
  8563. if (modalImgTitle) modalImgTitle.textContent = dict.insertImg;
  8564. const modalTableTitle = document.getElementById('table-modal-title');
  8565. if (modalTableTitle) modalTableTitle.textContent = dict.insertTable;
  8566. const modalFindTitle = document.getElementById('find-replace-title');
  8567. if (modalFindTitle) modalFindTitle.textContent = dict.findReplace;
  8568. // Theme titles
  8569. const mThemeToggle = document.getElementById('mobile-theme-toggle');
  8570. if (mThemeToggle) {
  8571. const currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
  8572. mThemeToggle.innerHTML = `<i class="bi bi-${currentTheme === 'dark' ? 'sun' : 'moon'} me-2"></i> ${currentTheme === 'dark' ? dict.lightMode : dict.darkMode}`;
  8573. }
  8574. // Stats Labels
  8575. const minReadEl = document.getElementById('lbl-min-read');
  8576. if (minReadEl) minReadEl.textContent = dict.minRead;
  8577. const wordsEl = document.getElementById('lbl-words');
  8578. if (wordsEl) wordsEl.textContent = dict.words;
  8579. const charsEl = document.getElementById('lbl-chars');
  8580. if (charsEl) charsEl.textContent = dict.chars;
  8581. const mMinReadEl = document.getElementById('lbl-mobile-min-read');
  8582. if (mMinReadEl) mMinReadEl.textContent = dict.minRead;
  8583. const mWordsEl = document.getElementById('lbl-mobile-words');
  8584. if (mWordsEl) mWordsEl.textContent = dict.words;
  8585. const mCharsEl = document.getElementById('lbl-mobile-chars');
  8586. if (mCharsEl) mCharsEl.textContent = dict.chars;
  8587. // Placeholder
  8588. if (markdownEditor) {
  8589. markdownEditor.placeholder = dict.placeholder;
  8590. }
  8591. // Trigger state tracking update
  8592. updateDocumentStats();
  8593. // Mark current selected dropdown items as active
  8594. document.querySelectorAll('.lang-select-item').forEach(item => {
  8595. if (item.getAttribute('data-lang') === lang) {
  8596. item.classList.add('active');
  8597. } else {
  8598. item.classList.remove('active');
  8599. }
  8600. });
  8601. }
  8602. function detectAndInitLanguage() {
  8603. const urlParams = new URLSearchParams(window.location.search);
  8604. let lang = urlParams.get('lang');
  8605. if (!lang) {
  8606. const hash = window.location.hash;
  8607. const hashParams = new URLSearchParams(hash.includes('?') ? hash.split('?')[1] : '');
  8608. lang = hashParams.get('lang');
  8609. }
  8610. if (!lang) {
  8611. lang = localStorage.getItem('app-lang');
  8612. }
  8613. if (!lang && navigator.language) {
  8614. const navLang = navigator.language.toLowerCase();
  8615. if (navLang.startsWith('zh-tw') || navLang.startsWith('zh-hk') || navLang.startsWith('zh-hant')) lang = 'tw';
  8616. else if (navLang.startsWith('zh')) lang = 'zh';
  8617. else if (navLang.startsWith('ja')) lang = 'ja';
  8618. else if (navLang.startsWith('ko')) lang = 'ko';
  8619. else if (navLang.startsWith('pt')) lang = 'pt';
  8620. else if (navLang.startsWith('es')) lang = 'es';
  8621. else if (navLang.startsWith('fr')) lang = 'fr';
  8622. else if (navLang.startsWith('de')) lang = 'de';
  8623. else if (navLang.startsWith('ru')) lang = 'ru';
  8624. else if (navLang.startsWith('it')) lang = 'it';
  8625. else if (navLang.startsWith('tr')) lang = 'tr';
  8626. else if (navLang.startsWith('pl')) lang = 'pl';
  8627. else if (navLang.startsWith('uk')) lang = 'uk';
  8628. }
  8629. if (!lang || !I18N_DICTS[lang]) {
  8630. lang = 'en';
  8631. }
  8632. applyTranslations(lang);
  8633. }
  8634. // Language selectors click event listeners
  8635. document.addEventListener('click', function(e) {
  8636. const item = e.target.closest('.lang-select-item');
  8637. if (item) {
  8638. e.preventDefault();
  8639. const lang = item.getAttribute('data-lang');
  8640. applyTranslations(lang);
  8641. localStorage.setItem('app-lang', lang);
  8642. // Update browser search parameters dynamically without page reload
  8643. const url = new URL(window.location.href);
  8644. url.searchParams.set('lang', lang);
  8645. window.history.replaceState({}, '', url.toString());
  8646. }
  8647. });
  8648. // Accessibility dynamic screen reader announcer helper
  8649. function announceToScreenReader(message) {
  8650. const announcer = document.getElementById('app-accessibility-announcer');
  8651. if (!announcer) return;
  8652. announcer.textContent = '';
  8653. clearTimeout(announceToScreenReader._timeoutId);
  8654. announceToScreenReader._timeoutId = setTimeout(() => {
  8655. announcer.textContent = message;
  8656. }, 50);
  8657. }
  8658. // Visual skeleton loader generator for emoji list
  8659. function renderEmojiSkeletons() {
  8660. const grid = document.getElementById('emoji-modal-grid');
  8661. if (!grid) return;
  8662. // PERF-007: Clear elements using textContent
  8663. grid.textContent = '';
  8664. const fragment = document.createDocumentFragment();
  8665. for (let i = 0; i < 18; i++) {
  8666. const item = document.createElement('div');
  8667. item.className = 'emoji-item skeleton-placeholder';
  8668. item.setAttribute('aria-hidden', 'true');
  8669. item.style.border = '1px solid var(--border-color)';
  8670. item.style.borderRadius = '10px';
  8671. item.style.padding = '10px';
  8672. item.style.display = 'flex';
  8673. item.style.flexDirection = 'column';
  8674. item.style.alignItems = 'center';
  8675. item.style.gap = '8px';
  8676. const preview = document.createElement('span');
  8677. preview.className = 'emoji-preview skeleton-circle';
  8678. item.appendChild(preview);
  8679. const shortcodeRow = document.createElement('div');
  8680. shortcodeRow.className = 'emoji-shortcode';
  8681. const code = document.createElement('span');
  8682. code.className = 'skeleton-text';
  8683. code.style.width = '60px';
  8684. shortcodeRow.appendChild(code);
  8685. item.appendChild(shortcodeRow);
  8686. fragment.appendChild(item);
  8687. }
  8688. grid.appendChild(fragment);
  8689. }
  8690. // Visual skeleton loader generator for GitHub file list tree
  8691. function renderGitHubImportTreeSkeleton() {
  8692. if (!githubImportTree) return;
  8693. // PERF-007: Clear elements using textContent
  8694. githubImportTree.textContent = '';
  8695. const wrapper = document.createElement('div');
  8696. wrapper.className = 'github-import-tree-skeleton';
  8697. const list = document.createElement('ul');
  8698. list.style.listStyle = 'none';
  8699. list.style.paddingLeft = '4px';
  8700. list.style.margin = '0';
  8701. for (let i = 0; i < 4; i++) {
  8702. const folderItem = document.createElement('li');
  8703. folderItem.style.margin = '6px 0';
  8704. const folderSpan = document.createElement('span');
  8705. folderSpan.className = 'skeleton-placeholder skeleton-tree-folder';
  8706. folderItem.appendChild(folderSpan);
  8707. const subList = document.createElement('ul');
  8708. subList.style.listStyle = 'none';
  8709. subList.style.paddingLeft = '18px';
  8710. subList.style.margin = '0';
  8711. for (let j = 0; j < 2; j++) {
  8712. const fileItem = document.createElement('li');
  8713. fileItem.style.margin = '4px 0';
  8714. const fileSpan = document.createElement('span');
  8715. fileSpan.className = 'skeleton-placeholder skeleton-tree-file';
  8716. fileItem.appendChild(fileSpan);
  8717. subList.appendChild(fileItem);
  8718. }
  8719. folderItem.appendChild(subList);
  8720. list.appendChild(folderItem);
  8721. }
  8722. wrapper.appendChild(list);
  8723. githubImportTree.appendChild(wrapper);
  8724. }
  8725. // Run detection
  8726. detectAndInitLanguage();
  8727. // Intercept all link clicks in the preview pane to open them securely and prevent page navigation
  8728. if (markdownPreview) {
  8729. markdownPreview.addEventListener('click', function(e) {
  8730. const link = e.target.closest('a');
  8731. if (link) {
  8732. const href = link.getAttribute('href');
  8733. if (href) {
  8734. if (href.startsWith('#')) {
  8735. const targetId = decodeURIComponent(href.slice(1));
  8736. let targetEl = null;
  8737. if (targetId) {
  8738. try {
  8739. targetEl = markdownPreview.querySelector(`[id="${CSS.escape(targetId)}"]`) ||
  8740. markdownPreview.querySelector(`[name="${CSS.escape(targetId)}"]`);
  8741. } catch (err) {
  8742. targetEl = Array.from(markdownPreview.querySelectorAll('[id], [name]')).find(el => {
  8743. return el.getAttribute('id') === targetId || el.getAttribute('name') === targetId;
  8744. });
  8745. }
  8746. if (!targetEl) {
  8747. const cleanTargetId = targetId.toLowerCase().replace(/[^a-z0-9]/g, '');
  8748. if (cleanTargetId) {
  8749. targetEl = Array.from(markdownPreview.querySelectorAll('h1, h2, h3, h4, h5, h6')).find(heading => {
  8750. const cleanText = heading.textContent.toLowerCase().replace(/[^a-z0-9]/g, '');
  8751. return cleanText === cleanTargetId;
  8752. });
  8753. }
  8754. }
  8755. }
  8756. if (targetEl) {
  8757. e.preventDefault();
  8758. isProgrammaticScrolling = true;
  8759. // Scroll preview pane to target heading
  8760. targetEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
  8761. // Scroll editor pane to the matching synced position
  8762. const previewScrollRange = previewPane.scrollHeight - previewPane.clientHeight;
  8763. const targetRatio = previewScrollRange > 0 ? Math.min(1, Math.max(0, targetEl.offsetTop / previewScrollRange)) : 0;
  8764. const editorScrollPosition = targetRatio * (markdownEditor.scrollHeight - markdownEditor.clientHeight);
  8765. markdownEditor.scrollTo({
  8766. top: editorScrollPosition,
  8767. behavior: 'smooth'
  8768. });
  8769. if (window.programmaticScrollTimeout) {
  8770. clearTimeout(window.programmaticScrollTimeout);
  8771. }
  8772. window.programmaticScrollTimeout = setTimeout(() => {
  8773. isProgrammaticScrolling = false;
  8774. }, 1000);
  8775. }
  8776. return;
  8777. }
  8778. e.preventDefault();
  8779. // Defense-in-depth: check that the URL protocol is safe
  8780. let isSafe = false;
  8781. try {
  8782. const parsed = new URL(href, window.location.href);
  8783. isSafe = ['http:', 'https:', 'mailto:', 'tel:', 'blob:'].includes(parsed.protocol);
  8784. } catch (err) {
  8785. // If URL constructor fails, it might be a relative path without a base, which is safe to resolve
  8786. isSafe = !href.trim().toLowerCase().startsWith('javascript:');
  8787. }
  8788. if (isSafe) {
  8789. if (typeof Neutralino !== 'undefined') {
  8790. Neutralino.os.open(href);
  8791. } else {
  8792. window.open(href, '_blank', 'noopener,noreferrer');
  8793. }
  8794. } else {
  8795. console.warn('Blocked opening potentially unsafe URL:', href);
  8796. }
  8797. }
  8798. }
  8799. });
  8800. }
  8801. // Register Service Worker for offline capabilities
  8802. if ('serviceWorker' in navigator) {
  8803. window.addEventListener('load', function() {
  8804. navigator.serviceWorker.register('sw.js').then(function(registration) {
  8805. console.log('ServiceWorker registration successful with scope: ', registration.scope);
  8806. }, function(err) {
  8807. console.log('ServiceWorker registration failed: ', err);
  8808. });
  8809. });
  8810. }
  8811. });