Skip to content

Commit

Permalink
feat: new DOM feature ForceResponsiveViewportFeature
Browse files Browse the repository at this point in the history
This feature will add a meta viewport element to the head element to
have consistent layout viewports across websites and content.
  • Loading branch information
jsamr committed Sep 25, 2020
1 parent f715b5f commit 25ed358
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
40 changes: 40 additions & 0 deletions packages/core/src/features/ForceResponsiveViewportFeature.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import script from './ForceResponsiveViewportFeature.webjs';
import { FeatureBuilder } from '../FeatureBuilder';
import type { FeatureConstructor } from '../Feature';

/**
* An object describing customization for the fix viewport feature.
*
* @public
*/
export interface ForceResponsiveViewportOptions {
/**
* Maximum pinch-zoom scale.
*
* @defaultvalue 1
*/
maxScale?: number;
}

const defaultOptions: ForceResponsiveViewportOptions = {
maxScale: 1
};

/**
* This feature inserts or replace a `<meta name="viewport" content="width=device-width" />`
* tag in the head to guarantee that the layout viewport will match
* device-width (hence, “responsive”). Minimum scale is locked to 1, but you
* can customize maximum scale to allow pinch-zoom gestures.
* See {@link https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag | MDN—Using the viewport meta tag ...}
*
* @public
*/
export const ForceResponsiveViewportFeature: FeatureConstructor<ForceResponsiveViewportOptions> = new FeatureBuilder(
{
script,
defaultOptions,
className: 'ForceResponsiveViewportFeature',
featureIdentifier:
'org.formidable-webview/webshell.force-responsive-viewport'
}
).build();
23 changes: 23 additions & 0 deletions packages/core/src/features/ForceResponsiveViewportFeature.webjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
function ForceResponsiveViewportFeature(context) {
var options = context.options || {};
var maxScale = options.maxScale || 1;
var metaViewportContent =
'width=device-width, ' +
'initial-scale=1, ' +
'minimum-scale=1, ' +
'maximum-scale=' +
maxScale;
var metaElements = document.getElementsByTagName('meta');
Array.prototype.forEach.call(metaElements, function (elem) {
elem.name === 'viewport' && elem.parentNode.removeChild(elem);
});
var metaViewport = document.createElement('meta');
metaViewport.setAttribute('name', 'viewport');
metaViewport.setAttribute('content', metaViewportContent);
var head = document.getElementsByTagName('head')[0];
if (!head) {
head = document.createElement('head');
document.documentElement.appendChild(head);
}
head.appendChild(metaViewport);
}

0 comments on commit 25ed358

Please sign in to comment.