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

MAUI integration #1368

Draft
wants to merge 3 commits into
base: main
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/Framework/Framework/Configuration/DotvvmConfiguration.cs
Expand Up @@ -364,6 +364,13 @@ private static void RegisterResources(DotvvmConfiguration configuration)
debugName: "DotVVM.Framework.obj.javascript.root_spa_debug.dotvvm-root.js"),
dependencies: new[] { ResourceConstants.KnockoutJSResourceName },
module: true);
configuration.Resources.RegisterScript(ResourceConstants.DotvvmResourceName + ".internal-webview",
new EmbeddedResourceLocation(
typeof(DotvvmConfiguration).Assembly,
"DotVVM.Framework.obj.javascript.root_webview.dotvvm-root.js",
debugName: "DotVVM.Framework.obj.javascript.root_webview_debug.dotvvm-root.js"),
dependencies: new[] { ResourceConstants.KnockoutJSResourceName },
module: true);
configuration.Resources.Register(ResourceConstants.DotvvmResourceName,
new InlineScriptResource(@"", ResourceRenderPosition.Anywhere, defer: true) {
Dependencies = new[] { ResourceConstants.DotvvmResourceName + ".internal" }
Expand Down
17 changes: 16 additions & 1 deletion src/Framework/Framework/DotVVM.Framework.csproj
Expand Up @@ -26,6 +26,8 @@
<EmbeddedResource Include="obj/javascript/root-only-debug/dotvvm-root.js" />
<EmbeddedResource Include="obj/javascript/root-spa/dotvvm-root.js" />
<EmbeddedResource Include="obj/javascript/root-spa-debug/dotvvm-root.js" />
<EmbeddedResource Include="obj/javascript/root-webview/dotvvm-root.js" />
<EmbeddedResource Include="obj/javascript/root-webview-debug/dotvvm-root.js" />
<EmbeddedResource Include="Resources\Scripts\Globalize\globalize.min.js" />
<EmbeddedResource Include="Resources\Scripts\knockout-latest.js" />
<EmbeddedResource Include="Resources\Scripts\knockout-latest.debug.js" />
Expand Down Expand Up @@ -115,8 +117,21 @@
<TypescriptFile Include="Resources/Scripts/**/*.ts" />
</ItemGroup>

<ItemGroup>
<None Remove="Resources\Scripts\webview\webview.ts" />
</ItemGroup>

<ItemGroup>
<TypescriptFile Remove="Resources\Scripts\webview\messaging.ts" />
<TypescriptFile Remove="Resources\Scripts\webview\webview.ts" />
</ItemGroup>

<ItemGroup>
<Content Include="Resources\Scripts\webview\webview.ts" />
</ItemGroup>

<!-- BeforeBuild is ran for every target framework. However, unless its input files change, this target is skipped. -->
<Target Name="CompileJS" Inputs="@(TypescriptFile)" Outputs="obj/javascript/root-only/dotvvm-root.js;obj/javascript/root-only-debug/dotvvm-root.js;obj/javascript/root-spa/dotvvm-root.js;obj/javascript/root-spa-debug/dotvvm-root.js" BeforeTargets="DispatchToInnerBuilds;BeforeBuild">
<Target Name="CompileJS" Inputs="@(TypescriptFile)" Outputs="obj/javascript/root-only/dotvvm-root.js;obj/javascript/root-only-debug/dotvvm-root.js;obj/javascript/root-spa/dotvvm-root.js;obj/javascript/root-spa-debug/dotvvm-root.js;obj/javascript/root-webview/dotvvm-root.js;obj/javascript/root-webview-debug/dotvvm-root.js" BeforeTargets="DispatchToInnerBuilds;BeforeBuild">

<PropertyGroup>
<EnvOverrides>NO_COLOR=1;FORCE_COLOR=0;TERM=dumb</EnvOverrides>
Expand Down
2 changes: 2 additions & 0 deletions src/Framework/Framework/Resources/Scripts/compileConstants.ts
@@ -1,6 +1,8 @@
declare var compileConstants : {
/** If the compiled bundle is for SPA applications */
isSpa: boolean,
/** If the compiled bundle is for WebView-hosted applications */
isWebview: boolean,
/** If the compiled bundle is unminified */
debug: boolean
};
15 changes: 12 additions & 3 deletions src/Framework/Framework/Resources/Scripts/dotvvm-base.ts
Expand Up @@ -16,6 +16,10 @@ type DotvvmCoreState = {
_viewModelCacheId?: string
_virtualDirectory: string
_initialUrl: string,
_routeName: string,
_routeParameters: {
[name: string]: any
},
_stateManager: StateManager<RootViewModel>
}

Expand Down Expand Up @@ -60,7 +64,8 @@ export function clearViewModelCache() {
delete getCoreState()._viewModelCache;
}
export function getCulture(): string { return getCoreState()._culture; }

export function getRouteName(): string { return getCoreState()._routeName; }
export function getRouteParameters(): { [name: string]: any } { return getCoreState()._routeParameters; }
export function getStateManager(): StateManager<RootViewModel> { return getCoreState()._stateManager }

let initialViewModelWrapper: any;
Expand All @@ -85,7 +90,9 @@ export function initCore(culture: string): void {
_culture: culture,
_initialUrl: thisViewModel.url,
_virtualDirectory: thisViewModel.virtualDirectory!,
_stateManager: manager
_stateManager: manager,
_routeName: thisViewModel.routeName,
_routeParameters: thisViewModel.routeParameters
}

// store cached viewmodel
Expand All @@ -106,7 +113,9 @@ export function initCore(culture: string): void {
_culture: currentCoreState!._culture,
_initialUrl: a.serverResponseObject.url,
_virtualDirectory: a.serverResponseObject.virtualDirectory!,
_stateManager: currentCoreState!._stateManager
_stateManager: currentCoreState!._stateManager,
_routeName: a.serverResponseObject.routeName,
_routeParameters: a.serverResponseObject.routeParameters
}
});
}
Expand Down
14 changes: 11 additions & 3 deletions src/Framework/Framework/Resources/Scripts/dotvvm-root.ts
@@ -1,4 +1,4 @@
import { initCore, getViewModel, getViewModelObservable, initBindings, getCulture, getState, getStateManager } from "./dotvvm-base"
import { initCore, getViewModel, getViewModelObservable, initBindings, getCulture, getState, getStateManager, getRouteName, getRouteParameters } from "./dotvvm-base"
import * as events from './events'
import * as spa from "./spa/spa"
import * as validation from './validation/validation'
Expand Down Expand Up @@ -30,6 +30,7 @@ import * as string from './utils/stringHelper'
import { StateManager } from "./state-manager"
import { DotvvmEvent } from "./events"
import * as dateTime from './utils/dateTimeHelper'
import * as webview from './webview/webview'

if (window["dotvvm"]) {
throw new Error('DotVVM is already loaded!')
Expand Down Expand Up @@ -86,6 +87,8 @@ const dotvvmExports = {
get viewModel() { return getViewModel() }
}
},
get routeName() { return getRouteName() },
get routeParameters() { return getRouteParameters() },
get state() { return getState() },
patchState(a: any) {
getStateManager().patchState(a)
Expand Down Expand Up @@ -136,13 +139,18 @@ if (compileConstants.isSpa) {
(dotvvmExports as any).isSpaReady = isSpaReady;
(dotvvmExports as any).handleSpaNavigation = handleSpaNavigation;
}

if (compileConstants.isWebview) {
(dotvvmExports as any).webview = webview;
}
if (compileConstants.debug) {
(dotvvmExports as any).debug = true
}

declare global {
const dotvvm: typeof dotvvmExports & {debug?: true, isSpaReady?: typeof isSpaReady, handleSpaNavigation?: typeof handleSpaNavigation};
const dotvvm: typeof dotvvmExports &
{ isSpaReady?: typeof isSpaReady, handleSpaNavigation?: typeof handleSpaNavigation } &
{ webview?: typeof webview } &
{ debug?: true };

interface Window {
dotvvm: typeof dotvvmExports
Expand Down
3 changes: 3 additions & 0 deletions src/Framework/Framework/Resources/Scripts/postback/http.ts
Expand Up @@ -3,12 +3,15 @@ import { DotvvmPostbackError } from '../shared-classes';
import { logInfoVerbose, logWarning } from '../utils/logging';
import { keys } from '../utils/objects';
import { addLeadingSlash, concatUrl } from '../utils/uri';
import { webMessageFetch } from '../webview/messaging';

export type WrappedResponse<T> = {
readonly result: T,
readonly response?: Response
}

const fetch = compileConstants.isWebview ? webMessageFetch : window.fetch;

export async function getJSON<T>(url: string, spaPlaceHolderUniqueId?: string, signal?: AbortSignal, additionalHeaders?: { [key: string]: string }): Promise<WrappedResponse<T>> {
const headers = new Headers();
headers.append('Accept', 'application/json');
Expand Down
2 changes: 1 addition & 1 deletion src/Framework/Framework/Resources/Scripts/spa/spa.ts
Expand Up @@ -14,7 +14,7 @@ export const isSpaReady = ko.observable(false);
export function init(): void {
const spaPlaceHolders = getSpaPlaceHolders();
if (spaPlaceHolders.length == 0) {
throw new Error("No SpaContentPlaceHolder control was found!");
return; // if there are no SPA placeholder, ignore the SPA plugin
}

window.addEventListener("hashchange", event => handleHashChangeWithHistory(spaPlaceHolders, false));
Expand Down
92 changes: 92 additions & 0 deletions src/Framework/Framework/Resources/Scripts/webview/messaging.ts
@@ -0,0 +1,92 @@
type ReceivedMessage = { messageId: number } &
(
{ action: "HttpRequest", body: string, headers: [{ Key: string, Value: string }], status: number }
);

const pendingRequests: { resolve: (result: any) => void, reject: (result: any) => void }[] = [];

// send messages
export function sendMessage(message: any) {
(window.external as any).sendMessage(message);
}

export async function sendMessageAndWaitForResponse<T>(message: any): Promise<T> {
message.id = pendingRequests.length;
const promise = new Promise<T>((resolve, reject) => {
pendingRequests[message.id] = { resolve, reject };
sendMessage(message);
});
return await promise;
}

// handle commands from the webview
(window.external as any).receiveMessage(async (json: any) => {

function handleCommand(message: ReceivedMessage) {
if (message.action === "HttpRequest") {
// handle incoming HTTP request responses
const promise = pendingRequests[message.messageId]

const headers = new Headers();
for (const h of message.headers) {
headers.append(h.Key, h.Value);
}
const response = new Response(message.body, { headers, status: message.status });
promise.resolve(response);
return;

} else {
// allow register custom message processors
for (const processor of messageProcessors) {
const result = processor(message);
if (typeof result !== "undefined") {
return result;
}
}
throw `Command ${message.action} not found!`;
}
}

const message = <ReceivedMessage>JSON.parse(json);
try {
const result = await handleCommand(message);
if (typeof result !== "undefined") {
sendMessage({
type: "HandlerCommand",
id: message.messageId,
result: JSON.stringify(result)
});
}
}
catch (err) {
sendMessage({
type: "HandlerCommand",
id: message.messageId,
errorMessage: JSON.stringify(err)
});
}
});

type MessageProcessor = (processor: { action: string }) => any;
const messageProcessors: MessageProcessor[] = [];

export function registerMessageProcessor(processor: MessageProcessor) {
messageProcessors.push(processor);
}

export async function webMessageFetch(url: string, init: RequestInit): Promise<Response> {
if (init.method?.toUpperCase() === "GET") {
return await window.fetch(url, init);
}

const headers: any = {};
(<Headers>init.headers)?.forEach((v, k) => headers[k] = v);

return await sendMessageAndWaitForResponse<Response>({
type: "HttpRequest",
url,
method: init.method || "GET",
headers: headers,
body: init.body as string
});
}
6 changes: 6 additions & 0 deletions src/Framework/Framework/Resources/Scripts/webview/webview.ts
@@ -0,0 +1,6 @@
import { sendMessage, registerMessageProcessor } from './messaging';

export {
sendMessage,
registerMessageProcessor
};
Expand Up @@ -149,6 +149,12 @@ public void BuildViewModel(IDotvvmRequestContext context, object? commandResult)
result["renderedResources"] = JArray.FromObject(context.ResourceManager.GetNamedResourcesInOrder().Select(r => r.Name));
}

if (context.Route != null)
{
result["routeName"] = context.Route.RouteName;
result["routeParameters"] = new JObject(context.Parameters.Select(p => new JProperty(p.Key, p.Value)).ToArray());
}

// TODO: do not send on postbacks
if (validationRules?.Count > 0) result["validationRules"] = validationRules;

Expand Down
23 changes: 13 additions & 10 deletions src/Framework/Framework/rollup.config.js
Expand Up @@ -8,7 +8,7 @@ const build = process.env.BUILD || "debug";
const production = build == "production";
const suffix = production ? "" : "-debug";

const config = ({ minify, input, output, spa }) => ({
const config = ({ minify, input, output, spa, webview }) => ({
input,

output: [
Expand All @@ -30,7 +30,8 @@ const config = ({ minify, input, output, spa }) => ({
commonjs(),
replace({
"compileConstants.isSpa": spa,
"compileConstants.debug": !minify,
"compileConstants.isWebview": webview,
"compileConstants.debug": !minify
}),

minify && terser({
Expand Down Expand Up @@ -82,23 +83,25 @@ const config = ({ minify, input, output, spa }) => ({
})

export default [
// config({ minify: production, input: ['./Resources/Scripts/dotvvm-root.ts', './Resources/Scripts/dotvvm-light.ts'], output: "default" }),
config({
minify: production,
input: ['./Resources/Scripts/dotvvm-root.ts'],
output: "root-only" + suffix,
spa: false
spa: false,
webview: false
}),
config({
minify: production,
input: ['./Resources/Scripts/dotvvm-root.ts'],
output: "root-spa" + suffix,
spa: true,
webview: false
}),
//config({
// minify: production,
// input: ['./Resources/Scripts/dotvvm-light.ts'],
// output: "root-light",
// spa: false
//})
config({
minify: production,
input: ['./Resources/Scripts/dotvvm-root.ts'],
output: "root-webview" + suffix,
spa: true,
webview: true
})
]