Skip to content

Commit

Permalink
Add response online validator (#23)
Browse files Browse the repository at this point in the history
* response and toolbar in rtl languages issue fixed

    * body aligment in search mode fixed

    * body issue on dark mode fixed

    Co-authored-by: Arash Goodarzi <[email protected]>

Co-authored-by: Arash Goodarzi <[email protected]>
  • Loading branch information
aarashgoodarzi and Arash Goodarzi authored Oct 2, 2022
1 parent 584abc1 commit c5c9838
Show file tree
Hide file tree
Showing 4 changed files with 119 additions and 19 deletions.
85 changes: 70 additions & 15 deletions Sources/NetShears/UI/BodyDetailViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import UIKit

final class BodyDetailViewController: UIViewController, ShowLoaderProtocol {

@IBOutlet weak var bottomViewInputConstraint: NSLayoutConstraint!
@IBOutlet weak var toolBar: UIToolbar!
@IBOutlet weak var labelWordFinded: UILabel!
Expand All @@ -19,37 +20,85 @@ final class BodyDetailViewController: UIViewController, ShowLoaderProtocol {
static let kPadding: CGFloat = 10.0

var bodyExportType: BodyExportType = .default

var textColor: UIColor {
guard #available(iOS 13.0, *) else {
return .black
}
return UIColor(dynamicProvider: { trait in
switch trait.userInterfaceStyle {
case .light:
return .black
case .dark:
return .white
case .unspecified:
return .gray
@unknown default:
return .gray
}
})
}
var searchController: UISearchController?
var highlightedWords: [NSTextCheckingResult] = []
var data: Data?
var indexOfWord: Int = 0

let jsonValidatorOnline = JSONValidatorOnline()

deinit {
NotificationCenter.default.removeObserver(self)
}

override func viewDidLoad() {
super.viewDidLoad()

setupObservers()
setupTextView()
setupNavigationItems()
setupNextPreviousButtons()
addSearchController()
hideViewInValidatorButtonIfNeeded()
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setBody()
}

private func setupObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(BodyDetailViewController.handleKeyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(BodyDetailViewController.handleKeyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}

private func setupTextView() {
textView.font = UIFont(name: "Courier", size: 14)
textView.dataDetectorTypes = UIDataDetectorTypes.link
setupAlignmentAndColor()
}

private func setupAlignmentAndColor() {
textView.textAlignment = .left
textView.textColor = textColor
}

private func setupNavigationItems() {
let shareButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareContent(_:)))
let searchButton = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(showSearch))
navigationItem.rightBarButtonItems = [searchButton, shareButton]
}

private func setupNextPreviousButtons() {
buttonPrevious.isEnabled = false
buttonNext.isEnabled = false
addSearchController()
guard UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft, var items = toolBar.items else {
return
}
items.reverse()
toolBar.items = items
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
private func setBody() {
let hud = showLoader(view: view)
RequestExporter.body(data, bodyExportType: bodyExportType ) { [weak self] (stringData) in
RequestExporter.body(data, bodyExportType: bodyExportType) { [weak self] stringData in
let formattedJSON = stringData
DispatchQueue.main.async {
self?.textView.text = formattedJSON
Expand All @@ -58,15 +107,6 @@ final class BodyDetailViewController: UIViewController, ShowLoaderProtocol {
}
}

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

// MARK: - Search
func addSearchController(){
searchController = UISearchController(searchResultsController: nil)
Expand All @@ -87,6 +127,14 @@ final class BodyDetailViewController: UIViewController, ShowLoaderProtocol {
definesPresentationContext = true
}

func hideViewInValidatorButtonIfNeeded() {
if #available(iOS 11.0, *) {
return
}
let irRTL = view.semanticContentAttribute == .forceRightToLeft
_ = irRTL ? toolBar.items?.removeLast() : toolBar.items?.removeFirst()
}

@IBAction func previousStep(_ sender: UIBarButtonItem?) {
indexOfWord -= 1
if indexOfWord < 0 {
Expand All @@ -103,6 +151,10 @@ final class BodyDetailViewController: UIViewController, ShowLoaderProtocol {
getCursor()
}

@IBAction func openValidatorTapped(_ sender: Any) {
jsonValidatorOnline.open(jsonString: textView.text, on: self)
}

func getCursor() {
let value = highlightedWords[indexOfWord]
if let range = textView.convertRange(range: value.range) {
Expand All @@ -114,6 +166,7 @@ final class BodyDetailViewController: UIViewController, ShowLoaderProtocol {
textView.setContentOffset(CGPoint(x: 0, y: rect.origin.y - BodyDetailViewController.kPadding), animated: true)
}
cursorAnimation(with: value.range)
setupAlignmentAndColor()
}
}

Expand Down Expand Up @@ -192,14 +245,16 @@ extension BodyDetailViewController: UISearchBarDelegate {

extension BodyDetailViewController {
func resetSearchText() {
let attributedString = NSMutableAttributedString(attributedString: self.textView.attributedText)
let prettyString = textView.attributedText.string.prettyPrintedJSON ?? textView.attributedText.string
let attributedString = NSMutableAttributedString(string: prettyString)
attributedString.addAttribute(.backgroundColor, value: UIColor.clear, range: NSRange(location: 0, length: self.textView.attributedText.length))
attributedString.addAttribute(.font, value: UIFont(name: "Courier", size: 14)!, range: NSRange(location: 0, length: self.textView.attributedText.length))

self.textView.attributedText = attributedString
self.labelWordFinded.text = "0 of 0"
self.buttonPrevious.isEnabled = false
self.buttonNext.isEnabled = false
setupAlignmentAndColor()
}

func cursorAnimation(with range: NSRange) {
Expand Down
11 changes: 8 additions & 3 deletions Sources/NetShears/UI/Flow.storyboard
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17701" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="B9l-eh-LuR">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="20037" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="B9l-eh-LuR">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17703"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="20020"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
Expand Down Expand Up @@ -111,9 +111,14 @@
<rect key="frame" x="0.0" y="623" width="375" height="44"/>
<items>
<barButtonItem style="plain" systemItem="flexibleSpace" id="RNb-pa-Z9b"/>
<barButtonItem title="View in Validator" id="Xjg-eS-cAm">
<connections>
<action selector="openValidatorTapped:" destination="S40-LP-XSy" id="Bx9-e4-Egz"/>
</connections>
</barButtonItem>
<barButtonItem style="plain" id="Dvu-s4-6n6">
<view key="customView" contentMode="scaleToFill" id="wDm-Tn-1Yd">
<rect key="frame" x="134" y="5.5" width="177" height="33"/>
<rect key="frame" x="150" y="5.5" width="177" height="33"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="0 of 0" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="VxO-VX-XW4">
Expand Down
40 changes: 40 additions & 0 deletions Sources/NetShears/Utils/JSONEditorOnline.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//
// File.swift
//
//
// Created by Arash on 9/14/22.
//

import UIKit
import SafariServices

struct JSONValidatorOnline {

func open(jsonString: String?, on vc: UIViewController) {
guard let jsonString = jsonString,
let encodedJson = jsonString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
else {
print("NetShears - jsonString not received")
return
}
let base = "https://jsoneditoronline.org/#left=json."
let mode = "&mode=tree"
let url = base + encodedJson + mode
openBrowser(for: url, on: vc)
}

private func openBrowser(for url: String, on vc: UIViewController) {
guard #available(iOS 11.0, *) else {
print("NetShears - iOS version not supported")
return
}
let config = SFSafariViewController.Configuration()
config.entersReaderIfAvailable = true
guard let url = URL(string: url) else {
print("NetShears - invalid url")
return
}
let browserVc = SFSafariViewController(url: url, configuration: config)
vc.present(browserVc, animated: true)
}
}
2 changes: 1 addition & 1 deletion Sources/NetShears/Utils/RequestExporter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ final class RequestExporter: NSObject {

static func body(_ body: Data?, splitLength: Int? = nil, bodyExportType: BodyExportType) -> String {
if case .custom(let text) = bodyExportType {
return text
return text.prettyPrintedJSON ?? text
}

guard body != nil else {
Expand Down

0 comments on commit c5c9838

Please sign in to comment.