-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathlib.js
263 lines (241 loc) · 11.4 KB
/
lib.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/* global monaco, jQuery */
(function(NS, $) {
var RE_JSON_REFERENCE = /\s*"reference"\s*:\s*"([^"]*)"\s*?,?$/;
var RE_XML_REFERENCE = /\s*<reference\s+value\s*=\s*"([^"]*)"\s*\/>s*?$/;
var windowUrlObject = new URL(location.href);
var fhirUrlString = windowUrlObject.searchParams.get("url");
var fhirUrlObject = fhirUrlString ? new URL(fhirUrlString) : undefined;
var RESOURCES = [
"Account", "ActivityDefinition", "AdverseEvent", "AllergyIntolerance", "Appointment", "AppointmentResponse",
"AuditEvent", "Basic", "Binary", "BiologicallyDerivedProduct", "BodyStructure", "Bundle", "CapabilityStatement",
"CarePlan", "CareTeam", "ChargeItem", "ChargeItemDefinition", "Claim", "ClaimResponse", "ClinicalImpression",
"CodeSystem", "Communication", "CommunicationRequest", "CompartmentDefinition", "Composition", "ConceptMap",
"Condition", "Consent", "Contract", "Coverage", "CoverageEligibilityRequest", "CoverageEligibilityResponse",
"DetectedIssue", "Device", "DeviceDefinition", "DeviceMetric", "DeviceRequest", "DeviceUseStatement",
"DiagnosticReport", "DocumentManifest", "DocumentReference", "DomainResource", "EffectEvidenceSynthesis",
"Encounter", "Endpoint", "EnrollmentRequest", "EnrollmentResponse", "EpisodeOfCare", "EventDefinition",
"Evidence", "EvidenceVariable", "ExampleScenario", "ExplanationOfBenefit", "FamilyMemberHistory", "Flag",
"Goal", "GraphDefinition", "Group", "GuidanceResponse", "HealthcareService", "ImagingStudy", "Immunization",
"ImmunizationEvaluation", "ImmunizationRecommendation", "ImplementationGuide", "InsurancePlan",
"Invoice", "Library", "Linkage", "List", "Location", "Measure", "MeasureReport", "Media", "Medication",
"MedicationAdministration", "MedicationDispense", "MedicationKnowledge", "MedicationRequest",
"MedicationStatement", "MedicinalProduct", "MedicinalProductAuthorization", "MedicinalProductContraindication",
"MedicinalProductIndication", "MedicinalProductIngredient", "MedicinalProductInteraction",
"MedicinalProductManufactured", "MedicinalProductPackaged", "MedicinalProductPharmaceutical",
"MedicinalProductUndesirableEffect", "MessageDefinition", "MessageHeader", "MolecularSequence",
"NamingSystem", "NutritionOrder", "Observation", "ObservationDefinition", "OperationDefinition",
"OperationOutcome", "Organization", "OrganizationAffiliation", "Parameters", "Patient", "PaymentNotice",
"PaymentReconciliation", "Person", "PlanDefinition", "Practitioner", "PractitionerRole", "Procedure",
"Provenance", "Questionnaire", "QuestionnaireResponse", "RelatedPerson", "RequestGroup", "ResearchDefinition",
"ResearchElementDefinition", "ResearchStudy", "ResearchSubject", "Resource", "RiskAssessment", "Schedule",
"SearchParameter", "ServiceRequest", "Slot", "Specimen", "SpecimenDefinition", "StructureDefinition",
"StructureMap", "Subscription", "Substance", "SubstanceNucleicAcid", "SubstancePolymer", "SubstanceProtein",
"SubstanceReferenceInformation", "SubstanceSourceMaterial", "SubstanceSpecification", "SupplyDelivery",
"SupplyRequest", "Task", "TerminologyCapabilities", "TestReport", "TestScript", "ValueSet", "VerificationResult",
"VisionPrescription"
];
var FHIR_PATH = new RegExp("(metadata|" + RESOURCES.join("|") + ")(/([^/]+)?)?$");
/**
* Uses the jQuery Ajax to fetch the given URL but does not even parse it
* since we only want to use the textContent of the response.
* @param {String} url
* @returns {Promise<jQuery.jqXHR>}
*/
function fetchURL(url) {
return $.ajax({
url : url,
converters: {
"* text" : String,
"text html": true,
"text json": String,
"text xml" : String
}
});
}
/**
* Given a loaded jQuery AJAX request, reads the Content-type response
* header and returns a Monaco language based on that. Supported languages
* are json and xml. Everything else will default to "text"
* @param {jQuery.XHR} xhr
* @returns {String}
*/
function getResponseLanguage(xhr) {
var type = xhr.getResponseHeader("Content-type");
if (type.indexOf("application/fhir+json") === 0) {
return "json";
}
if (type.indexOf("application/json") === 0) {
return "json";
}
if (type.indexOf("application/fhir+xml") === 0) {
return "xml";
}
if (type.indexOf("application/xml") === 0) {
return "xml";
}
return "text";
}
function getFhirBaseUrl() {
if (!fhirUrlObject) {
return undefined
}
const url = new URL(fhirUrlObject)
url.pathname = url.pathname.replace(FHIR_PATH, "")
return url
}
/**
* Given a current language creates and returns an object that has two
* provider methods - one for the mouse-over references preview widget
* and one that will turn references into links
* @param {String} lang Should be "json" or "xml"
*/
function createReferenceProvider(lang) {
return {
provideLinks: function(model) {
var re = lang == "json" ? RE_JSON_REFERENCE : RE_XML_REFERENCE;
var strRe = String(re);
strRe = strRe.substring(1, strRe.length - 1); // Remove the regex slashes
return model.findMatches(strRe, false, true, true, false, true).map(function(res) {
var url = new URL(res.matches[1], getFhirBaseUrl())
if (lang == "json") {
url.searchParams.set("_format", "json")
}
else if (lang == "xml") {
url.searchParams.set("_format", "xml")
}
var lineText = model.getValueInRange(res.range);
var match = lineText.match(re);
var returnUrl = new URL(windowUrlObject)
returnUrl.searchParams.set("url", url.href)
return {
range: {
startLineNumber: res.range.startLineNumber,
endLineNumber : res.range.endLineNumber,
endColumn : match[0].indexOf(match[1]) + match[1].length + 1,
startColumn : match[0].indexOf(match[1]) + 1
},
url: returnUrl.href
};
})
},
provideHover: function(model, position) {
var re = lang == "json" ? RE_JSON_REFERENCE : RE_XML_REFERENCE;
var range = new monaco.Range(
position.lineNumber,
1,
position.lineNumber,
model.getLineMaxColumn(position.lineNumber)
);
var lineText = model.getValueInRange(range);
var match = lineText.match(re);
if (!match) {
return null;
}
var url = new URL(match[1], getFhirBaseUrl())
if (lang == "json") {
url.searchParams.set("_format", "json")
}
else if (lang == "xml") {
url.searchParams.set("_format", "xml")
}
return fetchURL(url.href)
.then(function(data, textStatus, xhr) {
var _lang = getResponseLanguage(xhr);
return {
range: range,
contents: [
'**' + match[1] + '**',
{
language: _lang,
value: data
}
]
};
})
}
}
}
/**
* Creates the Monaco editor
* @param {Element} container The editor container element
* @param {jQuery.XHR} xhr The loaded ajax request
* @param {Function} cb Callback to be called when the editor is ready
* @returns {void}
*/
function createEditor(container, xhr, cb) {
var lang = getResponseLanguage(xhr);
require.config({ paths: { 'vs': 'monaco-editor/min/vs' }});
require(['vs/editor/editor.main'], function() {
var model = monaco.editor.createModel(xhr.responseText, lang);
var editor = monaco.editor.create(container, {
model: model,
automaticLayout: true,
emptySelectionClipboard: false,
folding: true,
fontFamily: "Menlo, monospace",
fontSize: 13,
glyphMargin: true,
lineHeight: 16,
mouseWheelZoom: true,
parameterHints: false,
quickSuggestions: false,
readOnly: true,
renderLineHighlight: "all",
scrollBeyondLastLine: false,
snippetSuggestions: "none",
theme: windowUrlObject.searchParams.get("dark") ? "vs-dark" : "vs",
wrappingColumn: 3000
});
if (lang) {
var provider = createReferenceProvider(lang);
monaco.languages.registerHoverProvider(lang, provider);
monaco.languages.registerLinkProvider(lang, provider);
}
cb && cb(null, editor);
});
}
/**
* Initializes the app. Attempts to load the url (from the query string
* "url" parameter) and if successful, creates an instance of the Monaco
* editor to render the result.
* @param {String} containerID The ID of the container element that will
* host the editor.
* @returns {void}
* @global
*/
function init(containerID) {
var container = document.getElementById(containerID);
var message = $('<div class="message"/>').appendTo(container);
var dark = !!windowUrlObject.searchParams.get("dark")
$("body").toggleClass("dark", dark);
$("[name=dark]").prop("disabled", !dark);
if (fhirUrlString) {
$(".input-wrap input").val(fhirUrlString);
message.text('Loading...');
fetchURL(fhirUrlString).then(function(result, code, xhr) {
createEditor(container, xhr, function() { message.remove(); });
}, function(xhr) {
if (xhr.responseJSON || xhr.responseXML) {
createEditor(container, xhr, function() { message.remove(); });
}
else {
var msg = "";
if (xhr.status) {
msg += xhr.status + " ";
}
msg += xhr.statusText || "Failed to load URL!"
if (msg == "error") {
msg = "Failed to load URL!";
}
message.text(msg);
// message.text(xhr.responseText || "Failed to load URL!");
}
});
}
else {
message.text('No "url" parameter given!');
}
}
// export the init function as global
NS.init = init;
})(window, jQuery);