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

fix: sub routing for apps #66

Merged
merged 3 commits into from
Mar 7, 2023
Merged
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
2 changes: 1 addition & 1 deletion backend/internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ func (server *Server) Run() error {

// TODO: Move the compiler routes to a separate file/into compiler
// Apps
server.router.GET("/api/app-resources/:id/base.html", func(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
server.router.GET("/api/app-resources/:id/base/*filepath", func(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
id := params.ByName("id")
res.Header().Set("Content-Type", "text/html; charset=utf-8")

Expand Down
60 changes: 41 additions & 19 deletions backend/internal/server/web_prod.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"strings"

"github.com/julienschmidt/httprouter"
"robinplatform.dev/internal/log"
)

//go:generate rm -rf web
Expand All @@ -32,13 +33,27 @@ func (server *Server) loadRoutes() {
return err
}
if !entry.IsDir() {
route := strings.TrimPrefix(assetPath, "web")
routes := []string{strings.TrimPrefix(assetPath, "web")}

if strings.HasSuffix(assetPath, ".html") {
route = regexp.MustCompile(`\[([^\]]+)\]`).ReplaceAllString(route, ":$1")
route = strings.TrimSuffix(route, ".html")
wildcardStartIndex := strings.Index(routes[0], "[[...")
if wildcardStartIndex != -1 {
wildcardName := routes[0][wildcardStartIndex+5:]
wildcardName = wildcardName[:len(wildcardName)-7]

routes = []string{
routes[0][:wildcardStartIndex-1],
routes[0][:wildcardStartIndex] + "*" + wildcardName,
}
}

for idx := range routes {
routes[idx] = regexp.MustCompile(`\[([^\]]+)\]`).ReplaceAllString(routes[idx], ":$1")
routes[idx] = strings.TrimSuffix(routes[idx], ".html")

if strings.HasSuffix(route, "/index") {
route = strings.TrimSuffix(route, "index")
if strings.HasSuffix(routes[0], "/index") {
routes[idx] = strings.TrimSuffix(routes[idx], "index")
}
}
}

Expand All @@ -47,20 +62,27 @@ func (server *Server) loadRoutes() {
mimetype = "text/html"
}

router.GET(route, func(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
file, err := nextBuild.Open(assetPath)
if os.IsNotExist(err) {
// TODO: serve 404 page
res.WriteHeader(404)
res.Write([]byte("404 - Not Found"))
} else if err != nil {
res.WriteHeader(500)
res.Write([]byte(err.Error()))
} else {
res.Header().Set("Content-Type", mimetype)
io.Copy(res, file)
}
})
for _, route := range routes {
logger.Debug("Registering route", log.Ctx{
"route": route,
"path": assetPath,
})

router.GET(route, func(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
file, err := nextBuild.Open(assetPath)
if os.IsNotExist(err) {
// TODO: serve 404 page
res.WriteHeader(404)
res.Write([]byte("404 - Not Found"))
} else if err != nil {
res.WriteHeader(500)
res.Write([]byte(err.Error()))
} else {
res.Header().Set("Content-Type", mimetype)
io.Copy(res, file)
}
})
}
}
return nil
})
Expand Down
10 changes: 9 additions & 1 deletion backend/robin.servers.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
{
"devServers": {
"cli": "go run github.com/mitranim/gow -e 'go,tsx,html' run ./cmd/cli start"
"cli": {
"healthChecks": [
{
"type": "tcp",
"port": 9010
}
],
"command": "go run github.com/mitranim/gow -e 'go,tsx,html' run ./cmd/cli start"
}
}
}
11 changes: 9 additions & 2 deletions frontend/components/AppWindow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ function AppWindowContent({ id, setTitle }: AppWindowProps) {

const iframeRef = React.useRef<HTMLIFrameElement | null>(null);
const [error, setError] = React.useState<string | null>(null);
const subRoute = React.useMemo(
() =>
router.isReady
? router.asPath.substring('/app/'.length + id.length)
: null,
[router.isReady, router.asPath, id],
);

React.useEffect(() => {
const onMessage = (message: MessageEvent) => {
Expand Down Expand Up @@ -128,7 +135,7 @@ function AppWindowContent({ id, setTitle }: AppWindowProps) {
<RestartAppButton />

<Link
href={`/app/${id}/settings`}
href={`/app-settings/${id}`}
className={cx(
styles.toolbarButton,
'robin-rounded robin-bg-dark-purple',
Expand All @@ -143,7 +150,7 @@ function AppWindowContent({ id, setTitle }: AppWindowProps) {

<iframe
ref={iframeRef}
src={`http://localhost:9010/api/app-resources/${id}/base.html`}
src={`http://localhost:9010/api/app-resources/${id}/base${subRoute}`}
style={{ border: '0', flexGrow: 1, width: '100%', height: '100%' }}
/>
</>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { useRouter } from 'next/router';
import { AppToolbar } from '../../../components/AppToolbar';
import { Settings } from '../../../components/Settings';
import { AppToolbar } from '../../components/AppToolbar';
import { Settings } from '../../components/Settings';
import { z } from 'zod';
import { useRpcMutation, useRpcQuery } from '../../../hooks/useRpcQuery';
import { Button } from '../../../components/Button';
import { useRpcMutation, useRpcQuery } from '../../hooks/useRpcQuery';
import { Button } from '../../components/Button';
import { ArrowLeftIcon } from '@primer/octicons-react';
import { toast } from 'react-hot-toast';
import { Alert } from '../../../components/Alert';
import { Spinner } from '../../../components/Spinner';
import { Alert } from '../../components/Alert';
import { Spinner } from '../../components/Spinner';
import { useQueryClient } from '@tanstack/react-query';
import Head from 'next/head';

Expand Down