Skip to content

Commit

Permalink
feat!: serve offline-stub.html
Browse files Browse the repository at this point in the history
`/offline-stub.html` returns either user-provided (via @pwa(offliePath) or the default
generated offline page.
  • Loading branch information
Johannes Eriksson committed Mar 25, 2021
1 parent 2b9d1cc commit 27ec0b0
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 131 deletions.
19 changes: 14 additions & 5 deletions flow-client/src/main/resources/META-INF/resources/frontend/Flow.ts
Expand Up @@ -37,9 +37,14 @@ interface FlowRoot {
$server: any;
}

export interface Resolver {
baseUrl: string;
}

export interface NavigationParameters {
pathname: string;
search: string;
resolver?: Resolver;
}

export interface PreventCommands {
Expand Down Expand Up @@ -141,6 +146,8 @@ export class Flow {
// Store last action pathname so as we can check it in events
this.pathname = params.pathname;

const baseUrl = params.resolver ? params.resolver!.baseUrl : '/';

if ($wnd.Vaadin.connectionState.online) {
// @ts-ignore
try {
Expand All @@ -149,14 +156,14 @@ export class Flow {
if (error instanceof FlowUiInitializationError) {
// error initializing Flow: assume connection lost
$wnd.Vaadin.connectionState.state = ConnectionState.CONNECTION_LOST;
return this.offlineStubAction();
return this.offlineStubAction(baseUrl);
} else {
throw error;
}
}
} else {
// insert an offline stub
return this.offlineStubAction();
return this.offlineStubAction(baseUrl);
}

// When an action happens, navigation will be resolved `onBeforeEnter`
Expand Down Expand Up @@ -394,9 +401,11 @@ export class Flow {
});
}

private async offlineStubAction() {
await import('./OfflineStub');
const offlineStub = document.createElement('vaadin-offline-stub') as HTMLRouterContainer;
private async offlineStubAction(baseUrl: string) {
const offlineStub = document.createElement('iframe') as HTMLRouterContainer;
const offlineStubPath = baseUrl + (baseUrl.endsWith('/') ? '' : ' /') + 'offline-stub.html';
offlineStub.setAttribute('src', offlineStubPath);
offlineStub.setAttribute('style', 'width: 100%; height: 100%; border: 0');
this.response = undefined;

let onlineListener: ConnectionStateChangeListener | undefined;
Expand Down

This file was deleted.

8 changes: 4 additions & 4 deletions flow-client/src/test/frontend/FlowTests.ts
Expand Up @@ -19,8 +19,6 @@ const flowRoot = window.document.body as any;

const stubVaadinPushSrc = '/src/test/frontend/stubVaadinPush.js';

const OFFLINE_STUB_NAME = 'vaadin-offline-stub';

// A `changes` array that adds a div with 'Foo' text to body
const changesResponse = `[
{
Expand Down Expand Up @@ -655,7 +653,8 @@ suite("Flow", () => {
search: ''
};
const view = await route.action(params);
assert.equal(view.localName, OFFLINE_STUB_NAME);
assert.equal(view.localName, 'iframe');
assert.equal(view.getAttribute('src'), '/offline-stub.html');

// @ts-ignore
let onBeforeEnterReturns = view.onBeforeEnter(params, {});
Expand All @@ -682,7 +681,8 @@ suite("Flow", () => {

const view = await route.action(params);
assert.isNotNull(view);
assert.equal(view.localName, OFFLINE_STUB_NAME);
assert.equal(view.localName, 'iframe');
assert.equal(view.getAttribute('src'), '/offline-stub.html');

assert.equal(indicator.getAttribute('style'), 'display: none');

Expand Down
18 changes: 12 additions & 6 deletions flow-server/src/main/java/com/vaadin/flow/server/PwaRegistry.java
Expand Up @@ -33,11 +33,14 @@
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.LoggerFactory;

import com.vaadin.flow.server.communication.PwaHandler;
import com.vaadin.flow.server.startup.ApplicationRouteRegistry;

import elemental.json.Json;
Expand Down Expand Up @@ -235,15 +238,18 @@ private String initializeRuntimeServiceWorker(
StringBuilder stringBuilder = new StringBuilder();

// List of icons for precache
List<String> filesToCache = getIcons().stream()
Collection<String> filesToCache = getIcons().stream()
.filter(PwaIcon::shouldBeCached).map(PwaIcon::getCacheFormat)
.collect(Collectors.toList());
.collect(Collectors.toCollection(LinkedHashSet::new));

// When offlinePath is in use, it is also an offline resource to
// When custom offlinePath is in use, it is also an offline resource to
// precache
if (pwaConfiguration.isOfflinePathEnabled()) {
filesToCache.add(offlinePageCache());
filesToCache.add(offlinePageCache(pwaConfiguration.getOfflinePath()));
}
// Offline stub to be shown within an <iframe> in the app shell
filesToCache
.add(offlinePageCache(PwaHandler.DEFAULT_OFFLINE_STUB_PATH));

// Add manifest to precache
filesToCache.add(manifestCache());
Expand Down Expand Up @@ -403,9 +409,9 @@ public String getRuntimeServiceWorkerJs() {
return runtimeServiceWorkerJs;
}

private String offlinePageCache() {
private String offlinePageCache(String offlinePath) {
return String.format(WORKBOX_CACHE_FORMAT,
pwaConfiguration.getOfflinePath(), offlineHash);
offlinePath, offlineHash);
}

private String manifestCache() {
Expand Down
Expand Up @@ -18,7 +18,9 @@
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.vaadin.flow.function.SerializableSupplier;
Expand All @@ -43,6 +45,7 @@
*/
public class PwaHandler implements RequestHandler {
public static final String SW_RUNTIME_PRECACHE_PATH = "/sw-runtime-resources-precache.js";
public static final String DEFAULT_OFFLINE_STUB_PATH = "offline-stub.html";

private final Map<String, RequestHandler> requestHandlerMap = new HashMap<>();
private final SerializableSupplier<PwaRegistry> pwaRegistryGetter;
Expand Down Expand Up @@ -79,17 +82,22 @@ private void init(PwaRegistry pwaRegistry) {
});
}

// Assume that offline page and offline stub (for display within app)
// are the same. This may change in the future.
List<String> offlinePaths = new ArrayList<>();
if (pwaRegistry.getPwaConfiguration().isOfflinePathEnabled()) {
// Offline page handling
requestHandlerMap.put(
pwaRegistry.getPwaConfiguration().relOfflinePath(),
(session, request, response) -> {
response.setContentType("text/html");
try (PrintWriter writer = response.getWriter()) {
writer.write(pwaRegistry.getOfflineHtml());
}
return true;
});
offlinePaths
.add(pwaRegistry.getPwaConfiguration().relOfflinePath());
}
offlinePaths.add("/" + DEFAULT_OFFLINE_STUB_PATH);
for (String offlinePath : offlinePaths) {
requestHandlerMap.put(offlinePath, (session, request, response) -> {
response.setContentType("text/html");
try (PrintWriter writer = response.getWriter()) {
writer.write(pwaRegistry.getOfflineHtml());
}
return true;
});
}

// manifest.webmanifest handling
Expand Down
Expand Up @@ -228,14 +228,11 @@ public void offlineTsView_navigateToServerView_offlineStubShown()
try {
$("main-view").first().$("a").id("menu-hello").click();

waitForElementPresent(By.tagName("vaadin-offline-stub"));
waitForElementPresent(By.tagName("iframe"));
WebElement offlineStub = findElement(
By.tagName("vaadin-offline-stub"));

Assert.assertFalse(
"vaadin-offline-stub shadow root expected to contain an element with class offline",
findInShadowRoot(offlineStub, By.className("offline"))
.isEmpty());
By.tagName("iframe"));
driver.switchTo().frame(offlineStub);
Assert.assertNotNull(findElement(By.className("offline")));
} finally {
setConnectionType(NetworkConnection.ConnectionType.ALL);
}
Expand All @@ -252,14 +249,11 @@ public void offlineServerView_navigateToServerView_offlineStubShown()
try {
$("main-view").first().$("a").id("menu-hello").click();

waitForElementPresent(By.tagName("vaadin-offline-stub"));
waitForElementPresent(By.tagName("iframe"));
WebElement offlineStub = findElement(
By.tagName("vaadin-offline-stub"));

Assert.assertFalse(
"vaadin-offline-stub shadow root expected to contain an element with class offline",
findInShadowRoot(offlineStub, By.className("offline"))
.isEmpty());
By.tagName("iframe"));
driver.switchTo().frame(offlineStub);
Assert.assertNotNull(findElement(By.className("offline")));
} finally {
setConnectionType(NetworkConnection.ConnectionType.ALL);
}
Expand All @@ -274,11 +268,11 @@ public void offlineStub_backOnline_stubRemoved_serverViewShown()
setConnectionType(NetworkConnection.ConnectionType.AIRPLANE_MODE);
try {
$("main-view").first().$("a").id("menu-hello").click();
waitForElementPresent(By.tagName("vaadin-offline-stub"));
waitForElementPresent(By.tagName("iframe"));

setConnectionType(NetworkConnection.ConnectionType.ALL);

waitForElementNotPresent(By.tagName("vaadin-offline-stub"));
waitForElementNotPresent(By.tagName("iframe"));
Assert.assertNotNull(findElement(By.id(NAVIGATE_ABOUT)));
} finally {
setConnectionType(NetworkConnection.ConnectionType.ALL);
Expand Down

0 comments on commit 27ec0b0

Please sign in to comment.