Code Monkey home page Code Monkey logo

box-content-preview's Introduction

Project Status Mergify Status Styled With Prettier build status version npm version

The Box Content Preview library allows developers to easily embed high quality and interactive previews of Box files in desktop and mobile web applications. The JavaScript library fetches information about the file and its converted representations through the Box API, chooses the appropriate viewer for the file type, dynamically loads the necessary static assets and file representations, and finally renders the file. Box Content Preview also allows previews of multiple files to be loaded in the same container and exposes arrows to navigate between those files.

This library powers Preview in the main Box web application as well as the 'Get Embed Link' Box API endpoint.

Browser Support

  • Desktop Chrome, Firefox, Safari, Edge
  • Limited support for mobile web - previews will render but some controls may not work

Effective September 1, 2023, Box is discontinuing support for Internet Explorer 11 (IE 11) in Preview SDK. If your application requires IE 11 support, we recommend using the release versions of Preview SDK that were made available before August 15th, 2023. Our team will address any critical blocker and security issues specifically related to IE 11 until October 15, 2023. Following this date, we will no longer provide active support for IE 11 in Preview SDK.

We encourage all users to update their applications to utilize modern browsers for optimal performance, security, and compatibility with the latest features in Preview SDK.

Current Version

  • Version: v2.109.0
  • Locale: en-US

https://cdn01.boxcdn.net/platform/preview/2.109.0/en-US/preview.js https://cdn01.boxcdn.net/platform/preview/2.109.0/en-US/preview.css

Supported Locales

To use a different locale, replace en-US in the URLs above with any of the following supported locales.

en-AU, en-CA, en-GB, en-US, bn-IN, da-DK, de-DE, es-419, es-ES, fi-FI, fr-CA, fr-FR, hi-IN,it-IT, ja-JP, ko-KR, nb-NO, nl-NL, pl-PL, pt-BR, ru-RU, sv-SE, tr-TR, zh-CN, zh-TW

Supported File Types

Box Content Preview supports 100+ file types, including most document and image formats, HD video, 3D models, 360-degress images, and 360-degree videos. You can find the full list of supported file types on Box Support .

Usage

Including Preview as a library

You can self-host the Box Content Preview library or reference the versions available on Box's CDN.

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>Box Content Preview Demo</title>

    <!-- Latest version of Preview SDK for your locale -->
    <script src="https://cdn01.boxcdn.net/platform/preview/2.109.0/en-US/preview.js"></script>
    <link
      rel="stylesheet"
      href="https://cdn01.boxcdn.net/platform/preview/2.109.0/en-US/preview.css"
    />
  </head>
  <body>
    <div class="preview-container" style="height:400px;width:575px"></div>
    <script>
      var preview = new Box.Preview();
      preview.show('93392244621', 'EqFyi1Yq1tD9mxY8F38sxDfp73pFd7FP', {
        container: '.preview-container',
      });
    </script>
  </body>
</html>

Self-hosting

To self-host the Box Content Preview library, follow these steps:

  1. Either fork the repo and check out the version you want to host or download the specific version as a zip:
  1. Install dependencies and build the library with yarn install && yarn build:i18n && yarn:build:prod
  2. Self-host everything except for the dev folder from the /dist folder. You must not alter the folder structure and third-party needs to be in the same folder as 2.4.0. For example, if you self-host using a box-assets directory, these URLs must be accessible:
  • https://cdn.YOUR_SITE.com/box-assets/2.4.0/en-US/preview.js
  • https://cdn.YOUR_SITE.com/box-assets/third-party/text/0.114.0/papaparse.min.js
  • https://cdn.YOUR_SITE.com/box-assets/third-party/model3d/1.12.0/three.min.js

Importing Preview as a React Component

Preview can also be used as a React Component with the Box Element framework. The source code for the Content Preview Element wrapper is located at https://github.com/box/box-ui-elements/tree/master/src/components/ContentPreview. Please reference https://github.com/box/box-content-preview-demo for a minimal React application using this wrapper.

CORS (Cross-Origin Resource Sharing)

For security purposes, you must whitelist your application's HTTP origin, omitting any trailing slash, in the configuration section of the Developer Console. For example, CodePen's domain is whitelisted for the demo application below.

Screenshot of CORS whitelist

Demo

View a demo and sample code on CodePen - http://codepen.io/box-platform/pen/rmZdjm.

Initialization

var preview = new Box.Preview();
preview.show(fileId, accessToken, { options });

Where fileId is a string Box_File id and accessToken is a Box API access token.

Parameters & Options

var preview = new Box.Preview();
preview.show(fileId, accessToken, {
    container: '.preview-container',
    sharedLink: 'https://app.box.com/v/foo',
    sharedLinkPassword: 'bar',
    collection: [FILE_ID, '123', '234', ...],
    header: 'light',
    logoUrl: 'http://i.imgur.com/xh8j3E2.png',
    showAnnotations: true,
    showDownload: true
});
Parameter Description
fileId Box file ID
accessToken Either a string auth token or a token generator function, see below for details
Option Default Description
container document.body DOM node or selector where Preview should be placed
sharedLink Shared link URL
sharedLinkPassword Shared link password
collection List of file IDs to iterate over for previewing
header light String value of none or dark or light that controls header visibility and theme
logoUrl URL of logo to show in header
showAnnotations false Whether annotations and annotation controls are shown. This option will be overridden by viewer-specific annotation options if they are set. See Box Annotations for more details
showDownload false Whether download button is shown
autoFocus true Whether preview should focus itself when a file loads
useHotkeys true Whether hotkeys (keyboard shortcuts) are enabled
fixDependencies false Temporarily patches AMD to properly load Preview's dependencies. You may need to enable this if your project uses RequireJS
disableEventLog false Disables client-side preview event log. Previewing with this option enabled will not increment access stats (content access is still logged server-side)
fileOptions {} Mapping of file ID to file-level options. See the File Option table below for details
previewWMPref any String value of all, any, or none that sets how previews of watermarked files behave. See https://community.box.com/t5/Sharing-Content-with-Box/Watermarking-Files/ta-p/30766 for more information about watermarking and https://community.box.com/t5/Collaborate-By-Inviting-Others/Understanding-Collaborator-Permission-Levels/ta-p/144 for more information about permissions and collaboration roles.

all forces watermarked previews. If the file type supports watermarking, users with can_preview permissions will see a watermarked preview. If the file type cannot be watermarked, no preview is shown.

any is the default watermarking behavior in the Box Web Application. If the file type supports watermarking, users with can_preview permissions will see a watermarked preview. If the file type cannot be watermarked, users that have both can_preview and can_upload permissions will see a non-watermarked preview and no preview otherwise.

none forces non-watermarked previews. Users that have both can_preview and can_upload permissions will see a non-watermarked preview and no preview otherwise.
downloadWM false Whether the download of a watermarked file should be watermarked. This option does not affect non-watermarked files. If true, users will be able to download watermarked versions of supported file types as long as they have can_preview permissions (any collaboration role except for Uploader).
viewers {} Maps options to a valid viewer type
viewers.Document.disableFontFace viewers.Presentation.disableFontFace false By default, fonts are converted to OpenType fonts and loaded via font face rules. If disabled, fonts will be rendered using a built-in font renderer that constructs the glyphs with primitive path commands. Use this option at your own risk
responseInterceptor Function to intercept responses. For an example see https://codepen.io/box-platform/pen/jLdxEv
requestInterceptor Function to intercept requests. For an example see https://codepen.io/box-platform/pen/jLdxEv
File Option Default Description
fileVersionId (Current) File version ID to preview. This must be a valid non-current file version ID. Use Get Versions to fetch a list of file versions
startAt {} Options for starting location. See the Start At table below for details
Start At Description
unit Supported values: "pages" for documents; "seconds" for media
value Integer value specifying the start location

Example

This configuration will attempt to Preview a non-current version of the given file (a document, in this case) at a specific starting page:

var FILE_ID = '12345';
var TOKEN = 'abcdefg';
preview.show(FILE_ID, TOKEN, {
  fileOptions: {
    [FILE_ID]: {
      fileVersionId: '54321',
      startAt: {
        unit: 'pages',
        value: 2,
      },
    },
  },
});

Access Token

Box Content Preview needs an access token to make Box API calls. You can either get an access token from the token endpoint (https://developer.box.com/reference#token) or generate a developer token on your application management page (https://blog.box.com/blog/introducing-developer-tokens/).

If your application requires the end user to only be able to access a subset of the Content Preview functionality, you can use Token Exchange to appropriately downscope your App/Managed or Service Account token to a resulting token that has the desired set of permissions, and can thus, be securely passed to the end user client initializing the Content Preview.

Below are a set of new Box Element-specific scopes to go alongside Token Exchange. These allow developers to enable/disable UI controls on the Content Preview by configuring the appropriate scopes on the downscoped token. To learn more, see Special Scopes for Box Elements.

Wish to learn more about when, why and how you can use Token Exchange with the Content Preview? See our blueprint on Customizing Access for the Box Elements.

Base Scope

Scope Name What permissions does it grant?
base_preview Allows preview access to a file or files in a folder based on user/file/token permissions

Feature Scopes

Scope Name What permissions does it grant?
item_download Allows files/folders contents to be downloaded
annotation_view_self Allows user to view their own annotations
annotation_view_all Allows user to view all annotations on the file
annotation_edit Allows user to edit their own annotations (includes annotation_view_self)

Sample Scenarios

Scenario Scope Combinations
User wants basic preview functionality + download base_preview + item_download
User wants basic preview functionality + ability to edit own annotations base_preview + annotation_edit
User wants basic preview functionality + ability to view all annotations + ability to edit own annotations base_preview + annotation_view_all + annotation_edit

Token Generator Function

The Preview library optionally takes a token generator function instead of a string token. Using a token generator function allows you to dynamically determine what tokens Preview should use. For example, you can pass in different access tokens for each file or make sure your token is refreshed and valid before showing a preview. The token generator function should return a promise that resolves in either a single string token that applies to all of the files being previewed or a map of typed file IDs to access token for those files.

// Example token generator function that resolves to a single access token
var singleTokenGenerator = function() {
  return someApi.getToken().then(function(data) {
    return data.token;
  });
};

// Example token generator function that resolves to a map of tokens
var mapTokenGenerator = function() {
  return Promise.resolve({
    file_1234: 'some_token_abcd',
    file_2345: 'some_token_bcde',
  });
};

Viewers

The name of a viewer can be one of the following Document, Presentation, MP3, MP4, Dash, Image, Text, SWF, Image360, Video360, Model3d, CSV, Markdown. Call preview.getViewers() to get the list of possible viewers.

Additional Methods

preview.hide() hides the preview.

preview.updateCollection(/* Array[file ids] */ collection) updates the collection to navigate through. Assumes the currently visible file is part of this new collection.

preview.getCurrentCollection() returns the current collection if any.

preview.navigateLeft() shows previous file in the collection.

preview.navigateRight() shows next file in the collection.

preview.navigateToIndex(index) shows the specified index in the current collection.

preview.getCurrentFile() returns the current file being previewed if any. The file object structure is the same as returned by the Box API.

preview.getCurrentViewer() returns the current viewer instance. May be undefined if the viewer isn't ready yet and waiting on conversion to happen.

preview.enableViewers(/* String|Array[String] */ viewers) enables one or more viewers based on VIEWERNAME.

preview.disableViewers(/* String|Array[String] */ viewers) disables one or more viewers based on VIEWERNAME. Viewers can also be disabled by setting disabled: true on the specific viewer option inside options.

preview.enableHotkeys() enables hotkeys (keyboard shortcuts).

preview.disableHotkeys() disables hotkeys (keyboard shortcuts).

preview.print() prints the file if printable.

preview.download() downloads the file if downloadable.

preview.resize() resizes the current preview if applicable. This function only needs to be called when preview's viewport has changed while the window object has not. If the window is resizing, then preview will automatically resize itself.

preview.getViewers() lists all the available viewers.

preview.prefetchViewers(/* Array[String] */) prefetches static assets for the specified viewers that the browser can cache for performance benefits.

Events

The preview object exposes addListener and removeListener for binding to events. Event listeners should be bound before show() is called, otherwise events can be missed.

var preview = new Box.Preview();
var listener = (value) => {
    // Do something with value
};

// Attach listener before calling show otherwise events can be missed
preview.addListener(EVENTNAME, listener);

// Show a preview
preview.show(...);

// Remove listener when appropriate
preview.removeListener(EVENTNAME, listener);

EVENTNAME can be one of the following

  • viewer event will be fired when we have the viewer instance first available. This will be the same object that is also a property included in the load event. Preview fires this event before load so that clients can attach their listeners before the load event is fired.

  • load event will be fired on every preview load when show() is called or if inter-preview navigation occurs. The event data will contain:

  {
      error: 'message', // Error message if any error occurred while loading
      viewer: {...},    // Instance of the current viewer object if no error occurred
      metrics: {...},   // Performance metrics
      file: {...}       // Box file object with properties defined in file.js
  }
  • navigate event will be fired when navigation happens. The event includes the file ID of the file being navigated to, and this event will fire before load.

  • notification event will be fired when either the preview wrapper or one of the viewers wants to notify something like a warning or non-fatal error. The event data will contain:

  {
      message: 'message', // Message to show
      type: 'warning'    // 'warning', 'notice', or 'error'
  }
  • viewerevent Each viewer will fire its own sets of events. For example, the Image viewer will fire rotate or resize, etc. while other viewers may fire another set of events. The preview wrapper will also re-emit events at the preview level, with event data containing:
  {
      event: EVENTNAME,         // Event name
      data: DATA,               // Event data object
      viewerName: VIEWERNAME,   // Name of the viewer. See VIEWERNAME above
      fileId: fileId            // The file id
  }

Example event usage

preview.addListener('viewer', viewer => {
  viewer.addListener('rotate', () => {
    // Do something when a viewer rotates a preview
  });
});

preview.addListener('load', data => {
  var viewer = data.viewer;
  viewer.addListener('rotate', () => {
    // Do something when a viewer rotates a preview
  });
});

preview.addListener('viewerevent', data => {
  if (data.viewerName === 'Image') {
    if (data.event === 'rotate') {
      // Do something when an image preview is rotated
    }
  } else if (data.viewerName === 'Image360') {
    if (data.event === 'rotate') {
      // Do something different when a 360-degree image is rotated
    }
  } else {
  }
});

preview.addListener('rotate', data => {
  if (data.viewerName === 'Image') {
    // Do something when an image preview is rotated
  } else if (data.viewerName === 'Image360') {
    // Do something different when a 360-degree image is rotated
  } else {
  }
});

Development Setup

  1. Install latest LTS version of Node https://nodejs.org/en/download.
  2. Install yarn package manager https://yarnpkg.com/en/docs/install. Alternatively, you can replace any yarn command with npm.
  3. Fork the upstream repo https://github.com/box/box-content-preview.
  4. Clone your fork locally git clone [email protected]:[YOUR GITHUB USERNAME]/box-content-preview.git.
  5. Navigate to the cloned folder cd box-content-preview
  6. Add the upstream repo to your remotes git remote add upstream [email protected]:box/box-content-preview.git.
  7. Verify your remotes are properly set up git remote -v. You should pull updates from the Box repo upstream and push changes to your fork origin.
  8. Install dependencies yarn install
  9. Test your first build! yarn build
  10. To automatically rsync files after a Webpack build, add a build/rsync.json file with a location field. This file should look like:
{
    "location": "YOUR_DESIRED_RSYNC_LOCATION_HERE"
}

While Developing

Install the following plugins in your preferred editor

  • Editor Config (standardizes basic editor configuration)
  • ESLint (Javascript linting)
  • Prettier & Prettier - ESLint (Automatic Javascript formatting following ESLint config)
  • Stylelint (CSS linting)

Yarn commands

  • yarn build to generate resource bundles and JS webpack bundles.
  • yarn start to only generate JS webpack bundles on file changes.
  • yarn start:dev to launch a webpack-dev-server instance for local development.
  • yarn test to run all unit tests with Jest.
  • yarn test path/to/filename.js to run Jest only for that file and/or its related tests.
  • yarn test:watch to run all unit tests with Jest for debugging.
  • yarn test:watch path/to/src/filename.js to run Jest only for that file and/or its related tests for debugging.

For more script commands see package.json. Test coverage reports are available under reports/coverage.

Support

If you have any questions, please search our issues list to see if they have been previously answered. Report new issues here.

For general Box Platform, API, and Box Element questions, please visit our developer forum or contact us via one of our available support channels.

Copyright and License

Copyright 2016-present Box, Inc. All Rights Reserved.

Licensed under the Box Software License Agreement v.20170516. You may not use this file except in compliance with the License. You may obtain a copy of the License at

https://developer.box.com/docs/box-sdk-license

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

box-content-preview's People

Contributors

arturfrombox avatar bfoxx1906 avatar bhh1988 avatar boxmoji avatar chencodes avatar conradjchan avatar cweeii avatar dandemicco avatar dependabot[bot] avatar fsuarez-globant avatar ikerr avatar ivanthai avatar jchan106 avatar jeeyi avatar jstoffan avatar justinholdstock avatar karelee7 avatar machoper avatar manishph avatar marcoartaviaq avatar matiaslionel avatar mickr avatar miibond avatar minh-ng avatar patlm avatar pramodsum avatar priyajeet avatar swfree avatar tille avatar tonyjin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

box-content-preview's Issues

npm package

I'd like to use just preview.js via npm/yarn but without React. Do you have any plans to provide an npm package of just box-content-preview?

Media FullScreen but the icon is not correct

Please fill out the following template so we can reproduce and fix your issue as quickly as possible!

Environment:

  • Preview version: 1.12.0
  • Browser name and version: Chrome
  • Operating system and version: Mac OS X EI

Steps to reproduce the problem:

  1. Open a video to preview
    2.Enter FullScreen
    3.The class 'bp-enter-fullscreen-icon' should be change to 'bp-exit-fullscreen-icon'

What is the expected behavior? (Screenshots can be helpful here)
the icon should be change to 'bp-exit-fullscreen-icon'

What went wrong? (Screenshots can be helpful here)
qq20171019-154624 2xLink to application or sample code:

If relevant, link to file (or attach file here):

Is there a way to change the base request url?

Is there a way to change the base url?

For example, instead of https://api.box.com can I configure box-content-preview to make its requests to https://[MY-DOMAIN]/api/box ?

Let me explain my use case. We have a multi-tenant app. We allow tenants to bring their own domain. We've automated many of the setup steps, but one of the remaining steps is to login to the Box dev console and add the domain for CORS (AFAICT there isn't a way to programmatically update this list). The list is fairly long list and the process is error prone.

If I could route box-content-preview requests to my backend and proxy to https://api.box.com/2.0/ CORS would no longer be in play.

Markdown Preview ordered lists broken

Environment:

Steps to reproduce the problem:

  1. Create a new markdown file with extension .md
  2. In that markdown file create an ordered list, example:
A list of ordered items:

1. List item number one
1. List item number two
1. List item number three
   * Item 4
   * Item 5
  1. Preview the file in Box

What is the expected behavior? (Screenshots can be helpful here)
It is expected that the ordered list's list-style-type is decimal. Example:
image

What went wrong? (Screenshots can be helpful here)
The items of the ordered list are rendered as bullet points:
image

Link to application or sample code:
The reason for this behaviour seems to be the following entry in the preview.css file:
image

Can the list-style-type be changed to decimal for .bp-text-plain ol or maybe introduce a new class for the markdown context?

Problem loading a word document with MS Office Drawing object

Environment:

  • Preview version: 1.21.0
  • Browser name and version: Firefox 52.2.0
  • Operating system and version: Windows 7

Steps to reproduce the problem:

  1. Have a document in word with a drawing object.
  2. Display the document using box preview library.

What is the expected behavior? (Screenshots can be helpful here)

It should display the document.
Here an example of the drawing object with which is not loading the Content Preview.

ms office drawing object - word document

What went wrong? (Screenshots can be helpful here)

It displaying the following message

image

Something to mention is that document is available for download, but not displaying on preview.

Make FindBar Optional

Hello,

First off, thanks for your hard work on this JavaScript library. I wanted to know if making the find bar optional is something you'd consider? The reason for such a change is we're using this library to display a PDF that spans the height of the page rather than in a container element. In trying to achieve this, we removed the preview.css stylesheet from our code and overwrote a few styles. The last change involves disabling the "findBar" functionality since we need the scrollbar to happen along the page window and not the container element. I also noticed this library disables the browers native "search bar" which we'd be fine using if we could turn off the "findBar" functionality which disables it. So to do this, I've forked your library and made turning off the "findBar" optional -- default true. It would be used like:

preview.show(..., { useFindBar: false })

Here's a link to those code changes which I can turn into a pull request if this seems like a change you'd accept. Otherwise, let me know if there's an alternate route I can take to achieve this.

Thanks!
George

DocFindBar close triggers error

Environment:

  • Preview version: 1.28.0
  • Browser name and version: Chrome - 63.0.3239.132
  • Operating system and version: MacOS 10.11.6

Steps to reproduce the problem:

  1. cmd + f to get the find box
  2. Type in search.
  3. Clicking the "close" x

What is the expected behavior? (Screenshots can be helpful here)

What went wrong? (Screenshots can be helpful here)
Clicking the close x triggers a error in console "Cannot read property 'value' of undefined". The find box then does not go away.

Arrows and finding the search term is working properly. Only issue with the close button. I first started interacting with this at v1.24.0 and have seen this problem since then.

I am using the CDN browser link so don't know this for sure but I am guessing the error is thrown at line 389 of src/lib/viewers/doc/DocFindBar.js if thats any help.

image

Add caching (for offline mode)

Is it possible to load all HTML of a document so we can cache it and use offline on the device?
I see that slides of content preloading HTML dynamically.
Thanks

Base index.html has invalid markup

The base index.html file for the preview has invalid HTML markup. Their are two (and unclosed <body> tags.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Box Content Preview</title>
<link rel='stylesheet prefetch' href='https://cdn01.boxcdn.net/platform/preview/1.19.1/en-US/preview.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="preview-container"></div>
</body>
<script src='https://cdn.polyfill.io/v2/polyfill.js?features=es6,Intl'></script>
<script src='https://cdn01.boxcdn.net/platform/preview/1.19.1/en-US/preview.js'></script>



    <script  src="js/index.js"></script>




</body>

</html>

the height of container is not responsive as the height of windows?

Please fill out the following template so we can reproduce and fix your issue as quickly as possible!

Environment:

  • Preview version: v1.19.1
  • Browser name and version: Chrome, FireFox.
  • Operating system and version: Windows, Mac.

Steps to reproduce the problem:

  1. set the value of the container height to 100% (as the attachment).
  2. open the Content Preview page.
  3. you can see that the height of the content preview is only 246px height_of_content_preview.

What is the expected behavior? (Screenshots can be helpful here)
the height of the container be responsive as the height of the windows.

What went wrong? (Screenshots can be helpful here)
the height of the content preview is only 246px
height_of_content_preview

Link to application or sample code:
https://github.com/hearttang/box-ui-element/blob/master/templates/contentPreview.pug

If relevant, link to file (or attach file here):

hosting the SDK

[reposting from https://community.box.com/t5/Box-Developer-Forum/hosting-the-Content-Preview-SDK/m-p/49805 at the request of the moderator there]

The documentation at https://developer.box.com/docs/box-content-preview says

You can self-host the Preview UI Element or reference the versions hosted on the Box CDN.

but when I tried to use a copy I had saved locally, it failed on findScriptLocation. Apparently it depends on its name being hard-coded? And in the comment where it calls findScriptLocation, it refers to using that as a base for "all preview assets."

Does that mean there are other assets I'd have to host as well, in addition to the two files preview.js and .css?

Using our hosts would avoid adding exceptions to our security policy.

Safari: Switching tracks (video/audio) after buffering reaches the end freezes the video

Please fill out the following template so we can reproduce and fix your issue as quickly as possible!

Environment:

  • Preview version: All
  • Browser name and version: Safari 10.1.2 (have not tried other versions)
  • Operating system and version: Mac OSX 10.11.6

Steps to reproduce the problem:

  1. Play HD Video on Safari, and wait until the buffer is filled to the end of the video (or skip ahead to the end in order to do so).
  2. Initiate a change of stream (e.g. force HD via settings, or change audio track if there's multiple audio).

What is the expected behavior?
Video switches streams and continues

What went wrong?
The video freezes and never recovers.

This is a shaka-player bug. See shaka-project/shaka-player#992 . When this is fixed, we should try to upgrade, but we also need to watch out for #360

Option to change output view (one by each other)

Environment:

  • 1.17.0
  • Chrome
  • Windows 10

Steps to reproduce the problem:

  1. Upload PPT file
  2. Try to open it using BoxContentPreview.js (it works)
  3. Try to make it looks like slides following each other (by scrolling)

What is the expected behavior?
Is it possible somehow to make it looks like PDF preview. I mean every slider on own slide. E.g.
[slide 1]
[slide 2]
[slide 3]
Instead of <[slide 1]>[slider 2][slide 3]

There is a possibility to do same with Viewer.js (crocodoc), but it will be deprecated soon.
Thanks

publish API documentation

When I went digging a little to find out how I might update a token, I found that there's already a method to do this, complete with documented parameters and types. But that wasn't on https://developer.box.com/docs/box-content-preview or in the preview.js you direct people to load (since that's minified), it was only because I was stumbling around in the GitHub sources that I saw it.

Please make this API documentation (that you've already written!) more discoverable from the Box Developers site. Thanks!

Add option to suppress "preview" event logging

It's a common use case for platforms and web applications to prefetch/preload data but not have them visible to the user. For example, we want to load multiple ContentPreview instances ahead of time and only log an actual preview event when the user interacts/sees the preview element on the page.

For this, we need to actually suppress the current Preview logging that happens out of the box, and talking with Tony, it should be fine since content access is always logged. Furthermore, we'd need a way to log the preview event for the content after user has interacted with it in some way.

Presentation with audio

Environment:

  • Preview version: 1.21.0
  • Browser name and version: Firefox 52.2.0
  • Operating system and version: Windows 7

Steps to reproduce the problem:

  1. Load a presentation with audio using box preview library.

What is the expected behavior? (Screenshots can be helpful here)

Load audio for presentation.

image

What went wrong? (Screenshots can be helpful here)

Just displaying the presentation. Is there a way to reproduce the audio on content preview? or those are not supported files?

document how to include under Karma

Due to #521, we can't use our regular build chain with this, so we're having trouble with integrating code that uses this into our test suite.

Can you suggest a way for us to set up our karma.conf so that Box.Preview is available at test time?

Preferably without having to re-fetch preview.js from the network with every test run.

Or is there a mock implementation of Box.Preview we should load instead?

Preview toolbar

Got a couple of questions:

  1. Can the toolbar (which appears on hover over the content)

localhost_3000_u_0_v3_negotiation_192912aa-423c-4e05-9bde-ed909d79f42a_materials_instructions1

be moved to top next to the 'print' & 'download' buttons?
  1. Can the 'print' button be removed? I can remove it using css but was looking for a more general solution.

Incomplete documentation

Documentation seems to be missing some of the data. One of the missing data that i've been able to find is Listener assetsloaded.

SSL warnings

Getting the three warnings when previewing a box content:

The SSL certificate used to load resources from https://cdn01.boxcdn.net will be distrusted in M66. Once distrusted, users will be prevented from loading these resources. See https://g.co/chrome/symantecpkicerts for more information.
The SSL certificate used to load resources from https://api.box.com will be distrusted in M70. Once distrusted, users will be prevented from loading these resources. See https://g.co/chrome/symantecpkicerts for more information.
The SSL certificate used to load resources from https://public.boxcloud.com will be distrusted in M70. Once distrusted, users will be prevented from loading these resources. See https://g.co/chrome/symantecpkicerts for more informatio

Switching audio/video tracks resets the subtitles to default

Please fill out the following template so we can reproduce and fix your issue as quickly as possible!

Environment:

  • Preview version: all
  • Browser name and version: all
  • Operating system and version: all

Steps to reproduce the problem:

  1. Play a video with multiple subtitle tracks
  2. Select an alternate subtitle track
  3. Select a different video quality or audio track.
  4. See that the subtitles revert back to what they were before.

What is the expected behavior? (Screenshots can be helpful here)
Subtitles should be unaffected by change in video/audio track

What went wrong? (Screenshots can be helpful here)
Subtitles change. For example, if I was on originally english subtitles, and then select french subtitles, switching audio track or video quality resets to english subtitles again. I'm not sure if this is because it was the previous language, or if it's the default language, or if it's the first language in the menu. The menu will still say French in this case, but the subtitles shown will actually be English. Need to investigate more.

If relevant, link to file (or attach file here):
https://cloud.box.com/s/8v69y8k7awf7re56awe9d6lqf5zx56ut

Break out at the moment of concatenate with other files

Environment:

  • Preview version: 1.29.0
  • Browser name and version: Google Chrome Versión 63.0.3239.132
  • Operating system and version: Windows 10

Steps to reproduce the problem:

  1. yarn run prod
  2. Concatenate with other JS files

What is the expected behavior?
The box-content-preview library should work when is concatenated with another JS

What went wrong?
At the moment when the library its concatenated with other ones show this message
image

We're using your library in our project. In dev mode we're including all files listed and works just fine.
But when we build for production, our process takes all JS and minifies and concat all files in a single one (builtApp.js)
At this point, there is a check (https://github.com/box/box-content-preview/blob/master/src/lib/util.js#L603) for a <script... src=".../preview.js... that give us the error image

We're trying to sort this issue out by adding dependencies directly to our index.html pointing CDN but we would like to know why is that check, why do you expect to have it like that; maybe we can do some changes and minification would work on this project

Office Viewer not working with XLSX files.

Please fill out the following template so we can reproduce and fix your issue as quickly as possible!

Environment:

  • Preview version: Tested on 1.0.0 through 1.4.1
  • Browser name and version: Chrome (59.0.3071.115), Firefox (48)
  • Operating system and version:

Steps to reproduce the problem:

  1. Use preview.enableViewers('Office'); to enable the Office viewer.
  2. Use the SDK to preview an XLSX file. (see sample code used)

What is the expected behavior? (Screenshots can be helpful here)
The XLSX file should be previewed in the Office viewer

What went wrong? (Screenshots can be helpful here)
Content on the page
Error in console: openExcelOnlinePreviewer?fileId=206681973542:3 GET https://cdn01.boxcdn.net/webapp_assets/integration/css/undefined 404 (Not Found)
Error originates from the iFrame: https://app.box.com/integrations/officeonline/openExcelOnlinePreviewer?fileId=206681973542

Link to application or sample code:

preview.show(fileId, accessToken, {
              container: '.preview-container',
              header: 'none',
              logoUrl: '/static/images/icons/icon-72x72.png',
              showAnnotations: true,
              showDownload: true
            });

If relevant, link to file (or attach file here):
Tried with multiple XLSX files. None seemed to work.
Monthly budget.xlsx

Load event listener error

Hi,

Some of our users are getting an error from the load event listener about 10 times a day each.
These files are either pdfs or word files.

Environment:

  • Preview version: 1.24.0
  • Browser name and version: Chrome 63
  • Operating system and version: Windows 10

I added logging to the error result to see what the issue is but it's seems generic.
I looked through the code and the error_refresh message is shown after the file failed to load.

It looks like that message appears after a failed fetch from the loadFromServer function.
Is there any reason why files would failed to load so many times a day?
Or any pointers to look at to track down the issue?

Below is the output from the load event listener.

Thanks

{
  "error": "We're sorry, the preview didn't load. Please refresh the page.",
  "metrics": {
    "locale": "box-viewer",
    "event": "preview",
    "browser": {
      "name": "Chrome",
      "swf": false,
      "svg": true,
      "mse": true,
      "webgl": true,
      "mp3": true,
      "dash": true,
      "box3d": true,
      "h264": {
        "baseline": true,
        "main": true,
        "high": true
      }
    },
    "client": {
      "name": "box-content-preview",
      "version": "1.24.0"
    },
    "converted": true,
    "cache": {
      "hit": false,
      "stale": false
    },
    "time": {
      "conversion": 0,
      "rendering": 220,
      "total": 220
    },
    "count": {
      "success": 1,
      "error": 2,
      "navigation": 0
    }
  },
  "file": {
    "id": "269035XXXXX"
  }
}

Some PDFs are not rendered correctly

Environment:

  • Preview version: 1.35
  • Browser name and version: Chrome 64
  • Operating system and version:OS X 10
  1. Upload a PDF to Box (not all document will result in this problem)
  2. View the PDF in Box Content Preview
  3. Refresh the PDF in Box Content Preview, observe colors are off

On the left, the document shows as expected, on the right is after refreshing document.

different colors

I have narrowed this issue down to the DocLoader.js. Specifically the following code:

   /**
     * Chooses a representation. Assumes that there will be only
     * one specific representation. In other words we will not have
     * two png representation entries with different properties.
     *
     * @param {Object} file - Box file
     * @param {Object} viewer - Chosen Preview viewer
     * @return {Object} The representation to load
     */
    determineRepresentation(file, viewer) {
        let repOverride;

        // For PDF files, use original rep unless PDF rep is successful since it'll be faster
        const rep = super.determineRepresentation(file, viewer);
        const status = RepStatus.getStatus(rep);
        if (file.extension === 'pdf' && rep.representation === 'pdf' && status !== STATUS_SUCCESS) {
            repOverride = getRepresentation(file, ORIGINAL_REP_NAME);
        }

        return repOverride || rep;
    }

Load document the first time - code defaults to the ORIGINAL represenation since the PDF representation is PENDING. It seems like the PDF representation is always pending till we open the document the first time

// This always works
{
  "content": {
    "url_template": "https://dl.boxcloud.com/api/2.0/files/283946684422/content?preview=true&version=298749103078"
  },
  "representation": "ORIGINAL",
  "status": {
    "state": "success"
  }
}

Reload document and the PDF represenation is available i.e SUCCESS - code loads that and this is the representation that is wonky

// This doesn't always work
{
  "representation": "pdf",
  "properties": {},
  "info": {
    "url": "https://api.box.com/2.0/internal_files/283946684422/versions/298749103078/representations/pdf"
  },
  "status": {
    "state": "success"
  },
  "content": {
    "url_template": "https://dl.boxcloud.com/api/2.0/internal_files/283946684422/versions/298749103078/representations/pdf/content/{+asset_path}"
  }
}

Disable/enable hot keys doesn't work

Environment:

  • Preview version: 1.33.0, 1.33.1, 1.34.0
  • Browser name and version: Chrome 65.0.3325.162, Firefox 59.0.1, EDGE 38.14393.2068.0
  • Operating system and version: Windows 10

Steps to reproduce the problem:

  1. Open file preview
  2. Press CTRL + F

Expected behavior: When I call preview.disableHotkeys();, search in document shouldn't work.

Actual behavior: Search works.

CodePen

Vue + webpack

Halo guyz, how i can connet New Box View + Vue with yarn?
if i install box-ui-elements and import preview.js i see this.
2017-11-16 22-45-56

Box Content Previewer does not load document when targeted element is hidden

Environment:

  • Preview version: 1.21.0
  • Browser name and version: Chrome 63.0.3239.108 (Official Build) (64-bit)
  • Operating system and version: MacOs High Sierra version 10.13.1 (17B1003)

Steps to reproduce the problem:

  1. Go to this CodePen example (a forked version of this CodePen demo on Box developer doc site)
  2. Run the example
  3. Click on "Show viewer" button to display the box viewer div after a few seconds

What is the expected behavior?

  • The doc loads successfully in the viewer

What went wrong?

  • The doc failed to load in the viewer. The blue progress bar will stock at last 20%. The following error shows up in console: offsetParent is not set -- cannot scroll
  • If you remove the "display: none;" style from the "#viewer" div, the doc loads fine.
  • If you click on "Show viewer" button immediately after the page load, the doc loads fine.

Link to application or sample code:
https://codepen.io/brian17han/pen/rpMVbo

Our use case
We're embedding the Box Content Preview in our product and running into a problem. If the element passed to the previewer is attached to the dom, but initially hidden, the previewer (once shown) will be visible, but the document is not. The error "offsetParent is not set -- cannot scroll" appears in the console. If the window is resized or the previewer's zoom controls are used, the document will usually appear. A similar no-render occurred when we had previously tried using an embed link in a non-visible iframe. Has anyone else run into this? Everything works fine if the initial state of the element is visible, but loading a Box document that is not immediately shown is a common use case for us. Are there any workarounds?

App users' access tokens don't work for a content preview

Getting an access token for an app user as follows:

user = sdk.getAppAuthClient 'user', userID
user._session.getAccessToken()
   .then (token) ->
      res.json {token}

But when I try to use the access token in the preview, it doesn't show any preview saying "We're sorry, the preview didn't load. Please refresh the page."

If I generate a token from an enterprise user, everything works fine:

enterpriseClient = sdk.getAppAuthClient 'enterprise', enterpriseID
enterpriseClient._session.getAccessToken()
   .then (token) ->
      res.json {token}

When previewing lots of Box Files on same web page, the webpage will jump up and down

Please fill out the following template so we can reproduce and fix your issue as quickly as possible!

Environment:

  • Preview version:1.7.0
  • Browser name and version:chrome and firefox
  • Operating system and version: Mac OS 10.11.6

Steps to reproduce the problem:

  1. preview lots of box files on same webpage
  2. Programmtically focus on the viewer after it loads
// Programmtically focus on the viewer after it loads
 if (this.viewer && this.viewer.containerEl) {
        this.viewer.containerEl.focus();
 }
  1. I am not sure whether it is a good experience in this situation, because it will make the screen jump

What is the expected behavior? (Screenshots can be helpful here)
I don't want to focus on the viewer after it loads, so could you please
provide a method or param to prevent focus automatically in source code.

What went wrong? (Screenshots can be helpful here)
image
image
image

Link to application or sample code:

If relevant, link to file (or attach file here):

refreshing expired tokens

Downscoped tokens only live for about an hour.

So when viewing a long video — especially if you pause it for a while and come back later — the viewer stops with an error message, and the load event handler is sent an error like this:

Shaka error. Code = 1001, Category = 1, Severity = 2, Data = https://public.boxcloud.com/api/2.0/internal_files/269427057885/versions/283639980141/representations/dash/content/audio/0/292.m4s?access_token=1!big...Long...token&box_client_name=box-content-preview&box_client_version=1.24.0,401,,[object Object]

when Shaka's request for that next audio or video segment is denied with a 401 response.

(The players for other document types may have similar issues, but video is the one we're running into this issue with on a daily basis.)

To address this we need a few things:

  1. Know when it's time to replace the token, by
    a. detecting a "token expired" failure response when it happens, or
    b. learning up-front what the token's lifetime is when it's first provided to the Preview, or
    c. given a token, use some Box "tell me about this token" API to determine its expiration time.
  2. Have some way to update the token used by the Preview.
  • Turns out this already exists! Preview has an updateToken method. Also, accessToken may be a Promise-returning function, in which case it might not need to do updateToken at all, just re-get using the already provided generator.
  • but that documentation isn't published anywhere, which I'll file under issue #641

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

Load Failure When Previewing Multiple Files in Multiple Containers

Environment:

  • Preview version: 1.8.0
  • Browser name and version: Chrome
  • Operating system and version: Windows - Surface Pro

Steps to reproduce the problem:

  1. Preview multiple files on the same page with multiple containers
  2. Load page

What is the expected behavior? (Screenshots can be helpful here)
PDF's should all load at the same time
image

What went wrong? (Screenshots can be helpful here)
Not all PDF's load, some error out. Which PDF's load and don't seems to be totally arbitrary.
image

Link to application or sample code:
The main code that calls everything is:

for (var fileName in allFiles) {
                fileNames.push(allFiles[fileName]);
                var preview = new Box.Preview();
                preview.show(allFiles[fileName], ACCESS_TOKEN, {
                    container: '.x' + allFiles[fileName],
                    header: 'none',
                });
}

If relevant, link to file (or attach file here):

Print option is not working.

Looks like "preview.print()" method is not working.

Environment:
Preview version: 1.8.0
Browser name and version: Chrome
Operating system: Windows 10

Steps to reproduce the problem:
Load Preview
Click "Print" icon in Box header

What is the expected behavior?
Print popup has to shown.

What went wrong? (Screenshots can be helpful here)
Instead print popup, its takes me to 404 page. (Tried same with Box codepen example too, print method behaves same. )

capture

Preview fails to load when used with RequireJS

Environment:

  • Preview version: 1.20.2, 1.20.1 and 1.19.1
  • Browser name and version: Chrome V62.0.3202.94
  • Operating system and version: macOS Seirra 10.12.6

Steps to reproduce the problem:

Code used

var preview = new Box.Preview();
preview.show('<file-id>', '<acess_token>', {
   container: '.preview-container',
   showDownload: true
});

Files were imported using cdn https://cdn01.boxcdn.net/platform/preview/1.20.1/en-US/preview.js and css also.

What is the expected behavior? (Screenshots can be helpful here)

Preview for PDF file

What went wrong? (Screenshots can be helpful here)

An icon appears with text message PDFJS is not defined. (Please note same code is working for an image file)

in document search

Is there a way to start the preview with a search already initiated? I would like to show a preview from a search result, and show the document with the search term searched in the doc when it opens.

Files loading slowly and preloading

When viewing many files in succession, there is often a long delay while a file loads. Network issues aside, is there any way to preload files? When looking through the source, it seems there is some mention of this, but I couldn't get anything to make a noticeable difference in loading time.

What would your recommendations be here? Would also be glad to make a PR if necessary.

.tif files do not load

.tif files fail to load because of ImageBaseViewer.setOriginalImageSize
#338 should fix this by emulating the old behavior of continuing to load the UI even if the original dimensions could not be found

[question] drag or move pdf on zoom (hand tool)

I'm sure it's been asked, but is there a way to drag/move the pdf once it's resized above the available bounds of the container? Similar to how images work when scaled up in the viewer.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.