Convert a DOM DocumentType into a string, e.g. "<!DOCTYPE html>"
Browse Source

First implementation

tags/v0.1.0
Gerben 6 years ago
parent
commit
ef3d7069cf
4 changed files with 89 additions and 0 deletions
  1. +1
    -0
      .gitignore
  2. +13
    -0
      index.js
  3. +48
    -0
      index.test.js
  4. +27
    -0
      package.json

+ 1
- 0
.gitignore View File

@@ -0,0 +1 @@
node_modules

+ 13
- 0
index.js View File

@@ -0,0 +1,13 @@
export default function doctypeToString(doctype) {
if (doctype === null) {
return ''
}
const doctypeString = `<!DOCTYPE ${doctype.name}`
+ (doctype.publicId ? ` PUBLIC "${doctype.publicId}"` : '')
+ (doctype.systemId
? (doctype.publicId ? `` : ` SYSTEM`) + ` "${doctype.systemId}"`
: ``)
+ (doctype.internalSubset ? ` [${doctype.internalSubset}]` : ``)
+ `>`
return doctypeString
}

+ 48
- 0
index.test.js View File

@@ -0,0 +1,48 @@
import test from 'ava'
import Window from 'window';

import doctypeToString from '.'

function makeStubDocument(doctype) {
const window = new Window()
const parser = new window.DOMParser()
const doc = parser.parseFromString(
`${doctype}<html></html>`,
'text/html'
)
return doc
}

test('should return empty string if absent', t => {
const doctype = ''
const doc = makeStubDocument()
t.is(doctypeToString(doc.doctype), doctype)
})

test('should work for a HTML5-ish doctype', t => {
const doctype = '<!DOCTYPE html>'
const doc = makeStubDocument(doctype)
t.is(doctypeToString(doc.doctype), doctype)
})

test('should work for a HTML4-ish doctype', t => {
const doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">'
const doc = makeStubDocument(doctype)
t.is(doctypeToString(doc.doctype), doctype)
})

test('should work for a doctype without public id', t => {
const doctype = '<!DOCTYPE html SYSTEM "http://www.w3.org/TR/html4/loose.dtd">'
const doc = makeStubDocument(doctype)
t.is(doctypeToString(doc.doctype), doctype)
})

// Cannot test, as modern parsers do not to support internal declarations.
// test('should work for a doctype with internal declarations', t => {
// const doctype = `<!DOCTYPE html SYSTEM "example.dtd" [
// <!ENTITY foo "foo">
// <!ENTITY bar "bar">
// ]>`
// const doc = makeStubDocument(doctype)
// t.is(doctypeToString(doc.doctype), doctype)
// })

+ 27
- 0
package.json View File

@@ -0,0 +1,27 @@
{
"name": "doctype-to-string",
"version": "0.0.0",
"description": "Convert a DOM DocumentType into a string, e.g. \"<!DOCTYPE html>\"",
"main": "index.js",
"scripts": {
"test": "ava"
},
"author": "Gerben <gerben@treora.com>",
"license": "CC0-1.0",
"devDependencies": {
"ava": "^1.0.0-beta.3",
"babel-preset-env": "^1.6.1",
"babel-register": "^6.26.0",
"window": "^4.2.5"
},
"babel": {
"presets": [
"env"
]
},
"ava": {
"require": [
"babel-register"
]
}
}

Loading…
Cancel
Save