UIWindow.js 166 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549
  1. /**
  2. * Copyright (C) 2024 Puter Technologies Inc.
  3. *
  4. * This file is part of Puter.
  5. *
  6. * Puter is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published
  8. * by the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. import UIAlert from './UIAlert.js';
  20. import UIContextMenu from './UIContextMenu.js';
  21. import path from '../lib/path.js';
  22. import UITaskbarItem from './UITaskbarItem.js';
  23. import UIWindowLogin from './UIWindowLogin.js';
  24. import UIWindowPublishWebsite from './UIWindowPublishWebsite.js';
  25. import UIWindowItemProperties from './UIWindowItemProperties.js';
  26. import new_context_menu_item from '../helpers/new_context_menu_item.js';
  27. import refresh_item_container from '../helpers/refresh_item_container.js';
  28. import UIWindowSaveAccount from './UIWindowSaveAccount.js';
  29. import UIWindowEmailConfirmationRequired from './UIWindowEmailConfirmationRequired.js';
  30. import launch_app from "../helpers/launch_app.js"
  31. import UIWindowShare from './UIWindowShare.js';
  32. import item_icon from '../helpers/item_icon.js';
  33. const el_body = document.getElementsByTagName('body')[0];
  34. async function UIWindow(options) {
  35. const win_id = window.global_element_id++;
  36. window.last_window_zindex++;
  37. // options.dominant places the window in center close to top.
  38. options.dominant = options.dominant ?? false;
  39. // in case of file dialogs, the window is automatically dominant
  40. if(options.is_openFileDialog || options.is_saveFileDialog || options.is_directoryPicker)
  41. options.dominant = true;
  42. // we don't want to increment window_counter for dominant windows
  43. if(!options.dominant)
  44. window.window_counter++;
  45. // add this window's id to the window_stack
  46. window.window_stack.push(win_id);
  47. // =====================================
  48. // set options defaults
  49. // =====================================
  50. // indicates if sidebar is hidden, only applies to directory windows
  51. let sidebar_hidden = false;
  52. const default_window_top = ('calc(15% + ' + ((window.window_counter-1) % 10 * 20) + 'px)');
  53. // list of file types that are allowed, other types will be disabled but still shown
  54. options.allowed_file_types = options.allowed_file_types ?? '';
  55. options.app = options.app ?? '';
  56. options.allow_context_menu = options.allow_context_menu ?? true;
  57. options.allow_native_ctxmenu = options.allow_native_ctxmenu ?? false;
  58. options.allow_user_select = options.allow_user_select ?? false;
  59. options.backdrop = options.backdrop ?? false;
  60. options.body_css = options.body_css ?? {};
  61. options.border_radius = options.border_radius ?? undefined;
  62. options.draggable_body = options.draggable_body ?? false;
  63. options.element_uuid = options.element_uuid ?? window.uuidv4();
  64. options.center = options.center ?? false;
  65. options.close_on_backdrop_click = options.close_on_backdrop_click ?? true;
  66. options.disable_parent_window = options.disable_parent_window ?? false;
  67. options.has_head = options.has_head ?? true;
  68. options.height = options.height ?? 380;
  69. options.icon = options.icon ?? null;
  70. options.iframe_msg_uid = options.iframe_msg_uid ?? null;
  71. options.is_droppable = options.is_droppable ?? true;
  72. options.is_draggable = options.is_draggable ?? true;
  73. options.is_dir = options.is_dir ?? false;
  74. options.is_minimized = options.is_minimized ?? false;
  75. options.is_maximized = options.is_maximized ?? false;
  76. options.is_openFileDialog = options.is_openFileDialog ?? false;
  77. options.is_resizable = options.is_resizable ?? true;
  78. // if this is a fullpage window, it won't be resizable
  79. if(options.is_fullpage)
  80. options.is_resizable = false;
  81. // in the embedded/fullpage mode every window is on top since there is no taskbar to switch between windows
  82. // if user has specifically asked for this window to NOT stay on top, honor it.
  83. if((window.is_embedded || window.is_fullpage_mode) && !options.parent_uuid && options.stay_on_top !== false)
  84. options.stay_on_top = true;
  85. // Keep the window on top of all previously opened windows
  86. options.stay_on_top = options.stay_on_top ?? false;
  87. options.is_saveFileDialog = options.is_saveFileDialog ?? false;
  88. options.show_minimize_button = options.show_minimize_button ?? true;
  89. options.on_close = options.on_close ?? undefined;
  90. options.parent_uuid = options.parent_uuid ?? null;
  91. options.selectable_body = (options.selectable_body === undefined || options.selectable_body === true) ? true : false;
  92. options.show_in_taskbar = options.show_in_taskbar ?? true;
  93. options.show_maximize_button = options.show_maximize_button ?? true;
  94. options.single_instance = options.single_instance ?? false;
  95. options.sort_by = options.sort_by ?? 'name';
  96. options.sort_order = options.sort_order ?? 'asc';
  97. options.title = options.title ?? null;
  98. options.top = options.top ?? default_window_top;
  99. options.type = options.type ?? null;
  100. options.update_window_url = options.update_window_url ?? false;
  101. options.layout = options.layout ?? 'icons';
  102. options.width = options.width ?? 680;
  103. options.window_css = options.window_css ?? {};
  104. options.window_class = (options.window_class !== undefined ? ' ' + options.window_class : '');
  105. options.is_visible = options.is_visible ?? true;
  106. // if only one instance is allowed, bring focus to the window that is already open
  107. if(options.single_instance && options.app !== ''){
  108. let $already_open_window = $(`.window[data-app="${html_encode(options.app)}"]`);
  109. if($already_open_window.length){
  110. $(`.window[data-app="${html_encode(options.app)}"]`).focusWindow();
  111. return;
  112. }
  113. }
  114. // left
  115. if(!options.dominant && !options.center){
  116. options.left = options.left ?? ((window.innerWidth/2 - options.width/2) +(window.window_counter-1) % 10 * 30) + 'px';
  117. }else if(!options.dominant && options.center){
  118. options.left = options.left ?? ((window.innerWidth/2 - options.width/2)) + 'px';
  119. }
  120. else if(options.dominant){
  121. options.left = (window.innerWidth/2 - options.width/2) + 'px';
  122. }
  123. else
  124. options.left = options.left ?? ((window.innerWidth/2 - options.width/2) + 'px');
  125. // top
  126. if(!options.dominant && !options.center){
  127. options.top = options.top ?? ((window.innerHeight/2 - options.height/2) +(window.window_counter-1) % 10 * 30) + 'px';
  128. }else if(!options.dominant && options.center){
  129. options.top = options.top ?? ((window.innerHeight/2 - options.height/2)) + 'px';
  130. }
  131. else if(options.dominant){
  132. options.top = (window.innerHeight * 0.15);
  133. }
  134. else if(isMobile.phone)
  135. options.top = 100;
  136. if(isMobile.phone){
  137. options.left = 0;
  138. options.top = window.toolbar_height + 'px';
  139. options.width = '100%';
  140. options.height = 'calc(100% - ' + window.toolbar_height + 'px)';
  141. }else{
  142. options.width += 'px'
  143. options.height += 'px'
  144. }
  145. // =====================================
  146. // cover page
  147. // =====================================
  148. if(options.cover_page){
  149. options.left = 0;
  150. options.top = 0;
  151. options.width = '100%';
  152. options.height = '100%';
  153. }
  154. // --------------------------------------------------------
  155. // HTML for Window
  156. // --------------------------------------------------------
  157. let h = '';
  158. // Window
  159. let zindex = options.stay_on_top ? (99999999 + window.last_window_zindex + 1 + ' !important') : window.last_window_zindex;
  160. let user_set_url_params = [];
  161. if (options.params !== undefined) {
  162. for (let key in options.params) {
  163. user_set_url_params.push(key + "=" + options.params[key]);
  164. }
  165. if(user_set_url_params.length > 0)
  166. user_set_url_params = '?'+ user_set_url_params.join('&');
  167. }
  168. h += `<div class="window window-active
  169. ${options.cover_page ? 'window-cover-page' : ''}
  170. ${options.uid !== undefined ? 'window-'+options.uid : ''}
  171. ${options.window_class}
  172. ${options.allow_user_select ? ' allow-user-select' : ''}
  173. ${options.is_openFileDialog || options.is_saveFileDialog || options.is_directoryPicker ? 'window-filedialog' : ''}"
  174. id="window-${win_id}"
  175. data-allowed_file_types = "${html_encode(options.allowed_file_types)}"
  176. data-app="${html_encode(options.app)}"
  177. data-app_uuid="${html_encode(options.app_uuid ?? '')}"
  178. data-disable_parent_window = "${html_encode(options.disable_parent_window)}"
  179. data-name="${html_encode(options.title)}"
  180. data-path ="${html_encode(options.path)}"
  181. data-uid ="${html_encode(options.uid)}"
  182. data-element_uuid="${html_encode(options.element_uuid)}"
  183. data-parent_uuid="${html_encode(options.parent_uuid)}"
  184. ${options.parent_instance_id ? `data-parent_instance_id="${options.parent_instance_id}"` : ''}
  185. data-id ="${win_id}"
  186. data-iframe_msg_uid ="${html_encode(options.iframe_msg_uid)}"
  187. data-is_dir ="${options.is_dir}"
  188. data-return_to_parent_window = "${options.return_to_parent_window}"
  189. data-initiating_app_uuid = "${html_encode(options.initiating_app_uuid)}"
  190. data-is_openFileDialog ="${options.is_openFileDialog}"
  191. data-is_saveFileDialog ="${options.is_saveFileDialog}"
  192. data-is_directoryPicker ="${options.is_directoryPicker}"
  193. data-is_fullpage ="${options.is_fullpage ? 1 : 0}"
  194. data-is_minimized ="${options.is_minimized ? 1 : 0}"
  195. data-is_maximized ="${options.is_maximized ? 1 : 0}"
  196. data-layout ="${options.layout}"
  197. data-stay_on_top ="${options.stay_on_top}"
  198. data-sort_by ="${options.sort_by ?? 'name'}"
  199. data-sort_order ="${options.sort_order ?? 'asc'}"
  200. data-multiselectable = "${options.selectable_body}"
  201. data-update_window_url = "${options.update_window_url}"
  202. data-user_set_url_params = "${html_encode(user_set_url_params)}"
  203. data-initial_zindex = "${zindex}"
  204. style=" z-index: ${zindex};
  205. ${options.width !== undefined ? 'width: ' + html_encode(options.width) +'; ':''}
  206. ${options.height !== undefined ? 'height: ' + html_encode(options.height) +'; ':''}
  207. ${options.border_radius !== undefined ? 'border-radius: ' + html_encode(options.border_radius) +'; ':''}
  208. "
  209. >`;
  210. // window mask
  211. h += `<div class="window-disable-mask">`;
  212. //busy indicator
  213. h += `<div class="busy-indicator">BUSY</div>`;
  214. h += `</div>`;
  215. // Head
  216. if(options.has_head){
  217. h += `<div class="window-head">`;
  218. // draggable handle which also contains icon and title
  219. h+=`<div class="window-head-draggable">`;
  220. // icon
  221. if(options.icon)
  222. h += `<img class="window-head-icon" />`;
  223. // title
  224. h += `<span class="window-head-title" title="${html_encode(options.title)}"></span>`;
  225. h += `</div>`;
  226. // Minimize button, only if window is resizable and not embedded
  227. if(options.is_resizable && options.show_minimize_button && !window.is_embedded)
  228. h += `<span class="window-action-btn window-minimize-btn" style="margin-left:0;"><img src="${html_encode(window.icons['minimize.svg'])}" draggable="false"></span>`;
  229. // Maximize button
  230. if(options.is_resizable && options.show_maximize_button)
  231. h += `<span class="window-action-btn window-scale-btn"><img src="${html_encode(window.icons['scale.svg'])}" draggable="false"></span>`;
  232. // Close button
  233. h += `<span class="window-action-btn window-close-btn"><img src="${html_encode(window.icons['close.svg'])}" draggable="false"></span>`;
  234. h += `</div>`;
  235. }
  236. // Sidebar
  237. if(options.is_dir && !isMobile.phone){
  238. h += `<div class="window-sidebar disable-user-select hide-scrollbar"
  239. style="${window.window_sidebar_width ? 'width: ' + html_encode(window.window_sidebar_width) + 'px !important;' : ''}"
  240. draggable="false"
  241. >`;
  242. // favorites
  243. h += `<h2 class="window-sidebar-title disable-user-select">Favorites</h2>`;
  244. h += `<div draggable="false" title="Home" class="window-sidebar-item disable-user-select ${options.path === window.home_path ? 'window-sidebar-item-active' : ''}" data-path="${html_encode(window.home_path)}"><img draggable="false" class="window-sidebar-item-icon" src="${html_encode(window.icons['folder-home.svg'])}">Home</div>`;
  245. h += `<div draggable="false" title="Documents" class="window-sidebar-item disable-user-select ${options.path === window.docs_path ? 'window-sidebar-item-active' : ''}" data-path="${html_encode(window.docs_path)}"><img draggable="false" class="window-sidebar-item-icon" src="${html_encode(window.icons['folder-documents.svg'])}">Documents</div>`;
  246. h += `<div draggable="false" title="Public" class="window-sidebar-item disable-user-select ${options.path === window.public_path ? 'window-sidebar-item-active' : ''}" data-path="${html_encode(window.public_path)}"><img draggable="false" class="window-sidebar-item-icon" src="${html_encode(window.icons['folder-public.svg'])}">Public</div>`;
  247. h += `<div draggable="false" title="Pictures" class="window-sidebar-item disable-user-select ${options.path === window.pictures_path ? 'window-sidebar-item-active' : ''}" data-path="${html_encode(window.pictures_path)}"><img draggable="false" class="window-sidebar-item-icon" src="${html_encode(window.icons['folder-pictures.svg'])}">Pictures</div>`;
  248. h += `<div draggable="false" title="Desktop" class="window-sidebar-item disable-user-select ${options.path === window.desktop_path ? 'window-sidebar-item-active' : ''}" data-path="${html_encode(window.desktop_path)}"><img draggable="false" class="window-sidebar-item-icon" src="${html_encode(window.icons['folder-desktop.svg'])}">Desktop</div>`;
  249. h += `<div draggable="false" title="Videos" class="window-sidebar-item disable-user-select ${options.path === window.videos_path ? 'window-sidebar-item-active' : ''}" data-path="${html_encode(window.videos_path)}"><img draggable="false" class="window-sidebar-item-icon" src="${html_encode(window.icons['folder-videos.svg'])}">Videos</div>`;
  250. h += `</div>`;
  251. }
  252. // Menubar
  253. if(window.menubar_style === 'window'){
  254. h += `<div class="window-menubar" data-window-id="${win_id}"></div>`;
  255. }else if(window.menubar_style === 'desktop'){
  256. $('.toolbar-puter-logo').after(`<div class="window-menubar window-menubar-global" data-window-id="${win_id}"></div>`);
  257. }
  258. // Navbar
  259. if(options.is_dir){
  260. h += `<div class="window-navbar">`;
  261. h += `<div style="float:left; margin-left:5px; margin-right:5px;">`;
  262. // Back
  263. h += `<img draggable="false" class="window-navbar-btn window-navbar-btn-back window-navbar-btn-disabled" src="${html_encode(window.icons['arrow-left.svg'])}" title="Click to go back.">`;
  264. // Forward
  265. h += `<img draggable="false" class="window-navbar-btn window-navbar-btn-forward window-navbar-btn-disabled" src="${html_encode(window.icons['arrow-right.svg'])}" title="Click to go forward.">`;
  266. // Up
  267. h += `<img draggable="false" class="window-navbar-btn window-navbar-btn-up ${options.path === '/' ? 'window-navbar-btn-disabled' : ''}" src="${html_encode(window.icons['arrow-up.svg'])}" title="Click to go one directory up.">`;
  268. h += `</div>`;
  269. // Path
  270. h += `<div class="window-navbar-path">${window.navbar_path(options.path, window.user.username)}</div>`;
  271. // Path editor
  272. h += `<input class="window-navbar-path-input" data-path="${html_encode(options.path)}" value="${html_encode(options.path)}" spellcheck="false"/>`;
  273. // Layout settings
  274. h += `<img class="window-navbar-layout-settings" src="${html_encode(options.layout === 'icons' ? window.icons['layout-icons.svg'] : window.icons['layout-list.svg'])}" draggable="false">`;
  275. h += `</div>`;
  276. }
  277. // Body
  278. h += `<div
  279. class="window-body${options.is_dir ? ' item-container' : ''}${options.iframe_url !== undefined || options.iframe_srcdoc !== undefined ? ' window-body-app' : ''}${options.is_saveFileDialog || options.is_openFileDialog || options.is_directoryPicker ? ' window-body-filedialog' : ''}"
  280. data-allowed_file_types="${html_encode(options.allowed_file_types)}"
  281. data-path="${html_encode(options.path)}"
  282. data-multiselectable = "${options.selectable_body}"
  283. data-sort_by ="${options.sort_by ?? 'name'}"
  284. data-sort_order ="${options.sort_order ?? 'asc'}"
  285. data-uid ="${options.uid}"
  286. id="window-body-${win_id}"
  287. style="${!options.has_head ? ' height: 100%;' : ''}">`;
  288. // iframe, for apps
  289. if(options.iframe_url || options.iframe_srcdoc){
  290. // <iframe>
  291. // Important: we don't allow allow-same-origin when iframe_srcdoc is used because this would allow the iframe to access the parent window's DOM, localStorage, etc.
  292. // this is a security risk and must be avoided.
  293. h += `<iframe tabindex="-1"
  294. data-app="${html_encode(options.app)}"
  295. class="window-app-iframe"
  296. frameborder="0"
  297. ${options.iframe_url ? 'src="'+ html_encode(options.iframe_url)+'"' : ''}
  298. ${options.iframe_srcdoc ? 'srcdoc="'+ html_encode(options.iframe_srcdoc) +'"' : ''}
  299. allow = "accelerometer; camera; encrypted-media; gamepad; display-capture; geolocation; gyroscope; microphone; midi; clipboard-read; clipboard-write; fullscreen;"
  300. allowtransparency="true"
  301. allowpaymentrequest="true"
  302. allowfullscreen="true"
  303. webkitallowfullscreen="webkitallowfullscreen"
  304. mozallowfullscreen="mozallowfullscreen"
  305. sandbox="allow-forms allow-modals allow-pointer-lock allow-popups allow-popups-to-escape-sandbox ${options.iframe_srcdoc ? '' : 'allow-same-origin'} allow-scripts allow-top-navigation-by-user-activation allow-downloads allow-presentation allow-storage-access-by-user-activation"></iframe>`;
  306. }
  307. // custom body
  308. else if(options.body_content !== undefined){
  309. h += options.body_content;
  310. }
  311. // Directory
  312. if(options.is_dir){
  313. // Detail layout header
  314. h += window.explore_table_headers();
  315. // Maybe render iframe for users public directory
  316. (() => {
  317. if ( options.is_saveFileDialog || options.is_openFileDialog || options.is_directoryPicker ) {
  318. return false;
  319. }
  320. if ( ! options.path || ! options.path.startsWith('/') ) { // sus
  321. return false;
  322. }
  323. const components = options.path.slice(1).split('/');
  324. if ( components.length === 2 && components[1] === 'Public' ) {
  325. const username = components[0];
  326. h += `<iframe
  327. style="display:block;width:100%"
  328. tabindex="-1"
  329. frameborder="0"
  330. src="http://${username}.at.${window.hosting_domain}"
  331. height=150
  332. ></iframe>
  333. `;
  334. }
  335. })();
  336. // Add 'This folder is empty' message by default
  337. h += `<div class="explorer-empty-message">This folder is empty</div>`;
  338. h += `<div class="explorer-error-message">Error message is missing</div>`;
  339. // Loading spinner
  340. h += `<div class="explorer-loading-spinner">`;
  341. h +=`<svg style="display:block; margin: 0 auto; " xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24"><title>circle anim</title><g fill="#212121" class="nc-icon-wrapper"><g class="nc-loop-circle-24-icon-f"><path d="M12 24a12 12 0 1 1 12-12 12.013 12.013 0 0 1-12 12zm0-22a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2z" fill="#212121" opacity=".4"></path><path d="M24 12h-2A10.011 10.011 0 0 0 12 2V0a12.013 12.013 0 0 1 12 12z" data-color="color-2"></path></g><style>.nc-loop-circle-24-icon-f{--animation-duration:0.5s;transform-origin:12px 12px;animation:nc-loop-circle-anim var(--animation-duration) infinite linear}@keyframes nc-loop-circle-anim{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style></g></svg>`;
  342. h += `<p class="explorer-loading-spinner-msg">${i18n('loading')}...</p>`;
  343. h += `</div>`;
  344. }
  345. h += `</div>`;
  346. // Explorer footer
  347. if(options.is_dir && !options.is_saveFileDialog && !options.is_openFileDialog && !options.is_directoryPicker){
  348. h += `<div class="explorer-footer">`
  349. h += `<span class="explorer-footer-item-count"></span>`;
  350. h += `<span class="explorer-footer-seperator">|</span>`;
  351. h += `<span class="explorer-footer-selected-items-count"></span>`;
  352. h += `</div>`;
  353. }
  354. // is_saveFileDialog
  355. if(options.is_saveFileDialog){
  356. h += `<div class="window-filedialog-prompt">`;
  357. h += `<div style="display:flex;">`;
  358. h += `<input type="text" class="savefiledialog-filename" autocorrect="off" spellcheck="false" value="${html_encode(options.saveFileDialog_default_filename) ?? ''}">`;
  359. h += `<button class="button button-small filedialog-cancel-btn">Cancel</button>`;
  360. h += `<button class="button `;
  361. if(options.saveFileDialog_default_filename === undefined || options.saveFileDialog_default_filename === '')
  362. h+= `disabled `;
  363. h += `button-small button-primary savefiledialog-save-btn">Save</button>`;
  364. h += `</div>`;
  365. h += `</div>`;
  366. }
  367. // is_openFileDialog
  368. else if(options.is_openFileDialog){
  369. h += `<div class="window-filedialog-prompt">`;
  370. h += `<div style="text-align:right;">`;
  371. h += `<button class="button button-small filedialog-cancel-btn">Cancel</button>`;
  372. h += `<button class="button disabled button-small button-primary openfiledialog-open-btn">Open</button>`;
  373. h += `</div>`;
  374. h += `</div>`;
  375. }
  376. // is_directoryPicker
  377. else if(options.is_directoryPicker){
  378. h += `<div class="window-filedialog-prompt">`;
  379. h += `<div style="text-align:right;">`;
  380. h += `<button class="button button-small filedialog-cancel-btn">Cancel</button>`;
  381. h += `<button class="button button-small button-primary directorypicker-select-btn" style="margin-left:10px;">Select</button>`;
  382. h += `</div>`;
  383. h += `</div>`;
  384. }
  385. h += `</div>`;
  386. // backdrop
  387. if(options.backdrop){
  388. let backdrop_zindex;
  389. // backdrop should also cover over taskbar
  390. let taskbar_zindex = $('.taskbar').css('z-index');
  391. if(taskbar_zindex === null || taskbar_zindex === undefined)
  392. backdrop_zindex = zindex;
  393. else{
  394. taskbar_zindex = parseInt(taskbar_zindex);
  395. backdrop_zindex = taskbar_zindex > zindex ? taskbar_zindex : zindex;
  396. }
  397. h = `<div class="window-backdrop" style="z-index:${backdrop_zindex};">` + h + `</div>`;
  398. }
  399. // Append
  400. $(el_body).append(h);
  401. // disable_parent_window
  402. if(options.disable_parent_window && options.parent_uuid !== null){
  403. const $el_parent_window = $(`.window[data-element_uuid="${options.parent_uuid}"]`);
  404. const $el_parent_disable_mask = $el_parent_window.find('.window-disable-mask');
  405. //disable parent window
  406. $el_parent_window.addClass('window-disabled')
  407. $el_parent_disable_mask.show();
  408. $el_parent_disable_mask.css('z-index', parseInt($el_parent_window.css('z-index')) + 1);
  409. $el_parent_window.find('iframe').blur();
  410. }
  411. // Add Taskbar Item
  412. if(!options.is_openFileDialog && !options.is_saveFileDialog && !options.is_directoryPicker && options.show_in_taskbar){
  413. // add icon if there is no similar app already open
  414. if($(`.taskbar-item[data-app="${options.app}"]`).length === 0){
  415. UITaskbarItem({
  416. icon: options.icon,
  417. name: options.title,
  418. app: options.app,
  419. open_windows_count: 1,
  420. onClick: function(){
  421. let open_window_count = parseInt($(`.taskbar-item[data-app="${options.app}"]`).attr('data-open-windows'));
  422. if(open_window_count === 0){
  423. launch_app({
  424. name: options.app,
  425. })
  426. }else{
  427. return false;
  428. }
  429. }
  430. });
  431. if(options.app)
  432. $(`.taskbar-item[data-app="${options.app}"] .active-taskbar-indicator`).show();
  433. }else{
  434. if(options.app){
  435. $(`.taskbar-item[data-app="${options.app}"]`).attr('data-open-windows', parseInt($(`.taskbar-item[data-app="${options.app}"]`).attr('data-open-windows')) + 1);
  436. $(`.taskbar-item[data-app="${options.app}"] .active-taskbar-indicator`).show();
  437. }
  438. }
  439. }
  440. // if directory, set window_nav_history and window_nav_history_current_position
  441. if(options.is_dir){
  442. window.window_nav_history[win_id] = [options.path];
  443. window.window_nav_history_current_position[win_id] = 0;
  444. }
  445. // get all the elements needed
  446. const el_window = document.querySelector(`#window-${win_id}`);
  447. const el_window_head = document.querySelector(`#window-${win_id} > .window-head`);
  448. const el_window_sidebar = document.querySelector(`#window-${win_id} > .window-sidebar`);
  449. const el_window_head_title = document.querySelector(`#window-${win_id} > .window-head .window-head-title`);
  450. const el_window_head_icon = document.querySelector(`#window-${win_id} > .window-head .window-head-icon`);
  451. const el_window_head_scale_btn = document.querySelector(`#window-${win_id} > .window-head > .window-scale-btn`);
  452. const el_window_navbar_back_btn = document.querySelector(`#window-${win_id} .window-navbar-btn-back`);
  453. const el_window_navbar_forward_btn = document.querySelector(`#window-${win_id} .window-navbar-btn-forward`);
  454. const el_window_navbar_up_btn = document.querySelector(`#window-${win_id} .window-navbar-btn-up`);
  455. const el_window_body = document.querySelector(`#window-${win_id} > .window-body`);
  456. const el_window_app_iframe = document.querySelector(`#window-${win_id} > .window-body > .window-app-iframe`);
  457. const el_savefiledialog_filename = document.querySelector(`#window-${win_id} .savefiledialog-filename`);
  458. const el_savefiledialog_save_btn = document.querySelector(`#window-${win_id} .savefiledialog-save-btn`);
  459. const el_filedialog_cancel_btn = document.querySelector(`#window-${win_id} .filedialog-cancel-btn`);
  460. const el_openfiledialog_open_btn = document.querySelector(`#window-${win_id} .openfiledialog-open-btn`);
  461. const el_directorypicker_select_btn = document.querySelector(`#window-${win_id} .directorypicker-select-btn`);
  462. // attach optional event listeners
  463. el_window.on_before_exit = options.on_before_exit;
  464. // disable menubar by default
  465. $(el_window).find('.window-menubar').hide();
  466. if(options.is_maximized){
  467. // save original size and position
  468. $(el_window).attr({
  469. 'data-left-before-maxim': ((window.innerWidth/2 - 680/2) +(window.window_counter-1) % 10 * 30) + 'px',
  470. 'data-top-before-maxim': default_window_top,
  471. 'data-width-before-maxim': '680px',
  472. 'data-height-before-maxim': '350px',
  473. 'data-is_maximized': '1',
  474. });
  475. // shrink icon
  476. $(el_window).find('.window-scale-btn>img').attr('src', window.icons['scale-down-3.svg']);
  477. // set new size and position
  478. $(el_window).css({
  479. 'top': window.toolbar_height + 'px',
  480. 'left': '0',
  481. 'width': '100%',
  482. 'height': `calc(100% - ${window.taskbar_height + window.toolbar_height + 1}px)`,
  483. 'transform': 'none',
  484. });
  485. }
  486. // when a window is created, focus is brought to it and
  487. // therefore it is the current active element
  488. window.active_element = el_window;
  489. // set name
  490. $(el_window_head_title).html(html_encode(options.title));
  491. // set icon
  492. if(options.icon)
  493. $(el_window_head_icon).attr('src', options.icon.image ?? options.icon);
  494. // root folder of a shared user?
  495. if(options.is_dir && (options.path.split('/').length - 1) === 1 && options.path !== '/'+window.user.username){
  496. $(el_window_head_icon).attr('src', window.icons['shared.svg']);
  497. }
  498. // focus on this window and deactivate other windows
  499. if ( options.is_visible ) {
  500. $(el_window).focusWindow();
  501. }
  502. if (window.animate_window_opening) {
  503. // animate window opening
  504. $(el_window).css({
  505. 'opacity': '0',
  506. 'transition': 'opacity 70ms ease-in-out',
  507. });
  508. // Use requestAnimationFrame to schedule a function to run at the next repaint of the browser window
  509. requestAnimationFrame(() => {
  510. // Change the window's opacity to 1 and scale to 1 to create an opening effect
  511. $(el_window).css({
  512. 'opacity': '1',
  513. })
  514. // Set a timeout to run after the transition duration (100ms)
  515. setTimeout(function () {
  516. // Remove the transition property, so future CSS changes won't be animated
  517. $(el_window).css({
  518. 'transition': 'none',
  519. })
  520. }, 70);
  521. });
  522. }
  523. // =====================================
  524. // Center relative to parent window
  525. // =====================================
  526. if(options.parent_center && options.parent_uuid){
  527. const $parent_window = $(`.window[data-element_uuid="${options.parent_uuid}"]`);
  528. const parent_window_width = $parent_window.width();
  529. const parent_window_height = $parent_window.height();
  530. const parent_window_left = $parent_window.offset().left;
  531. const parent_window_top = $parent_window.offset().top;
  532. const window_height = $(el_window).height();
  533. const window_width = $(el_window).width();
  534. options.left = parent_window_left + parent_window_width/2 - window_width/2;
  535. options.top = parent_window_top + parent_window_height/2 - window_height/2;
  536. $(el_window).css({
  537. 'left': options.left + 'px',
  538. 'top': options.top + 'px',
  539. });
  540. }
  541. // onAppend() - using show() is a hack to make sure window is visible AND onAppend is called when
  542. // window is actually appended and usable.
  543. // NOTE: there is another is_visible condition below
  544. if ( options.is_visible ) {
  545. $(el_window).show(0, function(e){
  546. // if SaveFileDialog, bring focus to the el_savefiledialog_filename and select all
  547. if(options.is_saveFileDialog){
  548. let item_name = el_savefiledialog_filename.value;
  549. const extname = path.extname('/' + item_name);
  550. if(extname !== '')
  551. el_savefiledialog_filename.setSelectionRange(0, item_name.length - extname.length)
  552. else
  553. $(el_savefiledialog_filename).select();
  554. $(el_savefiledialog_filename).get(0).focus({preventScroll:true});
  555. }
  556. //set custom window css
  557. $(el_window).css(options.window_css);
  558. // onAppend()
  559. if(options.onAppend && typeof options.onAppend === 'function'){
  560. options.onAppend(el_window);
  561. }
  562. });
  563. }
  564. if(options.is_saveFileDialog){
  565. //------------------------------------------------
  566. // SaveFileDialog > Save button
  567. //------------------------------------------------
  568. $(el_savefiledialog_save_btn).on('click', function(e){
  569. const filename = $(el_savefiledialog_filename).val();
  570. try{
  571. window.validate_fsentry_name(filename)
  572. }catch(err){
  573. UIAlert(err.message, 'error', 'OK')
  574. return;
  575. }
  576. const target_path = path.join($(el_window).attr('data-path'), filename);
  577. if(options.onSaveFileDialogSave && typeof options.onSaveFileDialogSave === 'function')
  578. options.onSaveFileDialogSave(target_path, el_window)
  579. })
  580. //------------------------------------------------
  581. // SaveFileDialog > Enter
  582. //------------------------------------------------
  583. $(el_savefiledialog_filename).on('keypress', function(event) {
  584. if(event.which === 13){
  585. $(el_savefiledialog_save_btn).trigger('click');
  586. }
  587. })
  588. //------------------------------------------------
  589. // Enable/disable Save button based on input
  590. //------------------------------------------------
  591. $(el_savefiledialog_filename).bind('keydown change input paste', function(){
  592. if($(this).val() !== '')
  593. $(el_savefiledialog_save_btn).removeClass('disabled');
  594. else
  595. $(el_savefiledialog_save_btn).addClass('disabled');
  596. })
  597. $(el_savefiledialog_filename).get(0).focus({preventScroll:true});
  598. }
  599. if(options.is_openFileDialog){
  600. //------------------------------------------------
  601. // OpenFileDialog > Open button
  602. //------------------------------------------------
  603. $(el_openfiledialog_open_btn).on('click', async function(e){
  604. const selected_els = $(el_window).find('.item-selected[data-is_dir="0"]');
  605. let selected_files;
  606. // No item selected
  607. if(selected_els.length === 0)
  608. return;
  609. // ------------------------------------------------
  610. // Item(s) selected
  611. // ------------------------------------------------
  612. else{
  613. selected_files = []
  614. // an array that hold the items to sign
  615. const items_to_sign = [];
  616. // prepare items to sign
  617. for(let i=0; i<selected_els.length; i++)
  618. items_to_sign.push({uid: $(selected_els[i]).attr('data-uid'), action: 'write', path: $(selected_els[i]).attr('data-path')});
  619. // sign items
  620. selected_files = await puter.fs.sign(options.initiating_app_uuid, items_to_sign);
  621. selected_files = selected_files.items;
  622. selected_files = Array.isArray(selected_files) ? selected_files : [selected_files];
  623. // change path of each item to preserve privacy
  624. for(let i=0; i<selected_files.length; i++)
  625. selected_files[i].path = privacy_aware_path(selected_files[i].path)
  626. }
  627. const ifram_msg_uid = $(el_window).attr('data-iframe_msg_uid');
  628. if(options.return_to_parent_window){
  629. window.opener.postMessage({
  630. msg: "fileOpenPicked",
  631. original_msg_id: ifram_msg_uid,
  632. items: Array.isArray(selected_files) ? [...selected_files] : [selected_files],
  633. // LEGACY SUPPORT, remove this in the future when Polotno uses the new SDK
  634. // this is literally put in here to support Polotno's legacy code
  635. ...(selected_files.length === 1 && selected_files[0])
  636. }, '*');
  637. window.close();
  638. window.open('','_self').close();
  639. }
  640. else if(options.parent_uuid){
  641. // send event to iframe
  642. const target_iframe = $(`.window[data-element_uuid="${options.parent_uuid}"]`).find('.window-app-iframe').get(0);
  643. if(target_iframe){
  644. target_iframe.contentWindow.postMessage({
  645. msg: "fileOpenPicked",
  646. original_msg_id: ifram_msg_uid,
  647. items: Array.isArray(selected_files) ? [...selected_files] : [selected_files],
  648. // LEGACY SUPPORT, remove this in the future when Polotno uses the new SDK
  649. // this is literally put in here to support Polotno's legacy code
  650. ...(selected_files.length === 1 && selected_files[0])
  651. }, '*');
  652. }
  653. // focus on iframe
  654. $(target_iframe).get(0)?.focus({preventScroll:true});
  655. // send file_opened event
  656. const file_opened_event = new CustomEvent('file_opened', {detail: Array.isArray(selected_files) ? [...selected_files] : [selected_files]});
  657. // dispatch event to parent window
  658. $(`.window[data-element_uuid="${options.parent_uuid}"]`).get(0)?.dispatchEvent(file_opened_event);
  659. $(el_window).close();
  660. }
  661. })
  662. }
  663. else if(options.is_directoryPicker){
  664. //------------------------------------------------
  665. // DirectoryPicker > Select button
  666. //------------------------------------------------
  667. $(el_directorypicker_select_btn).on('click', async function(e){
  668. const selected_els = $(el_window).find('.item-selected[data-is_dir="1"]');
  669. let selected_dirs;
  670. // ------------------------------------------------
  671. // No item selected, return current directory
  672. // ------------------------------------------------
  673. if(selected_els.length === 0){
  674. selected_dirs = await puter.fs.sign(options.initiating_app_uuid, {uid: $(el_window).attr('data-uid'), action: 'write'})
  675. selected_dirs = selected_dirs.items;
  676. }
  677. // ------------------------------------------------
  678. // directorie(s) selected
  679. // ------------------------------------------------
  680. else{
  681. selected_dirs = []
  682. // an array that hold the items to sign
  683. const items_to_sign = [];
  684. // prepare items to sign
  685. for(let i=0; i<selected_els.length; i++)
  686. items_to_sign.push({uid: $(selected_els[i]).attr('data-uid'), action: 'write', path: $(selected_els[i]).attr('data-path')});
  687. // sign items
  688. selected_dirs = await puter.fs.sign(options.initiating_app_uuid, items_to_sign);
  689. selected_dirs = selected_dirs.items;
  690. selected_dirs = Array.isArray(selected_dirs) ? selected_dirs : [selected_dirs];
  691. // change path of each item to preserve privacy
  692. for(let i=0; i<selected_dirs.length; i++)
  693. selected_dirs[i].path = privacy_aware_path(selected_dirs[i].path)
  694. }
  695. const ifram_msg_uid = $(el_window).attr('data-iframe_msg_uid');
  696. if(options.return_to_parent_window){
  697. window.opener.postMessage({
  698. msg: "directoryPicked",
  699. original_msg_id: ifram_msg_uid,
  700. items: Array.isArray(selected_dirs) ? [...selected_dirs] : [selected_dirs],
  701. // LEGACY SUPPORT, remove this in the future when Polotno uses the new SDK
  702. // this is literally put in here to support Polotno's legacy code
  703. ...(selected_dirs.length === 1 && selected_dirs[0])
  704. }, '*');
  705. window.close();
  706. window.open('','_self').close();
  707. }
  708. if(options.parent_uuid){
  709. // Send directoryPicked event to iframe
  710. const target_iframe = $(`.window[data-element_uuid="${options.parent_uuid}"]`).find('.window-app-iframe').get(0);
  711. if(target_iframe){
  712. target_iframe.contentWindow.postMessage({
  713. msg: "directoryPicked",
  714. original_msg_id: ifram_msg_uid,
  715. items: Array.isArray(selected_dirs) ? [...selected_dirs] : [selected_dirs],
  716. }, '*');
  717. }
  718. $(target_iframe).get(0).focus({preventScroll:true});
  719. $(el_window).close();
  720. }
  721. })
  722. }
  723. if(options.is_saveFileDialog || options.is_openFileDialog || options.is_directoryPicker){
  724. //------------------------------------------------
  725. // FileDialog > Cancel button
  726. //------------------------------------------------
  727. $(el_filedialog_cancel_btn).on('click', function(e){
  728. if(options.return_to_parent_window){
  729. window.close();
  730. window.open('','_self').close();
  731. }
  732. $(el_window).hide(0, ()=>{
  733. // re-anable parent window
  734. $(`.window[data-element_uuid="${options.parent_uuid}"]`).removeClass('window-disabled');
  735. $(`.window[data-element_uuid="${options.parent_uuid}"]`).find('.window-disable-mask').hide();
  736. $(el_window).close();
  737. })
  738. })
  739. }
  740. if(options.is_dir){
  741. window.navbar_path_droppable(el_window);
  742. window.sidebar_item_droppable(el_window);
  743. // --------------------------------------------------------
  744. // Back button
  745. // --------------------------------------------------------
  746. $(el_window_navbar_back_btn).on('click', function(e){
  747. // if history menu is open don't continue
  748. if($(el_window_navbar_back_btn).hasClass('has-open-contextmenu'))
  749. return;
  750. // if ctrl/cmd are pressed, open in new window
  751. if(e.ctrlKey || e.metaKey){
  752. const dirpath = window.window_nav_history[win_id].at(window.window_nav_history_current_position[win_id] - 1);
  753. UIWindow({
  754. path: dirpath,
  755. title: dirpath === '/' ? window.root_dirname : path.basename(dirpath),
  756. icon: window.icons['folder.svg'],
  757. // uid: $(el_item).attr('data-uid'),
  758. is_dir: true,
  759. });
  760. }
  761. // ... otherwise, open in same window
  762. else{
  763. window.window_nav_history_current_position[win_id] > 0 && window.window_nav_history_current_position[win_id]--;
  764. const new_path = window.window_nav_history[win_id].at(window.window_nav_history_current_position[win_id]);
  765. // update window path
  766. window.update_window_path(el_window, new_path);
  767. }
  768. })
  769. // --------------------------------------------------------
  770. // Back button click-hold
  771. // --------------------------------------------------------
  772. $(el_window_navbar_back_btn).on('taphold', function() {
  773. let items = [];
  774. const pos = el_window_navbar_back_btn.getBoundingClientRect();
  775. for(let index = window.window_nav_history_current_position[win_id] - 1; index >= 0; index--){
  776. const history_item = window.window_nav_history[win_id].at(index);
  777. // build item for context menu
  778. items.push({
  779. html: `<span>${history_item === window.home_path ? 'Home' : path.basename(history_item)}</span>`,
  780. val: index,
  781. onClick: async function(e){
  782. let history_index = e.value;
  783. window.window_nav_history_current_position[win_id] = history_index;
  784. const new_path = window.window_nav_history[win_id].at(window.window_nav_history_current_position[win_id]);
  785. // if ctrl/cmd are pressed, open in new window
  786. if(e.ctrlKey || e.metaKey && (new_path !== undefined && new_path !== null)){
  787. UIWindow({
  788. path: new_path,
  789. title: new_path === '/' ? window.root_dirname : path.basename(new_path),
  790. icon: window.icons['folder.svg'],
  791. is_dir: true,
  792. });
  793. }
  794. // update window path
  795. else{
  796. window.update_window_path(el_window, new_path);
  797. }
  798. }
  799. })
  800. }
  801. // Menu
  802. UIContextMenu({
  803. position: {top: pos.top + pos.height + 3, left: pos.left},
  804. parent_element: el_window_navbar_back_btn,
  805. items: items,
  806. })
  807. })
  808. // --------------------------------------------------------
  809. // Forward button
  810. // --------------------------------------------------------
  811. $(el_window_navbar_forward_btn).on('click', function(e){
  812. // if history menu is open don't continue
  813. if($(el_window_navbar_forward_btn).hasClass('has-open-contextmenu'))
  814. return;
  815. // if ctrl/cmd are pressed, open in new window
  816. if(e.ctrlKey || e.metaKey){
  817. const dirpath = window.window_nav_history[win_id].at(window.window_nav_history_current_position[win_id] + 1);
  818. UIWindow({
  819. path: dirpath,
  820. title: dirpath === '/' ? window.root_dirname : path.basename(dirpath),
  821. icon: window.icons['folder.svg'],
  822. // uid: $(el_item).attr('data-uid'),
  823. is_dir: true,
  824. });
  825. }
  826. // ... otherwise, open in same window
  827. else{
  828. window.window_nav_history_current_position[win_id]++;
  829. // get last path in history
  830. const target_path = window.window_nav_history[win_id].at(window.window_nav_history_current_position[win_id]);
  831. // update window path
  832. if(target_path !== undefined){
  833. window.update_window_path(el_window, target_path);
  834. }
  835. }
  836. })
  837. // --------------------------------------------------------
  838. // forward button click-hold
  839. // --------------------------------------------------------
  840. $(el_window_navbar_forward_btn).on('taphold', function() {
  841. let items = [];
  842. const pos = el_window_navbar_forward_btn.getBoundingClientRect();
  843. for(let index = window.window_nav_history_current_position[win_id] + 1; index < window.window_nav_history[win_id].length; index++){
  844. const history_item = window.window_nav_history[win_id].at(index);
  845. // build item for context menu
  846. items.push({
  847. html: `<span>${history_item === window.home_path ? 'Home' : path.basename(history_item)}</span>`,
  848. val: index,
  849. onClick: async function(e){
  850. let history_index = e.value;
  851. window.window_nav_history_current_position[win_id] = history_index;
  852. const new_path = window.window_nav_history[win_id].at(window.window_nav_history_current_position[win_id]);
  853. // if ctrl/cmd are pressed, open in new window
  854. if(e.ctrlKey || e.metaKey && (new_path !== undefined && new_path !== null)){
  855. UIWindow({
  856. path: new_path,
  857. title: new_path === '/' ? window.root_dirname : path.basename(new_path),
  858. icon: window.icons['folder.svg'],
  859. is_dir: true,
  860. });
  861. }
  862. // update window path
  863. else{
  864. window.update_window_path(el_window, new_path);
  865. }
  866. }
  867. })
  868. }
  869. // Menu
  870. UIContextMenu({
  871. parent_element: el_window_navbar_forward_btn,
  872. position: {top: pos.top + pos.height + 3, left: pos.left},
  873. items: items,
  874. })
  875. })
  876. // --------------------------------------------------------
  877. // Up button
  878. // --------------------------------------------------------
  879. $(el_window_navbar_up_btn).on('click', function(e){
  880. const target_path = path.resolve(path.join($(el_window).attr('data-path'), '..'));
  881. // if ctrl/cmd are pressed, open in new window
  882. if(e.ctrlKey || e.metaKey && (target_path !== undefined && target_path !== null)){
  883. UIWindow({
  884. path: target_path,
  885. title: target_path === '/' ? window.root_dirname : path.basename(target_path),
  886. icon: window.icons['folder.svg'],
  887. // uid: $(el_item).attr('data-uid'),
  888. is_dir: true,
  889. });
  890. }
  891. // ... otherwise, open in same window
  892. else if(target_path !== undefined && target_path !== null){
  893. // update history
  894. window.window_nav_history[win_id] = window.window_nav_history[win_id].slice(0, window.window_nav_history_current_position[win_id]+1);
  895. window.window_nav_history[win_id].push(target_path);
  896. window.window_nav_history_current_position[win_id]++;
  897. // update window path
  898. window.update_window_path(el_window, target_path);
  899. }
  900. })
  901. const layouts = ['icons', 'list', 'details'];
  902. $(el_window).find('.window-navbar-layout-settings').on('contextmenu taphold', function() {
  903. let cur_layout = $(el_window).attr('data-layout');
  904. let items = [];
  905. for(let i=0; i<layouts.length; i++){
  906. items.push({
  907. html: `<span style="text-transform: capitalize;">${layouts[i]}</span>`,
  908. icon: cur_layout === layouts[i] ? '✓' : '',
  909. onClick: async function(e){
  910. window.update_window_layout(el_window, layouts[i]);
  911. window.set_layout($(el_window).attr('data-uid'), layouts[i]);
  912. }
  913. })
  914. }
  915. UIContextMenu({
  916. parent_element: this,
  917. items: items,
  918. })
  919. })
  920. $(el_window).find('.window-navbar-layout-settings').on('click', function() {
  921. let cur_layout = $(el_window).attr('data-layout');
  922. for(let i=0; i<layouts.length; i++){
  923. if(cur_layout === layouts[i]){
  924. if(i === layouts.length - 1){
  925. window.update_window_layout(el_window, layouts[0]);
  926. window.set_layout($(el_window).attr('data-uid'), layouts[0]);
  927. }else{
  928. window.update_window_layout(el_window, layouts[i+1]);
  929. window.set_layout($(el_window).attr('data-uid'), layouts[i+1]);
  930. }
  931. break;
  932. }
  933. }
  934. })
  935. // --------------------------------------------------------
  936. // directory content
  937. // --------------------------------------------------------
  938. //auth
  939. if(!window.is_auth() && !(await UIWindowLogin()))
  940. return;
  941. // --------------------------------------------------------
  942. // SIDEBAR sharing
  943. // --------------------------------------------------------
  944. if(options.is_dir && !isMobile.phone){
  945. puter.fs.readdir('/').then(function(shared_users){
  946. let ht = '';
  947. if(shared_users && shared_users.length - 1 > 0){
  948. ht += `<h2 class="window-sidebar-title disable-user-select">Shared with me</h2>`;
  949. for (let index = 0; index < shared_users.length; index++) {
  950. const shared_user = shared_users[index];
  951. // don't show current user's folder!
  952. if(shared_user.name === window.user.username)
  953. continue;
  954. ht += `<div class="window-sidebar-item disable-user-select ${options.path === shared_user.path ? 'window-sidebar-item-active' : ''}"
  955. data-path="${shared_user.path}"
  956. data-sharing-username="${html_encode(shared_user.name)}"
  957. title="${html_encode(shared_user.name)}"
  958. data-is_shared="1">
  959. <img class="window-sidebar-item-icon" src="${html_encode(window.icons['shared-outline.svg'])}">${shared_user.name}
  960. </div>`;
  961. }
  962. }
  963. $(el_window).find('.window-sidebar').append(ht);
  964. $(el_window).find('.window-sidebar-item:not(.ui-droppable)').droppable({
  965. accept: '.item',
  966. tolerance: 'pointer',
  967. drop: function( event, ui ) {
  968. // check if item was actually dropped on this navbar path
  969. if($(window.mouseover_window).attr('data-id') !== $(el_window).attr('data-id')){
  970. return;
  971. }
  972. const items_to_share = []
  973. // first item
  974. items_to_share.push({
  975. uid: $(ui.draggable).attr('data-uid'),
  976. path: $(ui.draggable).attr('data-path'),
  977. icon: $(ui.draggable).find('.item-icon img').attr('src'),
  978. name: $(ui.draggable).find('.item-name').text(),
  979. });
  980. // all subsequent items
  981. const cloned_items = document.getElementsByClassName('item-selected-clone');
  982. for(let i =0; i<cloned_items.length; i++){
  983. const source_item = document.getElementById('item-' + $(cloned_items[i]).attr('data-id'));
  984. if(!source_item) continue;
  985. items_to_share.push({
  986. uid: $(source_item).attr('data-uid'),
  987. path: $(source_item).attr('data-path'),
  988. icon: $(source_item).find('.item-icon img').attr('src'),
  989. name: $(source_item).find('.item-name').text(),
  990. })
  991. }
  992. // if alt key is down, create shortcut items
  993. if(event.altKey){
  994. items_to_share.forEach((item_to_move) => {
  995. window.create_shortcut(
  996. path.basename($(item_to_move).attr('data-path')),
  997. $(item_to_move).attr('data-is_dir') === '1',
  998. $(this).attr('data-path'),
  999. null,
  1000. $(item_to_move).attr('data-shortcut_to') === '' ? $(item_to_move).attr('data-uid') : $(item_to_move).attr('data-shortcut_to'),
  1001. $(item_to_move).attr('data-shortcut_to_path') === '' ? $(item_to_move).attr('data-path') : $(item_to_move).attr('data-shortcut_to_path'),
  1002. );
  1003. });
  1004. }
  1005. // move items
  1006. else{
  1007. UIWindowShare(items_to_share, $(this).attr('data-sharing-username'));
  1008. }
  1009. $('.item-container').droppable('enable')
  1010. $(this).removeClass('window-sidebar-item-drag-active');
  1011. return false;
  1012. },
  1013. over: function(event, ui){
  1014. // check if item was actually hovered over this window
  1015. if($(window.mouseover_window).attr('data-id') !== $(el_window).attr('data-id'))
  1016. return;
  1017. // Don't do anything if the dragged item is NOT a UIItem
  1018. if(!$(ui.draggable).hasClass('item'))
  1019. return;
  1020. // highlight this item
  1021. $(this).addClass('window-sidebar-item-drag-active');
  1022. $('.ui-draggable-dragging').css('opacity', 0.2)
  1023. $('.item-selected-clone').css('opacity', 0.2)
  1024. // disable all window bodies
  1025. $('.item-container').droppable( 'disable' )
  1026. },
  1027. out: function(event, ui){
  1028. // Don't do anything if the dragged element is NOT a UIItem
  1029. if(!$(ui.draggable).hasClass('item'))
  1030. return;
  1031. // unselect item if item is dragged out
  1032. $(this).removeClass('window-sidebar-item-drag-active');
  1033. $('.ui-draggable-dragging').css('opacity', 'initial')
  1034. $('.item-selected-clone').css('opacity', 'initial')
  1035. $('.item-container').droppable( 'enable' )
  1036. }
  1037. });
  1038. }).catch(function(err){
  1039. console.error(err);
  1040. })
  1041. }
  1042. // get directory content
  1043. refresh_item_container(el_window_body, options);
  1044. }
  1045. // set iframe url
  1046. if (options.iframe_url){
  1047. $(el_window_app_iframe).attr('src', options.iframe_url)
  1048. //bring focus to iframe
  1049. el_window_app_iframe.contentWindow.focus();
  1050. }
  1051. // set the position of window
  1052. if(!options.is_maximized){
  1053. $(el_window).css('top', options.top)
  1054. $(el_window).css('left', options.left)
  1055. }
  1056. if ( options.is_visible ) {
  1057. $(el_window).css('display', 'block');
  1058. }
  1059. // mousedown on the window body will unselect selected items if neither ctrl nor command are pressed
  1060. $(el_window_body).on('mousedown', function(e){
  1061. if($(e.target).hasClass('window-body') && !e.ctrlKey && !e.metaKey){
  1062. $(el_window_body).find('.item-selected').removeClass('item-selected');
  1063. window.update_explorer_footer_selected_items_count(el_window);
  1064. // if this is openFileDialog, disable the Open button
  1065. if(options.is_openFileDialog)
  1066. $(el_openfiledialog_open_btn).addClass('disabled')
  1067. }
  1068. })
  1069. // on_close event
  1070. $(el_window).on('remove', function(e){
  1071. // if on_close callback is set, call it
  1072. options.on_close?.();
  1073. })
  1074. // --------------------------------------------------------
  1075. // Backdrop click
  1076. // --------------------------------------------------------
  1077. if(options.backdrop && options.close_on_backdrop_click){
  1078. $(el_window).closest('.window-backdrop').on('mousedown', function(e){
  1079. if($(e.target).hasClass('window-backdrop')){
  1080. $(el_window).close();
  1081. }
  1082. })
  1083. }
  1084. // --------------------------------------------------------
  1085. // Selectable
  1086. // only for Desktop screens
  1087. // --------------------------------------------------------
  1088. if(options.is_dir && options.selectable_body && !isMobile.phone && !isMobile.tablet){
  1089. let selected_ctrl_items = [];
  1090. // init viselect
  1091. const selection = new SelectionArea({
  1092. selectionContainerClass: '.selection-area-container',
  1093. container: `#window-body-${win_id}`,
  1094. selectables: [`#window-body-${win_id} .item`],
  1095. startareas: [`#window-body-${win_id}`],
  1096. boundaries: [`#window-body-${win_id}`],
  1097. behaviour: {
  1098. overlap: 'drop',
  1099. intersect: 'touch',
  1100. startThreshold: 10,
  1101. scrolling: {
  1102. speedDivider: 10,
  1103. manualSpeed: 750,
  1104. startScrollMargins: {x: 0, y: 0}
  1105. }
  1106. },
  1107. features: {
  1108. touch: true,
  1109. range: true,
  1110. singleTap: {
  1111. allow: true,
  1112. intersect: 'native'
  1113. }
  1114. }
  1115. });
  1116. selection.on('beforestart', ({store, event}) => {
  1117. selected_ctrl_items = [];
  1118. return $(event.target).is(`#window-body-${win_id}`)
  1119. })
  1120. .on('beforedrag', evt => {
  1121. })
  1122. .on('start', ({store, event}) => {
  1123. if (!event.ctrlKey && !event.metaKey) {
  1124. for (const el of store.stored) {
  1125. el.classList.remove('item-selected');
  1126. }
  1127. selection.clearSelection();
  1128. }
  1129. })
  1130. .on('move', ({store: {changed: {added, removed}}, event}) => {
  1131. for (const el of added) {
  1132. // if ctrl or meta key is pressed and the item is already selected, then unselect it
  1133. if((event.ctrlKey || event.metaKey) && $(el).hasClass('item-selected')){
  1134. el.classList.remove('item-selected');
  1135. selected_ctrl_items.push(el);
  1136. }
  1137. // otherwise select it
  1138. else{
  1139. el.classList.add('item-selected');
  1140. // the latest selected item is the active element
  1141. window.active_element = el;
  1142. }
  1143. }
  1144. for (const el of removed) {
  1145. el.classList.remove('item-selected');
  1146. // in case this item was selected by ctrl+click before, then reselect it again
  1147. if(selected_ctrl_items.includes(el))
  1148. $(el).addClass('item-selected');
  1149. }
  1150. window.update_explorer_footer_selected_items_count(el_window);
  1151. // If this is openFileDialog, enable/disable the Open button accordingly
  1152. if(options.is_openFileDialog && $(el_window).find('.item-selected').length)
  1153. $(el_openfiledialog_open_btn).removeClass('disabled')
  1154. else
  1155. $(el_openfiledialog_open_btn).addClass('disabled')
  1156. })
  1157. .on('stop', ({store, event}) => {
  1158. // If this is openFileDialog, enable/disable the Open button accordingly
  1159. if(options.is_openFileDialog && $(el_window).find('.item-selected').length)
  1160. $(el_openfiledialog_open_btn).removeClass('disabled')
  1161. else
  1162. $(el_openfiledialog_open_btn).addClass('disabled')
  1163. });
  1164. }
  1165. // --------------------------------------------------------
  1166. // Droppable
  1167. // --------------------------------------------------------
  1168. $(el_window_body).droppable({
  1169. accept: '.item',
  1170. greedy: true,
  1171. tolerance: "pointer",
  1172. drop: async function( e, ui ) {
  1173. // check if item was actually dropped on this window
  1174. if($(window.mouseover_window).attr('data-id') !== $(el_window).attr('data-id'))
  1175. return;
  1176. // can't drop anything here but a UIItem
  1177. if(!$(ui.draggable).hasClass('item'))
  1178. return;
  1179. // --------------------------------------------------
  1180. // In case this was dropped on an App window
  1181. // --------------------------------------------------
  1182. if(el_window_app_iframe !== null){
  1183. const items_to_move = []
  1184. // first item
  1185. items_to_move.push(ui.draggable);
  1186. // all subsequent items
  1187. const cloned_items = document.getElementsByClassName('item-selected-clone');
  1188. for(let i =0; i<cloned_items.length; i++){
  1189. const source_item = document.getElementById('item-' + $(cloned_items[i]).attr('data-id'));
  1190. if(source_item !== null)
  1191. items_to_move.push(source_item);
  1192. }
  1193. // sign all items
  1194. const items_to_sign = []
  1195. // prepare items to sign
  1196. for(let i=0; i<items_to_move.length; i++)
  1197. items_to_sign.push({uid: $(items_to_move[i]).attr('data-uid'), action: 'write', path: $(items_to_move[i]).attr('data-path')});
  1198. // sign items
  1199. let signatures = await puter.fs.sign(options.app_uuid, items_to_sign);
  1200. signatures = signatures.items;
  1201. signatures = Array.isArray(signatures) ? signatures : [signatures];
  1202. // prepare items
  1203. let items = [];
  1204. for (let index = 0; index < signatures.length; index++) {
  1205. const item = signatures[index];
  1206. items.push({
  1207. name: item.fsentry_name,
  1208. readURL: item.read_url,
  1209. writeURL: item.write_url,
  1210. metadataURL: item.metadata_url,
  1211. isDirectory: item.fsentry_is_dir,
  1212. path: privacy_aware_path(item.path),
  1213. uid: item.uid,
  1214. })
  1215. }
  1216. // send to app iframe
  1217. el_window_app_iframe.contentWindow.postMessage({
  1218. msg: "itemsOpened",
  1219. original_msg_id: $(el_window).attr('data-iframe_msg_uid'),
  1220. items: items,
  1221. }, '*');
  1222. // if item is dragged over an app iframe, highlight the iframe
  1223. var rect = el_window_app_iframe.getBoundingClientRect();
  1224. // if mouse is inside iframe, send drag message to iframe
  1225. el_window_app_iframe.contentWindow.postMessage({msg: "drop", x: (window.mouseX - rect.left), y: (window.mouseY - rect.top), items: items}, '*');
  1226. // bring focus to this window
  1227. $(el_window).focusWindow();
  1228. }
  1229. // if this window is not a directory, cancel drop.
  1230. // why not simply only launch droppable on directories? this is because
  1231. // if a window is not droppable and an item is dropped on it, the app will think
  1232. // it was dropped on desktop.
  1233. if(!options.is_dir){
  1234. return false;
  1235. }
  1236. // If dropped on the same window, do not proceed
  1237. if($(ui.draggable).closest('.item-container').attr('data-path') === $(window.mouseover_window).attr('data-path') && !e.ctrlKey){
  1238. return;
  1239. }
  1240. // If ctrl is pressed and source is Trashed, cancel whole operation
  1241. if(e.ctrlKey && path.dirname($(ui.draggable).attr('data-path')) === window.trash_path)
  1242. return;
  1243. // Unselect already selected items
  1244. $(el_window_body).find('.item-selected').removeClass('item-selected')
  1245. const items_to_move = []
  1246. // first item
  1247. items_to_move.push(ui.draggable);
  1248. // all subsequent items
  1249. const cloned_items = document.getElementsByClassName('item-selected-clone');
  1250. for(let i =0; i<cloned_items.length; i++){
  1251. const source_item = document.getElementById('item-' + $(cloned_items[i]).attr('data-id'));
  1252. if(source_item !== null){
  1253. items_to_move.push(source_item);
  1254. }
  1255. }
  1256. // --------------------------------------------------------
  1257. // if this is the home directory of another user, show the sharing dialog
  1258. // --------------------------------------------------------
  1259. let cur_path = $(el_window).attr('data-path');
  1260. if(countSubstr(cur_path, '/') === 1 && cur_path !== '/'+window.user.username){
  1261. let username = cur_path.split('/')[1];
  1262. const items_to_share = []
  1263. // first item
  1264. items_to_share.push({
  1265. uid: $(ui.draggable).attr('data-uid'),
  1266. path: $(ui.draggable).attr('data-path'),
  1267. icon: $(ui.draggable).find('.item-icon img').attr('src'),
  1268. name: $(ui.draggable).find('.item-name').text(),
  1269. });
  1270. // all subsequent items
  1271. const cloned_items = document.getElementsByClassName('item-selected-clone');
  1272. for(let i =0; i<cloned_items.length; i++){
  1273. const source_item = document.getElementById('item-' + $(cloned_items[i]).attr('data-id'));
  1274. if(!source_item) continue;
  1275. items_to_share.push({
  1276. uid: $(source_item).attr('data-uid'),
  1277. path: $(source_item).attr('data-path'),
  1278. icon: $(source_item).find('.item-icon img').attr('src'),
  1279. name: $(source_item).find('.item-name').text(),
  1280. })
  1281. }
  1282. UIWindowShare(items_to_share, username);
  1283. return;
  1284. }
  1285. // If ctrl key is down, copy items. Except if target is Trash
  1286. if(e.ctrlKey && $(window.mouseover_window).attr('data-path') !== window.trash_path){
  1287. // Copy items
  1288. window.copy_items(items_to_move, $(window.mouseover_window).attr('data-path'))
  1289. }
  1290. // if alt key is down, create shortcut items
  1291. else if(e.altKey){
  1292. items_to_move.forEach((item_to_move) => {
  1293. window.create_shortcut(
  1294. path.basename($(item_to_move).attr('data-path')),
  1295. $(item_to_move).attr('data-is_dir') === '1',
  1296. $(window.mouseover_window).attr('data-path'),
  1297. null,
  1298. $(item_to_move).attr('data-shortcut_to') === '' ? $(item_to_move).attr('data-uid') : $(item_to_move).attr('data-shortcut_to'),
  1299. $(item_to_move).attr('data-shortcut_to_path') === '' ? $(item_to_move).attr('data-path') : $(item_to_move).attr('data-shortcut_to_path'),
  1300. );
  1301. });
  1302. }
  1303. // otherwise, move items
  1304. else{
  1305. window.move_items(items_to_move, $(window.mouseover_window).attr('data-path'));
  1306. }
  1307. },
  1308. over: function(event, ui){
  1309. // Don't do anything if the dragged item is NOT a UIItem
  1310. if(!$(ui.draggable).hasClass('item'))
  1311. return;
  1312. },
  1313. out: function(event, ui){
  1314. // Don't do anything if the dragged item is NOT a UIItem
  1315. if(!$(ui.draggable).hasClass('item'))
  1316. return;
  1317. }
  1318. });
  1319. // --------------------------------------------------------
  1320. // Double Click on Head
  1321. // double click on a window head will maximize or shrink window
  1322. // only maximize/shrink if window is marked `is_resizable`
  1323. // --------------------------------------------------------
  1324. if(options.is_resizable){
  1325. $(el_window_head).dblclick(function () {
  1326. window.scale_window(el_window);
  1327. })
  1328. }
  1329. $(el_window_head).mousedown(function () {
  1330. if(window_is_snapped){
  1331. $( el_window ).draggable( "option", "cursorAt", { left: width_before_snap/2 } );
  1332. }
  1333. })
  1334. // --------------------------------------------------------
  1335. // Click On The `Scale` Button
  1336. // (the little rectangle in the window head)
  1337. // --------------------------------------------------------
  1338. if(options.is_resizable){
  1339. $(el_window_head_scale_btn).click(function () {
  1340. window.scale_window(el_window);
  1341. })
  1342. }
  1343. // --------------------------------------------------------
  1344. // Dragster
  1345. // If a local item is dragged over this window, bring it to front
  1346. // --------------------------------------------------------
  1347. let drag_enter_timeout;
  1348. $(el_window).dragster({
  1349. enter: function (dragsterEvent, event) {
  1350. // make sure to cancel any previous timeouts otherwise the window will be brought to front multiple times
  1351. clearTimeout(drag_enter_timeout);
  1352. // If items are dragged over this window long enough, bring it to front
  1353. drag_enter_timeout = setTimeout(function(){
  1354. // focus window
  1355. $(el_window).focusWindow();
  1356. }, 1400);
  1357. },
  1358. leave: function (dragsterEvent, event) {
  1359. // cancel the timeout for 'bringing window to front'
  1360. clearTimeout(drag_enter_timeout);
  1361. },
  1362. drop: function (dragsterEvent, event) {
  1363. // cancel the timeout for 'bringing window to front'
  1364. clearTimeout(drag_enter_timeout);
  1365. },
  1366. over: function (dragsterEvent, event) {
  1367. // cancel the timeout for 'bringing window to front'
  1368. clearTimeout(drag_enter_timeout);
  1369. }
  1370. });
  1371. // --------------------------------------------------------
  1372. // Dragster
  1373. // Allow dragging of local files onto this window, if it's is_dir
  1374. // --------------------------------------------------------
  1375. $(el_window_body).dragster({
  1376. enter: function (dragsterEvent, event) {
  1377. if(options.is_dir){
  1378. // remove any context menu that might be open
  1379. $('.context-menu').remove();
  1380. // highlight this item container
  1381. $(el_window).find('.item-container').addClass('item-container-active');
  1382. }
  1383. },
  1384. leave: function (dragsterEvent, event) {
  1385. if(options.is_dir){
  1386. $(el_window).find('.item-container').removeClass('item-container-active');
  1387. }
  1388. },
  1389. drop: function (dragsterEvent, event) {
  1390. const e = event.originalEvent;
  1391. if(options.is_dir){
  1392. // if files were dropped...
  1393. if(e.dataTransfer?.items?.length>0){
  1394. window.upload_items(e.dataTransfer.items, $(el_window).attr('data-path'))
  1395. }
  1396. // de-highlight all windows
  1397. $('.item-container').removeClass('item-container-active');
  1398. }
  1399. e.stopPropagation();
  1400. e.preventDefault();
  1401. return false;
  1402. }
  1403. });
  1404. // --------------------------------------------------------
  1405. // Close button
  1406. // --------------------------------------------------------
  1407. $(`#window-${win_id} > .window-head > .window-close-btn`).click(function () {
  1408. $(el_window).close({
  1409. shrink_to_target: options.on_close_shrink_to_target
  1410. });
  1411. })
  1412. // --------------------------------------------------------
  1413. // Minimize button
  1414. // --------------------------------------------------------
  1415. $(`#window-${win_id} > .window-head > .window-minimize-btn`).click(function () {
  1416. $(el_window).hideWindow();
  1417. })
  1418. // --------------------------------------------------------
  1419. // Draggable
  1420. // --------------------------------------------------------
  1421. let width_before_snap = 0;
  1422. let height_before_snap = 0;
  1423. let window_is_snapped = false;
  1424. let snap_placeholder_active = false;
  1425. let snap_trigger_timeout;
  1426. if(options.is_draggable){
  1427. let window_snap_placeholder = $(
  1428. `<div class="window-snap-placeholder animate__animated animate__zoomIn animate__faster">
  1429. <div class="window-snap-placeholder-inner"></div>
  1430. </div>`
  1431. );
  1432. $(el_window).draggable({
  1433. start: function(e, ui){
  1434. // if window is snapped, unsnap it and reset its position to where it was before snapping
  1435. if(options.is_resizable && window_is_snapped){
  1436. window_is_snapped = false;
  1437. $(el_window).css({
  1438. 'width': width_before_snap,
  1439. 'height': height_before_snap + 'px',
  1440. });
  1441. // if at any point the window's width is "too small", hide the sidebar
  1442. if($(el_window).width() < window.window_width_threshold_for_sidebar){
  1443. if(width_before_snap >= window.window_width_threshold_for_sidebar && !sidebar_hidden){
  1444. $(el_window_sidebar).hide();
  1445. }
  1446. sidebar_hidden = true;
  1447. }
  1448. // if at any point the window's width is "big enough", show the sidebar
  1449. else if($(el_window).width() >= window.window_width_threshold_for_sidebar){
  1450. if(sidebar_hidden){
  1451. $(el_window_sidebar).show();
  1452. }
  1453. sidebar_hidden = false;
  1454. }
  1455. }
  1456. $(el_window).addClass('window-dragging');
  1457. // rm window from original_window_position
  1458. window.original_window_position[$(el_window).attr('id')] = undefined;
  1459. // since jquery draggable sets the z-index automatically we need this to
  1460. // bring windows to the front when they are clicked.
  1461. window.last_window_zindex = parseInt($(el_window).css('z-index'));
  1462. //transform causes draggable to start inaccurately
  1463. $(el_window).css('transform', 'none');
  1464. },
  1465. drag: function ( e, ui ) {
  1466. $(el_window_app_iframe).css('pointer-events', 'none');
  1467. $('.window').css('pointer-events', 'none');
  1468. // jqueryui changes the z-index automatically, if the stay_on_top flag is set
  1469. // make sure window stays on top
  1470. $(`.window[data-stay_on_top="true"]`).css('z-index', 999999999)
  1471. if($(el_window).attr('data-is_maximized') === '1'){
  1472. $(el_window).attr('data-is_maximized', '0');
  1473. // maximize icon
  1474. $(el_window_head_scale_btn).find('img').attr('src', window.icons['scale.svg']);
  1475. }
  1476. // --------------------------------------------------------
  1477. // Snap to screen edges
  1478. // --------------------------------------------------------
  1479. if(options.is_resizable){
  1480. clearTimeout(snap_trigger_timeout);
  1481. // if window is not snapped, check if it should be snapped
  1482. snap_trigger_timeout = setTimeout(function(){
  1483. // if cursor is not in a snap zone, don't snap
  1484. if(!window.current_active_snap_zone){
  1485. return;
  1486. }
  1487. // if dragging has stopped by now, don't snap
  1488. if(!$(el_window).hasClass('window-dragging')){
  1489. return;
  1490. }
  1491. // W
  1492. if(!window_is_snapped && window.current_active_snap_zone === 'w'){
  1493. window_snap_placeholder.css({
  1494. 'display': 'block',
  1495. 'width': '50%',
  1496. 'height': window.desktop_height,
  1497. 'top': window.toolbar_height,
  1498. 'left': 0,
  1499. 'z-index': window.last_window_zindex - 1,
  1500. })
  1501. }
  1502. // NW
  1503. else if(!window_is_snapped && window.current_active_snap_zone === 'nw'){
  1504. window_snap_placeholder.css({
  1505. 'display': 'block',
  1506. 'width': '50%',
  1507. 'height': window.desktop_height/2,
  1508. 'top': window.toolbar_height,
  1509. 'left': 0,
  1510. 'z-index': window.last_window_zindex - 1,
  1511. })
  1512. }
  1513. // NE
  1514. else if(!window_is_snapped && window.current_active_snap_zone ==='ne'){
  1515. window_snap_placeholder.css({
  1516. 'display': 'block',
  1517. 'width': '50%',
  1518. 'height': window.desktop_height/2,
  1519. 'top': window.toolbar_height,
  1520. 'left': window.desktop_width/2,
  1521. 'z-index': window.last_window_zindex - 1,
  1522. })
  1523. }
  1524. // E
  1525. else if(!window_is_snapped && window.current_active_snap_zone ==='e'){
  1526. window_snap_placeholder.css({
  1527. 'display': 'block',
  1528. 'width': '50%',
  1529. 'height': window.desktop_height,
  1530. 'top': window.toolbar_height,
  1531. 'left': 'initial',
  1532. 'right': 0,
  1533. 'z-index': window.last_window_zindex - 1,
  1534. })
  1535. }
  1536. // N
  1537. else if(!window_is_snapped && window.current_active_snap_zone ==='n'){
  1538. window_snap_placeholder.css({
  1539. 'display': 'block',
  1540. 'width': window.desktop_width,
  1541. 'height': window.desktop_height,
  1542. 'top': window.toolbar_height,
  1543. 'left': 0,
  1544. 'z-index': window.last_window_zindex - 1,
  1545. })
  1546. }
  1547. // SW
  1548. else if(!window_is_snapped && window.current_active_snap_zone ==='sw'){
  1549. window_snap_placeholder.css({
  1550. 'display': 'block',
  1551. 'top': window.toolbar_height + window.desktop_height/2,
  1552. 'left': 0,
  1553. 'width': '50%',
  1554. 'height': window.desktop_height/2,
  1555. 'z-index': window.last_window_zindex - 1,
  1556. })
  1557. }
  1558. // SE
  1559. else if(!window_is_snapped && window.current_active_snap_zone ==='se'){
  1560. window_snap_placeholder.css({
  1561. 'display': 'block',
  1562. 'top': window.toolbar_height + window.desktop_height/2,
  1563. 'left': window.desktop_width/2,
  1564. 'width': '50%',
  1565. 'height': window.desktop_height/2,
  1566. 'z-index': window.last_window_zindex - 1,
  1567. })
  1568. }
  1569. // If snap placeholder is not active, append it and make it active
  1570. if(!window_is_snapped && !snap_placeholder_active){
  1571. snap_placeholder_active = true;
  1572. $(el_body).append(window_snap_placeholder);
  1573. }
  1574. // save window size before snap
  1575. width_before_snap = $(el_window).width();
  1576. height_before_snap = $(el_window).height();
  1577. }, 500);
  1578. // if mouse is not in a snap zone, hide snap placeholder
  1579. if(snap_placeholder_active && !window.current_active_snap_zone){
  1580. snap_placeholder_active = false;
  1581. window_snap_placeholder.fadeOut(80);
  1582. }
  1583. }
  1584. },
  1585. stop: function () {
  1586. let window_will_snap = false;
  1587. $( el_window ).draggable( "option", "cursorAt", false );
  1588. $(el_window).removeClass('window-dragging');
  1589. $(el_window).attr({
  1590. 'data-orig-top': $(el_window).position().top,
  1591. 'data-orig-left': $(el_window).position().left,
  1592. })
  1593. $(el_window_app_iframe).css('pointer-events', 'all');
  1594. $('.window').css('pointer-events', 'initial');
  1595. // jqueryui changes the z-index automatically, if the stay_on_top flag is set
  1596. // make sure window stays on top with the initial zindex though
  1597. $(`.window[data-stay_on_top="true"]`).each(function(){
  1598. $(this).css('z-index', $(this).attr('data-initial_zindex'))
  1599. })
  1600. if(options.is_resizable && snap_placeholder_active && !window_is_snapped){
  1601. window_will_snap = true;
  1602. $(window_snap_placeholder).css('padding', 0);
  1603. setTimeout(function(){
  1604. // snap to w
  1605. if(window.current_active_snap_zone === 'w'){
  1606. $(el_window).css({
  1607. 'top': window.toolbar_height,
  1608. 'left': 0,
  1609. 'width': '50%',
  1610. 'height': window.desktop_height,
  1611. })
  1612. }
  1613. // snap to nw
  1614. else if(window.current_active_snap_zone === 'nw'){
  1615. $(el_window).css({
  1616. 'top': window.toolbar_height,
  1617. 'left': 0,
  1618. 'width': '50%',
  1619. 'height': window.desktop_height/2,
  1620. })
  1621. }
  1622. // snap to ne
  1623. else if(window.current_active_snap_zone === 'ne'){
  1624. $(el_window).css({
  1625. 'top': window.toolbar_height,
  1626. 'left': '50%',
  1627. 'width': '50%',
  1628. 'height': window.desktop_height/2,
  1629. })
  1630. }
  1631. // snap to sw
  1632. else if(window.current_active_snap_zone === 'sw'){
  1633. $(el_window).css({
  1634. 'top': window.toolbar_height + window.desktop_height/2,
  1635. 'left': 0,
  1636. 'width': '50%',
  1637. 'height': window.desktop_height/2,
  1638. })
  1639. }
  1640. // snap to se
  1641. else if(window.current_active_snap_zone === 'se'){
  1642. $(el_window).css({
  1643. 'top': window.toolbar_height + window.desktop_height/2,
  1644. 'left': window.desktop_width/2,
  1645. 'width': '50%',
  1646. 'height': window.desktop_height/2,
  1647. })
  1648. }
  1649. // snap to e
  1650. else if(window.current_active_snap_zone === 'e'){
  1651. $(el_window).css({
  1652. 'top': window.toolbar_height,
  1653. 'left': '50%',
  1654. 'width': '50%',
  1655. 'height': window.desktop_height,
  1656. })
  1657. }
  1658. // snap to n
  1659. else if(window.current_active_snap_zone === 'n'){
  1660. window.scale_window(el_window);
  1661. }
  1662. // snap placeholder is no longer active
  1663. snap_placeholder_active = false;
  1664. // hide snap placeholder
  1665. window_snap_placeholder.css('display', 'none');
  1666. window_snap_placeholder.css('padding', '10px');
  1667. // mark window as snapped
  1668. window_is_snapped = true;
  1669. // if at any point the window's width is "too small", hide the sidebar
  1670. if($(el_window).width() < window.window_width_threshold_for_sidebar){
  1671. if(width_before_snap >= window.window_width_threshold_for_sidebar && !sidebar_hidden){
  1672. $(el_window_sidebar).hide();
  1673. }
  1674. sidebar_hidden = true;
  1675. }
  1676. // if at any point the window's width is "big enough", show the sidebar
  1677. else if($(el_window).width() >= window.window_width_threshold_for_sidebar){
  1678. if(sidebar_hidden){
  1679. $(el_window_sidebar).show();
  1680. }
  1681. sidebar_hidden = false;
  1682. }
  1683. }, 100);
  1684. }
  1685. // if window is dropped below the taskbar, move it up
  1686. // the lst '- 30' is to account for the window head
  1687. if($(el_window).position().top > window.innerHeight - window.taskbar_height - 30 && !window_will_snap){
  1688. $(el_window).animate({
  1689. top: window.innerHeight - window.taskbar_height - 60,
  1690. }, 100);
  1691. }
  1692. // if window is dropped too far to the right, move it left
  1693. if($(el_window).position().left > window.innerWidth - 50 && !window_will_snap){
  1694. $(el_window).animate({
  1695. left: window.innerWidth - 50,
  1696. }, 100);
  1697. }
  1698. // if window is dropped too far to the left, move it right
  1699. if(($(el_window).position().left + $(el_window).width() - 150 )< 0 && !window_will_snap){
  1700. $(el_window).animate({
  1701. left: -1 * ($(el_window).width() - 150),
  1702. }, 100);
  1703. }
  1704. },
  1705. handle: `.window-head-draggable` + (options.draggable_body ? `, .window-body` : ``),
  1706. stack: `.window`,
  1707. scroll: false,
  1708. containment: '.window-container',
  1709. });
  1710. }
  1711. // --------------------------------------------------------
  1712. // Resizable
  1713. // --------------------------------------------------------
  1714. if(options.is_resizable){
  1715. if($(el_window).width() < window.window_width_threshold_for_sidebar){
  1716. $(el_window_sidebar).hide();
  1717. sidebar_hidden = true;
  1718. }
  1719. $(el_window).resizable({
  1720. handles: "n, ne, nw, e, s, se, sw, w",
  1721. minWidth: 200,
  1722. minHeight: 200,
  1723. start: function(){
  1724. window.a_window_is_resizing = true;
  1725. $(el_window_app_iframe).css('pointer-events', 'none');
  1726. $('.window').css('pointer-events', 'none');
  1727. },
  1728. resize: function (e, ui) {
  1729. // if at any point the window's width is "too small", hide the sidebar
  1730. if(ui.size.width < window.window_width_threshold_for_sidebar){
  1731. if(ui.originalSize.width >= window.window_width_threshold_for_sidebar && !sidebar_hidden){
  1732. $(el_window_sidebar).hide();
  1733. }
  1734. sidebar_hidden = true;
  1735. }
  1736. // if at any point the window's width is "big enough", show the sidebar
  1737. else if(ui.size.width >= window.window_width_threshold_for_sidebar){
  1738. if(sidebar_hidden){
  1739. $(el_window_sidebar).show();
  1740. }
  1741. sidebar_hidden = false;
  1742. }
  1743. // when resizing the top of the window, make sure the window head is not hidden behind the toolbar
  1744. if($(el_window).position().top < window.toolbar_height){
  1745. var difference = window.toolbar_height - $(el_window).position().top;
  1746. $(el_window).css({
  1747. 'top': window.toolbar_height,
  1748. 'height': ui.size.height - difference // Reduce the height by the difference
  1749. });
  1750. // don't resize
  1751. return false;
  1752. }
  1753. },
  1754. stop: function () {
  1755. window.a_window_is_resizing = false;
  1756. $(el_window_app_iframe).css('pointer-events', 'all');
  1757. $('.window').css('pointer-events', 'initial');
  1758. $(el_window_sidebar).resizable("option", "maxWidth", el_window.getBoundingClientRect().width/2);
  1759. $(el_window).attr({
  1760. 'data-orig-width': $(el_window).width(),
  1761. 'data-orig-height': $(el_window).height(),
  1762. })
  1763. // maximize icon
  1764. $(el_window_head_scale_btn).find('img').attr('src', window.icons['scale.svg']);
  1765. $(el_window).attr('data-is_maximized', '0');
  1766. },
  1767. containment: 'parent',
  1768. })
  1769. }
  1770. // --------------------------------------------------------
  1771. // Sidebar Resizable
  1772. // --------------------------------------------------------
  1773. let side = $(el_window).find('.window-sidebar')
  1774. side.resizable({
  1775. handles: "e,w",
  1776. minWidth: 100,
  1777. maxWidth: el_window.getBoundingClientRect().width/2,
  1778. start: function(){
  1779. $(el_window_app_iframe).css('pointer-events', 'none');
  1780. $('.window').css('pointer-events', 'none');
  1781. },
  1782. stop: function () {
  1783. $(el_window_app_iframe).css('pointer-events', 'all');
  1784. $('.window').css('pointer-events', 'initial');
  1785. const new_width = $(el_window_sidebar).width();
  1786. // save new width in the cloud, to user's settings
  1787. puter.kv.set({key: "window_sidebar_width", value: new_width});
  1788. // save new width locally, to window object
  1789. window.window_sidebar_width = new_width;
  1790. }
  1791. })
  1792. // --------------------------------------------------------
  1793. // Alt/Option + Shift + click on window head will open a prompt to enter iframe url
  1794. // --------------------------------------------------------
  1795. $(el_window_head).on('click', function(e){
  1796. if(e.altKey && e.shiftKey && el_window_app_iframe !== null){
  1797. let url = prompt("Enter URL", options.iframe_url);
  1798. if(url){
  1799. $(el_window_app_iframe).attr('src', url);
  1800. }
  1801. }
  1802. })
  1803. // --------------------------------------------------------
  1804. // Head Context Menu
  1805. // --------------------------------------------------------
  1806. $(el_window_head).bind("contextmenu taphold", function (event) {
  1807. // dimiss taphold on regular devices
  1808. if(event.type==='taphold' && !isMobile.phone && !isMobile.tablet)
  1809. return;
  1810. const $target = $(event.target);
  1811. // Cases in which native ctx menu should be preserved
  1812. if(options.allow_native_ctxmenu || $target.hasClass('allow-native-ctxmenu') || $target.is('input') || $target.is('textarea'))
  1813. return true;
  1814. // custom ctxmenu for all other elements
  1815. event.preventDefault();
  1816. // If window has no head, don't show ctxmenu
  1817. if(!options.has_head)
  1818. return;
  1819. let menu_items = [];
  1820. // -------------------------------------------
  1821. // Maximize/Minimize
  1822. // -------------------------------------------
  1823. if(options.is_resizable){
  1824. menu_items.push({
  1825. html: $(el_window).attr('data-is_maximized') === '0' ? 'Maximize' : 'Restore',
  1826. onClick: function(){
  1827. // maximize window
  1828. window.scale_window(el_window);
  1829. }
  1830. });
  1831. menu_items.push({
  1832. html: 'Minimize',
  1833. onClick: function(){
  1834. $(el_window).hideWindow();
  1835. }
  1836. });
  1837. // -
  1838. menu_items.push('-')
  1839. }
  1840. // -------------------------------------------
  1841. // Close
  1842. // -------------------------------------------
  1843. menu_items.push({
  1844. html: 'Close',
  1845. onClick: function(){
  1846. $(el_window).close();
  1847. }
  1848. });
  1849. UIContextMenu({
  1850. parent_element: el_window_head,
  1851. items: menu_items,
  1852. parent_id: win_id,
  1853. })
  1854. })
  1855. // --------------------------------------------------------
  1856. // Body Context Menu
  1857. // --------------------------------------------------------
  1858. $(el_window_body).bind("contextmenu taphold", function (event) {
  1859. // dimiss taphold on regular devices
  1860. if(event.type==='taphold' && !isMobile.phone && !isMobile.tablet)
  1861. return;
  1862. const $target = $(event.target);
  1863. // Cases in which native ctx menu should be preserved
  1864. if(options.allow_native_ctxmenu || $target.hasClass('allow-native-ctxmenu') || $target.is('input') || $target.is('textarea'))
  1865. return true
  1866. // custom ctxmenu for all other elements
  1867. event.preventDefault();
  1868. if(options.allow_context_menu && event.target === el_window_body){
  1869. // Regular directories
  1870. if($(el_window).attr('data-path') !== window.trash_path){
  1871. UIContextMenu({
  1872. parent_element: el_window_body,
  1873. items: [
  1874. // -------------------------------------------
  1875. // Sort by
  1876. // -------------------------------------------
  1877. {
  1878. html: i18n('sort_by'),
  1879. items: [
  1880. {
  1881. html: i18n('name'),
  1882. icon: $(el_window).attr('data-sort_by') === 'name' ? '✓' : '',
  1883. onClick: async function(){
  1884. window.sort_items(el_window_body, 'name', $(el_window).attr('data-sort_order'));
  1885. window.set_sort_by($(el_window).attr('data-uid'), 'name', $(el_window).attr('data-sort_order'))
  1886. }
  1887. },
  1888. {
  1889. html: i18n('date_modified'),
  1890. icon: $(el_window).attr('data-sort_by') === 'modified' ? '✓' : '',
  1891. onClick: async function(){
  1892. window.sort_items(el_window_body, 'modified', $(el_window).attr('data-sort_order'));
  1893. window.set_sort_by($(el_window).attr('data-uid'), 'modified', $(el_window).attr('data-sort_order'))
  1894. }
  1895. },
  1896. {
  1897. html: i18n('type'),
  1898. icon: $(el_window).attr('data-sort_by') === 'type' ? '✓' : '',
  1899. onClick: async function(){
  1900. window.sort_items(el_window_body, 'type', $(el_window).attr('data-sort_order'));
  1901. window.set_sort_by($(el_window).attr('data-uid'), 'type', $(el_window).attr('data-sort_order'))
  1902. }
  1903. },
  1904. {
  1905. html: i18n('size'),
  1906. icon: $(el_window).attr('data-sort_by') === 'size' ? '✓' : '',
  1907. onClick: async function(){
  1908. window.sort_items(el_window_body, 'size', $(el_window).attr('data-sort_order'));
  1909. window.set_sort_by($(el_window).attr('data-uid'), 'size', $(el_window).attr('data-sort_order'))
  1910. }
  1911. },
  1912. // -------------------------------------------
  1913. // -
  1914. // -------------------------------------------
  1915. '-',
  1916. {
  1917. html: i18n('ascending'),
  1918. icon: $(el_window).attr('data-sort_order') === 'asc' ? '✓' : '',
  1919. onClick: async function(){
  1920. const sort_by = $(el_window).attr('data-sort_by')
  1921. window.sort_items(el_window_body, sort_by, 'asc');
  1922. window.set_sort_by($(el_window).attr('data-uid'), sort_by, 'asc')
  1923. }
  1924. },
  1925. {
  1926. html: i18n('descending'),
  1927. icon: $(el_window).attr('data-sort_order') === 'desc' ? '✓' : '',
  1928. onClick: async function(){
  1929. const sort_by = $(el_window).attr('data-sort_by')
  1930. window.sort_items(el_window_body, sort_by, 'desc');
  1931. window.set_sort_by($(el_window).attr('data-uid'), sort_by, 'desc')
  1932. }
  1933. },
  1934. ]
  1935. },
  1936. // -------------------------------------------
  1937. // Refresh
  1938. // -------------------------------------------
  1939. {
  1940. html: i18n('refresh'),
  1941. onClick: function(){
  1942. refresh_item_container(el_window_body, options);
  1943. }
  1944. },
  1945. // -------------------------------------------
  1946. // Show/Hide hidden files
  1947. // -------------------------------------------
  1948. {
  1949. html: i18n('show_hidden'),
  1950. icon: window.user_preferences.show_hidden_files ? '✓' : '',
  1951. onClick: function(){
  1952. window.mutate_user_preferences({
  1953. show_hidden_files : !window.user_preferences.show_hidden_files,
  1954. });
  1955. window.show_or_hide_files(document.querySelectorAll('.item-container'));
  1956. }
  1957. },
  1958. // -------------------------------------------
  1959. // -
  1960. // -------------------------------------------
  1961. '-',
  1962. // -------------------------------------------
  1963. // New
  1964. // -------------------------------------------
  1965. new_context_menu_item($(el_window).attr('data-path'), el_window_body),
  1966. // -------------------------------------------
  1967. // -
  1968. // -------------------------------------------
  1969. '-',
  1970. // -------------------------------------------
  1971. // Paste
  1972. // -------------------------------------------
  1973. {
  1974. html: i18n('paste'),
  1975. disabled: (window.clipboard.length === 0 || $(el_window).attr('data-path') === '/') ? true : false,
  1976. onClick: function(){
  1977. if(window.clipboard_op === 'copy')
  1978. window.copy_clipboard_items($(el_window).attr('data-path'), el_window_body);
  1979. else if(window.clipboard_op === 'move')
  1980. window.move_clipboard_items(el_window_body)
  1981. }
  1982. },
  1983. // -------------------------------------------
  1984. // Undo
  1985. // -------------------------------------------
  1986. {
  1987. html: i18n('undo'),
  1988. disabled: window.actions_history.length > 0 ? false : true,
  1989. onClick: function(){
  1990. window.undo_last_action();
  1991. }
  1992. },
  1993. // -------------------------------------------
  1994. // Upload Here
  1995. // -------------------------------------------
  1996. {
  1997. html: i18n('upload_here'),
  1998. disabled: $(el_window).attr('data-path') === '/' ? true : false,
  1999. onClick: function(){
  2000. window.init_upload_using_dialog(el_window_body, $(el_window).attr('data-path') + '/');
  2001. }
  2002. },
  2003. // -------------------------------------------
  2004. // -
  2005. // -------------------------------------------
  2006. '-',
  2007. // -------------------------------------------
  2008. // Publish As Website
  2009. // -------------------------------------------
  2010. {
  2011. html: i18n('publish_as_website'),
  2012. disabled: !options.is_dir,
  2013. onClick: async function () {
  2014. if (window.require_email_verification_to_publish_website) {
  2015. if (window.user.is_temp &&
  2016. !await UIWindowSaveAccount({
  2017. send_confirmation_code: true,
  2018. message: i18n('save_account_to_publish'),
  2019. window_options: {
  2020. backdrop: true,
  2021. close_on_backdrop_click: false,
  2022. }
  2023. }))
  2024. return;
  2025. else if (!window.user.email_confirmed && !await UIWindowEmailConfirmationRequired())
  2026. return;
  2027. }
  2028. UIWindowPublishWebsite($(el_window).attr('data-uid'), $(el_window).attr('data-name'), $(el_window).attr('data-path'));
  2029. }
  2030. },
  2031. // -------------------------------------------
  2032. // Deploy as App
  2033. // -------------------------------------------
  2034. {
  2035. html: i18n('deploy_as_app'),
  2036. disabled: !options.is_dir,
  2037. onClick: async function () {
  2038. launch_app({
  2039. name: 'dev-center',
  2040. file_path: $(el_window).attr('data-path'),
  2041. file_uid: $(el_window).attr('data-uid'),
  2042. params: {
  2043. source_path: $(el_window).attr('data-path'),
  2044. }
  2045. })
  2046. }
  2047. },
  2048. // -------------------------------------------
  2049. // -
  2050. // -------------------------------------------
  2051. '-',
  2052. // -------------------------------------------
  2053. // Properties
  2054. // -------------------------------------------
  2055. {
  2056. html: i18n('properties'),
  2057. onClick: function(){
  2058. let window_height = 500;
  2059. let window_width = 450;
  2060. let left = window.mouseX;
  2061. left -= 200;
  2062. left = left > (window.innerWidth - window_width)? (window.innerWidth - window_width) : left;
  2063. let top = window.mouseY;
  2064. top = top > (window.innerHeight - (window_height + window.taskbar_height + window.toolbar_height))? (window.innerHeight - (window_height + window.taskbar_height + window.toolbar_height)) : top;
  2065. UIWindowItemProperties(options.title, options.path, options.uid, left, top, window_width, window_height);
  2066. }
  2067. },
  2068. ]
  2069. });
  2070. }
  2071. // Trash conext menu
  2072. else{
  2073. UIContextMenu({
  2074. parent_element: el_window_body,
  2075. items: [
  2076. // -------------------------------------------
  2077. // Empty Trash
  2078. // -------------------------------------------
  2079. {
  2080. html: i18n('empty_trash'),
  2081. disabled: false,
  2082. onClick: async function(){
  2083. // TODO: Merge this with window.empty_trash()
  2084. const alert_resp = await UIAlert({
  2085. message: i18n('empty_trash_confirmation'),
  2086. buttons:[
  2087. {
  2088. label: i18n('yes'),
  2089. value: 'yes',
  2090. type: 'primary',
  2091. },
  2092. {
  2093. label: i18n('no'),
  2094. value: 'no',
  2095. },
  2096. ]
  2097. })
  2098. if(alert_resp === 'no')
  2099. return;
  2100. // todo this has to be case-insensitive but the `i` selector doesn't work on ^=
  2101. $(`.item[data-path^="${html_encode(window.trash_path)}/"]`).each(function(){
  2102. window.delete_item(this);
  2103. })
  2104. // update other clients
  2105. if(window.socket){
  2106. window.socket.emit('trash.is_empty', {is_empty: true});
  2107. }
  2108. // use the 'empty trash' icon
  2109. $(`.item[data-path="${html_encode(window.trash_path)}" i], .item[data-shortcut_to_path="${html_encode(window.trash_path)}" i]`).find('.item-icon > img').attr('src', window.icons['trash.svg']);
  2110. }
  2111. },
  2112. ]
  2113. });
  2114. }
  2115. }
  2116. });
  2117. // --------------------------------------------------------
  2118. // Head Context Menu
  2119. // --------------------------------------------------------
  2120. if(options.has_head){
  2121. $(el_window_head).bind("contextmenu taphold", function (event) {
  2122. event.preventDefault();
  2123. return false;
  2124. })
  2125. }
  2126. // --------------------------------------------------------
  2127. // Droppable sidebar items
  2128. // --------------------------------------------------------
  2129. $(el_window).find('.window-sidebar-item').each(function (index){
  2130. // todo only continue if this item is a dir
  2131. const el_item = this;
  2132. $(el_item).dragster({
  2133. enter: function (dragsterEvent, event) {
  2134. $(el_item).addClass('item-selected');
  2135. },
  2136. leave: function (dragsterEvent, event) {
  2137. $(el_item).removeClass('item-selected');
  2138. },
  2139. drop: function (dragsterEvent, event) {
  2140. const e = event.originalEvent;
  2141. $(el_item).removeClass('item-selected');
  2142. // if files were dropped...
  2143. if(e.dataTransfer?.items?.length > 0){
  2144. window.upload_items(e.dataTransfer.items, $(el_item).attr('data-path'))
  2145. }
  2146. e.stopPropagation();
  2147. e.preventDefault();
  2148. return false;
  2149. }
  2150. });
  2151. })
  2152. //set styles
  2153. $(el_window_body).css(options.body_css);
  2154. // is fullpage?
  2155. if(options.is_fullpage){
  2156. $(el_window).hide()
  2157. setTimeout(function(){
  2158. window.enter_fullpage_mode(el_window);
  2159. $(el_window).show()
  2160. }, 50);
  2161. }
  2162. return el_window;
  2163. }
  2164. function delete_window_element (el_window){
  2165. // if this is the active element, set it to null
  2166. if(window.active_element === el_window){
  2167. window.active_element = null;
  2168. }
  2169. // remove DOM element
  2170. $(el_window).remove();
  2171. // if no other windows open, reset window_counter
  2172. // resetting window counter is important so that next window opens at the center of the screen
  2173. if($('.window').length === 0)
  2174. window.window_counter = 0;
  2175. }
  2176. $(document).on('click', '.window-sidebar-item', async function(e){
  2177. const el_window = $(this).closest('.window');
  2178. const parent_win_id = $(el_window).attr('data-id');
  2179. const item_path = $(this).attr('data-path');
  2180. // ctrl/cmd + click will open in new window
  2181. if(e.metaKey || e.ctrlKey){
  2182. UIWindow({
  2183. path: item_path,
  2184. title: path.basename(item_path),
  2185. icon: await item_icon({is_dir: true, path: item_path}),
  2186. // todo
  2187. // uid: $(el_item).attr('data-uid'),
  2188. is_dir: true,
  2189. // todo
  2190. // sort_by: $(el_item).attr('data-sort_by'),
  2191. app: 'explorer',
  2192. // top: options.maximized ? 0 : undefined,
  2193. // left: options.maximized ? 0 : undefined,
  2194. // height: options.maximized ? `calc(100% - ${window.taskbar_height + 1}px)` : undefined,
  2195. // width: options.maximized ? `100%` : undefined,
  2196. });
  2197. }
  2198. // update window path only if it's a new path AND no ctrl/cmd key pressed
  2199. else if(item_path !== $(el_window).attr('data-path')){
  2200. window.window_nav_history[parent_win_id] = window.window_nav_history[parent_win_id].slice(0, window.window_nav_history_current_position[parent_win_id] + 1);
  2201. window.window_nav_history[parent_win_id].push(item_path);
  2202. window.window_nav_history_current_position[parent_win_id]++;
  2203. window.update_window_path(el_window, item_path);
  2204. }
  2205. })
  2206. $(document).on('contextmenu', '.window-sidebar', function(e){
  2207. e.preventDefault();
  2208. e.stopPropagation();
  2209. return false;
  2210. })
  2211. $(document).on('contextmenu taphold', '.window-sidebar-item', function(event){
  2212. // dismiss taphold on regular devices
  2213. if(event.type==='taphold' && !isMobile.phone && !isMobile.tablet)
  2214. return;
  2215. event.preventDefault();
  2216. event.stopPropagation();
  2217. // todo
  2218. // $(this).addClass('window-sidebar-item-highlighted');
  2219. const item = this;
  2220. UIContextMenu({
  2221. parent_element: $(this),
  2222. items: [
  2223. //--------------------------------------------------
  2224. // Open
  2225. //--------------------------------------------------
  2226. {
  2227. html: "Open",
  2228. onClick: function(){
  2229. $(item).trigger('click');
  2230. }
  2231. },
  2232. //--------------------------------------------------
  2233. // Open in New Window
  2234. //--------------------------------------------------
  2235. {
  2236. html: "Open in New Window",
  2237. onClick: async function(){
  2238. let item_path = $(item).attr('data-path');
  2239. UIWindow({
  2240. path: item_path,
  2241. title: path.basename(item_path),
  2242. icon: await item_icon({is_dir: true, path: item_path}),
  2243. // todo
  2244. // uid: $(el_item).attr('data-uid'),
  2245. is_dir: true,
  2246. // todo
  2247. // sort_by: $(el_item).attr('data-sort_by'),
  2248. app: 'explorer',
  2249. // top: options.maximized ? 0 : undefined,
  2250. // left: options.maximized ? 0 : undefined,
  2251. // height: options.maximized ? `calc(100% - ${window.taskbar_height + 1}px)` : undefined,
  2252. // width: options.maximized ? `100%` : undefined,
  2253. });
  2254. }
  2255. }
  2256. ]
  2257. });
  2258. return false;
  2259. })
  2260. $(document).on('dblclick', '.window .ui-resizable-handle', function(e){
  2261. let el_window = $(this).closest('.window');
  2262. // bottom
  2263. if($(this).hasClass('ui-resizable-s')){
  2264. let height = window.innerHeight - $(el_window).position().top - window.taskbar_height -1;
  2265. $(el_window).height(height);
  2266. }
  2267. // top
  2268. else if($(this).hasClass('ui-resizable-n')){
  2269. let height = $(el_window).height() + $(el_window).position().top - window.toolbar_height;
  2270. $(el_window).css({
  2271. height: height,
  2272. top: window.toolbar_height,
  2273. });
  2274. }
  2275. // right
  2276. else if($(this).hasClass('ui-resizable-e')){
  2277. let width = window.innerWidth - $(el_window).position().left;
  2278. $(el_window).css({
  2279. width: width,
  2280. });
  2281. }
  2282. // left
  2283. else if($(this).hasClass('ui-resizable-w')){
  2284. let width = $(el_window).width() + $(el_window).position().left;
  2285. $(el_window).css({
  2286. width: width,
  2287. left: 0
  2288. });
  2289. }
  2290. // bottom left
  2291. else if($(this).hasClass('ui-resizable-sw')){
  2292. let width = $(el_window).width() + $(el_window).position().left;
  2293. let height = window.innerHeight - $(el_window).position().top - window.taskbar_height -1;
  2294. $(el_window).css({
  2295. width: width,
  2296. height: height,
  2297. left: 0
  2298. });
  2299. }
  2300. // bottom right
  2301. else if($(this).hasClass('ui-resizable-se')){
  2302. let width = window.innerWidth - $(el_window).position().left;
  2303. let height = window.innerHeight - $(el_window).position().top - window.taskbar_height -1;
  2304. $(el_window).css({
  2305. width: width,
  2306. height: height,
  2307. });
  2308. }
  2309. // top right
  2310. else if($(this).hasClass('ui-resizable-ne')){
  2311. let width = window.innerWidth - $(el_window).position().left;
  2312. let height = $(el_window).height() + $(el_window).position().top - window.toolbar_height;
  2313. $(el_window).css({
  2314. width: width,
  2315. height: height,
  2316. top: window.toolbar_height,
  2317. });
  2318. }
  2319. // top left
  2320. else if($(this).hasClass('ui-resizable-nw')){
  2321. let width = $(el_window).width() + $(el_window).position().left;
  2322. let height = $(el_window).height() + $(el_window).position().top - window.toolbar_height;
  2323. $(el_window).css({
  2324. width: width,
  2325. height: height,
  2326. top: window.toolbar_height,
  2327. left:0,
  2328. });
  2329. }
  2330. })
  2331. $(document).on('click', '.window-navbar-path', function(e){
  2332. if(!$(e.target).hasClass('window-navbar-path'))
  2333. return;
  2334. $(e.target).hide();
  2335. $(e.target).siblings('.window-navbar-path-input').show().select();
  2336. })
  2337. $(document).on('blur', '.window-navbar-path-input', function(e){
  2338. $(e.target).hide();
  2339. $(e.target).siblings('.window-navbar-path').show().select();
  2340. })
  2341. $(document).on('keyup', '.window-navbar-path-input', function(e){
  2342. if (e.key === 'Enter' || e.keyCode === 13) {
  2343. window.update_window_path($(e.target).closest('.window'), $(e.target).val());
  2344. $(e.target).hide();
  2345. $(e.target).siblings('.window-navbar-path').show().select();
  2346. }
  2347. })
  2348. $(document).on('click', '.window-navbar-path-dirname', function(e){
  2349. const $el_parent_window = $(this).closest('.window');
  2350. const parent_win_id = $($el_parent_window).attr('data-id');
  2351. // open in new window
  2352. if(e.metaKey || e.ctrlKey){
  2353. const dirpath = $(this).attr('data-path');
  2354. UIWindow({
  2355. path: dirpath,
  2356. title: dirpath === '/' ? window.root_dirname : path.basename(dirpath),
  2357. icon: window.icons['folder.svg'],
  2358. // uid: $(el_item).attr('data-uid'),
  2359. is_dir: true,
  2360. app: 'explorer',
  2361. });
  2362. }
  2363. // only change dir if target is not the same as current path
  2364. else if($el_parent_window.attr('data-path') !== $(this).attr('data-path')){
  2365. window.window_nav_history[parent_win_id] = window.window_nav_history[parent_win_id].slice(0, window.window_nav_history_current_position[parent_win_id]+1);
  2366. window.window_nav_history[parent_win_id].push($(this).attr('data-path'));
  2367. window.window_nav_history_current_position[parent_win_id] = window.window_nav_history[parent_win_id].length - 1;
  2368. window.update_window_path($el_parent_window, $(this).attr('data-path'));
  2369. }
  2370. })
  2371. $(document).on('contextmenu taphold', '.window-navbar', function(event){
  2372. // don't disable system ctxmenu on the address bar input
  2373. if($(event.target).hasClass('window-navbar-path-input'))
  2374. return;
  2375. // dismiss taphold on regular devices
  2376. if(event.type==='taphold' && !isMobile.phone && !isMobile.tablet)
  2377. return;
  2378. event.preventDefault();
  2379. event.stopPropagation();
  2380. return false;
  2381. })
  2382. $(document).on('contextmenu taphold', '.window-navbar-path-dirname', function(event){
  2383. // dismiss taphold on regular devices
  2384. if(event.type==='taphold' && !isMobile.phone && !isMobile.tablet)
  2385. return;
  2386. event.preventDefault();
  2387. const menu_items = [];
  2388. const el = this;
  2389. // -------------------------------------------
  2390. // Open
  2391. // -------------------------------------------
  2392. menu_items.push({
  2393. html: 'Open',
  2394. onClick: ()=>{
  2395. $(this).trigger('click');
  2396. }
  2397. });
  2398. // -------------------------------------------
  2399. // Open in New Window
  2400. // (only if the item is on a window)
  2401. // -------------------------------------------
  2402. menu_items.push({
  2403. html: 'Open in New Window',
  2404. onClick: function(){
  2405. UIWindow({
  2406. path: $(el).attr('data-path'),
  2407. title: $(el).attr('data-path') === '/' ? window.root_dirname : path.basename($(el).attr('data-path')),
  2408. icon: window.icons['folder.svg'],
  2409. uid: $(el).attr('data-uid'),
  2410. is_dir: true,
  2411. app: 'explorer',
  2412. });
  2413. }
  2414. });
  2415. // -------------------------------------------
  2416. // -
  2417. // -------------------------------------------
  2418. menu_items.push('-'),
  2419. // -------------------------------------------
  2420. // Paste
  2421. // -------------------------------------------
  2422. menu_items.push({
  2423. html: "Paste",
  2424. disabled: window.clipboard.length > 0 ? false : true,
  2425. onClick: function(){
  2426. if(window.clipboard_op === 'copy')
  2427. window.copy_clipboard_items($(el).attr('data-path'), null);
  2428. else if(window.clipboard_op === 'move')
  2429. window.move_clipboard_items(null, $(el).attr('data-path'))
  2430. }
  2431. })
  2432. UIContextMenu({
  2433. parent_element: $(this),
  2434. items: menu_items
  2435. });
  2436. })
  2437. // if the click is on the mask, bring focus to the active child window
  2438. $(document).on('click', '.window-disable-mask', async function(e){
  2439. e.stopPropagation();
  2440. e.preventDefault();
  2441. return false;
  2442. })
  2443. // --------------------------------------------------------
  2444. // Navbar Dir Droppable
  2445. // --------------------------------------------------------
  2446. window.navbar_path_droppable = (el_window)=>{
  2447. $(el_window).find('.window-navbar-path-dirname').droppable({
  2448. accept: '.item',
  2449. tolerance: 'pointer',
  2450. drop: function( event, ui ) {
  2451. // check if item was actually dropped on this navbar path
  2452. if($(window.mouseover_window).attr('data-id') !== $(el_window).attr('data-id')){
  2453. return;
  2454. }
  2455. const items_to_move = []
  2456. // first item
  2457. items_to_move.push(ui.draggable);
  2458. // all subsequent items
  2459. const cloned_items = document.getElementsByClassName('item-selected-clone');
  2460. for(let i =0; i<cloned_items.length; i++){
  2461. const source_item = document.getElementById('item-' + $(cloned_items[i]).attr('data-id'));
  2462. if(source_item !== null)
  2463. items_to_move.push(source_item);
  2464. }
  2465. // if alt key is down, create shortcut items
  2466. if(event.altKey){
  2467. items_to_move.forEach((item_to_move) => {
  2468. window.create_shortcut(
  2469. path.basename($(item_to_move).attr('data-path')),
  2470. $(item_to_move).attr('data-is_dir') === '1',
  2471. $(this).attr('data-path'),
  2472. null,
  2473. $(item_to_move).attr('data-shortcut_to') === '' ? $(item_to_move).attr('data-uid') : $(item_to_move).attr('data-shortcut_to'),
  2474. $(item_to_move).attr('data-shortcut_to_path') === '' ? $(item_to_move).attr('data-path') : $(item_to_move).attr('data-shortcut_to_path'),
  2475. );
  2476. });
  2477. }
  2478. // move items
  2479. else{
  2480. window.move_items(items_to_move, $(this).attr('data-path'));
  2481. }
  2482. $('.item-container').droppable('enable')
  2483. $(this).removeClass('window-navbar-path-dirname-active');
  2484. return false;
  2485. },
  2486. over: function(event, ui){
  2487. // check if item was actually hovered over this window
  2488. if($(window.mouseover_window).attr('data-id') !== $(el_window).attr('data-id'))
  2489. return;
  2490. // Don't do anything if the dragged item is NOT a UIItem
  2491. if(!$(ui.draggable).hasClass('item'))
  2492. return;
  2493. // highlight this dirname
  2494. $(this).addClass('window-navbar-path-dirname-active');
  2495. $('.ui-draggable-dragging').css('opacity', 0.2)
  2496. $('.item-selected-clone').css('opacity', 0.2)
  2497. // disable all window bodies
  2498. $('.item-container').droppable( 'disable' )
  2499. },
  2500. out: function(event, ui){
  2501. // Don't do anything if the dragged element is NOT a UIItem
  2502. if(!$(ui.draggable).hasClass('item'))
  2503. return;
  2504. // unselect directory if item is dragged out
  2505. $(this).removeClass('window-navbar-path-dirname-active');
  2506. $('.ui-draggable-dragging').css('opacity', 'initial')
  2507. $('.item-selected-clone').css('opacity', 'initial')
  2508. $('.item-container').droppable( 'enable' )
  2509. }
  2510. });
  2511. }
  2512. /**
  2513. * Constructs a XSS-safe string that represents a navigation bar path.
  2514. * The result is a string with HTML span elements for each directory in the path, each accompanied by a separator icon.
  2515. * Each span element has a `data-path` attribute holding the encoded path to that directory, and contains the encoded directory name as text.
  2516. * The root directory name is a constant defined in globals.js, represented as 'root_dirname'.
  2517. *
  2518. * @param {string} abs_path - The absolute path to be displayed in the navigation bar. It should be a string with directories separated by slashes ('/').
  2519. *
  2520. * @returns {string} A string of HTML spans and separators, each span representing a directory in the navigation bar.
  2521. *
  2522. */
  2523. window.navbar_path = (abs_path)=>{
  2524. const dirs = (abs_path === '/' ? [''] : abs_path.split('/'));
  2525. const dirpaths = (abs_path === '/' ? ['/'] : [])
  2526. const path_seperator_html = `<img class="path-seperator" draggable="false" src="${html_encode(window.icons['triangle-right.svg'])}">`;
  2527. if(dirs.length > 1){
  2528. for(let i=0; i<dirs.length; i++){
  2529. dirpaths[i] = '';
  2530. for(let j=1; j<=i; j++){
  2531. dirpaths[i] += '/'+dirs[j];
  2532. }
  2533. }
  2534. }
  2535. let str = `${path_seperator_html}<span class="window-navbar-path-dirname" data-path="${html_encode('/')}">${html_encode(window.root_dirname)}</span>`;
  2536. for(let k=1; k<dirs.length; k++){
  2537. str += `${path_seperator_html}<span class="window-navbar-path-dirname" data-path="${html_encode(dirpaths[k])}">${dirs[k] === 'Trash' ? i18n('trash') : html_encode(dirs[k])}</span>`;
  2538. }
  2539. return str;
  2540. }
  2541. window.update_window_path = async function(el_window, target_path){
  2542. const win_id = $(el_window).attr('data-id');
  2543. const el_window_navbar_forward_btn = $(el_window).find('.window-navbar-btn-forward');
  2544. const el_window_navbar_back_btn = $(el_window).find('.window-navbar-btn-back');
  2545. const el_window_navbar_up_btn = $(el_window).find('.window-navbar-btn-up');
  2546. const el_window_body = $(el_window).find('.window-body');
  2547. const el_window_item_container = $(el_window).find('.item-container');
  2548. const el_window_navbar_path_input = $(el_window).find('.window-navbar-path-input');
  2549. const is_dir = ($(el_window).attr('data-is_dir') === '1' || $(el_window).attr('data-is_dir') === 'true');
  2550. const old_path = $(el_window).attr('data-path');
  2551. // update sidebar items' active status
  2552. $(el_window).find(`.window-sidebar-item`).removeClass('window-sidebar-item-active');
  2553. $(el_window).find(`.window-sidebar-item[data-path="${html_encode(target_path)}"]`).addClass('window-sidebar-item-active');
  2554. // clean
  2555. $(el_window).find('.explore-table-headers-th > .header-sort-icon').html('');
  2556. if(is_dir){
  2557. // if nav history for this window is empty, disable forward btn
  2558. if(window.window_nav_history[win_id] && window.window_nav_history[win_id].length - 1 === window.window_nav_history_current_position[win_id])
  2559. $(el_window_navbar_forward_btn).addClass('window-navbar-btn-disabled');
  2560. // ... else, enable forawrd btn
  2561. else
  2562. $(el_window_navbar_forward_btn).removeClass('window-navbar-btn-disabled');
  2563. // disable back button if path is root
  2564. if(window.window_nav_history_current_position[win_id] === 0)
  2565. $(el_window_navbar_back_btn).addClass('window-navbar-btn-disabled');
  2566. // ... enable back btn in all other cases
  2567. else
  2568. $(el_window_navbar_back_btn).removeClass('window-navbar-btn-disabled');
  2569. // disabled Up button if this is root
  2570. if(target_path === '/')
  2571. $(el_window_navbar_up_btn).addClass('window-navbar-btn-disabled');
  2572. // ... enable back btn in all other cases
  2573. else
  2574. $(el_window_navbar_up_btn).removeClass('window-navbar-btn-disabled');
  2575. $(el_window_item_container).attr('data-path', target_path);
  2576. $(el_window).find('.window-navbar-path').html(window.navbar_path(target_path, window.user.username));
  2577. // empty body to be filled with the results of /readdir
  2578. $(el_window_body).find('.item').removeItems()
  2579. // add the 'Detail View' table header
  2580. if($(el_window).find('.explore-table-headers').length === 0)
  2581. $(el_window_body).prepend(window.explore_table_headers());
  2582. // 'Detail View' table header is hidden by default
  2583. $(el_window).find('.explore-table-headers').hide();
  2584. // system directories with custom icons and predefined names
  2585. if(target_path === window.desktop_path){
  2586. $(el_window).find('.window-head-icon').attr('src', window.icons['folder-desktop.svg']);
  2587. $(el_window).find('.window-head-title').text('Desktop')
  2588. }else if (target_path === window.home_path){
  2589. $(el_window).find('.window-head-icon').attr('src', window.icons['folder-home.svg']);
  2590. $(el_window).find('.window-head-title').text('Home')
  2591. }else if (target_path === window.docs_path){
  2592. $(el_window).find('.window-head-icon').attr('src', window.icons['folder-documents.svg']);
  2593. $(el_window).find('.window-head-title').text('Documents')
  2594. }else if (target_path === window.public_path){
  2595. $(el_window).find('.window-head-icon').attr('src', window.icons['folder-public.svg']);
  2596. $(el_window).find('.window-head-title').text('Public')
  2597. }else if (target_path === window.videos_path){
  2598. $(el_window).find('.window-head-icon').attr('src', window.icons['folder-videos.svg']);
  2599. $(el_window).find('.window-head-title').text('Videos')
  2600. }else if (target_path === window.pictures_path){
  2601. $(el_window).find('.window-head-icon').attr('src', window.icons['folder-pictures.svg']);
  2602. $(el_window).find('.window-head-title').text('Pictures')
  2603. }// root folder of a shared user?
  2604. else if((target_path.split('/').length - 1) === 1 && target_path !== '/'+window.user.username)
  2605. $(el_window).find('.window-head-icon').attr('src', window.icons['shared.svg']);
  2606. else
  2607. $(el_window).find('.window-head-icon').attr('src', window.icons['folder.svg']);
  2608. }
  2609. $(el_window).attr('data-path', html_encode(target_path));
  2610. $(el_window).attr('data-name', html_encode(path.basename(target_path)));
  2611. // /stat
  2612. if(target_path !== '/'){
  2613. try{
  2614. puter.fs.stat(target_path, function(fsentry){
  2615. $(el_window).removeClass('window-' + $(el_window).attr('data-uid'));
  2616. $(el_window).addClass('window-' + fsentry.id);
  2617. $(el_window).attr('data-uid', fsentry.id);
  2618. $(el_window).attr('data-sort_by', fsentry.sort_by ?? 'name');
  2619. $(el_window).attr('data-sort_order', fsentry.sort_order ?? 'asc');
  2620. $(el_window).attr('data-layout', fsentry.layout ?? 'icons');
  2621. $(el_window_item_container).attr('data-uid', fsentry.id);
  2622. // title
  2623. if (target_path === window.home_path)
  2624. $(el_window).find('.window-head-title').text('Home')
  2625. else
  2626. $(el_window).find('.window-head-title').text(fsentry.name);
  2627. // data-name
  2628. $(el_window).attr('data-name', html_encode(fsentry.name));
  2629. // data-path
  2630. $(el_window).attr('data-path', html_encode(target_path));
  2631. $(el_window_navbar_path_input).val(target_path);
  2632. $(el_window_navbar_path_input).attr('data-path', target_path);
  2633. // update layout
  2634. window.update_window_layout(el_window, fsentry.layout);
  2635. // update explore header if in details view
  2636. if(fsentry.layout === 'details'){
  2637. window.update_details_layout_sort_visuals(el_window, fsentry.sort_by, fsentry.sort_order);
  2638. }
  2639. });
  2640. }catch(err){
  2641. UIAlert(err.responseText)
  2642. // todo optim: this is dumb because updating the window should only happen if this /readdir request is successful,
  2643. // in that case there is no need for using update_window_path on error!!
  2644. window.update_window_path(el_window, old_path);
  2645. }
  2646. }
  2647. // path is '/' (global root)
  2648. else{
  2649. $(el_window).removeClass('window-' + $(el_window).attr('data-uid'));
  2650. $(el_window).addClass('window-null');
  2651. $(el_window).attr('data-uid', 'null');
  2652. $(el_window).attr('data-name', '');
  2653. $(el_window).find('.window-head-title').text(window.root_dirname);
  2654. }
  2655. if(is_dir){
  2656. refresh_item_container(el_window_body);
  2657. window.navbar_path_droppable(el_window)
  2658. }
  2659. window.update_explorer_footer_selected_items_count(el_window);
  2660. }
  2661. // --------------------------------------------------------
  2662. // Sidebar Item Droppable
  2663. // --------------------------------------------------------
  2664. window.sidebar_item_droppable = (el_window)=>{
  2665. $(el_window).find('.window-sidebar-item').droppable({
  2666. accept: '.item',
  2667. tolerance: 'pointer',
  2668. drop: function( event, ui ) {
  2669. // check if item was actually dropped on this navbar path
  2670. if($(window.mouseover_window).attr('data-id') !== $(el_window).attr('data-id')){
  2671. return;
  2672. }
  2673. const items_to_move = []
  2674. // first item
  2675. items_to_move.push(ui.draggable);
  2676. // all subsequent items
  2677. const cloned_items = document.getElementsByClassName('item-selected-clone');
  2678. for(let i =0; i<cloned_items.length; i++){
  2679. const source_item = document.getElementById('item-' + $(cloned_items[i]).attr('data-id'));
  2680. if(source_item !== null)
  2681. items_to_move.push(source_item);
  2682. }
  2683. // if alt key is down, create shortcut items
  2684. if(event.altKey){
  2685. items_to_move.forEach((item_to_move) => {
  2686. window.create_shortcut(
  2687. path.basename($(item_to_move).attr('data-path')),
  2688. $(item_to_move).attr('data-is_dir') === '1',
  2689. $(this).attr('data-path'),
  2690. null,
  2691. $(item_to_move).attr('data-shortcut_to') === '' ? $(item_to_move).attr('data-uid') : $(item_to_move).attr('data-shortcut_to'),
  2692. $(item_to_move).attr('data-shortcut_to_path') === '' ? $(item_to_move).attr('data-path') : $(item_to_move).attr('data-shortcut_to_path'),
  2693. );
  2694. });
  2695. }
  2696. // move items
  2697. else{
  2698. window.move_items(items_to_move, $(this).attr('data-path'));
  2699. }
  2700. $('.item-container').droppable('enable')
  2701. $(this).removeClass('window-sidebar-item-drag-active');
  2702. return false;
  2703. },
  2704. over: function(event, ui){
  2705. // check if item was actually hovered over this window
  2706. if($(window.mouseover_window).attr('data-id') !== $(el_window).attr('data-id'))
  2707. return;
  2708. // Don't do anything if the dragged item is NOT a UIItem
  2709. if(!$(ui.draggable).hasClass('item'))
  2710. return;
  2711. // highlight this item
  2712. $(this).addClass('window-sidebar-item-drag-active');
  2713. $('.ui-draggable-dragging').css('opacity', 0.2)
  2714. $('.item-selected-clone').css('opacity', 0.2)
  2715. // disable all window bodies
  2716. $('.item-container').droppable( 'disable' )
  2717. },
  2718. out: function(event, ui){
  2719. // Don't do anything if the dragged element is NOT a UIItem
  2720. if(!$(ui.draggable).hasClass('item'))
  2721. return;
  2722. // unselect item if item is dragged out
  2723. $(this).removeClass('window-sidebar-item-drag-active');
  2724. $('.ui-draggable-dragging').css('opacity', 'initial')
  2725. $('.item-selected-clone').css('opacity', 'initial')
  2726. $('.item-container').droppable( 'enable' )
  2727. }
  2728. });
  2729. }
  2730. // closes a window
  2731. $.fn.close = async function(options) {
  2732. options = options || {};
  2733. $(this).each(async function() {
  2734. const el_iframe = $(this).find('.window-app-iframe');
  2735. const app_uses_sdk = el_iframe.length > 0 && el_iframe.attr('data-appUsesSDK') === 'true';
  2736. if(app_uses_sdk){
  2737. // get appInstanceID
  2738. const appInstanceID = el_iframe.closest('.window').attr('data-element_uuid');
  2739. // tell child app that this window is about to close, get its response
  2740. if(!options.bypass_iframe_messaging){
  2741. const resp = await window.sendWindowWillCloseMsg(el_iframe.get(0));
  2742. if(!resp.msg){
  2743. return false;
  2744. }
  2745. }
  2746. // remove the menubar from the window.menubars array
  2747. if(appInstanceID){
  2748. delete window.menubars[appInstanceID];
  2749. window.app_instance_ids.delete(appInstanceID);
  2750. }
  2751. }
  2752. if ( this.on_before_exit ) {
  2753. if ( ! await this.on_before_exit() ) return false;
  2754. }
  2755. // Process window close if this is a window
  2756. if($(this).hasClass('window')){
  2757. const win_id = parseInt($(this).attr('data-id'));
  2758. let window_uuid = $(this).attr('data-element_uuid');
  2759. // remove all instances of win_id from window.window_stack
  2760. _.pullAll(window.window_stack, [win_id]);
  2761. // taskbar update
  2762. let open_window_count = parseInt($(`.taskbar-item[data-app="${$(this).attr('data-app')}"]`).attr('data-open-windows'));
  2763. // update open window count of corresponding taskbar item
  2764. if(open_window_count > 0){
  2765. $(`.taskbar-item[data-app="${$(this).attr('data-app')}"]`).attr('data-open-windows', open_window_count - 1);
  2766. }
  2767. // decide whether to remove taskbar item
  2768. if(open_window_count === 1){
  2769. $(`.taskbar-item[data-app="${$(this).attr('data-app')}"] .active-taskbar-indicator`).hide();
  2770. window.remove_taskbar_item($(`.taskbar-item[data-app="${$(this).attr('data-app')}"][data-keep-in-taskbar="false"]`));
  2771. }
  2772. // if no more windows of this app are open, remove taskbar item
  2773. if(open_window_count - 1 === 0)
  2774. $(`.taskbar-item[data-app="${$(this).attr('data-app')}"] .active-taskbar-indicator`).hide();
  2775. // if a fullpage window is closed, show desktop and taskbar
  2776. if($(this).attr('data-is_fullpage') === '1'){
  2777. window.exit_fullpage_mode();
  2778. }
  2779. // FileDialog closed
  2780. if($(this).hasClass('window-filedialog') || $(this).attr('data-disable_parent_window') === 'true'){
  2781. // re-enable this FileDialog's parent window
  2782. $(`.window[data-element_uuid="${$(this).attr('data-parent_uuid')}"]`).addClass('window-active');
  2783. $(`.window[data-element_uuid="${$(this).attr('data-parent_uuid')}"]`).removeClass('window-disabled');
  2784. $(`.window[data-element_uuid="${$(this).attr('data-parent_uuid')}"]`).find('.window-disable-mask').hide();
  2785. // bring focus back to app iframe, if needed
  2786. $(`.window[data-element_uuid="${$(this).attr('data-parent_uuid')}"]`).focusWindow();
  2787. }
  2788. // Other types of windows closed
  2789. else{
  2790. // close any open FileDialogs belonging to this window
  2791. $(`.window-filedialog[data-parent_uuid="${window_uuid}"]`).close();
  2792. // bring focus to the last window in the window-stack (only if not minimized)
  2793. if(!_.isEmpty(window.window_stack)){
  2794. const $last_window_in_stack = $(`.window[data-id="${window.window_stack[window.window_stack.length - 1]}"]`);
  2795. // check if previous window is not minimized
  2796. if($last_window_in_stack !== null && $last_window_in_stack.attr('data-is_minimized') !== '1' && $last_window_in_stack.attr('data-is_minimized') !== 'true'){
  2797. $(`.window[data-id="${window.window_stack[window.window_stack.length - 1]}"]`).focusWindow();
  2798. }
  2799. // otherwise, change URL/Title to desktop
  2800. else{
  2801. window.history.replaceState(null, document.title, '/');
  2802. document.title = 'Puter';
  2803. }
  2804. // if it's explore
  2805. if($last_window_in_stack.attr('data-app') && $last_window_in_stack.attr('data-app').toLowerCase() === 'explorer'){
  2806. window.history.replaceState(null, document.title, '/');
  2807. document.title = 'Puter';
  2808. }
  2809. }
  2810. // otherwise, change URL/Title to desktop
  2811. else{
  2812. window.history.replaceState(null, document.title, '/');
  2813. document.title = 'Puter';
  2814. }
  2815. }
  2816. // close child windows
  2817. $(`.window[data-parent_uuid="${window_uuid}"]`).close();
  2818. // notify other apps that we're closing
  2819. window.report_app_closed(window_uuid, options.status_code ?? 0);
  2820. // remove backdrop
  2821. $(this).closest('.window-backdrop').remove();
  2822. // remove global menubars
  2823. $(`.window-menubar-global[data-window-id="${win_id}"]`).remove();
  2824. // remove DOM element
  2825. if(options?.shrink_to_target){
  2826. // get target location
  2827. const target_pos = $(options.shrink_to_target).position();
  2828. const target_size = $(options.shrink_to_target).get(0).getBoundingClientRect();
  2829. // animate window to target location
  2830. $(this).animate({
  2831. width: `1`,
  2832. height: `1`,
  2833. top: target_pos.top + target_size.height / 2,
  2834. left: target_pos.left + target_size.width / 2,
  2835. }, 300, () => {
  2836. // remove DOM element
  2837. delete_window_element(this);
  2838. });
  2839. }
  2840. else if(window.animate_window_closing){
  2841. // start shrink animation
  2842. $(this).css({
  2843. 'transition': 'transform 400ms',
  2844. 'transform': 'scale(0)',
  2845. });
  2846. // remove DOM element after fadeout animation
  2847. $(this).fadeOut(80, function(){
  2848. delete_window_element(this);
  2849. })
  2850. }else{
  2851. delete_window_element(this);
  2852. }
  2853. }
  2854. // focus back to desktop?
  2855. if(_.isEmpty(window.window_stack)){
  2856. // The following is to make sure the iphone keyboard is dismissed when the last window is closed
  2857. if(isMobile.phone || isMobile.tablet){
  2858. document.activeElement.blur();
  2859. $("input").blur();
  2860. }
  2861. // focus back to desktop
  2862. $('.desktop').find('.item-blurred').removeClass('item-blurred');
  2863. window.active_item_container = $('.desktop.item-container').get(0);
  2864. }
  2865. })
  2866. return this;
  2867. };
  2868. window.scale_window = (el_window)=>{
  2869. //maximize
  2870. if ($(el_window).attr('data-is_maximized') !== '1') {
  2871. // save original size and position
  2872. let el_window_rect = el_window.getBoundingClientRect();
  2873. $(el_window).attr({
  2874. 'data-left-before-maxim': el_window_rect.left + 'px',
  2875. 'data-top-before-maxim': el_window_rect.top + 'px',
  2876. 'data-width-before-maxim': $(el_window).css('width'),
  2877. 'data-height-before-maxim': $(el_window).css('height'),
  2878. 'data-is_maximized': '1',
  2879. });
  2880. // shrink icon
  2881. $(el_window).find('.window-scale-btn>img').attr('src', window.icons['scale-down-3.svg']);
  2882. // set new size and position
  2883. $(el_window).css({
  2884. 'top': window.toolbar_height+'px',
  2885. 'left': '0',
  2886. 'width': '100%',
  2887. 'height': `calc(100% - ${window.taskbar_height + window.toolbar_height + 1}px)`,
  2888. 'transform': 'none',
  2889. });
  2890. }
  2891. //shrink
  2892. else {
  2893. // set size and position to original before maximization
  2894. $(el_window).css({
  2895. 'top': $(el_window).attr('data-top-before-maxim'),
  2896. 'left': $(el_window).attr('data-left-before-maxim'),
  2897. 'width': $(el_window).attr('data-width-before-maxim'),
  2898. 'height': $(el_window).attr('data-height-before-maxim'),
  2899. 'transform': 'none',
  2900. });
  2901. // maximize icon
  2902. $(el_window).find('.window-scale-btn>img').attr('src', window.icons['scale.svg']);
  2903. $(el_window).attr({
  2904. 'data-is_maximized': 0,
  2905. });
  2906. }
  2907. // record window size and position before scaling
  2908. $(el_window).attr({
  2909. 'data-orig-width': $(el_window).width(),
  2910. 'data-orig-height': $(el_window).height(),
  2911. 'data-orig-top': $(el_window).position().top,
  2912. 'data-orig-left': $(el_window).position().left,
  2913. 'data-is_minimized': false,
  2914. })
  2915. }
  2916. window.update_explorer_footer_item_count = function(el_window){
  2917. //update dir count in explorer footer
  2918. let item_count = $(el_window).find('.item').length;
  2919. $(el_window).find('.explorer-footer .explorer-footer-item-count').html(item_count + ` ${i18n('item')}` + (item_count == 0 || item_count > 1 ? `${i18n('plural_suffix')}` : ''));
  2920. }
  2921. window.update_explorer_footer_selected_items_count = function(el_window){
  2922. //update dir count in explorer footer
  2923. let item_count = $(el_window).find('.item-selected').length;
  2924. if(item_count > 0){
  2925. $(el_window).find('.explorer-footer-seperator, .explorer-footer-selected-items-count').show();
  2926. $(el_window).find('.explorer-footer .explorer-footer-selected-items-count').html(item_count + ` ${i18n('item')}` + (item_count == 0 || item_count > 1 ? `${i18n('plural_suffix')}` : '') + ` ${i18n('selected')}`);
  2927. }else{
  2928. $(el_window).find('.explorer-footer-seperator, .explorer-footer-selected-items-count').hide();
  2929. }
  2930. }
  2931. window.set_sort_by = function(item_uid, sort_by, sort_order){
  2932. if(sort_order !== 'asc' && sort_order !== 'desc')
  2933. sort_order = 'asc';
  2934. $.ajax({
  2935. url: window.api_origin + "/set_sort_by",
  2936. type: 'POST',
  2937. data: JSON.stringify({
  2938. sort_by: sort_by,
  2939. item_uid: item_uid,
  2940. sort_order: sort_order,
  2941. }),
  2942. async: true,
  2943. contentType: "application/json",
  2944. headers: {
  2945. "Authorization": "Bearer "+window.auth_token
  2946. },
  2947. statusCode: {
  2948. 401: function () {
  2949. window.logout();
  2950. },
  2951. },
  2952. success: function (){
  2953. }
  2954. })
  2955. // update the sort_by & sort_order attr of every matching element
  2956. $(`[data-uid="${item_uid}"]`).attr({
  2957. 'data-sort_by': sort_by,
  2958. 'data-sort_order': sort_order,
  2959. });
  2960. }
  2961. window.explore_table_headers = function(){
  2962. let h = ``;
  2963. h += `<div class="explore-table-headers">`;
  2964. h += `<div class="explore-table-headers-th explore-table-headers-th--name">Name<span class="header-sort-icon"></span></div>`;
  2965. h += `<div class="explore-table-headers-th explore-table-headers-th--modified">Modified<span class="header-sort-icon"></span></div>`;
  2966. h += `<div class="explore-table-headers-th explore-table-headers-th--size">Size<span class="header-sort-icon"></span></div>`;
  2967. h += `<div class="explore-table-headers-th explore-table-headers-th--type">Type<span class="header-sort-icon"></span></div>`;
  2968. h += `</div>`;
  2969. return h;
  2970. }
  2971. window.update_window_layout = function(el_window, layout){
  2972. layout = layout ?? 'icons';
  2973. if(layout === 'icons'){
  2974. $(el_window).find('.explore-table-headers').hide();
  2975. $(el_window).find('.item-container').removeClass('item-container-list');
  2976. $(el_window).find('.item-container').removeClass('item-container-details');
  2977. $(el_window).find('.window-navbar-layout-settings').attr('src', window.icons['layout-icons.svg']);
  2978. $(el_window).attr('data-layout', layout)
  2979. }
  2980. else if(layout === 'list'){
  2981. $(el_window).find('.explore-table-headers').hide();
  2982. $(el_window).find('.item-container').removeClass('item-container-details');
  2983. $(el_window).find('.item-container').addClass('item-container-list');
  2984. $(el_window).find('.window-navbar-layout-settings').attr('src', window.icons['layout-list.svg'])
  2985. $(el_window).attr('data-layout', layout)
  2986. }
  2987. else if(layout === 'details'){
  2988. $(el_window).find('.explore-table-headers').show();
  2989. $(el_window).find('.item-container').removeClass('item-container-list');
  2990. $(el_window).find('.item-container').addClass('item-container-details');
  2991. $(el_window).find('.window-navbar-layout-settings').attr('src', window.icons['layout-details.svg'])
  2992. $(el_window).attr('data-layout', layout)
  2993. }
  2994. }
  2995. $.fn.showWindow = async function(options) {
  2996. $(this).each(async function() {
  2997. if($(this).hasClass('window')){
  2998. // show window
  2999. const el_window = this;
  3000. $(el_window).css({
  3001. 'transition': `top 0.2s, left 0.2s, bottom 0.2s, right 0.2s, width 0.2s, height 0.2s`,
  3002. top: $(el_window).attr('data-orig-top') + 'px',
  3003. left: $(el_window).attr('data-orig-left') + 'px',
  3004. width: $(el_window).attr('data-orig-width') + 'px',
  3005. height: $(el_window).attr('data-orig-height') + 'px',
  3006. });
  3007. $(el_window).css('z-index', ++window.last_window_zindex);
  3008. setTimeout(() => {
  3009. $(this).focusWindow();
  3010. }, 80);
  3011. // remove `transitions` a good while after setting css to make sure
  3012. // it doesn't interfere with an ongoing animation
  3013. setTimeout(() => {
  3014. $(el_window).css('transition', 'none');
  3015. }, 250);
  3016. }
  3017. })
  3018. return this;
  3019. };
  3020. window.toggle_empty_folder_message = function(el_item_container){
  3021. // if the item container is the desktop, don't show/hide the empty message
  3022. if($(el_item_container).hasClass('desktop'))
  3023. return;
  3024. // if the item container is empty, show the empty message
  3025. if($(el_item_container).has('.item').length === 0){
  3026. $(el_item_container).find('.explorer-empty-message').show();
  3027. }
  3028. // if the item container is not empty, hide the empty message
  3029. else{
  3030. $(el_item_container).find('.explorer-empty-message').hide();
  3031. }
  3032. }
  3033. $.fn.focusWindow = function(event) {
  3034. if(this.hasClass('window')){
  3035. const $app_iframe = $(this).find('.window-app-iframe');
  3036. const win_id = $(this).attr('data-id');
  3037. $('.window').not(this).removeClass('window-active');
  3038. $(this).addClass('window-active');
  3039. // disable pointer events on all windows' iframes, except for this window's iframe
  3040. $('.window-app-iframe').not($app_iframe).css('pointer-events', 'none');
  3041. // bring this window to front, only if it's not stay_on_top
  3042. if($(this).attr('data-stay_on_top') !== 'true'){
  3043. $(this).css('z-index', ++window.last_window_zindex);
  3044. }
  3045. // if this window has a parent, bring them to the front too
  3046. if($(this).attr('data-parent_uuid') !== 'null'){
  3047. $(`.window[data-element_uuid="${$(this).attr('data-parent_uuid')}"]`).css('z-index', window.last_window_zindex);
  3048. }
  3049. // if this window has child windows, bring them to the front too
  3050. if($(this).attr('data-element_uuid') !== 'null'){
  3051. $(`.window[data-parent_uuid="${$(this).attr('data-element_uuid')}"]`).css('z-index', ++window.last_window_zindex);
  3052. }
  3053. // hide other global menubars
  3054. $('.window-menubar-global').not(`.window-menubar-global[data-window-id="${win_id}"]`).hide();
  3055. // show this window's global menubar
  3056. $(`.window-menubar-global[data-window-id="${win_id}"]`).show();
  3057. // if a menubar or any of its items are clicked, don't focus the iframe. This is important to preserve the focus on the menubar
  3058. // and to enable keyboard navigation through the menubar items
  3059. if($(event?.target).hasClass('window-menubar') || $(event?.target).closest('.window-menubar').length > 0){
  3060. $($app_iframe).css('pointer-events', 'none');
  3061. $app_iframe.get(0)?.blur();
  3062. $app_iframe.get(0)?.contentWindow?.blur();
  3063. }
  3064. // if this has an iframe
  3065. else if(!$(this).hasClass('window-disabled') && $app_iframe.length > 0){
  3066. $($app_iframe).css('pointer-events', 'all');
  3067. $app_iframe.get(0)?.focus({preventScroll:true});
  3068. $app_iframe.get(0)?.contentWindow?.focus({preventScroll:true});
  3069. // todo check if iframe is using SDK before sending messages
  3070. $app_iframe.get(0).contentWindow.postMessage({msg: "focus"}, '*');
  3071. var rect = $app_iframe.get(0).getBoundingClientRect();
  3072. // send click event to iframe, if this focus event was triggered by a click or similar mouse event
  3073. if(
  3074. event !== undefined &&
  3075. (event.type === 'click' || event.type === 'dblclick' || event.type === 'contextmenu' || event.type === 'mousedown' || event.type === 'mouseup' || event.type === 'mousemove')
  3076. ){
  3077. $app_iframe.get(0).contentWindow.postMessage({msg: "click", x: (window.mouseX - rect.left), y: (window.mouseY - rect.top)}, '*');
  3078. }
  3079. }
  3080. // set active_item_container
  3081. window.active_item_container = $(this).find('.item-container').get(0);
  3082. // grey out all selected items on other windows/desktop
  3083. $('.item-container').not(window.active_item_container).find('.item-selected').addClass('item-blurred');
  3084. // update window-stack
  3085. window.window_stack.push(parseInt($(this).attr('data-id')));
  3086. // remove blurred class from items on this window
  3087. $(window.active_item_container).find('.item-blurred').removeClass('item-blurred');
  3088. //change window URL
  3089. const update_window_url = $(this).attr('data-update_window_url');
  3090. if(update_window_url === 'true' || update_window_url === null){
  3091. window.history.replaceState({window_id: $(this).attr('data-id')}, '', '/app/'+$(this).attr('data-app')+$(this).attr('data-user_set_url_params'));
  3092. document.title = $(this).attr('data-name');
  3093. }
  3094. $(`.taskbar .taskbar-item[data-app="${$(this).attr('data-app')}"]`).addClass('taskbar-item-active');
  3095. }else{
  3096. $('.window').find('.item-selected').addClass('item-blurred');
  3097. $('.desktop').find('.item-blurred').removeClass('item-blurred');
  3098. }
  3099. return this;
  3100. }
  3101. // hides a window
  3102. $.fn.hideWindow = async function(options) {
  3103. $(this).each(async function() {
  3104. if($(this).hasClass('window')){
  3105. // get taskbar item location
  3106. const taskbar_item_pos = $(`.taskbar .taskbar-item[data-app="${$(this).attr('data-app')}"]`).position();
  3107. $(this).attr({
  3108. 'data-orig-width': $(this).width(),
  3109. 'data-orig-height': $(this).height(),
  3110. 'data-orig-top': $(this).position().top,
  3111. 'data-orig-left': $(this).position().left,
  3112. 'data-is_minimized': true,
  3113. })
  3114. $(this).css({
  3115. 'transition': `top 0.2s, left 0.2s, bottom 0.2s, right 0.2s, width 0.2s, height 0.2s`,
  3116. width: `0`,
  3117. height: `0`,
  3118. top: 'calc(100% - 60px)',
  3119. left: taskbar_item_pos.left + 29,
  3120. });
  3121. // remove transitions a good while after setting css to make sure
  3122. // it doesn't interfere with an ongoing animation
  3123. setTimeout(() => {
  3124. $(this).css({
  3125. 'transition': 'none',
  3126. 'transform': 'none'
  3127. });
  3128. }, 250);
  3129. // update title and window URL
  3130. window.history.replaceState(null, document.title, '/');
  3131. document.title = 'Puter';
  3132. }
  3133. })
  3134. return this;
  3135. };
  3136. $(document).on('click', '.explore-table-headers-th', function(e){
  3137. let sort_by = 'name';
  3138. let sort_icon = `<img src="${window.icons['up-arrow.svg']}">`;
  3139. // current sort order
  3140. let sort_order = $(e.target).closest('.window').attr('data-sort_order') ?? 'asc';
  3141. // flip sort order
  3142. if(sort_order === 'asc'){
  3143. sort_order = 'desc';
  3144. sort_icon = `<img src="${window.icons['down-arrow.svg']}">`;
  3145. }else if(sort_order === 'desc'){
  3146. sort_icon = `<img src="${window.icons['up-arrow.svg']}">`;
  3147. sort_order = 'asc';
  3148. }
  3149. // remove active class from all headers
  3150. $(e.target).closest('.window').find('.explore-table-headers-th').removeClass('explore-table-headers-th-active');
  3151. // remove icons from all headers
  3152. $(e.target).closest('.window').find('.header-sort-icon').html('');
  3153. // add active class to this header
  3154. $(e.target).addClass('explore-table-headers-th-active');
  3155. // set sort icon
  3156. $(e.target).closest('.window').find('.explore-table-headers-th-active > .header-sort-icon').html(sort_icon);
  3157. // set sort_by
  3158. if($(e.target).hasClass('explore-table-headers-th--name')){
  3159. sort_by = 'name';
  3160. }else if($(e.target).hasClass('explore-table-headers-th--modified')){
  3161. sort_by = 'modified';
  3162. }else if($(e.target).hasClass('explore-table-headers-th--size')){
  3163. sort_by = 'size';
  3164. }else if($(e.target).hasClass('explore-table-headers-th--type')){
  3165. sort_by = 'type';
  3166. }
  3167. // sort
  3168. window.sort_items($(e.target).closest('.window-body'), sort_by, sort_order);
  3169. window.set_sort_by($(e.target).closest('.window').attr('data-uid'), sort_by, sort_order)
  3170. })
  3171. window.set_layout = function(item_uid, layout){
  3172. $.ajax({
  3173. url: window.api_origin + "/set_layout",
  3174. type: 'POST',
  3175. data: JSON.stringify({
  3176. item_uid: item_uid,
  3177. layout: layout,
  3178. }),
  3179. async: true,
  3180. contentType: "application/json",
  3181. headers: {
  3182. "Authorization": "Bearer "+window.auth_token
  3183. },
  3184. statusCode: {
  3185. 401: function () {
  3186. window.logout();
  3187. },
  3188. },
  3189. success: function (){
  3190. if(layout === 'details'){
  3191. let el_window = $(`.window[data-uid="${item_uid}"]`);
  3192. if(el_window.length > 0){
  3193. let sort_by = el_window.attr('data-sort_by');
  3194. let sort_order = el_window.attr('data-sort_order');
  3195. window.update_details_layout_sort_visuals(el_window, sort_by, sort_order);
  3196. }
  3197. }
  3198. }
  3199. })
  3200. }
  3201. window.update_details_layout_sort_visuals = function(el_window, sort_by, sort_order){
  3202. let sort_icon = '';
  3203. $(el_window).find('.explore-table-headers-th > .header-sort-icon').html('');
  3204. if(!sort_order || sort_order === 'asc')
  3205. sort_icon = `<img src="${window.icons['up-arrow.svg']}">`;
  3206. else if(sort_order === 'desc')
  3207. sort_icon = `<img src="${window.icons['down-arrow.svg']}">`;
  3208. if(!sort_by || sort_by === 'name'){
  3209. $(el_window).find('.explore-table-headers-th').removeClass('explore-table-headers-th-active');
  3210. $(el_window).find('.explore-table-headers-th--name').addClass('explore-table-headers-th-active');
  3211. $(el_window).find('.explore-table-headers-th--name > .header-sort-icon').html(sort_icon);
  3212. }else if(sort_by === 'size'){
  3213. $(el_window).find('.explore-table-headers-th').removeClass('explore-table-headers-th-active');
  3214. $(el_window).find('.explore-table-headers-th--size').addClass('explore-table-headers-th-active');
  3215. $(el_window).find('.explore-table-headers-th--size > .header-sort-icon').html(sort_icon);
  3216. }else if(sort_by === 'modified'){
  3217. $(el_window).find('.explore-table-headers-th').removeClass('explore-table-headers-th-active');
  3218. $(el_window).find('.explore-table-headers-th--modified').addClass('explore-table-headers-th-active');
  3219. $(el_window).find('.explore-table-headers-th--modified > .header-sort-icon').html(sort_icon);
  3220. }else if(sort_by === 'type'){
  3221. $(el_window).find('.explore-table-headers-th').removeClass('explore-table-headers-th-active');
  3222. $(el_window).find('.explore-table-headers-th--type').addClass('explore-table-headers-th-active');
  3223. $(el_window).find('.explore-table-headers-th--type > .header-sort-icon').html(sort_icon);
  3224. }
  3225. }
  3226. // This is a hack to fix the issue where the window scrolls to the bottom when an app scrolls.
  3227. // this is due to an issue with iframes being able to hijack the scroll event for the parent object.
  3228. // w3c is working on a fix for this, but it's not ready yet.
  3229. // more info here: https://github.com/w3c/webappsec-permissions-policy/issues/171
  3230. document.addEventListener('scroll', function (event) {
  3231. if($(event.target).hasClass('window-app') || $(event.target).hasClass('window-app-iframe') || $(event.target?.activeElement).hasClass('window-app-iframe')){
  3232. setTimeout(function(){
  3233. // scroll window back to top
  3234. $('.window-app').scrollTop(0);
  3235. // some times it's document that scrolls, so we need to check that too
  3236. $(document).scrollTop(0);
  3237. }, 1);
  3238. }
  3239. }, true);
  3240. export default UIWindow;