Loading gif while backend script is executed - django

So I've got a form and when I submit it, a backend script.py is executed in Django.
It makes some statistical analysis which takes about 8 secs and when it finishes I get redirected to a next page.
So I've been trying to find a way to implement a loading gif while the script is executed but I failed in every one of my efforts.
I was thinking about using AJAX and javascript onclick method (or even onsubmit),
but they didn't work.
Thank you all in advance.

I found this article in StackOverflow linked to a js code. Basically in this code, he is checking for if the body has something loaded in it. If it doesn't then he shows a loading page, maybe this will help.
Here is the links
Show loading image after click button and page load
function onReady(callback) {
var intervalID = window.setInterval(checkReady, 1000);
function checkReady() {
if (document.getElementsByTagName('body')[0] !== undefined) {
console.log(document.getElementsByTagName('body')[0]);
window.clearInterval(intervalID);
callback.call(this);
}
}
}
function show(id, value) {
document.getElementById(id).style.display = value ? 'block' : 'none';
}
onReady(function () {
show('page', true);
show('loading', false);
});
body {
background: #FFF url("http://i.imgur.com/KheAuef.png") top left repeat-x;
font-family:"Brush Script MT", cursive;
}
h1 {
font-size: 2em;
margin-bottom: 0.2em;
padding-bottom: 0;
}
p {
font-size: 1.5em;
margin-top: 0;
padding-top: 0;
}
#page {
display: none;
}
#loading {
display: block;
position: absolute;
top: 0;
left: 0;
z-index: 100;
width: 100vw;
height: 100vh;
background-color: rgba(192, 192, 192, 0.5);
background-image: url("http://i.stack.imgur.com/MnyxU.gif");
background-repeat: no-repeat;
background-position: center;
}
<div id="page">
<h1>The standard Lorem Ipsum passage</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div id="loading"></div>

Related

SwiftUI TextEditor: scrolling to top at text change

I am using SwiftUI 2's new TextEditor. What I'd like to do is the TextEditor to scroll to top automatically when it's text changes which currently is not the case.
Here's the example project's code:
import SwiftUI
struct ContentView: View {
#State private var text: String = Self.text1
static private var text1 = """
Text 1:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
static private var text2 = """
Text 2:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
var body: some View {
VStack {
TextEditor(text: $text)
.frame(maxHeight: 150)
Button("Toggle Text") {
if text == Self.text1 {
text = Self.text2
} else {
text = Self.text1
}
}
}
}
}
I found a few threads concerning ScrollView that did not help, couldn't find anything on TextEditor though.
Here is a possible solution using ScrollViewReader for SwiftUI 2.0 and ScrollView
var body: some View {
ScrollViewReader { sp in
ScrollView {
TextEditor(text: $text)
.id(0)
}.frame(maxHeight: 150)
Button("Toggle Text") {
if text == Self.text1 {
text = Self.text2
sp.scrollTo(0, anchor: .top)
} else {
text = Self.text1
sp.scrollTo(0, anchor: .top)
}
}
}
}

SwiftUI: set custom underline to text?

I have this piece of code:
var body: some View {
ZStack {
Color.black
.opacity(0.8)
.edgesIgnoringSafeArea(.all)
(Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ")
+
Text("eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ")
.underline(true, color: Color.yellow)
+
Text("quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."))
.font(.system(size: 20, weight: .bold))
.foregroundColor(.white)
.lineSpacing(4.0)
.padding(.horizontal, 12)
}
}
I would like to customize the underline, like increasing the offset and the line height. How can I do so?
Thank you for your help

How to create two text views that are the same size

I am working on a game and I have text views representing cards that can be flipped. There is text on each side of the card. I would like the card to be the same size on each side. i.e. I would like the card on the side with less text to be the same size as the card on the size with more text. I don't want to hard code the card size as sometimes there will be only one line of text and other times there will be multiple lines of text. Here is an excerpt of the code I currently have:
import SwiftUI
struct FlipTestView: View {
#State var flipped = false
var body: some View {
let flipDegrees = flipped ? 180.0 : 0
VStack {
ZStack() {
Text("Card One First Side Of Card")
.placedOnCard(Color.yellow)
.flipRotate(flipDegrees).opacity(flipped ? 0.0 : 1.0)
Text("""
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
""")
.placedOnCard(Color.green)
.flipRotate(-180 + flipDegrees).opacity(flipped ? 1.0 : 0.0)
}
.animation(.easeInOut(duration: 0.8))
.onTapGesture { flipped.toggle()}
}
}
}
struct FlipTestView_Previews: PreviewProvider {
static var previews: some View {
FlipTestView()
}
}
extension View {
func flipRotate(_ degrees : Double) -> some View {
return rotation3DEffect(Angle(degrees: degrees), axis: (x: 1.0, y: 0.0, z: 0.0))
}
func placedOnCard(_ color: Color) -> some View {
return
padding(15)
// .frame(width: 350, height: 65, alignment: .center).background(color)
.background(color)
.cornerRadius(16)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(Color.blue, lineWidth: 4)
)
}
}
Move the .placedOnCard to the ZStack that contains both sides, then it will be sized to the larger of the two sides. Here is a solution that refactors your code:
ZStack() {
Text("Card One First Side Of Card")
.opacity(flipped ? 0.0 : 1.0)
Text("""
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
""")
.flipRotate(180.0).opacity(flipped ? 1.0 : 0.0)
}
.placedOnCard(flipped ? Color.green : Color.yellow)
.flipRotate(flipDegrees)
.animation(.easeInOut(duration: 0.8))
.onTapGesture { flipped.toggle()}

How to implement a "read more" style button at the end of a text in SwiftUI

I have a very long text and I want to show just 3 lines with more button just like the picture and also a less button when the text is expand. Any idea of how to do it with SwiftUI?
var body: some View{
VStack{
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
}
}
This answer is a bit of a hack, because it does not truncate the actual string and apply the "..." suffix, which in my humble opinion would be the better engineered solution. That would require the programmer to determine the length of the string that fits within three lines, remove the last two words (to allow for the More/Less button) and apply the "..." suffix.
This solution limits the number of lines shown and literally covers the trailing end of the third line with a white background and the button. But it may be suitable for your case...
#State private var isExpanded: Bool = false
var body: some View{
VStack{
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
.lineLimit(isExpanded ? nil : 3)
.overlay(
GeometryReader { proxy in
Button(action: {
isExpanded.toggle()
}) {
Text(isExpanded ? "Less" : "More")
.font(.caption).bold()
.padding(.leading, 8.0)
.padding(.top, 4.0)
.background(Color.white)
}
.frame(width: proxy.size.width, height: proxy.size.height, alignment: .bottomTrailing)
}
)
}
}
You can learn how to do this by following Apple's "Introducing SwiftUI" tutorials. Specifically the "Creating a macOS app" tutorial, "Section 9 Build the Detail View".
I was also trying to achieve the similar Results as you. Also spent hours finding the solution when it was in front of me all along...!
The solution is to use ZStack along with ScrollView and GeometaryReader all at once...
struct CollapsableTextView: View {
let lineLimit: Int
#State private var expanded: Bool = false
#State private var showViewButton: Bool = false
private var text: String
init(_ text: String, lineLimit: Int) {
self.text = text
self.lineLimit = lineLimit
}
private var moreLessText: String {
if showViewButton {
return expanded ? "View Less" : "View More"
} else {
return ""
}
}
var body: some View {
VStack(alignment: .leading) {
ZStack {
Text(text)
.font(.body)
.lineLimit(expanded ? nil : lineLimit)
ScrollView(.vertical) {
Text(text)
.font(.body)
.background(
GeometryReader { proxy in
Color.clear
.onAppear {
showViewButton = proxy.size.height > CGFloat(22 * lineLimit)
}
.onChange(of: text) { _ in
showViewButton = proxy.size.height > CGFloat(22 * lineLimit)
}
}
)
}
.opacity(0.0)
.disabled(true)
.frame(height: 0.0)
}
Button(action: {
withAnimation {
expanded.toggle()
}
}, label: {
Text(moreLessText)
.font(.body)
.foregroundColor(.orange)
})
.opacity(showViewButton ? 1.0 : 0.0)
.disabled(!showViewButton)
.frame(height: showViewButton ? nil : 0.0)
}
}
}
struct CollapsableTextView_Previews: PreviewProvider {
static var previews: some View {
CollapsableTextView("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", lineLimit: 3)
}
}
The Most important part of this code is CGFloat(22 * lineLimit) here 22 is the height of single Line with the specified font used. You might have to change the height (i.e. 22 in this case) based upon your font...
Other than that every thing is pretty straight forward. I hope it might help...!
You can read this Medium article
struct ExpandableText: View {
#State private var expanded: Bool = false
#State private var truncated: Bool = false
#State private var shrinkText: String
private var text: String
let font: UIFont
let lineLimit: Int
init(_ text: String, lineLimit: Int, font: UIFont = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)) {
self.text = text
_shrinkText = State(wrappedValue: text)
self.lineLimit = lineLimit
self.font = font
}
var body: some View {
ZStack(alignment: .bottomLeading) {
Group {
Text(self.expanded ? text : shrinkText) + Text(moreLessText)
.bold()
.foregroundColor(.black)
}
.animation(.easeInOut(duration: 1.0), value: false)
.lineLimit(expanded ? nil : lineLimit)
.background(
// Render the limited text and measure its size
Text(text)
.lineLimit(lineLimit)
.background(GeometryReader { visibleTextGeometry in
Color.clear.onAppear() {
let size = CGSize(width: visibleTextGeometry.size.width, height: .greatestFiniteMagnitude)
let attributes:[NSAttributedString.Key:Any] = [NSAttributedString.Key.font: font]
///Binary search until mid == low && mid == high
var low = 0
var heigh = shrinkText.count
var mid = heigh ///start from top so that if text contain we does not need to loop
///
while ((heigh - low) > 1) {
let attributedText = NSAttributedString(string: shrinkText + moreLessText, attributes: attributes)
let boundingRect = attributedText.boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
if boundingRect.size.height > visibleTextGeometry.size.height {
truncated = true
heigh = mid
mid = (heigh + low)/2
} else {
if mid == text.count {
break
} else {
low = mid
mid = (low + heigh)/2
}
}
shrinkText = String(text.prefix(mid))
}
if truncated {
shrinkText = String(shrinkText.prefix(shrinkText.count - 2)) //-2 extra as highlighted text is bold
}
}
})
.hidden() // Hide the background
)
.font(Font(font)) ///set default font
///
if truncated {
Button(action: {
expanded.toggle()
}, label: {
HStack { //taking tap on only last line, As it is not possible to get 'see more' location
Spacer()
Text("")
}.opacity(0)
})
}
}
}
private var moreLessText: String {
if !truncated {
return ""
} else {
return self.expanded ? " read less" : " ... read more"
}
}
}
And use this ExpandableText in your view like bellow
ExpandableText("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut laborum", lineLimit: 6)

Charts.js -> Display / Load chart only when visible on the screen

This is my first question, I was searching for the answer here and on Google but to no avail.
I am preparing a website for accountancy company, they have requested a demo to be created with some data visualisations. I have opted to use 'charts.js'.
My problem is this, I want the chart to load only when visible on the screen. At the moment they all load at the same time therefore you miss the quite nice animation.
Extending on my question, I would like text next to the chart to 'ease-in' too, also only when visible on screen.
Would someone be kind enough to point me to the right material on the 'net, or maybe show me an easy way to achieve this?
Kindest regards and thank you in advance!
As requested, I am adding simple code that displays two charts below the screen. To make this work you will need Chart.js from here: Chart.js Website
index.html:
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Graphs</title>
<link rel="stylesheet" href="css/main.css">
<script src="js/Chart.js"></script>
</head>
<body>
<div class="graphs">
<div class="separator1"></div>
<div class="graph1">
<canvas id="myCanvas" width="475" height="400">Graph 1</canvas>
<script>
//Get the context of the canvas element we want to select
context = document.getElementById('myCanvas').getContext('2d');
var Line = {};
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(151,57,56,0.5)",
strokeColor : "rgba(151,57,56,1)",
pointColor : "rgba(151,57,56,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(59,97,150,0.5)",
strokeColor : "rgba(59,97,150,1)",
pointColor : "rgba(59,97,150,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
};
var options = { scaleOverlay : false, scaleOverride : false, scaleLineWidth : 1, pointDotRadius : 3, pointDotStrokeWidth : 1, animationSteps : 150 };
new Chart(context).Line(data, options);
</script>
</div>
<div class="text1">
<div class="innertext">
<h3>Praesent viverra</h3>
<hr/>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>
<div class="graph2">
<canvas id="myCanvas2" width="475" height="400">Graph 2</canvas>
<script>
//Get the context of the canvas element we want to select
context = document.getElementById('myCanvas2').getContext('2d');
var Pie = {};
var data = [
{
value: 30,
color:"#973938"
},
{
value : 50,
color : "#78963E"
},
{
value : 40,
color : "#3B6196"
},
{
value : 25,
color: "#F49D20"
},
{
value : 35,
color: "#FBDD13"
}
];
var options = { animationSteps : 150 };
new Chart(context).Pie(data, options);
</script>
</div>
<div class="text2">
<div class="innertext">
<h3>Praesent viverra</h3>
<hr/>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>
</body>
</html>
main.css:
.graph1 {
margin-left: 15%;
width: 33%;
float: left;
height: 450px;
display: block;
}
.graph1 canvas {
padding: 25px 25px 25px 25px;
}
.graph2 {
margin-right: 15%;
width: 33%;
float: right;
height: 450px;
display: block;
}
.graph2 canvas {
padding: 25px 25px 25px 25px;
}
.innertext {
padding-top: 25%;
}
.text1 {
margin-right: 15%;
width: 33%;
float: right;
height: 450px;
}
.text1 p {
text-align: center;
}
.text1 hr {
margin: 0 auto;
width: 40%;
text-align: center;
}
.text1 h3 {
text-align: center;
color: #636363;
}
.text2 {
margin-left: 15%;
width: 33%;
float: left;
height: 450px;
}
.text2 p {
text-align: center;
}
.text2 hr {
margin: 0 auto;
width: 40%;
text-align: center;
}
.text2 h3 {
text-align: center;
color: #636363;
}
.separator1 {
display: block;
margin: 0 auto;
width: 100%;
height: 1000px;
}
Thanks again to anyone willing to help!