UNPKG

vue3-open-weather-widget

Version:

Weather Widget is a Vue 3.0 project that displays the current weather conditions providing coordinates.

2 lines (1 loc) 12.9 kB
(function(h,e){typeof exports=="object"&&typeof module<"u"?e(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],e):(h=typeof globalThis<"u"?globalThis:h||self,e(h.WeatherVueWidget={},h.Vue))})(this,function(h,e){"use strict";function S(a){return a.toString().normalize("NFKD").toLowerCase().trim().replace(/\s+/g,"-").replace(/[^\w\-]+/g,"").replace(/\-\-+/g,"-")}const C=[{id:[200,201,202,210,211,212,221,230,231,232],main:"thunderstorm",icon:"11d,11n",wwIcon:"thunderstorm"},{id:[300,301,302,310,311,312,313,314,321,500,501,502,503,504],main:"rain",icon:"10d",wwIcon:"rain-shower-day"},{id:[300,301,302,310,311,312,313,314,321,500,501,502,503,504],main:"rain",icon:"10n",wwIcon:"rain-shower-night"},{id:[511],main:"rain",icon:"10n,10d",wwIcon:"hail"},{id:[511,520,521,522,531],main:"rain",icon:"10n,10d",wwIcon:"rain"},{id:[600,601,602,611,612,613,620,621,622],main:"snow",icon:"13d,13n",wwIcon:"snow"},{id:[615,616],main:"snow",icon:"13d,13n",wwIcon:"hail"},{id:[701,711,721,731,741,751,761,762,771,781],main:"mist,smoke,haze,dust,fog,sand,dust,ash,squall,tornado",icon:"50d,50n",wwIcon:"cloud-fog"},{id:[800],main:"clear",icon:"01d",wwIcon:"clear-sky-day"},{id:[800],main:"clear",icon:"01n",wwIcon:"clear-sky-night"},{id:[801],main:"clouds",icon:"02d",wwIcon:"few-clouds-day"},{id:[801],main:"clouds",icon:"02n",wwIcon:"few-clouds-night"},{id:[802,803,804],main:"clouds",icon:"03d,03n,04d,04n",wwIcon:"scattered-clouds"}];function y(a,n,i){let r="";return C.forEach(s=>{s.id.includes(a)&&s.main.includes(n.toLowerCase())&&s.icon.includes(i)&&(r=s.wwIcon)}),r}function I(a,n,i){let r="";try{r=`https://res.cloudinary.com/arslanportal/image/upload/v1695575351/weather-widget/ww-icon-${S(y(a,n,i))}.svg`}catch{console.error(`Image '@/assets/weather-widget-icons/ww-icon-${S(y(a,n,i))}.svg' not found!`)}return r}const B=e.defineComponent({props:{weatherForecast:{type:Object,required:!0}},computed:{getImage(){return I(this.weatherForecast.weatherId,this.weatherForecast.weatherMain,this.weatherForecast.weatherIcon)},getDay(){const a=new Date().toLocaleDateString("en",{weekday:"long"}),n=new Date(this.weatherForecast.date*1e3).toLocaleDateString("en",{weekday:"long"});return a===n?"Today":n}}}),ee="",f=(a,n)=>{const i=a.__vccOpts||a;for(const[r,s]of n)i[r]=s;return i},D=["title"],E={class:"day-header"},T={class:"weather-icon"},G=["src","alt"],A={class:"max-temp"},F={class:"min-temp"};function V(a,n,i,r,s,m){return e.openBlock(),e.createElementBlock("div",{class:"mini-widget",title:a.weatherForecast.weatherDescription},[e.createElementVNode("h6",E,e.toDisplayString(a.getDay),1),e.createElementVNode("div",T,[e.createElementVNode("img",{src:a.getImage,alt:a.weatherForecast.weatherMain},null,8,G)]),e.createElementVNode("p",A,e.toDisplayString(a.weatherForecast.maxTemperature)+"°C",1),e.createElementVNode("p",F,e.toDisplayString(a.weatherForecast.minTemperature)+"°C",1)],8,D)}const W=f(B,[["render",V],["__scopeId","data-v-a026b5c1"]]),b={AF:"Afghanistan",AL:"Albania",DZ:"Algeria",AS:"American Samoa",AD:"Andorra",AO:"Angola",AI:"Anguilla",AQ:"Antarctica",AG:"Antigua and Barbuda",AR:"Argentina",AM:"Armenia",AW:"Aruba",AU:"Australia",AT:"Austria",AZ:"Azerbaijan",BS:"Bahamas (the)",BH:"Bahrain",BD:"Bangladesh",BB:"Barbados",BY:"Belarus",BE:"Belgium",BZ:"Belize",BJ:"Benin",BM:"Bermuda",BT:"Bhutan",BO:"Bolivia (Plurinational State of)",BQ:"Bonaire, Sint Eustatius and Saba",BA:"Bosnia and Herzegovina",BW:"Botswana",BV:"Bouvet Island",BR:"Brazil",IO:"British Indian Ocean Territory (the)",BN:"Brunei Darussalam",BG:"Bulgaria",BF:"Burkina Faso",BI:"Burundi",CV:"Cabo Verde",KH:"Cambodia",CM:"Cameroon",CA:"Canada",KY:"Cayman Islands (the)",CF:"Central African Republic (the)",TD:"Chad",CL:"Chile",CN:"China",CX:"Christmas Island",CC:"Cocos (Keeling) Islands (the)",CO:"Colombia",KM:"Comoros (the)",CD:"Congo (the Democratic Republic of the)",CG:"Congo (the)",CK:"Cook Islands (the)",CR:"Costa Rica",HR:"Croatia",CU:"Cuba",CW:"Curaçao",CY:"Cyprus",CZ:"Czechia",CI:"Côte d'Ivoire",DK:"Denmark",DJ:"Djibouti",DM:"Dominica",DO:"Dominican Republic (the)",EC:"Ecuador",EG:"Egypt",SV:"El Salvador",GQ:"Equatorial Guinea",ER:"Eritrea",EE:"Estonia",SZ:"Eswatini",ET:"Ethiopia",FK:"Falkland Islands (the) [Malvinas]",FO:"Faroe Islands (the)",FJ:"Fiji",FI:"Finland",FR:"France",GF:"French Guiana",PF:"French Polynesia",TF:"French Southern Territories (the)",GA:"Gabon",GM:"Gambia (the)",GE:"Georgia",DE:"Germany",GH:"Ghana",GI:"Gibraltar",GR:"Greece",GL:"Greenland",GD:"Grenada",GP:"Guadeloupe",GU:"Guam",GT:"Guatemala",GG:"Guernsey",GN:"Guinea",GW:"Guinea-Bissau",GY:"Guyana",HT:"Haiti",HM:"Heard Island and McDonald Islands",VA:"Holy See (the)",HN:"Honduras",HK:"Hong Kong",HU:"Hungary",IS:"Iceland",IN:"India",ID:"Indonesia",IR:"Iran (Islamic Republic of)",IQ:"Iraq",IE:"Ireland",IM:"Isle of Man",IL:"Israel",IT:"Italy",JM:"Jamaica",JP:"Japan",JE:"Jersey",JO:"Jordan",KZ:"Kazakhstan",KE:"Kenya",KI:"Kiribati",KP:"Korea (the Democratic People's Republic of)",KR:"Korea (the Republic of)",KW:"Kuwait",KG:"Kyrgyzstan",LA:"Lao People's Democratic Republic (the)",LV:"Latvia",LB:"Lebanon",LS:"Lesotho",LR:"Liberia",LY:"Libya",LI:"Liechtenstein",LT:"Lithuania",LU:"Luxembourg",MO:"Macao",MG:"Madagascar",MW:"Malawi",MY:"Malaysia",MV:"Maldives",ML:"Mali",MT:"Malta",MH:"Marshall Islands (the)",MQ:"Martinique",MR:"Mauritania",MU:"Mauritius",YT:"Mayotte",MX:"Mexico",FM:"Micronesia (Federated States of)",MD:"Moldova (the Republic of)",MC:"Monaco",MN:"Mongolia",ME:"Montenegro",MS:"Montserrat",MA:"Morocco",MZ:"Mozambique",MM:"Myanmar",NA:"Namibia",NR:"Nauru",NP:"Nepal",NL:"Netherlands (the)",NC:"New Caledonia",NZ:"New Zealand",NI:"Nicaragua",NE:"Niger (the)",NG:"Nigeria",NU:"Niue",NF:"Norfolk Island",MP:"Northern Mariana Islands (the)",NO:"Norway",OM:"Oman",PK:"Pakistan",PW:"Palau",PS:"Palestine, State of",PA:"Panama",PG:"Papua New Guinea",PY:"Paraguay",PE:"Peru",PH:"Philippines (the)",PN:"Pitcairn",PL:"Poland",PT:"Portugal",PR:"Puerto Rico",QA:"Qatar",MK:"Republic of North Macedonia",RO:"Romania",RU:"Russian Federation (the)",RW:"Rwanda",RE:"Réunion",BL:"Saint Barthélemy",SH:"Saint Helena, Ascension and Tristan da Cunha",KN:"Saint Kitts and Nevis",LC:"Saint Lucia",MF:"Saint Martin (French part)",PM:"Saint Pierre and Miquelon",VC:"Saint Vincent and the Grenadines",WS:"Samoa",SM:"San Marino",ST:"Sao Tome and Principe",SA:"Saudi Arabia",SN:"Senegal",RS:"Serbia",SC:"Seychelles",SL:"Sierra Leone",SG:"Singapore",SX:"Sint Maarten (Dutch part)",SK:"Slovakia",SI:"Slovenia",SB:"Solomon Islands",SO:"Somalia",ZA:"South Africa",GS:"South Georgia and the South Sandwich Islands",SS:"South Sudan",ES:"Spain",LK:"Sri Lanka",SD:"Sudan (the)",SR:"Suriname",SJ:"Svalbard and Jan Mayen",SE:"Sweden",CH:"Switzerland",SY:"Syrian Arab Republic",TW:"Taiwan",TJ:"Tajikistan",TZ:"Tanzania, United Republic of",TH:"Thailand",TL:"Timor-Leste",TG:"Togo",TK:"Tokelau",TO:"Tonga",TT:"Trinidad and Tobago",TN:"Tunisia",TR:"Turkey",TM:"Turkmenistan",TC:"Turks and Caicos Islands (the)",TV:"Tuvalu",UG:"Uganda",UA:"Ukraine",AE:"United Arab Emirates (the)",GB:"United Kingdom of Great Britain and Northern Ireland (the)",UM:"United States Minor Outlying Islands (the)",US:"United States of America (the)",UY:"Uruguay",UZ:"Uzbekistan",VU:"Vanuatu",VE:"Venezuela (Bolivarian Republic of)",VN:"Viet Nam",VG:"Virgin Islands (British)",VI:"Virgin Islands (U.S.)",WF:"Wallis and Futuna",EH:"Western Sahara",YE:"Yemen",ZM:"Zambia",ZW:"Zimbabwe",AX:"Åland Islands"};function M(a){return a?(a=a==null?void 0:a.toUpperCase(),b[a]):""}function k(a){return a?["N","NE","E","SE","S","SW","W","NW"][Math.round(a/45)%8]:""}const L=e.defineComponent({setup(a){let n={city:"---",country:"---",weatherId:800,weatherMain:"Clear",weatherIcon:"01d",weatherDescription:"clear",temperature:0,date:0,humidity:0,uvi:0,windSpeed:0,windDeg:0};const i=e.ref(n),r=e.ref([]),s=e.ref({city:"",country:"-"}),m=e.ref(!1),u=e.ref(!0),o=e.ref({lat:0,lon:0}),p=async()=>new Promise((l,t)=>{"geolocation"in navigator||t(new Error("Geolocation is not available.")),navigator.geolocation.getCurrentPosition(c=>{l(c)},c=>{t(c)})}),N=async()=>{if(o.value.lat===0||o.value.lon===0)return;const l=`https://api.openweathermap.org/geo/1.0/reverse?lon=${o.value.lon}&lat=${o.value.lat}&limit=1&appid=${a.openWeatherApiKey}`;await fetch(l).then(t=>t.json()).then(t=>{var w,d;const c=M((w=t[0])==null?void 0:w.country);i.value.country=c,s.value={city:(d=t[0])==null?void 0:d.name,country:c}})},g=async()=>{if(o.value.lat===0||o.value.lon===0)return;u.value=!0;const l=`https://api.openweathermap.org/data/2.5/onecall?lon=${o.value.lon}&lat=${o.value.lat}&units=metric&exclude=minutely,hourly&appid=${a.openWeatherApiKey}`;await fetch(l).then(t=>t.json()).then(t=>{if(t.current){const c={weatherId:t.current.weather[0].id,weatherMain:t.current.weather[0].main,weatherIcon:t.current.weather[0].icon,weatherDescription:t.current.weather[0].description,temperature:t.current.temp,date:t.current.dt,humidity:t.current.humidity,uvi:t.current.uvi,windSpeed:t.current.wind_speed,windDeg:t.current.wind_deg};i.value=c}if(t.daily){const c=t.daily,w=[];c.map(d=>{const x={weatherMain:d.weather[0].main,weatherId:d.weather[0].id,weatherDescription:d.weather[0].description,weatherIcon:d.weather[0].icon,date:d.dt,maxTemperature:Math.round(d.temp.max),minTemperature:Math.round(d.temp.min)};w.push(x)}),r.value=w.slice(0,6),u.value=!1}}).catch(t=>{throw u.value=!1,t})},J=async()=>{await g()},Y=()=>{m.value=!m.value};e.onBeforeMount(()=>{a.lat&&a.lon?(console.log("Fetching weather data from lat and lon"),o.value={lat:a.lat,lon:a.lon},N(),g()):(console.log("Fetching weather data from location"),p().then(l=>{o.value={lat:l.coords.latitude,lon:l.coords.longitude},N(),g()}).catch(l=>{console.log(l)}))});const q=e.computed(()=>I(i.value.weatherId,i.value.weatherMain,i.value.weatherIcon)),Q=e.computed(()=>k(i.value.windDeg)),v=e.computed(()=>M(i.value.country)),X=e.computed(()=>Math.round(i.value.temperature)),j=e.computed(()=>Math.round(i.value.windSpeed));return{location:s,weatherData:r,windDir:Q,currentWeather:i,country:v,temperature:X,windSpeed:j,weatherIcon:q,updateWeather:J,makeItRain:Y,rain:m,isLoading:u}},components:{MiniForecastWidget:W},props:{openWeatherApiKey:{type:String,required:!0},lat:{type:Number,required:!1},lon:{type:Number,required:!1}}}),ae="",R=a=>(e.pushScopeId("data-v-7c64cd7a"),a=a(),e.popScopeId(),a),P={class:"current-weather"},_={class:"weather-icon"},K=["src"],U={class:"weather-detail"},H={class:"weather-description"},$={key:0,class:"mini-forecast-widget-wrapper"},O=R(()=>e.createElementVNode("div",{class:"loader"},null,-1));function Z(a,n,i,r,s,m){const u=e.resolveComponent("MiniForecastWidget");return e.openBlock(),e.createElementBlock(e.Fragment,null,[e.withDirectives(e.createVNode(e.Transition,{name:"fade"},{default:e.withCtx(()=>[a.location.city?(e.openBlock(),e.createElementBlock("div",{key:0,class:e.normalizeClass(["widget-wrap weather",{rain:a.currentWeather.weatherMain==="Rain"||a.rain,snow:a.currentWeather.weatherMain==="Snow",overlay:a.isLoading}])},[e.createElementVNode("span",{title:"Toggle Rain Effect",onClick:n[0]||(n[0]=(...o)=>a.makeItRain&&a.makeItRain(...o)),class:"icon-rain-drop"}),e.createElementVNode("span",{title:"Refresh Weather",onClick:n[1]||(n[1]=(...o)=>a.updateWeather&&a.updateWeather(...o)),class:"icon-reload"}),e.createElementVNode("span",{onClick:n[2]||(n[2]=(...o)=>a.updateWeather&&a.updateWeather(...o)),class:"icon-reload"}),e.createElementVNode("div",P,[e.createElementVNode("div",_,[e.createElementVNode("img",{src:a.weatherIcon,alt:""},null,8,K)]),e.createElementVNode("div",U,[e.createElementVNode("h2",null,e.toDisplayString(a.location.city)+", "+e.toDisplayString(a.location.country),1),e.createElementVNode("h3",null,e.toDisplayString(a.temperature)+"°C",1),e.createElementVNode("div",H,[e.createElementVNode("p",null,"Humidity: "+e.toDisplayString(a.currentWeather.humidity)+"%",1),e.createElementVNode("p",null,"UVI: "+e.toDisplayString(a.currentWeather.uvi),1),e.createElementVNode("p",null,"Wind: "+e.toDisplayString(a.windDir)+" "+e.toDisplayString(a.windSpeed)+"kmh",1)])])]),e.createVNode(e.Transition,{name:"slide-fade"},{default:e.withCtx(()=>[a.weatherData.length&&a.weatherData.length>0?(e.openBlock(),e.createElementBlock("div",$,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(a.weatherData,(o,p)=>(e.openBlock(),e.createBlock(u,{weatherForecast:o,key:p},null,8,["weatherForecast"]))),128))])):e.createCommentVNode("",!0)]),_:1})],2)):e.createCommentVNode("",!0)]),_:1},512),[[e.vShow,!a.isLoading]]),e.withDirectives(e.createVNode(e.Transition,{appear:"",name:"fade"},{default:e.withCtx(()=>[O]),_:1},512),[[e.vShow,a.isLoading]])],64)}const z=f(L,[["render",Z],["__scopeId","data-v-7c64cd7a"]]);h.WeatherWidget=z,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})});