feat: component viewer (#781)

* wip: component viewer

* feat: get component status from component viewer

* fix: remove unused property

* chore(deps): snjs 2.29.0

* fix: import location
This commit is contained in:
Mo
2021-12-24 10:41:02 -06:00
committed by GitHub
parent 237cd91acd
commit ebdae31965
39 changed files with 874 additions and 1012 deletions

View File

@@ -5,11 +5,14 @@ interface IProps {
expiredDate: string;
componentName: string;
featureStatus: FeatureStatus;
reloadStatus: () => void;
manageSubscription: () => void;
}
const statusString = (featureStatus: FeatureStatus, expiredDate: string, componentName: string) => {
const statusString = (
featureStatus: FeatureStatus,
expiredDate: string,
componentName: string
) => {
switch (featureStatus) {
case FeatureStatus.InCurrentPlanButExpired:
return `Your subscription expired on ${expiredDate}`;
@@ -25,9 +28,8 @@ const statusString = (featureStatus: FeatureStatus, expiredDate: string, compone
export const IsExpired: FunctionalComponent<IProps> = ({
expiredDate,
featureStatus,
reloadStatus,
componentName,
manageSubscription
manageSubscription,
}) => {
return (
<div className={'sn-component'}>
@@ -50,11 +52,13 @@ export const IsExpired: FunctionalComponent<IProps> = ({
</div>
</div>
<div className={'right'}>
<div className={'sk-app-bar-item'} onClick={() => manageSubscription()}>
<button className={'sn-button small success'}>Manage Subscription</button>
</div>
<div className={'sk-app-bar-item'} onClick={() => reloadStatus()}>
<button className={'sn-button small info'}>Reload</button>
<div
className={'sk-app-bar-item'}
onClick={() => manageSubscription()}
>
<button className={'sn-button small success'}>
Manage Subscription
</button>
</div>
</div>
</div>

View File

@@ -1,14 +1,6 @@
import { FunctionalComponent } from 'preact';
interface IProps {
isReloading: boolean;
reloadStatus: () => void;
}
export const OfflineRestricted: FunctionalComponent<IProps> = ({
isReloading,
reloadStatus,
}) => {
export const OfflineRestricted: FunctionalComponent = () => {
return (
<div className={'sn-component'}>
<div className={'sk-panel static'}>
@@ -16,38 +8,29 @@ export const OfflineRestricted: FunctionalComponent<IProps> = ({
<div className={'sk-panel-section stretch'}>
<div className={'sk-panel-column'} />
<div className={'sk-h1 sk-bold'}>
You have restricted this component to be used offline only.
You have restricted this component to not use a hosted version.
</div>
<div className={'sk-subtitle'}>
Offline components are not available in the web application.
Locally-installed components are not available in the web
application.
</div>
<div className={'sk-panel-row'} />
<div className={'sk-panel-row'}>
<div className={'sk-panel-column'}>
<div className={'sk-p'}>You can either:</div>
<div className={'sk-p'}>
To continue, choose from the following options:
</div>
<ul>
<li className={'sk-p'}>
Enable the Hosted option for this component by opening
Enable the Hosted option for this component by opening the
Preferences {'>'} General {'>'} Advanced Settings menu and{' '}
toggling 'Use hosted when local is unavailable' under this
components's options. Then press Reload below.
component's options. Then press Reload.
</li>
<li className={'sk-p'}>Use the desktop application.</li>
</ul>
</div>
</div>
<div className={'sk-panel-row'}>
{isReloading ? (
<div className={'sk-spinner info small'} />
) : (
<button
className={'sn-button small info'}
onClick={() => reloadStatus()}
>
Reload
</button>
)}
</div>
</div>
</div>
</div>

View File

@@ -3,7 +3,9 @@ import {
FeatureStatus,
SNComponent,
dateToLocalizedString,
ApplicationEvent,
ComponentViewer,
ComponentViewerEvent,
ComponentViewerError,
} from '@standardnotes/snjs';
import { WebApplication } from '@/ui_models/application';
import { FunctionalComponent } from 'preact';
@@ -22,9 +24,9 @@ import { openSubscriptionDashboard } from '@/hooks/manageSubscription';
interface IProps {
application: WebApplication;
appState: AppState;
componentUuid: string;
componentViewer: ComponentViewer;
requestReload?: (viewer: ComponentViewer) => void;
onLoad?: (component: SNComponent) => void;
templateComponent?: SNComponent;
manualDealloc?: boolean;
}
@@ -34,10 +36,10 @@ interface IProps {
*/
const MaxLoadThreshold = 4000;
const VisibilityChangeKey = 'visibilitychange';
const avoidFlickerTimeout = 7;
const MSToWaitAfterIframeLoadToAvoidFlicker = 35;
export const ComponentView: FunctionalComponent<IProps> = observer(
({ application, onLoad, componentUuid, templateComponent }) => {
({ application, onLoad, componentViewer, requestReload }) => {
const iframeRef = useRef<HTMLIFrameElement>(null);
const excessiveLoadingTimeout = useRef<
ReturnType<typeof setTimeout> | undefined
@@ -45,44 +47,33 @@ export const ComponentView: FunctionalComponent<IProps> = observer(
const [hasIssueLoading, setHasIssueLoading] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [isReloading, setIsReloading] = useState(false);
const [component] = useState<SNComponent>(
application.findItem(componentUuid) as SNComponent
);
const [featureStatus, setFeatureStatus] = useState<FeatureStatus>(
application.getFeatureStatus(component.identifier)
componentViewer.getFeatureStatus()
);
const [isComponentValid, setIsComponentValid] = useState(true);
const [error, setError] = useState<
'offline-restricted' | 'url-missing' | undefined
>(undefined);
const [isDeprecated, setIsDeprecated] = useState(false);
const [error, setError] = useState<ComponentViewerError | undefined>(
undefined
);
const [deprecationMessage, setDeprecationMessage] = useState<
string | undefined
>(undefined);
const [isDeprecationMessageDismissed, setIsDeprecationMessageDismissed] =
useState(false);
const [didAttemptReload, setDidAttemptReload] = useState(false);
const [contentWindow, setContentWindow] = useState<Window | null>(null);
const component = componentViewer.component;
const manageSubscription = useCallback(() => {
openSubscriptionDashboard(application);
}, [application]);
const reloadIframe = () => {
setTimeout(() => {
setIsReloading(true);
setTimeout(() => {
setIsReloading(false);
});
});
};
useEffect(() => {
const loadTimeout = setTimeout(() => {
handleIframeTakingTooLongToLoad();
}, MaxLoadThreshold);
excessiveLoadingTimeout.current = loadTimeout;
return () => {
excessiveLoadingTimeout.current &&
clearTimeout(excessiveLoadingTimeout.current);
@@ -91,42 +82,25 @@ export const ComponentView: FunctionalComponent<IProps> = observer(
}, []);
const reloadValidityStatus = useCallback(() => {
const offlineRestricted =
component.offlineOnly && !isDesktopApplication();
const hasUrlError = (function () {
if (isDesktopApplication()) {
return !component.local_url && !component.hasValidHostedUrl();
} else {
return !component.hasValidHostedUrl();
}
})();
const readonlyState =
application.componentManager.getReadonlyStateForComponent(component);
if (!readonlyState.lockReadonly) {
application.componentManager.setReadonlyStateForComponent(
component,
featureStatus !== FeatureStatus.Entitled
);
setFeatureStatus(componentViewer.getFeatureStatus());
if (!componentViewer.lockReadonly) {
componentViewer.setReadonly(featureStatus !== FeatureStatus.Entitled);
}
setIsComponentValid(!offlineRestricted && !hasUrlError);
setIsComponentValid(componentViewer.shouldRender());
if (!isComponentValid) {
if (isLoading && !isComponentValid) {
setIsLoading(false);
}
if (offlineRestricted) {
setError('offline-restricted');
} else if (hasUrlError) {
setError('url-missing');
} else {
setError(undefined);
}
setIsDeprecated(component.isDeprecated);
setDeprecationMessage(component.package_info.deprecation_message);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
setError(componentViewer.getError());
setDeprecationMessage(component.deprecationMessage);
}, [
componentViewer,
component.deprecationMessage,
featureStatus,
isComponentValid,
isLoading,
]);
useEffect(() => {
reloadValidityStatus();
@@ -141,9 +115,9 @@ export const ComponentView: FunctionalComponent<IProps> = observer(
return;
}
if (hasIssueLoading) {
reloadIframe();
requestReload?.(componentViewer);
}
}, [hasIssueLoading]);
}, [hasIssueLoading, componentViewer, requestReload]);
const handleIframeTakingTooLongToLoad = useCallback(async () => {
setIsLoading(false);
@@ -151,188 +125,133 @@ export const ComponentView: FunctionalComponent<IProps> = observer(
if (!didAttemptReload) {
setDidAttemptReload(true);
reloadIframe();
requestReload?.(componentViewer);
} else {
document.addEventListener(VisibilityChangeKey, onVisibilityChange);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleIframeLoad = useCallback(async (iframe: HTMLIFrameElement) => {
let hasDesktopError = false;
const canAccessWindowOrigin = isDesktopApplication();
if (canAccessWindowOrigin) {
try {
const contentWindow = iframe.contentWindow as Window;
if (!contentWindow.origin || contentWindow.origin === 'null') {
hasDesktopError = true;
}
// eslint-disable-next-line no-empty
} catch (e) {}
}
excessiveLoadingTimeout.current &&
clearTimeout(excessiveLoadingTimeout.current);
setContentWindow(iframe.contentWindow);
setTimeout(() => {
setIsLoading(false);
setHasIssueLoading(hasDesktopError);
onLoad?.(component);
}, avoidFlickerTimeout);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (contentWindow) {
application.componentManager.registerComponentWindow(
component,
contentWindow
);
}
return () => {
application.componentManager.onComponentIframeDestroyed(component.uuid);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [contentWindow]);
}, [componentViewer, didAttemptReload, onVisibilityChange, requestReload]);
useEffect(() => {
if (!iframeRef.current) {
setContentWindow(null);
return;
}
iframeRef.current.onload = () => {
const iframe = application.componentManager.iframeForComponent(
component.uuid
);
if (iframe) {
setTimeout(() => {
handleIframeLoad(iframe);
});
const iframe = iframeRef.current as HTMLIFrameElement;
iframe.onload = () => {
const contentWindow = iframe.contentWindow as Window;
let hasDesktopError = false;
const canAccessWindowOrigin = isDesktopApplication();
if (canAccessWindowOrigin) {
try {
if (!contentWindow.origin || contentWindow.origin === 'null') {
hasDesktopError = true;
}
} catch (e) {
console.error(e);
}
}
excessiveLoadingTimeout.current &&
clearTimeout(excessiveLoadingTimeout.current);
componentViewer.setWindow(contentWindow);
setTimeout(() => {
setIsLoading(false);
setHasIssueLoading(hasDesktopError);
onLoad?.(component);
}, MSToWaitAfterIframeLoadToAvoidFlicker);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [iframeRef.current]);
}, [onLoad, component, componentViewer]);
useEffect(() => {
const removeFeaturesChangedObserver = application.addEventObserver(
async () => {
setFeatureStatus(application.getFeatureStatus(component.identifier));
},
ApplicationEvent.FeaturesUpdated
const removeFeaturesChangedObserver = componentViewer.addEventObserver(
(event) => {
if (event === ComponentViewerEvent.FeatureStatusUpdated) {
setFeatureStatus(componentViewer.getFeatureStatus());
}
}
);
return () => {
removeFeaturesChangedObserver();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}, [componentViewer]);
useEffect(() => {
if (!componentUuid) {
application.componentManager.addTemporaryTemplateComponent(
templateComponent as SNComponent
);
}
return () => {
if (templateComponent) {
/** componentManager can be destroyed already via locking */
application.componentManager?.removeTemporaryTemplateComponent(
templateComponent
);
const removeActionObserver = componentViewer.addActionObserver(
(action, data) => {
switch (action) {
case ComponentAction.KeyDown:
application.io.handleComponentKeyDown(data.keyboardModifier);
break;
case ComponentAction.KeyUp:
application.io.handleComponentKeyUp(data.keyboardModifier);
break;
case ComponentAction.Click:
application.getAppState().notes.setContextMenuOpen(false);
break;
default:
return;
}
}
document.removeEventListener(VisibilityChangeKey, onVisibilityChange);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
const unregisterComponentHandler =
application.componentManager.registerHandler({
identifier: 'component-view-' + Math.random(),
areas: [component.area],
actionHandler: (component, action, data) => {
switch (action) {
case ComponentAction.SetSize:
application.componentManager.handleSetSizeEvent(
component,
data
);
break;
case ComponentAction.KeyDown:
application.io.handleComponentKeyDown(data.keyboardModifier);
break;
case ComponentAction.KeyUp:
application.io.handleComponentKeyUp(data.keyboardModifier);
break;
case ComponentAction.Click:
application.getAppState().notes.setContextMenuOpen(false);
break;
default:
return;
}
},
});
);
return () => {
unregisterComponentHandler();
removeActionObserver();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [component]);
}, [componentViewer, application]);
useEffect(() => {
const unregisterDesktopObserver = application
.getDesktopService()
.registerUpdateObserver((component: SNComponent) => {
if (component.uuid === component.uuid && component.active) {
reloadIframe();
requestReload?.(componentViewer);
}
});
return () => {
unregisterDesktopObserver();
};
}, [application]);
}, [application, requestReload, componentViewer]);
return (
<>
{hasIssueLoading && (
<IssueOnLoading
componentName={component.name}
reloadIframe={reloadIframe}
reloadIframe={() => {
reloadValidityStatus(), requestReload?.(componentViewer);
}}
/>
)}
{featureStatus !== FeatureStatus.Entitled && (
<IsExpired
expiredDate={dateToLocalizedString(component.valid_until)}
reloadStatus={reloadValidityStatus}
featureStatus={featureStatus}
componentName={component.name}
manageSubscription={manageSubscription}
/>
)}
{isDeprecated && !isDeprecationMessageDismissed && (
{deprecationMessage && !isDeprecationMessageDismissed && (
<IsDeprecated
deprecationMessage={deprecationMessage}
dismissDeprecationMessage={dismissDeprecationMessage}
/>
)}
{error == 'offline-restricted' && (
<OfflineRestricted
isReloading={isReloading}
reloadStatus={reloadValidityStatus}
/>
{error === ComponentViewerError.OfflineRestricted && (
<OfflineRestricted />
)}
{error == 'url-missing' && (
{error === ComponentViewerError.MissingUrl && (
<UrlMissing componentName={component.name} />
)}
{component.uuid && !isReloading && isComponentValid && (
{component.uuid && isComponentValid && (
<iframe
ref={iframeRef}
data-component-id={component.uuid}
data-component-viewer-id={componentViewer.identifier}
frameBorder={0}
data-attr-id={`component-iframe-${component.uuid}`}
src={application.componentManager.urlForComponent(component) || ''}
sandbox="allow-scripts allow-top-navigation-by-user-activation allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-modals allow-forms allow-downloads"
>
@@ -347,7 +266,7 @@ export const ComponentView: FunctionalComponent<IProps> = observer(
export const ComponentViewDirective = toDirective<IProps>(ComponentView, {
onLoad: '=',
componentUuid: '=',
templateComponent: '=',
componentViewer: '=',
requestReload: '=',
manualDealloc: '=',
});