Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Local Server #1

Draft
wants to merge 1 commit into
base: trunk
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,20 @@
<dict>
<key>SchemeUserState</key>
<dict>
<key>GutenbergKit-Package.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
<key>GutenbergKit.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>1</integer>
<integer>2</integer>
</dict>
<key>GutenbergKitTests.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>2</integer>
</dict>
<key>pg (Playground) 1.xcscheme</key>
<dict>
Expand Down Expand Up @@ -52,5 +62,13 @@
<integer>0</integer>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict>
<key>GutenbergKit</key>
<dict>
<key>primary</key>
<true/>
</dict>
</dict>
</dict>
</plist>
8 changes: 8 additions & 0 deletions Gutenberg-Info.plist
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSAppTransportSecurity</key>
<dict/>
</dict>
</plist>
4 changes: 4 additions & 0 deletions Gutenberg.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
/* Begin PBXFileReference section */
0C4F598B2BEFF4970028BD96 /* Gutenberg.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Gutenberg.app; sourceTree = BUILT_PRODUCTS_DIR; };
0C61AA062C25109600FA7E46 /* */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = ""; sourceTree = "<group>"; };
0C6C31992C2AE9CD00F2B038 /* Gutenberg-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = "Gutenberg-Info.plist"; sourceTree = "<group>"; };
0CF6E0402BEFF59600EDEE8A /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
0CF6E0422BEFF59600EDEE8A /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; };
0CF6E0432BEFF59600EDEE8A /* GutenbergApp.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GutenbergApp.swift; sourceTree = "<group>"; };
Expand All @@ -38,6 +39,7 @@
0C4F59822BEFF4970028BD96 = {
isa = PBXGroup;
children = (
0C6C31992C2AE9CD00F2B038 /* Gutenberg-Info.plist */,
0C61AA062C25109600FA7E46 /* */,
0CF6E03F2BEFF59600EDEE8A /* GutenbergDemo */,
0C4F598C2BEFF4970028BD96 /* Products */,
Expand Down Expand Up @@ -290,6 +292,7 @@
DEVELOPMENT_TEAM = NR8DLKJ7E6;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = "Gutenberg-Info.plist";
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
Expand Down Expand Up @@ -319,6 +322,7 @@
DEVELOPMENT_TEAM = NR8DLKJ7E6;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = "Gutenberg-Info.plist";
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"pins" : [
{
"identity" : "embassy",
"kind" : "remoteSourceControl",
"location" : "https://github.com/envoy/Embassy.git",
"state" : {
"revision" : "8469f2c1b334a7c1c3566e2cb2f97826c7cca898",
"version" : "4.1.6"
}
}
],
"version" : 2
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<key>Gutenberg.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
<integer>1</integer>
</dict>
</dict>
</dict>
Expand Down
5 changes: 4 additions & 1 deletion GutenbergDemo/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ struct ContentView: View {

struct EditorView: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> EditorViewController {
EditorViewController(service: .init(client: Client()))
let viewController = EditorViewController(service: .init(client: Client()))
viewController.webView.isInspectable = true
return viewController

}

func updateUIViewController(_ uiViewController: EditorViewController, context: Context) {
Expand Down
7 changes: 6 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,18 @@ let package = Package(
products: [
.library(name: "GutenbergKit", targets: ["GutenbergKit"])
],
dependencies: [
.package(url: "https://github.com/envoy/Embassy.git", from: "4.0.0"),
],
targets: [
.target(
name: "GutenbergKit",
dependencies: [.product(name: "Embassy", package: "Embassy")],
resources: [.copy("Gutenberg")]
),
.testTarget(
name: "GutenbergKitTests",
dependencies: ["GutenbergKit"]),
dependencies: ["GutenbergKit"]
)
]
)
125 changes: 125 additions & 0 deletions Sources/GutenbergKit/Sources/EditorLocalServer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import Embassy
import Foundation

// FIXME: rework
// This is just for the demo and is absolutely NOT production ready. It should
// be replaced with another framework.
final class EditorLocalServer {
var eventLoop: EventLoop!
var eventLoopThreadCondition: NSCondition!
var eventLoopThread: Thread!
var server: DefaultHTTPServer!

func run() throws {
NSLog("\(Date.now.timeIntervalSince1970))): EditorLocalServer.run")

eventLoop = try SelectorEventLoop(selector: try KqueueSelector())

server = DefaultHTTPServer(eventLoop: eventLoop, port: EditorConstants.port, app: makeApp())
try server.start()

NSLog("\(Date.now.timeIntervalSince1970): EditorLocalServer.didStart")

eventLoopThreadCondition = NSCondition()
eventLoopThread = Thread(target: self, selector: #selector(runEventLoop), object: nil)
eventLoopThread.start()

NSLog("\(Date.now.timeIntervalSince1970): EditorLocalServer.didStartThread")
}

private func makeApp() -> SWSGI {
{ (environment: [String: Any], startResponse: ((String, [(String, String)]) -> Void), sendBody: ((Data) -> Void)) in

guard let request = HTTPRequest(environment: environment) else {
return
}

NSLog("\(Date.now.timeIntervalSince1970): request: \(request)")

let path = request.path
if path.hasPrefix("/\(EditorConstants.gutenbergLocalPath)"), let url = URL(string: path) {
let resource = url.deletingPathExtension().lastPathComponent
let subdirectory = url.deletingLastPathComponent().absoluteString

guard let fileURL = Bundle.module.url(forResource: resource, withExtension: url.pathExtension, subdirectory: subdirectory) else {
// TODO: safe error handling
fatalError("missing resource: \(path)")
}

let data = try! Data(contentsOf: fileURL)

// TODO: send date
// TODO: pass proper contnet-type

let contentTypes = [
"js": "text/javascript",
"html": "text/html",
"css": "text/css"
]

startResponse("200 OK", [
("Content-Length", String(data.count)),
("Content-Type", "\(contentTypes[url.pathExtension]!); charset=utf-8")
])
// TODO: copy these outside of the module?

sendBody(data)
sendBody(Data())

return
}

// TODO: throw error
NSLog("unhandled request: \(request)")

}
}


@objc private func runEventLoop() {
NSLog("\(Date.now.timeIntervalSince1970): EditorLocalServer.runEventLoop")
eventLoop.runForever()
eventLoopThreadCondition.lock()
eventLoopThreadCondition.signal()
eventLoopThreadCondition.unlock()
}
}

enum EditorConstants {
static let port = 47197
static let gutenbergLocalPath = "Gutenberg"
}

//"SERVER_NAME": "[::1]",
//"SERVER_PROTOCOL" : "HTTP/1.1",
//"SERVER_PORT" : "53479",
//"REQUEST_METHOD": "GET",
//"SCRIPT_NAME" : "",
//"PATH_INFO" : "/",
//"HTTP_HOST": "[::1]:8889",
//"HTTP_USER_AGENT" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
//"HTTP_ACCEPT_LANGUAGE" : "en-US,en;q=0.8,zh-TW;q=0.6,zh;q=0.4,zh-CN;q=0.2",
//"HTTP_CONNECTION" : "keep-alive",
//"HTTP_ACCEPT" : "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
//"HTTP_ACCEPT_ENCODING" : "gzip, deflate, sdch",
//"swsgi.version" : "0.1",
//"swsgi.input" : (Function),
//"swsgi.error" : "",
//"swsgi.multiprocess" : false,
//"swsgi.multithread" : false,
//"swsgi.url_scheme" : "http",
//"swsgi.run_once" : false

private struct HTTPRequest {
let method: String
let path: String

init?(environment: [String: Any]) {
guard let method = environment["REQUEST_METHOD"] as? String,
let path = environment["PATH_INFO"] as? String else {
return nil
}
self.method = method
self.path = path
}
}
6 changes: 6 additions & 0 deletions Sources/GutenbergKit/Sources/EditorService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import Foundation
@MainActor
public final class EditorService {
private let client: EditorNetworkingClient
private let server: EditorLocalServer

@Published private(set) var blockTypes: [EditorBlockType] = []
@Published private(set) var rawBlockTypesResponseData: Data?
Expand All @@ -15,6 +16,11 @@ public final class EditorService {

public init(client: EditorNetworkingClient) {
self.client = client
self.server = EditorLocalServer()
}

func run() throws {
try server.run()
}

/// Prefetches the settings used by the editor.
Expand Down
18 changes: 14 additions & 4 deletions Sources/GutenbergKit/Sources/EditorViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@ public final class EditorViewController: UIViewController, GutenbergEditorContro
//
// }.store(in: &cancellables)

loadEditor()
do {
try loadEditor()
} catch {
delegate?.editor(self, didEncounterCriticalError: error)
}
}

// TODO: move
Expand All @@ -106,9 +110,15 @@ public final class EditorViewController: UIViewController, GutenbergEditorContro
}
}

private func loadEditor() {
let reactAppURL = Bundle.module.url(forResource: "index", withExtension: "html", subdirectory: "Gutenberg")!
webView.loadFileURL(reactAppURL, allowingReadAccessTo: Bundle.module.resourceURL!)
private func loadEditor() throws {
try service.run()

// FIXME: for some reason it adds 2 seconds delay
let localAppURL = URL(string: "http://localhost:\(EditorConstants.port)/\(EditorConstants.gutenbergLocalPath)/index.html")!
webView.load(URLRequest(url: localAppURL))

// let reactAppURL = Bundle.module.url(forResource: "index", withExtension: "html", subdirectory: "Gutenberg")!
// webView.loadFileURL(reactAppURL, allowingReadAccessTo: Bundle.module.resourceURL!)
}

// MARK: - Public API
Expand Down