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

feat: Implement offline SPX project compilation and web-based execution #6

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,7 @@

# Dependency directories (remove the comment below to include it)
# vendor/

.vscode/
.idea/
*.wasm
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,8 @@ generate token <https://github.com/settings/tokens>

```
$ ispx -ghtoken your_github_api_token github.com/goplus/FlappyCalf
```
```

### run spx offline demo

see [Offline SPX Project](offline_spx/README.md)
54 changes: 54 additions & 0 deletions offline_spx/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Offline SPX Project

## Introduction

This project allows users to compile SPX projects offline by uploading folders and then run and view them on the Web.
Users can upload the entire project folder, view the file structure and content, and run the project directly in the
browser.

index.html is as follows:

![index](./image/index.png)

## Features

- Folder Upload: Users can upload the entire SPX project folder.
- File Structure Viewing: After uploading, users can browse the tree structure of the folder.
- File Content Viewing: Users can view the content of each file uploaded.
- Online Execution: Users can run the SPX project in the web browser and view the results.

## How to Use

### Folder Upload

![folder_upload](./image/folder_upload.png)

- Click the "Select Folder" button.
- Choose your SPX project folder and upload it.

### View File Structure and Content

- After a successful upload, the file structure will be displayed on the page in a tree format.

![show_file_structure](./image/show_file_structure.png)
- Enter the file's project path (starting with the project name) to view the content in the respective area.

![file_content](./image/file_content.png)

### Run Project Online

![online_game](./image/online_game.png)

- Ensure that your project files include all necessary files for execution.
- Input the project name
- Click the "play project" button to start the project in the browser.
- The execution results will be displayed in the designated output area.

## Installation and Running

```sh
./build.sh
cp $GOROOT/misc/wasm/wasm_exec.js ./
```

run http server
2 changes: 2 additions & 0 deletions offline_spx/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/sh
GOOS=js GOARCH=wasm go build -tags canvas -o main.wasm main.go
43 changes: 43 additions & 0 deletions offline_spx/ifs/dir.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package ifs

import (
"bytes"
"fmt"
"io"
"io/ioutil"
)

// IndexedDBDir is the implementation of a fs.Dir
type IndexedDBDir struct {
assert string
}

func NewIndexedDBDir(assert string) *IndexedDBDir {
return &IndexedDBDir{
assert: assert,
}
}

// Open opens a file
func (d *IndexedDBDir) Open(file string) (ret io.ReadCloser, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("IndexedDBDir.Open %s panic %s", file, r)
}
}()

file = d.assert + "/" + file

content, err := readFileFromIndexedDB(file)
if err != nil {
err = fmt.Errorf("error reading file from IndexedDB: %w", err)
}
ret = ioutil.NopCloser(bytes.NewReader(content))
return
}

// Close closes the directory (in this implementation, this method does nothing)
func (d *IndexedDBDir) Close() error {
// In actual applications, you may need to perform cleanup operations
return nil
}
32 changes: 32 additions & 0 deletions offline_spx/ifs/direntry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package ifs

import (
"io/fs"
"os"
"time"
)

// IndexedDBDirEntry is the implementation of a fs.DirEntry
type IndexedDBDirEntry struct {
Path string
IsDirectory bool
Size int64
ModTime time.Time
}

func (e IndexedDBDirEntry) Name() string { return e.Path }
func (e IndexedDBDirEntry) IsDir() bool { return e.IsDirectory }
func (e IndexedDBDirEntry) Type() fs.FileMode {
if e.IsDir() {
return os.ModeDir
}
return 0 // file
}
func (e IndexedDBDirEntry) Info() (fs.FileInfo, error) {
return IndexedDBFileInfo{
name: e.Path,
size: e.Size,
modTime: e.ModTime,
isDir: e.IsDirectory,
}, nil
}
26 changes: 26 additions & 0 deletions offline_spx/ifs/fileinfo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package ifs

import (
"os"
"time"
)

// IndexedDBFileInfo is the implementation of an os.FileInfo
type IndexedDBFileInfo struct {
name string
size int64
modTime time.Time
isDir bool
}

func (fi IndexedDBFileInfo) Name() string { return fi.name }
func (fi IndexedDBFileInfo) Size() int64 { return fi.size }
func (fi IndexedDBFileInfo) Mode() os.FileMode {
if fi.isDir {
return os.ModeDir
}
return 0
}
func (fi IndexedDBFileInfo) ModTime() time.Time { return fi.modTime }
func (fi IndexedDBFileInfo) IsDir() bool { return fi.isDir }
func (fi IndexedDBFileInfo) Sys() interface{} { return nil }
74 changes: 74 additions & 0 deletions offline_spx/ifs/filesystem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package ifs

import (
"fmt"
"io/fs"
"path"
"strings"
)

// IndexedDBFileSystem is the implementation of a fsx.FileSystem
type IndexedDBFileSystem struct{}

func NewIndexedDBFileSystem() *IndexedDBFileSystem {
return &IndexedDBFileSystem{}
}

// ReadDir Read directory contents
func (IndexedDBFileSystem) ReadDir(dirname string) (ret []fs.DirEntry, err error) {
dirname = path.Clean(dirname)
if dirname != "." && !strings.HasSuffix(dirname, "/") {
dirname += "/"
}

uniqueEntries := make(map[string]bool)

filesList, err := getFilesStartingWith(dirname)
if err != nil {
err = fmt.Errorf("error getting files starting with %s: %w", dirname, err)
return
}

for _, filePath := range filesList {
// Get relative path
relativePath := strings.TrimPrefix(filePath, dirname)

// Split path to get possible direct subdirectories or files
splitPath := strings.Split(relativePath, "/")
if len(splitPath) > 0 {
entry := splitPath[0]
if _, exists := uniqueEntries[entry]; !exists {
isDir := len(splitPath) > 1 // If the length after splitting the path is greater than 1, it is a directory
fileProperties, err := getFileProperties(filePath)
if err != nil {
return nil, err
}

ret = append(ret, IndexedDBDirEntry{
Path: entry,
IsDirectory: isDir,
Size: fileProperties.Size,
ModTime: fileProperties.LastModified,
})
uniqueEntries[entry] = true
}
}

}

return
}

// ReadFile Read file contents
func (IndexedDBFileSystem) ReadFile(filename string) (ret []byte, err error) {
ret, err = readFileFromIndexedDB(filename)
if err != nil {
err = fmt.Errorf("error reading file from IndexedDB: %w", err)
}
return
}

// Join Connect path elements
func (IndexedDBFileSystem) Join(elem ...string) string {
return path.Join(elem...)
}
100 changes: 100 additions & 0 deletions offline_spx/ifs/filesystem.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// configuration of IndexedDB
const dbName = 'myDatabase';
const dbVersion = 2;
const storeName = 'files';

let db;
let request = indexedDB.open(dbName, dbVersion);

request.onupgradeneeded = function (event) {
let db = event.target.result;
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName, { keyPath: 'path' });
}
};

request.onsuccess = function (event) {
db = event.target.result;
};

request.onerror = function (event) {
console.error('Database error:', event.target.error);
};

// Read the contents of the specified file
function readFileFromIndexedDB(filePath) {
return new Promise((resolve, reject) => {
const transaction = db.transaction([storeName], 'readonly');
const store = transaction.objectStore(storeName);
const request = store.get(filePath);

request.onsuccess = function (event) {
const fileData = event.target.result;
if (fileData && fileData.content) {
resolve(new Uint8Array(fileData.content)); // 假设 content 是 ArrayBuffer
} else {
reject('File not found');
}
};

request.onerror = function (event) {
reject('Error reading file from IndexedDB: ' + event.target.errorCode);
};
});
}

// Get the size and last modified date of the specified file
function getFileProperties(filePath) {
return new Promise((resolve, reject) => {
const transaction = db.transaction([storeName], 'readonly');
const store = transaction.objectStore(storeName);
const request = store.get(filePath);

request.onsuccess = function (event) {
const fileData = event.target.result;
if (fileData) {
resolve({
size: fileData.size,
lastModified: fileData.lastModified
});
} else {
reject('File not found');
}
};

request.onerror = function (event) {
reject('Error querying file properties from IndexedDB: ' + event.target.errorCode);
};
});
}

// Get all files in the specified directory
function getFilesStartingWith(dirname) {
return new Promise((resolve, reject) => {
const transaction = db.transaction([storeName], 'readonly');
const store = transaction.objectStore(storeName);
const request = store.getAll();
const files = [];

request.onsuccess = function (event) {
const allFiles = event.target.result;
allFiles.forEach(file => {
if (file.path.startsWith(dirname)) {
files.push(file.path);
}
});
resolve(files);
};

request.onerror = function (event) {
reject('Error querying IndexedDB: ' + event.target.errorCode);
};
});
}



// Expose these functions to the global object
window.readFileFromIndexedDB = readFileFromIndexedDB;
window.getFileProperties = getFileProperties;
window.getFilesStartingWith = getFilesStartingWith;
Loading