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

Update to typescript #668

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions karma.conf.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
// const path = require('path')

module.exports = function (config) {
config.set({
frameworks: ['jasmine'],

frameworks: ['jasmine', 'karma-typescript'],

files: [
'test/**/*.spec.js'
{ pattern: 'test/**/*.ts' },
{ pattern: 'src/**/*.ts' }
],
exclude: [],

preprocessors: {
'test/**/*.js': ['webpack', 'sourcemap', 'coverage']
'**/*.ts': ['karma-typescript', 'sourcemap', 'coverage']
},
reporters: ['progress', 'coverage'],
reporters: ['dots', 'coverage', 'karma-typescript'],
coverageReporter: {
dir: 'coverage/',
type: 'lcov',
Expand Down
8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@
"repository": "https://github.com/crabbly/Print.js",
"license": "MIT",
"devDependencies": {
"@types/jasmine": "^3.4.0",
"karma": "^6.1.0",
"karma-cli": "^2.0.0",
"karma-typescript": "^5.5.3",
"typescript": "^5.0.2",
"@babel/core": "7.11.6",
"@babel/preset-env": "7.11.5",
"babel-loader": "8.1.0",
"coveralls": "3.1.0",
"css-loader": "4.2.2",
"istanbul-instrumenter-loader": "3.0.1",
"jasmine-core": "3.6.0",
"karma": "5.2.1",
"karma-chrome-launcher": "3.1.0",
"karma-coverage": "2.0.3",
"karma-jasmine": "4.0.1",
Expand All @@ -28,8 +32,10 @@
"sass-loader": "10.0.2",
"standard": "14.3.4",
"terser-webpack-plugin": "4.1.0",
"ts-loader": "^9.4.2",
"webpack": "4.44.1",
"webpack-cli": "3.3.12",
"source-map-loader": "^4.0.1",
"webpack-dev-server": "3.11.0"
},
"scripts": {
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion src/js/browser.js → src/js/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const Browser = {
isFirefox: () => {
return typeof InstallTrigger !== 'undefined'
},
getFirefoxMajorVersion: (userAgent) => {
getFirefoxMajorVersion: (userAgent = null) => {
userAgent = userAgent || navigator.userAgent
const firefoxVersionRegex = /firefox\/(\S+)/
const match = userAgent.toLowerCase().match(firefoxVersionRegex)
Expand Down
6 changes: 3 additions & 3 deletions src/js/functions.js → src/js/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,17 +64,17 @@ export function addHeader (printElement, params) {

export function addFooter (printElement, params) {
// Create the footer container div
let footerContainer = document.createElement('div')
const footerContainer = document.createElement('div')

// Check if the footer is text or raw html
if (isRawHTML(params.footer)) {
footerContainer.innerHTML = params.footer
} else {
// Create footer element
let footerElement = document.createElement('h1')
const footerElement = document.createElement('h1')

// Create footer text node
let footerNode = document.createTextNode(params.footer)
const footerNode = document.createTextNode(params.footer)

// Build and style
footerElement.appendChild(footerNode)
Expand Down
File renamed without changes.
File renamed without changes.
18 changes: 13 additions & 5 deletions src/js/init.js → src/js/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export default {
if (!params.printable) throw new Error('Missing printable information.')

// Validate type
if (!params.type || typeof params.type !== 'string' || printTypes.indexOf(params.type.toLowerCase()) === -1) {
if (!params.type || (typeof params.type !== 'string') || printTypes.indexOf(params.type.toLowerCase()) === -1) {
throw new Error('Invalid print type. Available types are: pdf, html, image and json.')
}

Expand All @@ -97,7 +97,9 @@ export default {
// To prevent duplication and issues, remove any used printFrame from the DOM
const usedFrame = document.getElementById(params.frameId)

if (usedFrame) usedFrame.parentNode.removeChild(usedFrame)
if (usedFrame) {
usedFrame.parentNode.removeChild(usedFrame)
}

// Create a new iframe for the print job
const printFrame = document.createElement('iframe')
Expand All @@ -122,7 +124,9 @@ export default {
// Attach css files
if (params.css) {
// Add support for single file
if (!Array.isArray(params.css)) params.css = [params.css]
if (!Array.isArray(params.css)) {
params.css = [params.css]
}

// Create link tags for each css file
params.css.forEach(file => {
Expand All @@ -147,8 +151,12 @@ export default {
params.onError(error)
} finally {
// Make sure there is no loading modal opened
if (params.showModal) Modal.close()
if (params.onLoadingEnd) params.onLoadingEnd()
if (params.showModal) {
Modal.close()
}
if (params.onLoadingEnd) {
params.onLoadingEnd()
}
}
} else {
Pdf.print(params, printFrame)
Expand Down
File renamed without changes.
File renamed without changes.
11 changes: 5 additions & 6 deletions src/js/pdf.js → src/js/pdf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ export default {
print: (params, printFrame) => {
// Check if we have base64 data
if (params.base64) {
if (params.printable.indexOf(',') !== -1) {
//If pdf base64 start with `data:application/pdf;base64,`,Excute the atob function will throw an error.So we get the content after `,`
params.printable = params.printable.split(',')[1];
}
if (params.printable.indexOf(',') !== -1) {
// If pdf base64 start with `data:application/pdf;base64,`,Excute the atob function will throw an error.So we get the content after `,`
params.printable = params.printable.split(',')[1]
}
const bytesArray = Uint8Array.from(atob(params.printable), c => c.charCodeAt(0))
createBlobAndPrint(params, printFrame, bytesArray)
return
Expand Down Expand Up @@ -51,8 +51,7 @@ export default {

function createBlobAndPrint (params, printFrame, data) {
// Pass response or base64 data to a blob and create a local object url
let localPdf = new window.Blob([data], { type: 'application/pdf' })
localPdf = window.URL.createObjectURL(localPdf)
let localPdf = window.URL.createObjectURL(new window.Blob([data], { type: 'application/pdf' }))

// Set iframe src with pdf document url
printFrame.setAttribute('src', localPdf)
Expand Down
14 changes: 7 additions & 7 deletions src/js/print.js → src/js/print.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,15 @@ function performPrint (iframeElement, params) {
try {
iframeElement.contentWindow.document.execCommand('print', false, null)
} catch (e) {
setTimeout(function(){
setTimeout(function () {
iframeElement.contentWindow.print()
},1000)
}, 1000)
}
} else {
// Other browsers
setTimeout(function(){
setTimeout(function () {
iframeElement.contentWindow.print()
},1000)
}, 1000)
}
} catch (error) {
params.onError(error)
Expand All @@ -82,7 +82,7 @@ function performPrint (iframeElement, params) {
}
}

function loadIframeImages (images) {
function loadIframeImages (images){
const promises = images.map(image => {
if (image.src && image.src !== window.location.href) {
return loadIframeImage(image)
Expand All @@ -93,11 +93,11 @@ function loadIframeImages (images) {
}

function loadIframeImage (image) {
return new Promise(resolve => {
return new Promise (resolve => {
const pollImage = () => {
!image || typeof image.naturalWidth === 'undefined' || image.naturalWidth === 0 || !image.complete
? setTimeout(pollImage, 500)
: resolve()
: resolve(true)
}
pollImage()
})
Expand Down
File renamed without changes.
1 change: 1 addition & 0 deletions src/js/types/browser.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare const InstallTrigger: any;
22 changes: 19 additions & 3 deletions src/index.d.ts → src/js/types/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,24 @@
export {}

declare function printJS(configuration: printJS.Configuration): void;
declare function printJS(source: string, type?: printJS.PrintTypes): void;

declare global {
interface Window {
printJS: Function;
StyleMedia: any;
chrome: any;
}

interface Document {
documentMode: any;
}

interface HTMLElement {
contentWindow: any;
contentDocument: any;
}
}
declare namespace printJS {
type PrintTypes = 'pdf' | 'html' | 'image' | 'json' | 'raw-html';

Expand Down Expand Up @@ -43,6 +61,4 @@ declare namespace printJS {
honorColor?: boolean;
imageStyle?: string;
}
}

export = printJS;
}
4 changes: 2 additions & 2 deletions test/unit/browser.spec.js → test/unit/browser.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ describe('Browser', () => {

describe('isChrome()', () => {
it('returns true for Google Chrome', () => {
const stubbedWindow = { chrome: {} }
const stubbedWindow = <Window & typeof globalThis> { chrome: {} }
expect(Browser.isChrome(stubbedWindow)).toBeTruthy()
})

it('returns false for non Google Chrome', () => {
const stubbedWindow = {}
const stubbedWindow = <Window & typeof globalThis> {}
expect(Browser.isChrome(stubbedWindow)).toBeFalsy()
})
})
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
40 changes: 40 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"compileOnSave": false,
"compilerOptions": {
"module": "esnext",
"strict": true,
"noImplicitAny": false,
"outDir": "tmp",
"moduleResolution": "node",
"esModuleInterop": true,
"experimentalDecorators": true,
"target": "es5",
"sourceMap": true,
"baseUrl": ".",
"allowSyntheticDefaultImports": true,
"types" : [
"jasmine",
"node"
],
"typeRoots": ["./node_modules/@types", "./src/js/types"],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]

},
"include": [
"src/**/*.ts",
"test/**/*.ts"
],
"exclude": [
"node_modules"
]
}
7 changes: 5 additions & 2 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ module.exports = {
mode: 'development',
devtool: 'source-map',
entry: [
'./src/index.js'
'./src/index.ts'
],
resolve: {
extensions: ['.ts', '.js', '.json']
},
output: {
library: 'printJS',
libraryTarget: 'umd',
Expand All @@ -23,7 +26,7 @@ module.exports = {
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
loader: 'ts-loader'
}
},
// TODO: Configure istanbul to interpret how webpack bundles files
Expand Down