article

Thursday, January 13, 2022

SwiftUI Grocery App UI

SwiftUI Grocery App UI
ContentView.swift
//
//  ContentView.swift
//  swiftuidev15ios
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var selected = "Home"
    
    var body: some View {
        
        NavigationView{
            VStack{
                if self.selected == "Home"{
                    Home()
                }
                else if self.selected == "Wishlist"{
                    GeometryReader{_ in
                        Text("Wishlist")
                    }
                }
                else{
                    GeometryReader{_ in
                        Text("Cart")
                    }
                }
                CustomTabView(selected: $selected)
            }
            .navigationBarTitle("")
            .navigationBarHidden(true)
            .navigationBarBackButtonHidden(true)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct CustomTabView : View {
    
    @Binding var selected : String
    
    var body : some View{
        HStack{
            ForEach(tabs,id: \.self){i in
                VStack(spacing: 10){
                    
                    Capsule()
                        .fill(Color.clear)
                        .frame(height: 5)
                        .overlay(
                            Capsule().fill(self.selected == i ? Color("Color") : Color.clear).frame(width: 55, height: 5)
                         )
                    
                    Button(action: {
                        self.selected = i
                    }) {
                        VStack{
                            Image(i).renderingMode(.original)
                            Text(i).foregroundColor(.black)
                        }
                    }
                }
            }
        }.padding(.horizontal)
    }
}
Home.swift
//
//  Home.swift
//  swiftuidev15ios
//
//  Created by Cairocoders
//

import SwiftUI

struct Home : View {
    
    @State var txt = ""
    
    var body : some View{
        
        VStack(spacing: 15){
            HStack(spacing: 12){
                Image("photo1").renderingMode(.original).resizable().frame(width: 30, height: 30)
                Text("Cairocoders").font(.body)
                
                Spacer()
                
                Button(action: {
                }) {
                    Image(systemName: "cart").renderingMode(.original)
                }
            }

            ScrollView(.vertical, showsIndicators: false) {
                VStack(spacing: 15){
                    HStack(spacing: 15){
                        HStack{
                            Image(systemName: "magnifyingglass").font(.body)
                            TextField("Search Groceries", text: $txt)
                        }.padding(10)
                        .background(Color("Color1"))
                        .cornerRadius(20)
                        
                        Button(action: {
                        }) {
                            Image(systemName: "mic").renderingMode(.original)
                        }
                    }
                    
                    Image("banner")
                        .resizable()
                        .frame(height: 170)
                        .cornerRadius(10)
                        .overlay(
                            VStack{
                                Spacer()
                                HStack{
                                    Text("GET 30% OFF").font(.title).foregroundColor(.white)
                                    Spacer()
                                }.padding()
                            }
                        )
                    
                    HStack{
                        Text("Categories").font(.title)
                        
                        Spacer()
                        
                        Button(action: {
                        }) {
                            Text("More")
                        }.foregroundColor(Color("Color"))
                        
                    }.padding(.vertical, 15)
                    
                    ScrollView(.horizontal, showsIndicators: false) {
                        HStack(spacing: 15){
                            ForEach(categories,id: \.self){i in
                                VStack{
                                    Image(i).renderingMode(.original)
                                    Text(i)
                                }
                            }
                        }
                    }

                    HomeBottomView()
                }
            }
        }//end VStack
        .padding(.horizontal)
        .background(Color.white)
    }
}

struct Home_Previews: PreviewProvider {
    static var previews: some View {
        Home()
    }
}


struct HomeBottomView : View {
    
    var body : some View{
        
        VStack(spacing: 15){
            HStack{
                Text("Deal of the Day").font(.title)
                
                Spacer()
                
                Button(action: {
                }) {
                    Text("More")
                }.foregroundColor(Color("Color"))
                
            }.padding(.vertical, 15)
            
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 15){
                    ForEach(dealoftheday){i in
                        DealCellView(data: i)
                    }
                }
            }
            
            HStack{
                Text("Popular").font(.title)
                Spacer()
            }.padding(.vertical, 15)
            
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 15){
                    ForEach(recipeitems){i in
                        PopularCellView(data: i)
                    }
                }
            }
        } //End VStack
    }
}

struct DealCellView : View {
    
    var data : deal
    @State var show = false
    
    var body : some View{
        ZStack{
            NavigationLink(destination: Detail(show: self.$show, viewdata: data), isActive: self.$show) {
                Text("")
            }
            VStack(spacing: 10){
                Image(data.image).resizable().scaledToFill().frame(width: 150, height: 150).cornerRadius(10)
                    
                Text(data.name).fontWeight(.semibold)
                Text(data.price).foregroundColor(.green).fontWeight(.semibold)
            }.onTapGesture {
                self.show.toggle()
            }
        }
    }
}

struct PopularCellView : View {
    
    var data : popular

    var body : some View{
        ZStack{
            VStack(spacing: 10){
                Image(data.image).resizable().scaledToFill().frame(width: 150, height: 150).cornerRadius(10)
                
                Text(data.name).fontWeight(.semibold)
                Text(data.price).foregroundColor(.green).fontWeight(.semibold)
            }
        }
    }
}
Detail.swift
//
//  Detail.swift
//  swiftuidev15ios
//
//  Created by Cairocoders
//

import SwiftUI

struct Detail : View {
    
    @Binding var show : Bool
    @State var count = 0
    let viewdata : deal
    
    var body : some View{
        
        VStack(spacing: 0){
            Image(viewdata.image)
                .resizable()
                .frame(height: UIScreen.main.bounds.height / 2.5)
                .edgesIgnoringSafeArea(.top)
                .overlay(
                    VStack{
                        HStack(spacing: 12){
                            Button(action: {
                                self.show.toggle()
                            }) {
                                Image(systemName: "arrow.left").renderingMode(.original)
                            }
                            
                            Spacer()
                            
                            Button(action: {
                            }) {
                                Image(systemName: "tray.and.arrow.down.fill").renderingMode(.original)
                            }
                            
                            Button(action: {
                            }) {
                                Image(systemName: "heart").renderingMode(.original)
                            }
                        }.padding()
                        
                        Spacer()
                    }
                )// End Overlay
            
            ScrollView(.vertical, showsIndicators: false) {
                VStack(alignment: .leading,spacing: 15){
                    Text(viewdata.name).font(.title)
                    
                    Text(viewdata.price).foregroundColor(.green)
                    
                    Divider().padding(.vertical, 15)
                    
                    HStack{
                        Text(viewdata.name)
                        
                        Spacer()
                        
                        Button(action: {
                        }) {
                            Image(systemName: "message.and.waveform").renderingMode(.original)
                        }
                    }
                    
                    Text("Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.").foregroundColor(.gray)
                    
                    HStack(spacing: 20){
                        Spacer(minLength: 12)
                        Button(action: {
                            self.count += 1
                        }) {
                            Image(systemName: "plus.circle").font(.largeTitle)
                        }.foregroundColor(.green)
                        
                        Text("\(self.count)")
                        
                        Button(action: {
                            if self.count != 0{
                                self.count -= 1
                            }
                        }) {
                            Image(systemName: "minus.circle").font(.largeTitle)
                        }.foregroundColor(.green)
                        
                        Button(action: {
                        }) {
                            Text("Add to Cart").padding()
                        }.foregroundColor(.white)
                        .background(Color("Color"))
                        .cornerRadius(12)
                        
                        Spacer(minLength: 12)
                    }
                }
                
            }.padding()
            .background(RoundedCorner().fill(Color.white))
            .padding(.top, -80)
            
            .navigationBarTitle("")
            .navigationBarHidden(true)
            .navigationBarBackButtonHidden(true)
            
        }
    }
}

struct Detail_Previews: PreviewProvider {
    @State static var show = false
    static var previews: some View {
        Detail(show: $show, viewdata: deal(id: 1, name: "Banana", price: "5 / kg", image: "1"))
    }
}

struct RoundedCorner : Shape {
    
    func path(in rect: CGRect) -> Path {
        
        let path = UIBezierPath(roundedRect: rect, byRoundingCorners: [.topLeft,.topRight], cornerRadii: CGSize(width: 35, height: 35))
        
        return Path(path.cgPath)
    }
}
Model.swift
//
//  Model.swift
//  swiftuidev15ios
//
//  Created by Cairocoders
//

import SwiftUI

var tabs = ["Home","Wishlist","Cart"]

var categories = ["Fruits","Vegetables","Beverages","Meat","Breads"]

struct deal : Identifiable {
    
    var id : Int
    var name : String
    var price : String
    var image : String
}

struct popular : Identifiable {
    
    var id : Int
    var name : String
    var price : String
    var image : String
}

var dealoftheday = [
    deal(id: 0, name: "Strawberry", price: "5.00 / kg",image: "1"),
    deal(id: 1, name: "Pineapples", price: "3.00 / kg",image: "2"),
    deal(id: 2, name: "Banana", price: "3.00 / pack",image: "4")
]

var recipeitems = [
    popular(id: 0, name: "Apple", price: "2.99 / kg",image: "3"),
    popular(id: 1, name: "Salad", price: "4.99 / pack",image: "5"),
    popular(id: 2, name: "Broccoli", price: "5.69",image: "6")
]

AngularJs Simple Shopping Cart

AngularJs Simple Shopping Cart

Bootstrap 5.1 Version
https://getbootstrap.com/docs/5.1/getting-started/introduction/

angularjs CDN
https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js
index.html
//index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8" name = "viewport" content = "width=device-width, initial-scale=1" />
<title>AngularJs Shopping Cart</title>
<link rel = "stylesheet" type = "text/css" href = "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"/>
</head>
<body ng-app="shoppingcart" ng-controller="shoppingCTR">
	<nav class="navbar navbar-expand-lg navbar-light bg-light">
	  <div class="container-fluid">
		<a class="navbar-brand" href="#">Cairocoders</a>
		<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
		  <span class="navbar-toggler-icon"></span>
		</button>
		<div class="collapse navbar-collapse" id="navbarNav">
		  <ul class="navbar-nav">
			<li class="nav-item">
			  <a class="nav-link active" aria-current="page" href="#">Home</a>
			</li>
		  </ul>
		</div>
	  </div>
	</nav>
	
	<div class="container">
	<div class="row">
		<h3 class = "text-primary">AngularJs Shopping Cart</h3>
		<hr style = "border-top:1px dotted #ccc;"/>
		<div id = "bg-background" class="col-8">
			<h4>PRODUCTS<h4>
			<hr style = "border-top:1px groovy #ccc;">
			<div id = "product">
				<div id = "p_list" ng-repeat = "product in products ">
					<span style="font-size:16px;">{{product.p_name}}</span>
					<center><img ng-src = "{{product.p_image}}"/></center>
					<div><label style="font-size:14px;">Price: ₱{{product.p_price}}</label></div>
					<center><button type = "button" class="btn btn-primary" ng-click = "add_cart(product)"> Add to cart</button></center>
				</div>
			</div>
		</div>
		<div class="col-4">
			<div class = "panel panel-primary">
				<div class = "panel-heading">
					<h5>MY CART</h5>
				</div>
				<div class = "panel-body table-responsive">
					<table class = "table">
						<thead>
							<tr>
								<th>Product</th>
								<th>Price</th>
								<th></th>
							</tr>
						</thead>
						<tbody>
							<tr ng-repeat = "cart in carts" ng-init = "setTotals(cart)">
								<td>{{cart.p_name}}</td>
								<td>₱{{cart.p_price}}</td>
								<td><button type = "button" ng-click = "remove_cart(cart)" class = "btn btn-danger"> X</button></td>
							</tr>
							<tr>
								<td align = "right">Total</td>
								<td>₱{{total}}</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>
		</div>
		</div>
	</div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script>
var app = angular.module("shoppingcart", [])
.controller("shoppingCTR", function($scope){
	$scope.carts=[];
	$scope.products = [
		{p_id: "1", p_name: "Dell Inspiron 15 3501", p_image: "images/1.jpg", p_price: 5900},
		{p_id: "2", p_name: "Asus X515 11th Gen intel", p_image: "images/2.jpg", p_price: 6800},
		{p_id: "3", p_name: "Lenovo IdealPad 3", p_image: "images/3.jpg", p_price: 4800},
	];
				
	$scope.add_cart = function(product){
		if(product){
			$scope.carts.push({p_id: product.p_id, p_name: product.p_name, p_price: product.p_price});
		}	
	}
						
	$scope.total = 0;
				
	$scope.setTotals = function(cart){
		if(cart){
			$scope.total += cart.p_price;
		}
	}
				
	$scope.remove_cart = function(cart){
		if(cart){
			$scope.carts.splice($scope.carts.indexOf(cart), 1);
			$scope.total -= cart.p_price;
		}
	}
});
</script>
<style>
#bg-background{
	background-color:#fff;
	padding:10px;
	border-radius:5px;
}
#product{
	padding:5px;
	clear:both;
}
#p_list{
	width:200px;
	max-width:200px;
	height:260px;
	padding:5px;
	border:1px solid #000;
	float:left;
	margin:15px;
}
#p_list img{
	height:150px; 
	width:150px;
}
</style>
</body>	
</html>

Wednesday, January 12, 2022

AngularJS Keypress Event Enter

AngularJS Keypress Event Enter

angularjs CDN
https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

index.html
//index.html
<!DOCTYPE html>
<html ng-app="appkeypress">
<head>
	<meta charset="utf-8">
	<title>AngularJS Keypress Event Enter </title>
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
	<div class="container">
		<h1 class="page-header text-center">AngularJS Keypress Event Enter</h1>
		<div class="col-sm-4 col-sm-offset-4">
			<input type="text" class="form-control" ng-model="myinput" my-enter="alertInput()">
		</div>
	</div>
<script>
	var app = angular.module('appkeypress', []);

	app.directive('myEnter', function () {
	    return function ($scope, element, attrs) {
	        element.bind("keydown keypress", function (event) {
	            if(event.which === 13) {
	                $scope.$apply(function (){
	                    $scope.$eval(attrs.myEnter);
	                });

	                event.preventDefault();
	            }
	        });
	    };
	});

	app.controller('myCtrl', function($scope){
		$scope.alertInput = function(){
			alert($scope.myinput);
		}
	});
</script>
</body>
</html>

Angular JS Ui-Router Toggle Active page

Angular JS Ui-Router Toggle Active page

index.html
//index.html
<!DOCTYPE html>
<html ng-app="activemenu">
<head>
	<title>Angular JS Ui-Router Toggle Active page</title>
	<meta charset="utf-8">
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
</head>
<body>
<nav ng-controller="mainCtrl" class="navbar navbar-default">
	<div class="container">
	    <div class="navbar-header">
		    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
		        <span class="sr-only">Toggle navigation</span>
		        <span class="icon-bar"></span>
		        <span class="icon-bar"></span>
		        <span class="icon-bar"></span>
		    </button>
	     	<a class="navbar-brand" href="#">Cairocoders</a>
	    </div>
	    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
	      	<ul class="nav navbar-nav">
	        	<li ng-class="active('/home')"><a ui-sref="home">Home</a></li>
	        	<li ng-class="active('/about')"><a ui-sref="about">About</a></li>
	        	<li ng-class="active('/blog')"><a ui-sref="blog">Blog</a></li>
	      	</ul>
	    </div>
	</div>
</nav>
<div class="container">
	<div ui-view></div>
</div>
<script>
var app = angular.module('activemenu', ['ui.router']);

app.config(function($stateProvider, $urlRouterProvider) {
    
    $urlRouterProvider.otherwise('/home');
    
    $stateProvider

        .state('home', {
            url: '/home',
            templateUrl: 'home.html'
        })
              
        .state('about', {
            url: '/about',
           	templateUrl: 'about.html', 
            
        })

        .state('blog', {
            url: '/blog',
            templateUrl: 'blog.html', 
        });
        
});

app.controller('mainCtrl', function($scope, $location){
	$scope.active = function(path){
		 return ($location.path() === path) ? 'active' : '';
	}
});
</script>
</body>
</html>
home.html
//home.html
<h4>This is the Home Page</h4>
<p><b>Home Tab</b> is active</p>
about.html
//about.html
<h4>This is the About Page</h4>
<p><b>About Tab</b> is active</p>
blog.html
//blog.html
<h4>This is the Blog Page</h4>
<p><b>Blog Tab</b> is active</p>

Tuesday, January 11, 2022

Python Flask Vue.js Axios - List All Data

Python Flask Vue.js Axios - List All Data

Install Flask-CORS extension https://flask-cors.readthedocs.io/

$ pip install -U flask-cors
from flask_cors import CORS

We'll be using the Vue CLI  https://cli.vuejs.org/

$ vue create client
This will require you to answer a few questions about the project.

Vue CLI v4.5.11
? Please pick a preset: (Use arrow keys)
❯ Default ([Vue 2] babel, eslint)
  Default (Vue 3 Preview) ([Vue 3] babel, eslint)
  Manually select features

Use the down arrow key to highlight

Run development server:
$ cd client
$ npm run serve

Install Bootstrap https://getbootstrap.com/docs/5.0/getting-started/download/
$ npm install bootstrap

Install Axios
https://github.com/axios/axios
$ npm install axios
app.py
 
from flask import Flask, jsonify
from flask_cors import CORS

MEMBERS = [
    {
        'id': '1',
        'name': 'cairocoders Ednalan',
        'email': 'cairocoders@gmail.com',
        'address': 'Olongapo city'
    },
    {
        'id': '2',
        'name': 'clydey Ednalan',
        'email': 'clydey@gmail.com',
        'address': 'Angles city'
    },
    {
        'id': '3',
        'name': 'claydren Ednalan',
        'email': 'clyderen@gmail.com',
        'address': 'San Fernando city'
    }
]

# configuration
DEBUG = True

# instantiate the app
app = Flask(__name__)
app.config.from_object(__name__)

# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})


# sanity check route
@app.route('/ping', methods=['GET'])
def ping_pong():
    return jsonify('pong!')

@app.route('/members', methods=['GET'])
def all_members():
    return jsonify({
        'status': 'success',
        'members': MEMBERS
    })

if __name__ == '__main__':
    app.run()
client/scr/main.js
//client/scr/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router';
import 'bootstrap/dist/css/bootstrap.css';

Vue.config.productionTip = false

new Vue({
  router,
  render: (h) => h(App),
}).$mount('#app');
client/src/App.vue
//client/src/App.vue
<template>
  <div id="app">
    <router-view/>
  </div>
</template>
client/src/Ping.vue
//client/src/Ping.vue
<template>
  <div>
    <p>{{ msg }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Ping',
  data() {
    return {
      msg: '',
    };
  },
  methods: {
    getMessage() {
      const path = 'http://localhost:5000/ping';
      axios.get(path)
        .then((res) => {
          console.log(res)
          this.msg = res.data;
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
  created() {
    this.getMessage();
  },
};
</script>
client/src/components/Home.vue
//client/src/components/Home.vue
<template>
  <div class="container">
    <div class="row">
      <div class="col-sm-10">
        <h1>Member</h1>
        <hr><br><br>
        <button type="button" class="btn btn-success btn-sm">Add Member</button>
        <br><br>
        <table class="table table-hover">
          <thead>
            <tr>
              <th scope="col">Name</th>
              <th scope="col">Email</th>
              <th scope="col">Address</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(rs, index) in members" :key="index">
              <td>{{ rs.name }}</td>
              <td>{{ rs.email }}</td>
              <td>{{ rs.address }}</td>
              <td>
                <div class="btn-group" role="group">
                  <button type="button" class="btn btn-warning btn-sm">Update</button>
                  <button type="button" class="btn btn-danger btn-sm">Delete</button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      members: [],
    };
  },
  methods: {
    getMembers() {
      const path = 'http://localhost:5000/members';
      axios.get(path)
        .then((res) => {
          console.log(res);
          this.members = res.data.members;
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
  created() {
    this.getMembers();
  },
};
</script>
client/src/router/index.js
//client/src/router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import Ping from '../components/Ping.vue';
import Home from '../components/Home.vue';

Vue.use(Router);

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
    },
    {
      path: '/ping',
      name: 'Ping',
      component: Ping,
    },
  ],
});

Sunday, January 9, 2022

SwiftUI Login Register - Firebase Auth and Firestore Database

SwiftUI Login Register - Firebase Auth and Firestore Database

ContentView.swift
//
//  ContentView.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//

import SwiftUI
import Firebase
import FirebaseStorage

struct ContentView: View {
    
    @State var isLoginMode = false
    @State var email = ""
    @State var password = ""
    @State var fname = ""
    @State var lname = ""
    @State var StatusMessage = ""
    
    @State var shouldShowImagePicker = false
    @State var image: UIImage?
    
    var body: some View {
        NavigationView {
            ScrollView {
 
                VStack(spacing: 16) {
                    Picker(selection: $isLoginMode, label: Text("Picker here")) {
                        Text("Login")
                            .tag(true)
                        Text("Create Account")
                            .tag(false)
                    }.pickerStyle(SegmentedPickerStyle())
                    
                    if !isLoginMode {
                        Button {
                            shouldShowImagePicker.toggle()
                        } label: {
                            VStack {
                                Image(systemName: "person.fill")
                                    .font(.system(size: 64))
                                    .padding()
                                    .foregroundColor(Color(.label))
                            }
                            .overlay(RoundedRectangle(cornerRadius: 64)
                                        .stroke(Color.black, lineWidth: 3)
                            )
                        }
                    }
                    if !isLoginMode {
                        Group {
                            TextField("First Name", text: $fname)
                            TextField("Last Name", text: $lname)
                            TextField("Email", text: $email)
                                .keyboardType(.emailAddress)
                                .autocapitalization(.none)
                            SecureField("Password", text: $password)
                        }
                        .padding()
                        .background(Color.white)
                        .cornerRadius(10)
                        
                        Button {
                            handleAction()
                        } label: {
                            HStack {
                                Spacer()
                                Text("Create Account")
                                    .foregroundColor(.white)
                                    .padding(.vertical, 10)
                                    .font(.system(size: 18, weight: .semibold))
                                Spacer()
                            }.background(Color.green)
     
                        }.cornerRadius(10)
                    }else {
                        Image("Login")
                            .resizable()
                            .scaledToFill()
                            .frame(width: 128, height: 128)
                            .cornerRadius(64)
                        
                        Group {
                            TextField("Email", text: $email)
                                .keyboardType(.emailAddress)
                                .autocapitalization(.none)
                            SecureField("Password", text: $password)
                        }
                        .padding()
                        .background(Color.white)
                        .cornerRadius(10)
                        
                        Button {
                            loginUser()
                        } label: {
                            HStack {
                                Spacer()
                                Text("Login")
                                    .foregroundColor(.white)
                                    .padding(.vertical, 10)
                                    .font(.system(size: 18, weight: .semibold))
                                Spacer()
                            }.background(Color.green)
     
                        }.cornerRadius(10)
                    }
                    
                    Text(self.StatusMessage)
                        .foregroundColor(Color.white)
                }
                .padding()
                
            } //End ScrollView
            .navigationViewStyle(StackNavigationViewStyle())
            .background(
                        LinearGradient(gradient: Gradient(colors: [.blue, .gray]), startPoint: .top, endPoint: .bottom)
                            .edgesIgnoringSafeArea(.all))
            
        }// End Navigation
    }
    
    private func loginUser() {
        Auth.auth().signIn(withEmail: email, password: password) { result, err in
            if let err = err {
                print("Failed to login user:", err)
                self.StatusMessage = "Failed to login user: \(err)"
                return
            }
 
            print("Successfully logged in as user: \(result?.user.uid ?? "")")
 
            self.StatusMessage = "Successfully logged in as user: \(result?.user.uid ?? "")"
        }
    }
    
    private func handleAction() {
        createNewAccount()
    }
    
    private func createNewAccount() {
        Auth.auth().createUser(withEmail: email, password: password) { result, err in
            if let err = err {
                print("Failed to create user:", err)
                self.StatusMessage = "Failed to create user: \(err)"
                return
            }
 
            print("Successfully created user: \(result?.user.uid ?? "")")
 
            self.StatusMessage = "Successfully created user: \(result?.user.uid ?? "")"
 
            self.storeUserInformation()
        }
    }
    
    private func storeUserInformation() {
        guard let uid = Auth.auth().currentUser?.uid else { return }
        let userData = ["fname": self.fname, "lname": self.lname, "email": self.email, "uid": uid]
        Firestore.firestore().collection("users")
            .document(uid).setData(userData) { err in
                if let err = err {
                    print(err)
                    self.StatusMessage = "\(err)"
                    return
                }

                print("Success")
            }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
DevSwiftUIApp.swift
//
//  DevSwiftUIApp.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//

import SwiftUI
import Firebase

@main
struct DevSwiftUIApp: App {
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
     
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
 
class AppDelegate: NSObject,UIApplicationDelegate{
     
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
         
        FirebaseApp.configure()
        return true
    }
}

Saturday, January 8, 2022

Django Custom Admin

Django Custom Admin

Jazzmin https://django-jazzmin.readthedocs.io/

AngularJS PHP Mysqli CRUD (Create, Read, Update and Delete) with Pagination, Search and Sort

AngularJS PHP Mysqli CRUD (Create, Read, Update and Delete) with Pagination, Search and Sort

Bootstrap 5.1 Version
https://getbootstrap.com/docs/5.1/getting-started/introduction/

https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css

angularjs CDN 
https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

dirPagination - AngularJS module for paginating

https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination

https://github.com/michaelbromley/angularUtils/blob/master/src/directives/pagination/dirPagination.js

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL,
  `created_at` date NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`, `created_at`) VALUES
(1, 'Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '2020-01-09'),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '2020-02-15'),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '2020-03-01'),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '2020-01-24'),
(5, 'Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '2020-01-11'),
(6, 'Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '2020-02-23'),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456, '2020-03-04'),
(9, 'Airi Satou updated', 'Pre-Sales Support updated', 'New York', 25, 4568, '2020-04-28'),
(10, 'Angelica Ramos updated', 'Sales Assistant updated', 'New York', 45, 456, '2020-01-12'),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '2020-02-06'),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '2020-03-21'),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '2020-04-14'),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '2020-01-29'),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465, '2020-02-22'),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '2020-03-10'),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '2020-04-26'),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '2020-01-17'),
(19, 'Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '2020-02-01'),
(20, 'Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '2020-03-19'),
(21, 'Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '2020-04-21');

ALTER TABLE `employee`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;

index.php
//index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularJS PHP Mysqli CRUD with Pagination Search and Sort </title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body ng-app="employeeapp" ng-controller="employeeCTR" ng-init="fetch()">
<div class="container">
    <h1 class="page-header text-center">AngularJS PHP Mysqli CRUD (Create, Read, Update and Delete) with Pagination, Search and Sort</h1>
    <div class="row">
		<div class="col-md-12">
			<div class="alert alert-success text-center" ng-show="success">
				<button type="button" class="close" ng-click="clearMessage()"><span aria-hidden="true">×</span></button>
				<i class="fa fa-check"></i> {{ successMessage }}
			</div>
			<div class="alert alert-danger text-center" ng-show="error">
				<button type="button" class="close" ng-lick="clearMessage()"><span aria-hidden="true">×</span></button>
				<i class="fa fa-warning"></i> {{ errorMessage }}
			</div>
			<div class="row">
				<div class="col-md-12">
					<button href="" class="btn btn-primary" ng-click="showAdd()"><i class="fa fa-plus"></i> Add New New Employee</button>
					<span class="pull-right">
						<input type="text" ng-model="search" class="form-control" placeholder="Search">
					</span>
				</div>
			</div>
			<table class="table table-bordered table-striped" style="margin-top:10px;">
				<thead>
                    <tr>
                        <th ng-click="sort('name')" class="text-center">Name
                        	<span class="pull-right">
                       			<i class="fa fa-sort gray" ng-show="sortKey!='name'"></i>
                       			<i class="fa fa-sort" ng-show="sortKey=='name'" ng-class="{'fa fa-sort-asc':reverse,'fa fa-sort-desc':!reverse}"></i>
                       		</span>
                        </th>
                        <th ng-click="sort('position')" class="text-center">Position
	                        <span class="pull-right">
	                       		<i class="fa fa-sort gray" ng-show="sortKey!='position'"></i>
	                       		<i class="fa fa-sort" ng-show="sortKey=='position'" ng-class="{'fa fa-sort-asc':reverse,'fa fa-sort-desc':!reverse}"></i>
	                       	</span>
                        </th>
                        <th ng-click="sort('office')" class="text-center">Office
                        	<span class="pull-right">
                       			<i class="fa fa-sort gray" ng-show="sortKey!='office'"></i>
                       			<i class="fa fa-sort" ng-show="sortKey=='office'" ng-class="{'fa fa-sort-asc':reverse,'fa fa-sort-desc':!reverse}"></i>
                       		</span>
                       	</th>                        
						<th class="text-center">Age</th>
                       	<th class="text-center">Salary</th>
                       	<th class="text-center">Action</th>
                    </tr>
                </thead>
				<tbody>
					<tr dir-paginate="rs in employee|orderBy:sortKey:reverse|filter:search|itemsPerPage:5">
						<td>{{ rs.name }}</td>
						<td>{{ rs.position }}</td>
						<td>{{ rs.office }}</td>
						<td>{{ rs.age }}</td>
						<td>$ {{ rs.salary }}</td>
						<td>
							<button type="button" class="btn btn-success" ng-click="showEdit(); selectEmployee(rs);"><i class="fa fa-edit"></i> Edit</button> 
							<button type="button" class="btn btn-danger" ng-click="showDelete(); selectEmployee(rs);"> <i class="fa fa-trash"></i> Delete</button>
						</td>

					</tr>
				</tbody>
			</table>
			<div class="pull-right" style="margin-top:-30px;">
				<dir-pagination-controls
				   max-size="5"
				   direction-links="true"
				   boundary-links="true" >
				</dir-pagination-controls>
				

			</div>
  
  
		</div>
	</div>
	<?php include('modal.php'); ?>
</div>
<script src="dirPaginate.js"></script>
<script src="angular.js"></script>
<style>
.pagination {
    display: inline-block;
    padding-left: 0;
    margin: 20px 0;
    border-radius: 4px;
}
.pagination>li {
    display: inline;
}
.pagination>li:first-child>a, .pagination>li:first-child>span {
    margin-left: 0;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
}
.pagination>.disabled>a, .pagination>.disabled>a:focus, .pagination>.disabled>a:hover, .pagination>.disabled>span, .pagination>.disabled>span:focus, .pagination>.disabled>span:hover {
    color: #777;
    cursor: not-allowed;
    background-color: #fff;
    border-color: #ddd;
}
.pagination>li>a, .pagination>li>span {
    position: relative;
    float: left;
    padding: 6px 12px;
    margin-left: -1px;
    line-height: 1.42857143;
    color: #337ab7;
    text-decoration: none;
    background-color: #fff;
    border: 1px solid #ddd;
}
.pagination>.active>a, .pagination>.active>a:focus, .pagination>.active>a:hover, .pagination>.active>span, .pagination>.active>span:focus, .pagination>.active>span:hover {
    z-index: 3;
    color: #fff;
    cursor: default;
    background-color: #337ab7;
    border-color: #337ab7;
}
</style>
</body>
</html>
angular.js
//angular.js
var app = angular.module('employeeapp', ['angularUtils.directives.dirPagination']);
app.controller('employeeCTR',function($scope, $http, $window){
	$scope.AddModal = false;
    $scope.EditModal = false;
    $scope.DeleteModal = false;

    $scope.errorname = false;

    $scope.showAdd = function(){
    	$scope.name = null;
    	$scope.position = null;
    	$scope.office = null;
    	$scope.errorname = false;
    	$scope.errorposition = false;
    	$scope.erroroffice = false;
    	$scope.AddModal = true;
    }
  
	$scope.fetch = function(){
        $http({
			method: 'GET',
            url: 'fetch.php',
        }).then(function (data){
            console.log(data)
            $scope.employee = data.data;      
        },function (error){
            console.log(error, 'can not get data.');
        });
    }

    $scope.sort = function(keyname){
        $scope.sortKey = keyname;   
        $scope.reverse = !$scope.reverse;
    }

    $scope.clearMessage = function(){
    	$scope.success = false;
    	$scope.error = false;
    }

    $scope.addnew = function(){
        $http({
			method: 'POST',
            url: 'add.php',
			data:{name:$scope.name, position:$scope.position, office:$scope.office}
        }).then(function (data){
            console.log(data)
        	if(data.data.name){
        		$scope.errorname = true;
        		$scope.errorposition = false;
        		$scope.erroroffice = false;
        		$scope.errorMessage = data.data.message;
        		$window.document.getElementById('name').focus();
        	}
        	else if(data.data.position){
        		$scope.errorname = false;
        		$scope.errorposition = true;
        		$scope.erroroffice = false;
        		$scope.errorMessage = data.data.message;
        		$window.document.getElementById('position').focus();
        	}
        	else if(data.data.office){
        		$scope.errorname = false;
        		$scope.errorposition = false;
        		$scope.erroroffice = true;
        		$scope.errorMessage = data.data.message;
        		$window.document.getElementById('office').focus();
        	}
        	else if(data.data.error){
        		$scope.errorname = false;
        		$scope.errorposition = false;
        		$scope.erroroffice = false;
        		$scope.error = true;
        		$scope.errorMessage = data.data.message;
        	}
        	else{
        		$scope.AddModal = false;
        		$scope.success = true;
        		$scope.successMessage = data.data.message;
        		$scope.fetch();
        	}     
        },function (error){
            console.log(error, 'can not get data.');
        });
    }

    $scope.selectEmployee = function(employee){
    	$scope.clickEmployee = employee;
    }

    $scope.showEdit = function(){
    	$scope.EditModal = true;
    }

    $scope.updateEmployee = function(){
        $http({
			method: 'POST',
            url: 'edit.php',
			data: $scope.clickEmployee
        }).then(function (data){
            console.log(data)
        	if(data.error){
        		$scope.error = true;
        		$scope.errorMessage = data.data.message;
        		$scope.fetch();
        	}
        	else{
        		$scope.success = true;
        		$scope.successMessage = data.data.message;
        	}     
        },function (error){
            console.log(error, 'can not get data.');
        });
    }

    $scope.showDelete = function(){
    	$scope.DeleteModal = true;
    }

    $scope.deleteEmployee = function(){
        $http({
			method: 'POST',
            url: 'delete.php',
			data: $scope.clickEmployee
        }).then(function (data){
            console.log(data)
        	if(data.data.error){
        		$scope.error = true;
        		$scope.errorMessage = data.data.message;
        	}
        	else{
        		$scope.success = true;
        		$scope.successMessage = data.data.message;
        		$scope.fetch();
        	}  
        },function (error){
            console.log(error, 'can not get data.');
        });
    }

});
conn.php
//conn.php
<?php
	$conn = new mysqli('localhost', 'root', '', 'testingdb');

	if ($conn->connect_error) {
	    die("Connection failed: " . $conn->connect_error);
	}
?>
fetch.php
//fetch.php
<?php
	include('conn.php');
	
	$output = array();
	$sql = "SELECT * FROM employee";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$output[] = $row;
	}

	echo json_encode($output);
?>
modal.php
//modal.php
<!-- Add Modal -->
<div class="myModal" ng-show="AddModal">
	<div class="modalContainer">
		<div class="modalHeader">
			<span class="headerTitle">Add New Employee</span>
			<button class="closeBtn pull-right" ng-click="AddModal = false">×</button>
		</div>
		<div class="modalBody">
			<div class="form-group">
				<label>Name:</label>
				<input type="text" class="form-control" ng-model="name" id="name">
				<span class="pull-right input-error" ng-show="errorFirstname">{{ errorMessage }}</span>
			</div>
			<div class="form-group">
				<label>Position:</label>
				<input type="text" class="form-control" ng-model="position" id="position">
				<span class="pull-right input-error" ng-show="errorposition">{{ errorMessage }}</span>
			</div>
			<div class="form-group">
				<label>Office:</label>
				<input type="text" class="form-control" ng-model="office" id="office">
				<span class="pull-right input-error" ng-show="erroroffice">{{ errorMessage }}</span>
			</div>
		</div>
		<hr>
		<div class="modalFooter">
			<div class="footerBtn pull-right">
				<button class="btn btn-default" ng-click="AddModal = false"><span class="glyphicon glyphicon-remove"></span> Cancel</button> <button class="btn btn-primary" ng-click="addnew()"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
			</div>
		</div>
	</div>
</div>

<!-- Edit Modal -->
<div class="myModal" ng-show="EditModal">
	<div class="modalContainer">
		<div class="editHeader">
			<span class="headerTitle">Edit Employee</span>
			<button class="closeEditBtn pull-right" ng-click="EditModal = false">×</button>
		</div>
		<div class="modalBody">
			<div class="form-group">
				<label>Name:</label>
				<input type="text" class="form-control" ng-model="clickEmployee.name">
			</div>
			<div class="form-group">
				<label>Position:</label>
				<input type="text" class="form-control" ng-model="clickEmployee.position">
			</div>
			<div class="form-group">
				<label>Office:</label>
				<input type="text" class="form-control" ng-model="clickEmployee.office">
			</div>
		</div>
		<hr>
		<div class="modalFooter">
			<div class="footerBtn pull-right">
				<button class="btn btn-default" ng-click="EditModal = false"><span class="glyphicon glyphicon-remove"></span> Cancel</button> <button class="btn btn-success" ng-click="EditModal = false; updateEmployee();"><span class="glyphicon glyphicon-check"></span> Save</button>
			</div>
		</div>
	</div>
</div>

<!-- Delete Modal -->
<div class="myModal" ng-show="DeleteModal">
	<div class="modalContainer">
		<div class="deleteHeader">
			<span class="headerTitle">Delete Employee</span>
			<button class="closeDelBtn pull-right" ng-click="DeleteModal = false">×</button>
		</div>
		<div class="modalBody">
			<h5 class="text-center">Are you sure you want to delete</h5>
			<h2 class="text-center">{{clickEmployee.name}}</h2>
		</div>
		<hr>
		<div class="modalFooter">
			<div class="footerBtn pull-right">
				<button class="btn btn-default" ng-click="DeleteModal = false"><span class="glyphicon glyphicon-remove"></span> Cancel</button> <button class="btn btn-danger" ng-click="DeleteModal = false; deleteEmployee(); "><span class="glyphicon glyphicon-trash"></span> Yes</button>
			</div>
		</div>
	</div>
</div>
edit.php
//edit.php
<?php
	include('conn.php');
    $data = json_decode(file_get_contents("php://input"));

    $out = array('error' => false);

    $name = $data->name;
    $position = $data->position;
    $office = $data->office;
    $id = $data->id;

   	$sql = "UPDATE employee SET name = '$name', position = '$position', office = '$office' WHERE id = '$id'";
   	$query = $conn->query($sql);

   	if($query){
   		$out['message'] = 'Employee updated Successfully';
   	}
   	else{
   		$out['error'] = true;
   		$out['message'] = 'Cannot update';
   	}

    echo json_encode($out);
?>
delete.php
//delete.php
<?php
	include('conn.php');
    $data = json_decode(file_get_contents("php://input"));

    $out = array('error' => false);

    $id = $data->id;

   	$sql = "DELETE FROM employee WHERE id = '$id'";
   	$query = $conn->query($sql);

   	if($query){
   		$out['message'] = 'Employee deleted Successfully';
   	}
   	else{
   		$out['error'] = true;
   		$out['message'] = 'Cannot delete';
   	}

    echo json_encode($out);
?>
add.php
//add.php
<?php
    include('conn.php');
    $data = json_decode(file_get_contents("php://input"));

    $out = array('error' => false, 'name' => false, 'position' => false, 'office' => false);

    $name = $data->name;
    $position = $data->position;
    $office = $data->office;

    if(empty($name)){
        $out['name'] = true;
        $out['message'] = 'name is required'; 
    } 
    elseif(empty($position)){
        $out['position'] = true;
        $out['message'] = 'position is required'; 
    }
    elseif(empty($office)){
        $out['office'] = true;
        $out['message'] = 'office is required'; 
    }
    else{
        $sql = "INSERT INTO employee (name, position, office, age, salary) VALUES ('$name', '$position', '$office', '25', '99')";
        $query = $conn->query($sql);

        if($query){
            $out['message'] = 'New Employee Added Successfully';
        }
        else{
            $out['error'] = true;
            $out['message'] = 'Cannot Add';
        }
    }
        
    echo json_encode($out);
?>
style.css
//style.css
.gray{
	color:gray;
}

.input-error{
	font-size:12px;
	color:#f44336;
}

.myModal{
	position:fixed;
	top:0;
	left:0;
	right:0;
	bottom:0;
	background: rgba(0, 0, 0, 0.4);
	z-index:100;
}

.modalContainer{
	width: 555px;
	background: #FFFFFF;
	margin:auto;
	margin-top:10px;
}

.modalHeader{
	padding:10px;
	background: #008CBA;
	color: #FFFFFF;
	height:50px;
	font-size:20px;
	padding-left:15px;
}

.editHeader{
	padding:10px;
	background: #4CAF50;
	color: #FFFFFF;
	height:50px;
	font-size:20px;
	padding-left:15px;
}

.deleteHeader{
	padding:10px;
	background: #f44336;
	color: #FFFFFF;
	height:50px;
	font-size:20px;
	padding-left:15px;
}

.modalBody{
	padding:30px;
}

.modalFooter{
	height:36px;
}

.footerBtn{
	margin-right:10px;
	margin-top:-9px;
}

.closeBtn{
	background: #008CBA;
	color: #FFFFFF;
	border:none;
}

.closeEditBtn{
	background: #4CAF50;
	color: #FFFFFF;
	border:none;
}

.closeDelBtn{
	background: #f44336;
	color: #FFFFFF;
	border:none;
}

Friday, January 7, 2022

AngularJS PHP Mysqli Sign Up with form validation and list records

AngularJS PHP Mysqli Sign Up with form validation and list records

Bootstrap CDN
https://getbootstrap.com/docs/4.3/getting-started/introduction/


angularjs CDN 
https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

CREATE TABLE `user` (
  `user_id` bigint(20) NOT NULL,
  `user_name` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `user_email` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `user_password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `user` (`user_id`, `user_name`, `user_email`, `user_password`) VALUES
(1, 'cairocoders', 'cairocoders@gmail.com', '86985e105f79b95d6bc918fb45ec7727'),
(2, 'tutorial101.blogspot.com', 'tutorial101@gmail.com', '86985e105f79b95d6bc918fb45ec7727');

ALTER TABLE `user`
  ADD PRIMARY KEY (`user_id`);

ALTER TABLE `user`
  MODIFY `user_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
index.php
//index.php
<!DOCTYPE html>
<html ng-app="angularsignup" ng-controller="signup_ctr" ng-init="showdata()">
<head>
<meta charset="UTF-8"> 
<title>AngularJS PHP Mysqli Sign Up with form validation and list records</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>  
</head>
<body>
<div class="container">
	<center><h1 class="page-header">AngularJS PHP Mysqli Sign Up with form validation and list records</h1></center>
	<div class="row">
		<div class="col-md-4">
			<form ng-submit="myFunc()">
				<h3>Signup Form</h3>
				<hr>
				<div class="form-group">
				    <label for="email">Email</label>
				    <input type="text" class="form-control" id="email" name="email" ng-model="email" placeholder="email@example.com">
				</div>
				<div class="form-group">
				    <label for="username">Username</label>
				    <input type="text" class="form-control" id="username" name="username" ng-model="username">
				</div>
				<div class="form-group">
				    <label for="password">Password</label>
				    <input type="password" class="form-control" id="password" name="password" ng-model="password">
				</div>
				<div class="form-group">
				    <label for="repassword">Re-type Password</label>
				    <input type="password" class="form-control" id="repassword" name="repassword" ng-model="repassword">
				</div>
				<div class="{{alert}}">
					<center>{{alerttext}}</center>
				</div>
				<hr>
				<button type="submit" class="btn btn-success" ng-click="register()"><span class="glyphicon glyphicon-pencil"></span> {{btnName}}</button>
			</form>
		</div>
		<div class="col-md-8">
			<h3>User List</h3>
			<table class="table table-hover table-bordered table-striped">
				<thead>
					<th>Email</th>
					<th>Username</th>
					<th>Password</th>
				</thead>
				<tbody>
					<tr ng-repeat="rs in user">
						<td>{{rs.user_email}}</td>
						<td>{{rs.user_name}}</td>
						<td>{{rs.user_password}}</td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</div>
<script src="app.js"></script>
</body>
</html>
app.js
//app.js
var app = angular.module("angularsignup", []);
app.controller("signup_ctr", function($scope, $http, $window) {
    $scope.alert = "alert alert-success";
    $scope.alerttext = "Fill up all the Fields";
    $scope.btnName = "Register";
    var email = $window.document.getElementById('email');
    var username = $window.document.getElementById('username');
    var password = $window.document.getElementById('password');
    var repassword = $window.document.getElementById('repassword');
    email.focus();
    $scope.register = function() {
        if ($scope.email == null){
            $scope.alerttext="Please input email";
            email.focus();
        }
        else if ($scope.username == null) {
            $scope.alerttext="Please input username";
            username.focus();
        } 
        else if ($scope.password == null) {
            $scope.alerttext="Please input password"; 
            password.focus();
        }
        else if($scope.password!=$scope.repassword){
            $scope.alerttext = "Password didn't match";
            repassword.focus();
        } 
        else {
            $scope.btnName = "Checking";
            setTimeout(function() {
				$http({
					method: 'POST',
					url: 'register.php',
					data:{email:$scope.email, username:$scope.username, password:$scope.password}
				}).then(function (data){
					console.log(data)
                    if(data.data==1){
                        $scope.alerttext="Invalid email format";
                        email.focus(); 
                    }
                    else if(data.data==2){
                        $scope.alerttext="Only letters, numbers and underscore allowed";
                        username.focus(); 
                    }
                    else if(data.data==3){
                        $scope.alerttext="Registration Successful";
                        $scope.showdata();
                        $scope.email="";
                        $scope.username="";
                        $scope.password="";
                        $scope.repassword="";
                        email.focus();
                        $scope.btnName = "Register";
                    }
                    else{
                        $scope.alerttext="Registration Failed";
                    }
				},function (error){
					console.log(error, 'can not get data.');
				});
            }, 3000);
        }
    }
    $scope.showdata = function() {
		$http({
            method: 'GET',
            url: 'fetch.php'
        }).then(function (data){
            console.log(data)
			$scope.user = data.data;
        },function (error){
            console.log(error, 'can not get data.');
        });
    }
    $scope.enter = function(keyEvent) {
        if (keyEvent.which === 13){
            register();
        }
    }
});
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
fetch.php
//fetch.php
<?php
	include('conn.php');
	$output = array();
	$query = $conn->query("select * from user"); 
	if ($query->num_rows > 0) {
	    while ($row = $query->fetch_array()) {
	        $output[] = $row;
	    }
	    echo json_encode($output);
	}
?>
register.php
//register.php
<?php
    include('conn.php');
    $data = json_decode(file_get_contents("php://input"));
    $email = mysqli_real_escape_string($conn, $data->email);
    $username = mysqli_real_escape_string($conn, $data->username);
    $password = mysqli_real_escape_string($conn, $data->password);
    $msg="";
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $msg=1; 
    }
    elseif (!preg_match("/^[a-zA-Z0-9_]*$/",$username)) {
        $msg=2; 
    }
    else{
        $password=md5($password);
        if ($conn->query("insert into user (user_email, user_name, user_password) values ('$email', '$username', '$password')")) {
            $msg=3;
        } else {
            $msg=4;
        }
    }
    echo json_encode($msg);    
?>

Thursday, January 6, 2022

AngularJS Preview before Upload

AngularJS Preview before Upload

angularjs CDN https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

//index.html
<!DOCTYPE html>
<html >
<head>
	<title>AngularJS Preview before Upload</title>
	<meta charset="utf-8">
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>  
</head>
<body ng-app="angularupload" ng-controller="uploader">
<div class="container">
	<h1 class="page-header text-center">AngularJS Preview before Upload</h1>
	<div class="row">
		<div class="col-md-3">
			<h3 class="text-center">Upload File</h3>
			<hr>
			<label>File:</label>
			<input type="file" file-input="files">
		</div>
		<div class="col-md-9">
			<div ng-show="filepreview">
			<img ng-src="{{filepreview}}" height="300px" width="300px">
			<h4>Filename: {{ name }}</h4>
			<h4>Size: {{ size }}</h4>
			</div>
		</div>
	</div>
</div>
<script>
var app = angular.module('angularupload', []);
app.directive('fileInput', ['$parse', function ($parse) {
	return {
      $scope: {
        fileinput: "=",
        filepreview: "="
      },
      link: function($scope, element, attributes) {
        element.bind("change", function(changeEvent) {
          	$scope.fileinput = changeEvent.target.files[0];
          	var reader = new FileReader();
          	reader.onload = function(loadEvent) {
            	$scope.$apply(function() {
            		$scope.filepreview = loadEvent.target.result;
            	});
          	}
          	reader.readAsDataURL($scope.fileinput);
          	$scope.name = $scope.fileinput.name;
          	$scope.size = $scope.fileinput.size;
        });
      }
    }
}]);
app.controller('uploader', function($scope, $http){

});
</script>
</body>
</html>

PHP Mysql OOP CRUD (Create, Read, Update and Delete)

PHP Mysql OOP CRUD (Create, Read, Update and Delete)


CREATE TABLE `user_tbl` (
  `id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `mobile` varchar(150) NOT NULL,
  `address` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user_tbl` (`id`, `name`, `email`, `mobile`, `address`) VALUES
(1, 'cairocoders Ednalan', 'cairocoders@gmail.com', '123456789', 'Olongapo City'),
(2, 'Airi Satou', 'AiriSatou@gmail.com', '123456789', 'Tokyo'),
(3, 'Ashton Cox', 'AshtonCox@gmail.com', '12345679', 'San Francisco');

ALTER TABLE `user_tbl`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `user_tbl`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
index.php
//index.php
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
	<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
	<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <title>PHP Mysql OOP CRUD (Create, Read, Update and Delete)</title>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-md-12 mt-5">
          <h1 class="text-center">PHP Mysql OOP CRUD (Create, Read, Update and Delete)</h1>
          <hr style="height: 1px;color: black;background-color: black;">
        </div>
      </div>
      <div class="row">
        <div class="col-md-12"><a href="add.php" class="btn btn-primary">Add New</a>
          <table class="table table-hover">
            <thead>
              <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Mobile No.</th>
                <th>Address</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <?php

                include 'model.php';
                $model = new Model();
                $rows = $model->fetch();
                $i = 1;
                if(!empty($rows)){
                  foreach($rows as $row){ 
              ?>
              <tr>
                <td><?php echo $i++; ?></td>
                <td><?php echo $row['name']; ?></td>
                <td><?php echo $row['email']; ?></td>
                <td><?php echo $row['mobile']; ?></td>
                <td><?php echo $row['address']; ?></td>
                <td>
                  <a href="read.php?id=<?php echo $row['id']; ?>" class="badge badge-info">Read</a>
                  <a href="delete.php?id=<?php echo $row['id']; ?>" class="badge badge-danger">Delete</a>
                  <a href="edit.php?id=<?php echo $row['id']; ?>" class="badge badge-success">Edit</a>
                </td>
              </tr>

              <?php
                }
              }else{
                echo "no data";
            }
              ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
</body>
</html>
model.php
//model.php
<?php 
	Class Model{

		private $server = "localhost";
		private $username = "root";
		private $password;
		private $db = "testingdb";
		private $conn;

		public function __construct(){
			try {
				
				$this->conn = new mysqli($this->server,$this->username,$this->password,$this->db);
			} catch (Exception $e) {
				echo "connection failed" . $e->getMessage();
			}
		}

		public function insert(){

			if (isset($_POST['submit'])) {
				if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['mobile']) && isset($_POST['address'])) {
					if (!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['mobile']) && !empty($_POST['address']) ) {
						
						$name = $_POST['name'];
						$mobile = $_POST['mobile'];
						$email = $_POST['email'];
						$address = $_POST['address'];

						$query = "INSERT INTO user_tbl (name,email,mobile,address) VALUES ('$name','$email','$mobile','$address')";
						if ($sql = $this->conn->query($query)) {
							echo "<script>alert('records added successfully');</script>";
							echo "<script>window.location.href = 'index.php';</script>";
						}else{
							echo "<script>alert('failed');</script>";
							echo "<script>window.location.href = 'index.php';</script>";
						}

					}else{
						echo "<script>alert('empty');</script>";
						echo "<script>window.location.href = 'index.php';</script>";
					}
				}
			}
		}

		public function fetch(){
			$data = null;

			$query = "SELECT * FROM user_tbl";
			if ($sql = $this->conn->query($query)) {
				while ($row = mysqli_fetch_assoc($sql)) {
					$data[] = $row;
				}
			}
			return $data;
		}

		public function delete($id){

			$query = "DELETE FROM user_tbl where id = '$id'";
			if ($sql = $this->conn->query($query)) {
				return true;
			}else{
				return false;
			}
		}

		public function fetch_single($id){

			$data = null;

			$query = "SELECT * FROM user_tbl WHERE id = '$id'";
			if ($sql = $this->conn->query($query)) {
				while ($row = $sql->fetch_assoc()) {
					$data = $row;
				}
			}
			return $data;
		}

		public function edit($id){

			$data = null;

			$query = "SELECT * FROM user_tbl WHERE id = '$id'";
			if ($sql = $this->conn->query($query)) {
				while($row = $sql->fetch_assoc()){
					$data = $row;
				}
			}
			return $data;
		}

		public function update($data){

			$query = "UPDATE user_tbl SET name='$data[name]', email='$data[email]', mobile='$data[mobile]', address='$data[address]' WHERE id='$data[id] '";

			if ($sql = $this->conn->query($query)) {
				return true;
			}else{
				return false;
			}
		}
	}
 ?>
 
read.php
//read.php
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
	<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
	<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <title>PHP Mysql OOP CRUD (Create, Read, Update and Delete)</title>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-md-12 mt-5">
          <h1 class="text-center">PHP Mysql OOP CRUD (Create, Read, Update and Delete)</h1>
          <hr style="height: 1px;color: black;background-color: black;">
        </div>
      </div>
      <div class="row">
        <div class="col-md-6 mx-auto">
          <?php
              include 'model.php';
              $model = new Model();
              $id = $_REQUEST['id'];
              $row = $model->fetch_single($id);
              if(!empty($row)){
          ?>
          <div class="card">
            <div class="card-header">
              Single Record
            </div>
            <div class="card-body">
              <p>Name = <?php echo $row['name']; ?></p>
              <p>Email = <?php echo $row['email']; ?></p>
              <p>Mobile No. = <?php echo $row['mobile']; ?></p>
              <p>Address = <?php echo $row['address']; ?></p>
            </div>
          </div>
          <?php
            }else{
            echo "no data";
          }
          ?>
        </div>
      </div>
    </div>
</body>
</html>
add.php
//add.php
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
	<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
	<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <title>PHP Mysql OOP CRUD (Create, Read, Update and Delete)</title>
</head>
<body>
    <div class="container">
      <div class="row">
        <div class="col-md-12 mt-5">
          <h1 class="text-center">PHP Mysql OOP CRUD (Create, Read, Update and Delete)</h1>
          <hr style="height: 1px;color: black;background-color: black;">
        </div>
      </div>
      <div class="row">
        <div class="col-md-5 mx-auto">
          <?php
              include 'model.php';
              $model = new Model();
              $insert = $model->insert();
          ?>
          <form action="" method="post">
            <div class="form-group">
              <label for="">Name</label>
              <input type="text" name="name" class="form-control">
            </div>
            <div class="form-group">
              <label for="">Email</label>
              <input type="email" name="email" class="form-control">
            </div>
            <div class="form-group">
              <label for="">Mobile No.</label>
              <input type="text" name="mobile" class="form-control">
            </div>
            <div class="form-group">
              <label for="">Address</label>
              <textarea name="address" id="" cols="" rows="3" class="form-control"></textarea>
            </div>
            <div class="form-group">
              <button type="submit" name="submit" class="btn btn-primary">Submit</button>
            </div>
          </form>
        </div>
      </div>
    </div>
</body>
</html>
edit.php
//edit.php
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
	<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
	<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <title>PHP Mysql OOP CRUD (Create, Read, Update and Delete)</title>
 </head>
 <body>
    <div class="container">
      <div class="row">
        <div class="col-md-12 mt-5">
          <h1 class="text-center">PHP Mysql OOP CRUD (Create, Read, Update and Delete)</h1>
          <hr style="height: 1px;color: black;background-color: black;">
        </div>
      </div>
      <div class="row">
        <div class="col-md-5 mx-auto">
          <?php
              include 'model.php';
              $model = new Model();
              $id = $_REQUEST['id'];
              $row = $model->edit($id);

              if (isset($_POST['update'])) {
                if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['mobile']) && isset($_POST['address'])) {
                  if (!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['mobile']) && !empty($_POST['address']) ) {
                    
                    $data['id'] = $id;
                    $data['name'] = $_POST['name'];
                    $data['mobile'] = $_POST['mobile'];
                    $data['email'] = $_POST['email'];
                    $data['address'] = $_POST['address'];

                    $update = $model->update($data);

                    if($update){
                      echo "<script>alert('record update successfully');</script>";
                      echo "<script>window.location.href = 'index.php';</script>";
                    }else{
                      echo "<script>alert('record update failed');</script>";
                      echo "<script>window.location.href = 'index.php';</script>";
                    }

                  }else{
                    echo "<script>alert('empty');</script>";
                    header("Location: edit.php?id=$id");
                  }
                }
              }
          ?>
          <form action="" method="post">
            <div class="form-group">
              <label for="">Name</label>
              <input type="text" name="name" value="<?php echo $row['name']; ?>" class="form-control">
            </div>
            <div class="form-group">
              <label for="">Email</label>
              <input type="email" name="email" value="<?php echo $row['email']; ?>" class="form-control">
            </div>
            <div class="form-group">
              <label for="">Mobile No.</label>
              <input type="text" name="mobile" value="<?php echo $row['mobile']; ?>" class="form-control">
            </div>
            <div class="form-group">
              <label for="">Address</label>
              <textarea name="address" id="" cols="" rows="3" class="form-control"><?php echo $row['address']; ?></textarea>
            </div>
            <div class="form-group">
              <button type="submit" name="update" class="btn btn-primary">Submit</button>
            </div>
          </form>
        </div>
      </div>
    </div>
</body>
</html>
delete.php
//delete.php
<?php 
	include 'model.php';
	$model = new Model();
	$id = $_REQUEST['id'];
	$delete = $model->delete($id);

	if ($delete) {
		echo "<script>alert('delete successfully');</script>";
		echo "<script>window.location.href = 'index.php';</script>";
	}
 ?>
 

Wednesday, January 5, 2022

SwiftUI Netflix UI Simple Design

SwiftUI Netflix UI Simple Design

ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    var body: some View {

        NavigationView{
                
            Home().navigationBarTitle("")
            .navigationBarHidden(true)
            .navigationBarBackButtonHidden(true)
            
        }.preferredColorScheme(.dark)

    }
}



struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}



struct Home : View {
    
    @State var txt = ""
    @State var show = false
    
    var body : some View{
        
        VStack(alignment: .leading, spacing: 20){
            
            HStack(spacing: 10){
                
                Button(action: {
                    
                    
                }) {
                    
                    Image("menu").renderingMode(.original)
                }
                
                Image("logo")
                
                Spacer()
                
                Button(action: {
                    
                    
                }) {
                    
                    Image("Notifications").renderingMode(.original)
                }
                
            }
            
            HStack(spacing: 15){
                
                Image(systemName: "magnifyingglass").font(.body)
                
                TextField("Search For Movies,Shows", text: $txt)
                
            }.padding()
                .background(Color.gray)
            
            ScrollView(.vertical, showsIndicators: false) {
                
                VStack(alignment: .leading, spacing: 15) {
                    
                    Text("Movies").font(.title)
                     
                     ZStack{
                         
                        NavigationLink(destination: Detail(show: $show), isActive: $show) {
                            
                            Text("")
                        }
                        
                        Image("top").resizable().onTapGesture {
                            
                            self.show.toggle()
                        }
                         
                         VStack{
                             
                             Spacer()
                             
                             HStack{
                             
                                 VStack(alignment: .leading, spacing: 10){
                                     
                                     Text("Journey 2: The Mysterious Island").font(.body)
                                     Text("Action Movie").font(.caption)
                                 }
                                 
                                 Spacer()
                                 
                                 Button(action: {
                                     
                                 }) {
                                     
                                     Image("play").renderingMode(.original)
                                 }
                                 
                             }
                             
                         }.padding()
                         
                     }.frame(height: 190)
                     
                     HStack{
                         
                         Spacer()
                         
                         Button(action: {
                             
                         }) {
                             
                             Text("View All")
                             
                         }.foregroundColor(Color.white)
                     }
                    
                    Text("Continue Watching")
                    
                    middleView()
                    BottomView()
                    
                }
 
            }.padding(.bottom, 25)
                

            
        }.padding(.horizontal)
        .edgesIgnoringSafeArea(.bottom)
        .preferredColorScheme(.dark)
    }
}

struct middleView : View {
    
    var body : some View{
        
        VStack(spacing: 15){
            
            ScrollView(.horizontal, showsIndicators: false) {
                
                HStack(spacing: 15){
                    
                    ForEach(datas){i in
                        
                        VStack(alignment: .leading,spacing: 0){
                            
                            Image(i.image)
                            
                            HStack{
                                
                                Spacer()
                                
                                Button(action: {
                                    
                                }) {
                                    
                                    Image("play").renderingMode(.original).resizable().frame(width: 25, height: 25)
                                    
                                }.padding(.top, -12)
                            }
                            
                            VStack(alignment: .leading){
                                
                                Text(i.name)
                                
                                ZStack{
                                    
                                    Capsule().fill(Color.gray)
                                    
                                    HStack{
                                    
                                        Capsule().fill(Color.green).frame(width: i.percentage)
                                        
                                        Spacer()
                                        
                                    }
                                    
                                }.frame(height: 5)
                                
                            }.padding(.horizontal,10)
                            .padding(.bottom, 10)


                        }.background(Color.gray)
                        .padding(.bottom)
                    }
                }
            }
        }
    }
}


struct BottomView : View {
    
    var body : some View{
        
        VStack(alignment: .leading,spacing: 15){
            
            Text("Explore By Genres")
            
            HStack{
                
                Button(action: {
                    
                }) {
                    
                    Text("Action").padding()
                    
                }.foregroundColor(.white)
                .background(Color.red)
                .cornerRadius(10)
                
                Spacer(minLength: 10)
                
                Button(action: {
                    
                }) {
                    
                    Text("Adventure").padding()
                    
                }.foregroundColor(.white)
                .background(Color.red)
                .cornerRadius(10)
                
                Spacer(minLength: 10)
                
                Button(action: {
                    
                }) {
                    
                    Text("Comedy").padding()
                    
                }.foregroundColor(.white)
                .background(Color.red)
                .cornerRadius(10)
                
            }
            
            Text("Trending")
            
            ScrollView(.horizontal, showsIndicators: false) {
                
                HStack(spacing: 15){
                    
                    ForEach(bottom,id: \.self){i in
                        
                        Image(i)
                    }
                }
            }
        }
    }
}
Detail.swift
 
//
//  Detail.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct Detail : View {
    
    @Binding var show : Bool
    
    var body : some View{
        
        VStack(spacing: 15){
            HStack(spacing: 15){
                
                Button(action: {
                    self.show.toggle()
                }) {
                    Image(systemName: "arrow.left").foregroundColor(Color.white)
                }
                
                Spacer()
                
                Button(action: {
                    actionSheet()
                }) {
                    Image("share").renderingMode(.original)
                }
                
                Button(action: {
                }) {
                    Image(systemName: "info.circle").foregroundColor(Color.white)
                }
                
            }.padding()
            
            ZStack{
                Image("detail").resizable()
                VStack(alignment: .leading,spacing: 12){
                    
                    Spacer()
                    
                    Text("ACTION")
                    Text("Journey 2: The Mysterious Island").font(.title)
                    
                    HStack(spacing: 10){
                        Text("98% Match")
                        Text("2012")
                        Image("hd")
                        
                        Spacer()
                    }
                    
                }.padding()
                
            }.frame(height: UIScreen.main.bounds.height / 2)
            .navigationBarTitle("")
            .navigationBarHidden(true)
            .navigationBarBackButtonHidden(true)
            
            ScrollView(.vertical, showsIndicators: false) {
                VStack(alignment: .leading, spacing: 15){
                    HStack{
                        Button(action: {
                            
                        }) {
                            HStack(spacing: 10){
                                Image(systemName: "play.fill")
                                Text("Play")
                            }.padding()
                        }.foregroundColor(.white)
                        .background(Color.red)
                        .cornerRadius(10)
                        
                        Button(action: {
                        }) {
                            HStack(spacing: 10){
                                Image(systemName: "plus")
                                Text("ADD TO LIST")
                            }.padding()
                            
                        }.foregroundColor(.white)
                        .background(Color.gray)
                        .cornerRadius(10)
                        
                        Spacer()
                    }
                    
                    HStack{
                        VStack(alignment: .leading, spacing: 10){
                            Text("Journey 2: The Mysterious Island")
                            Text("Sean Anderson partners with his mom's husband on a mission to find his grandfather, who is thought to be missing on a mythical island.").foregroundColor(.gray)
                        }
                    }.padding(.top, 15)
                    
                    Divider().padding(.vertical, 12)
                    
                    ForEach(popular){i in
                        VStack(alignment: .leading,spacing: 15){
                            HStack{
                                Image(i.image)
                                    .resizable().aspectRatio(contentMode: .fill)
                                VStack(alignment: .leading, spacing: 10){
                                    Text(i.name)
                                    Text(i.time)
                                }
                                
                                Spacer()
                                
                                Button(action: {
                                }) {
                                    Image(systemName: "arrow.down")
                                }
                            }
                            Text(i.desc)
                        }
                        
                    }.padding(.bottom, 15)
                }
            }.padding(.top, 15)
            .padding(.horizontal, 15)
            
        }.edgesIgnoringSafeArea(.bottom)
    }
    
    func actionSheet() {
        guard let urlShare = URL(string: "https://developer.apple.com/xcode/swiftui/") else { return }
           let activityVC = UIActivityViewController(activityItems: [urlShare], applicationActivities: nil)
           UIApplication.shared.windows.first?.rootViewController?.present(activityVC, animated: true, completion: nil)
    }
}

struct Detail_Previews: PreviewProvider {
    @State static var show = false
    static var previews: some View {
        Detail(show: $show)
    }
}
Model.swift
 
//
//  Model.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct type : Identifiable {
    
    var id : Int
    var name : String
    var image : String
    var percentage : CGFloat
}

var datas = [
    type(id: 0, name: "The Amazing Spider-Man", image: "1",percentage : 45),
    type(id: 1, name: "Fast and Furious Presents", image: "2",percentage: 90),
    type(id: 2, name: "Green Snake", image: "3",percentage: 53)
]

var bottom = ["b1","b2"]

struct polularlist : Identifiable {
    
    var id : Int
    var name : String
    var time : String
    var image : String
    var desc : String
}

var popular = [polularlist(id: 0, name: "Green Snake", time: "51 min", image: "3", desc: "While trying to free her sister from Fahai's clutches, Xio Qing winds up in a dystopian city and meets a mysterious man who can't recall his past life."),
               polularlist(id: 1, name: "How to Train Your Dragon 2", time: "44 min", image: "4", desc: "Five years have passed since Hiccup and Toothless united the dragons and Vikings of Berk. Now, they spend their time charting the island's unmapped territories. During one of their adventures, the pair discover a secret cave that houses hundreds of wild dragons"),
               polularlist(id: 2, name: "Aquaman", time: "63 min", image: "5", desc: "Once home to the most advanced civilization on Earth, the city of Atlantis is now an underwater kingdom ruled by the power-hungry King Orm. With a vast army at his disposal, Orm plans to conquer the remaining oceanic people -- and then the surface world.")]

Related Post