Skip to content

Commit

Permalink
Parse SVG response to document
Browse files Browse the repository at this point in the history
  • Loading branch information
stephband committed Dec 14, 2023
1 parent befbd07 commit aceea39
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
7 changes: 4 additions & 3 deletions modules/parse.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@

var mimetypes = {
xml: 'application/xml',
xml: 'application/xml',
html: 'text/html',
svg: 'image/svg+xml'
svg: 'image/svg+xml'
};

function parse(type, string) {
if (!string) { return; }

var mimetype = mimetypes[type.toLowerCase()];
// Accept 'svg' or 'SVG' or 'image/svg+xml'
var mimetype = mimetypes[type.toLowerCase()] || type;
var xml;

// Cludged from jQuery source...
Expand Down
23 changes: 21 additions & 2 deletions modules/request.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import choose from '../../fn/modules/choose.js';
import id from '../../fn/modules/id.js';

import create from './create.js';
import { parseHTML } from './parse.js';
import create from './create.js';
import { parseHTML, parseSVG } from './parse.js';

const assign = Object.assign;

Expand Down Expand Up @@ -195,15 +195,30 @@ function respondText(response) {

function respondDOM(response) {
return response.text().then((text) => (
// Is it a document?
/^\s*<!DOCTYPE html>/.test(text) ?
parseHTML(text) :
create('fragment', text)
));
}

function respondSVG(response) {
return response.text().then((text) => (
// Is it a document?
/^\s*<\?xml/.test(text) ?
parseSVG(text) :
// TODO: untested, don't know if this works on partial SVG
// fragments, I think probably not, I think we need to maybe
// make a <defs> instead. You have been warned.
(console.warn('Untested SVG fragment parsing in request.js!'),
create('fragment', text))
));
}

const responders = {
'text/plain': respondText,
'text/html': respondDOM,
'image/svg+xml': respondSVG,
'application/json': respondJSON,
'multipart/form-data': respondForm,
'application/x-www-form-urlencoded': respondForm,
Expand Down Expand Up @@ -232,6 +247,10 @@ function respond(response) {
}
const mimetype = contentType.replace(/\;.*$/, '');

if (window.DEBUG && !responders[mimetype]) {
console.warn('request() has no built-in response parser for mimetype "' + mimetype + '"');
}

return responders[mimetype](response);
}

Expand Down

0 comments on commit aceea39

Please sign in to comment.