Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

prismic.io

Package Overview
Dependencies
Maintainers
3
Versions
77
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

prismic.io - npm Package Compare versions

Comparing version 1.0.21 to 1.0.22

.coverrun

2

dist/prismic.io.min.js

@@ -1,1 +0,1 @@

!function(){Object.create||(Object.create=function(){function t(){}return function(e){if(1!=arguments.length)throw new Error("Object.create implementation only accepts one parameter.");return t.prototype=e,new t}}())}(),function(t,e){"use strict";function n(t,e,n,r,i,o){this.name=t,this.fields=e,this.form_method=n,this.rel=r,this.enctype=i,this.action=o}function r(t,e,n){this.api=t,this.form=e,this.data=n||{};for(var r in e.fields)e.fields[r]["default"]&&(this.data[r]=[e.fields[r]["default"]])}function i(t,e,n,r,i,o,s,a){this.page=t,this.results_per_page=e,this.results_size=n,this.total_results_size=r,this.total_pages=i,this.next_page=o,this.prev_page=s,this.results=a}function o(t,e,n,r){this.id=t,this.slug=e,this.type=n,this.tags=r}function s(t,e,n,r,i){this.ref=t,this.label=e,this.isMaster=n,this.scheduledAt=r,this.id=i}function a(){this.cache={},this.states={}}var u=function(t,e,n,r,i){var o=new u.fn.init(t,n,r,i);return e&&o.get(e),o},c=function(){return"undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest?function(t,e){var n=new XMLHttpRequest,r=function(){e(null,JSON.parse(n.responseText),n)},i=function(){var r=n.status;e(new Error("Unexpected status code ["+r+"] on URL "+t),null,n)};n.onreadystatechange=function(){4===n.readyState&&(n.status&&200==n.status?r():i())},n.open("GET",t,!0),n.setRequestHeader("Accept","application/json"),n.send()}:void 0},l=function(){return"undefined"!=typeof XDomainRequest?function(t,e){var n=new XDomainRequest,r=function(){e(null,JSON.parse(n.responseText),n)},i=function(t){e(new Error(t),null,n)};n.onload=function(){r(n)},n.onerror=function(){i("Unexpected status code on URL "+t)},n.open("GET",t,!0),n.ontimeout=function(){i("Request timeout")},n.onprogress=function(){},n.send()}:void 0},f=function(){if("function"==typeof require&&require("http")){var t={},n=require("http"),r=require("https"),i=require("url"),o=(require("querystring"),require("../package.json"));return function(s,a){if(t[s])a(null,t[s]);else{var u=i.parse(s),c="https:"==u.protocol?r:n,l={hostname:u.hostname,path:u.path,query:u.query,headers:{Accept:"application/json","User-Agent":"Prismic-javascript-kit/"+o.version+" NodeJS/"+process.version}};c.get(l,function(n){if(n.statusCode&&200==n.statusCode){var r="";n.setEncoding("utf8"),n.on("data",function(t){r+=t}),n.on("end",function(){var i=n.headers["cache-control"],o=i&&/max-age=(\d+)/.test(i)?parseInt(/max-age=(\d+)/.exec(i)[1]):e,u=JSON.parse(r);o&&(t[s]=u),a(null,u,n)})}else a(new Error("Unexpected status code ["+n.statusCode+"] on URL "+s),null,n)})}}}};u.fn=u.prototype={AT:"at",ANY:"any",SIMILAR:"similar",FULLTEXT:"fulltext",NUMBER:{GT:"number.gt",LT:"number.lt"},DATE:{AFTER:"date.after",BEFORE:"date.before",BETWEEN:"date.between"},DOCUMENT:{ID:"document.id",TYPE:"document.type",TAGS:"document.tags"},constructor:u,data:null,get:function(e){var n=this,r=this.url+(this.accessToken?"#"+this.accessToken:"");this.apiCache.getOrSet(r,5,function(t){n.requestHandler(n.url,function(e,r,i){e?t&&t(e,null,i):t&&t(null,n.parse(r),i)})},function(r,i,o){r?e&&e(r,null,o):(n.data=i,n.bookmarks=i.bookmarks,n.experiments=new t.Prismic.Experiments(i.experiments),e&&e(null,n,o))})},parse:function(t){var e,r,i,o,a,u,c,l={};for(c in t.forms)t.forms.hasOwnProperty(c)&&(u=t.forms[c],this.accessToken&&(u.fields.access_token={},u.fields.access_token.type="string",u.fields.access_token["default"]=this.accessToken),i=new n(u.name,u.fields,u.form_method,u.rel,u.enctype,u.action),l[c]=i);if(e=t.refs.map(function(t){return new s(t.ref,t.label,t.isMasterRef,t.scheduledAt,t.id)})||[],r=e.filter(function(t){return t.isMaster===!0}),o=t.types,a=t.tags,0===r.length)throw"No master ref.";return{bookmarks:t.bookmarks||{},refs:e,forms:l,master:r[0],types:o,tags:a,oauthInitiate:t.oauth_initiate,oauthToken:t.oauth_token}},init:function(t,e,n,r){return this.url=t+(e?(t.indexOf("?")>-1?"&":"?")+"access_token="+e:""),this.accessToken=e,this.requestHandler=n||c()||l()||f()||function(){throw new Error("No request handler available (tried XMLHttpRequest & NodeJS)")}(),this.apiCache=r||new a,this},forms:function(t){return this.form(t)},form:function(t){var e=this.data.forms[t];return e?new r(this,e,{}):void 0},master:function(){return this.data.master.ref},ref:function(t){for(var e=0;e<this.data.refs.length;e++)if(this.data.refs[e].label==t)return this.data.refs[e].ref},currentExperiment:function(){return this.experiments.current()},parseDoc:function(e){var n=[];e.linked_documents&&(n=e.linked_documents.map(function(t){return new o(t.id,t.slug,t.type,t.tags)}));var r={};for(var i in e.data[e.type])r[e.type+"."+i]=e.data[e.type][i];return new t.Prismic.Document(e.id,e.type,e.href,e.tags,e.slugs,n,r)}},u.fn.init.prototype=u.fn,n.prototype={},r.prototype={set:function(t,n){var r=this.form.fields[t];if(!r)throw new Error("Unknown field "+t);var i=this.data[t]||[];return(""===n||n===e)&&(n=null),r.multiple?n&&i.push(n):i=n&&[n],this.data[t]=i,this},ref:function(t){return this.set("ref",t)},query:function(t){if("string"==typeof t)return this.set("q",t);var e=[].slice.apply(arguments),n=[];return e.forEach(function(t){var e=0===t[1].indexOf("my.")||0===t[1].indexOf("document.")?t[1]:'"'+t[1]+'"';n.push("[:d = "+t[0]+"("+e+", "+function(){return t.slice(2).map(function(t){return"string"==typeof t?'"'+t+'"':Array.isArray(t)?"["+t.map(function(t){return'"'+t+'"'}).join(",")+"]":t instanceof Date?t.getTime():t}).join(",")}()+")]")}),this.query("["+n.join("")+"]")},pageSize:function(t){return this.set("pageSize",t)},page:function(t){return this.set("page",t)},orderings:function(t){return this.set("orderings",t)},submit:function(t){var e=this.form.action;if(this.data){var n=e.indexOf("?")>-1?"&":"?";for(var r in this.data){var o=this.data[r];if(o)for(var s=0;s<o.length;s++)e+=n+r+"="+encodeURIComponent(o[s]),n="&"}}this.api.requestHandler(e,function(e,n,r){if(e)return void t(e,null,r);var o=n.results.map(u.fn.parseDoc);t(null,new i(n.page,n.results_per_page,n.results_size,n.total_results_size,n.total_pages,n.next_page,n.prev_page,o||[]),r)})}},s.prototype={},a.prototype={get:function(t){var e=this.cache[t];return e&&(!this.isExpired(t)||this.isExpired(t)&&this.isInProgress(t))?e.data:null},set:function(t,e,n){this.cache[t]={data:e,expiredIn:n?Date.now()+1e3*n:0}},getOrSet:function(t,e,n,r){var i=this.get(t),o=this;if(i)r&&r(null,i);else{this.states[t]="progress";{n(function(n,i,s){o.set(t,i,e),delete o.states[t],r&&r(n,i,s)})}}},isExpired:function(t){var e=this.cache[t];return e?0!==e.expiredIn&&e.expiredIn<Date.now():!1},isInProgress:function(t){return"progress"===this.states[t]},exists:function(t){return!!this.cache[t]},remove:function(t){return delete this.cache[t]},clear:function(){this.cache={}}},t.Prismic={Api:u}}("object"==typeof exports&&exports?exports:"object"==typeof module&&module&&"object"==typeof module.exports?module.exports:window),function(t){"use strict";function e(){}function n(t,e,n,r,i,o,s){this.id=t,this.type=e,this.href=n,this.tags=r,this.slug=i?i[0]:"-",this.slugs=i,this.linkedDocuments=o,this.fragments=s}function r(t){this.fragments=t}function i(t){var e={};return t&&"[object Function]"===e.toString.call(t)}e.prototype={get:function(e){var n=this._getFragments(e);return n.length?t.Prismic.Fragments.initField(n[0]):null},getAll:function(e){return this._getFragments(e).map(function(e){return t.Prismic.Fragments.initField(e)},this)},getImage:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.Image?n:n instanceof t.Prismic.Fragments.StructuredText?n:null},getAllImages:function(e){var n=this.getAll(e);return n.map(function(e){if(e instanceof t.Prismic.Fragments.Image)return e;if(e instanceof t.Prismic.Fragments.StructuredText)throw new Error("Not done.");return null})},getImageView:function(e,n){var r=this.get(e);if(r instanceof t.Prismic.Fragments.Image)return r.getView(n);if(r instanceof t.Prismic.Fragments.StructuredText)for(var i=0;i<r.blocks.length;i++)if("image"==r.blocks[i].type)return r.blocks[i];return null},getAllImageViews:function(t,e){return this.getAllImages(t).map(function(t){return t.getView(e)})},getTimestamp:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.Timestamp?n.value:void 0},getDate:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.Date?n.value:void 0},getBoolean:function(t){var e=this.get(t);return e.value&&("yes"==e.value.toLowerCase()||"on"==e.value.toLowerCase()||"true"==e.value.toLowerCase())},getText:function(e,n){var r=this.get(e);return r instanceof t.Prismic.Fragments.StructuredText?r.blocks.map(function(t){return t.text?t.text+(n?n:""):void 0}).join("\n"):r instanceof t.Prismic.Fragments.Text&&r.value?r.value+(n?n:""):r instanceof t.Prismic.Fragments.Number&&r.value?r.value+(n?n:""):r instanceof t.Prismic.Fragments.Select&&r.value?r.value+(n?n:""):r instanceof t.Prismic.Fragments.Color&&r.value?r.value+(n?n:""):void 0},getStructuredText:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.StructuredText?n:null},getLink:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.WebLink||n instanceof t.Prismic.Fragments.DocumentLink||n instanceof t.Prismic.Fragments.ImageLink?n:null},getNumber:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.Number?n.value:null},getColor:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.Color?n.value:null},getGeoPoint:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.GeoPoint?n:null},getGroup:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.Group?n:null},getHtml:function(t,e){if(!i(e)){var n=e;e=function(t,e){return n.linkResolver(n,t,e)}}var r=this.get(t);return r&&r.asHtml?r.asHtml(e):null},asHtml:function(t){if(!i(t)){var e=t;t=function(t,n){return e.linkResolver(e,t,n)}}var n=[];for(var r in this.fragments){var o=this.get(r);n.push(o&&o.asHtml?'<section data-field="'+r+'">'+o.asHtml(t)+"</section>":"")}return n.join("")},asText:function(t){if(!i(t)){var e=t;t=function(t,n){return e.linkResolver(e,t,n)}}var n=[];for(var r in this.fragments){var o=this.get(r);n.push(o&&o.asText?o.asText(t):"")}return n.join("")},_getFragments:function(t){return this.fragments&&this.fragments[t]?Array.isArray(this.fragments[t])?this.fragments[t]:[this.fragments[t]]:[]}},n.prototype=Object.create(e.prototype,{}),r.prototype=Object.create(e.prototype,{}),t.Prismic.Document=n,t.Prismic.GroupDoc=r}("object"==typeof exports&&exports?exports:"object"==typeof module&&module&&"object"==typeof module.exports?module.exports:window),function(t){"use strict";function e(t){this.value=t}function n(t){this.value=t,this.document=t.document,this.isBroken=t.isBroken}function r(t){this.value=t}function i(t){this.value=t}function o(t){this.value=t}function s(t){this.value=t}function a(t){this.value=t}function u(t,e){this.latitude=t,this.longitude=e}function c(t){this.value=t}function l(t){this.value=new Date(t)}function f(t){var e=24==t.length?t.substring(0,22)+":"+t.substring(22,24):t;this.value=new Date(e)}function h(t){this.value=t}function p(t,e){this.main=t,this.views=e||{}}function m(t,e,n,r){this.url=t,this.width=e,this.height=n,this.alt=r}function d(e){this.value=[];for(var n=0;n<e.length;n++)this.value.push(new t.Prismic.GroupDoc(e[n]))}function g(t){this.blocks=t}function v(t){return t&&t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function y(t,e,n,r){if(!e||!e.length)return v(t);var i={},o={};e.forEach(function(t){i[t.start]||(i[t.start]=[]),o[t.end]||(o[t.end]=[]),i[t.start].push(t),o[t.end].unshift(t)});for(var s,a="",u=[],c=0,l=t.length+1;l>c;c++)o[c]&&o[c].forEach(function(){var t=u.pop(),e=k(t.span,t.text,r);0===u.length?a+=e:u[u.length-1].text+=e}),i[c]&&(i[c].sort(function(t,e){return e.end-e.start-(t.end-t.start)}),i[c].forEach(function(t){var e=null;if("hyperlink"==t.type){var r=b(t.data);if(!r)return console&&console.error&&console.error("Impossible to convert span.data as a Fragment",t),"";e=r.url(n),t.url=e}var i={span:t,text:""};u.push(i)})),c<t.length&&(s=t[c],0===u.length?a+=v(s):u[u.length-1].text+=v(s));return a}function b(t){var v,y;switch(t.type){case"Color":v=new a(t.value);break;case"Number":v=new c(t.value);break;case"Date":v=new l(t.value);break;case"Timestamp":v=new f(t.value);break;case"Text":v=new e(t.value);break;case"Embed":v=new h(t.value);break;case"GeoPoint":v=new u(t.value.latitude,t.value.longitude);break;case"Select":v=new s(t.value);break;case"Image":y=t.value.main,v=new p(new m(y.url,y.dimensions.width,y.dimensions.height,y.alt),{});for(var b in t.value.views)y=t.value.views[b],v.views[b]=new m(y.url,y.dimensions.width,y.dimensions.height,y.alt);break;case"StructuredText":v=new g(t.value);break;case"Link.document":v=new n(t.value);break;case"Link.web":v=new r(t.value);break;case"Link.file":v=new i(t.value);break;case"Link.image":v=new o(t.value);break;case"Group":v=new d(t.value);break;default:console&&console.log&&console.log("Fragment type not supported: ",t.type)}return v}function x(t){var e={};return t&&"[object Function]"===e.toString.call(t)}function k(t,e,n){if(n){var r=n(t,e);if(r)return r}var i={heading1:"h1",heading2:"h2",heading3:"h3",heading4:"h4",heading5:"h5",heading6:"h6",paragraph:"p",preformatted:"pre","list-item":"li","o-list-item":"li","group-list-item":"ul","group-o-list-item":"ol",strong:"strong",em:"em"};if(i[t.type]){var o=i[t.type],s=t.label?' class="'+t.label+'"':"";return"<"+o+s+">"+e+"</"+o+">"}if("image"==t.type){var a=t.label?" "+t.label:"",u='<img src="'+t.url+'" alt="'+t.alt+'">';return'<p class="block-img'+a+'">'+(t.linkUrl?'<a href="'+t.linkUrl+'">'+u+"</a>":u)+"</p>"}return"embed"==t.type?'<div data-oembed="'+t.embed_url+'" data-oembed-type="'+t.type+'" data-oembed-provider="'+t.provider_name+(t.label?'" class="'+t.label:"")+'">'+t.oembed.html+"</div>":"hyperlink"===t.type?'<a href="'+t.url+'">'+e+"</a>":"label"===t.type?'<span class="'+t.data.label+'">'+e+"</span>":"<!-- Warning: "+t.type+" not implemented. Upgrade the Developer Kit. -->"+e}e.prototype={asHtml:function(){return"<span>"+this.value+"</span>"},asText:function(){return this.value}},n.prototype={asHtml:function(t){return'<a href="'+this.url(t)+'">'+this.url(t)+"</a>"},url:function(t){return t(this.document,this.isBroken)},asText:function(t){return this.url(t)}},r.prototype={asHtml:function(){return'<a href="'+this.url()+'">'+this.url()+"</a>"},url:function(){return this.value.url},asText:function(){return this.url()}},i.prototype={asHtml:function(){return'<a href="'+this.url()+'">'+this.value.file.name+"</a>"},url:function(){return this.value.file.url},asText:function(){return this.url()}},o.prototype={asHtml:function(){return'<a href="'+this.url()+'"><img src="'+this.url()+'" alt="'+this.alt+'"></a>'},url:function(){return this.value.image.url},asText:function(){return this.url()}},s.prototype={asHtml:function(){return"<span>"+this.value+"</span>"},asText:function(){return this.value}},a.prototype={asHtml:function(){return"<span>"+this.value+"</span>"},asText:function(){return this.value}},u.prototype={asHtml:function(){return'<div class="geopoint"><span class="latitude">'+this.latitude+'</span><span class="longitude">'+this.longitude+"</span></div>"},asText:function(){return"("+this.latitude+","+this.longitude+")"}},c.prototype={asHtml:function(){return"<span>"+this.value+"</span>"},asText:function(){return this.value.toString()}},l.prototype={asHtml:function(){return"<time>"+this.value+"</time>"},asText:function(){return this.value.toString()}},f.prototype={asHtml:function(){return"<time>"+this.value+"</time>"},asText:function(){return this.value.toString()}},h.prototype={asHtml:function(){return this.value.oembed.html},asText:function(){return""}},p.prototype={getView:function(t){return"main"===t?this.main:this.views[t]},asHtml:function(){return this.main.asHtml()},asText:function(){return""}},m.prototype={ratio:function(){return this.width/this.height},asHtml:function(){return"<img src="+this.url+" width="+this.width+" height="+this.height+' alt="'+this.alt+'">'},asText:function(){return""}},d.prototype={asHtml:function(t){for(var e="",n=0;n<this.value.length;n++)e+=this.value[n].asHtml(t);return e},toArray:function(){return this.value},asText:function(t){for(var e="",n=0;n<this.value.length;n++)for(var r in this.value[n])e+=this.value[n][r].asText(t);return e}},g.prototype={getTitle:function(){for(var t=0;t<this.blocks.length;t++){var e=this.blocks[t];if(0===e.type.indexOf("heading"))return e}},getFirstParagraph:function(){for(var t=0;t<this.blocks.length;t++){var e=this.blocks[t];if("paragraph"==e.type)return e}},getParagraphs:function(){for(var t=[],e=0;e<this.blocks.length;e++){var n=this.blocks[e];"paragraph"==n.type&&t.push(n)}return t},getParagraph:function(t){return this.getParagraphs()[t]},getFirstImage:function(){for(var t=0;t<this.blocks.length;t++){var e=this.blocks[t];if("image"==e.type)return new m(e.url,e.dimensions.width,e.dimensions.height,e.alt)}},asHtml:function(t,e){var n,r,i=[],o=[];if(!x(t)){var s=t;t=function(t,e){return s.linkResolver(s,t,e)}}if(Array.isArray(this.blocks)){for(var a=0;a<this.blocks.length;a++){if(r=this.blocks[a],"image"==r.type&&r.linkTo){var u=b(r.linkTo);r.linkUrl=u.url(t)}"list-item"!==r.type&&"o-list-item"!==r.type?(i.push(r),n=null):n&&n.type=="group-"+r.type?n.blocks.push(r):(n={type:"group-"+r.type,blocks:[r]},i.push(n))}var c=function(n){var r="";return n.blocks?n.blocks.forEach(function(t){r+=k(t,c(t),e)}):r=y(n.text,n.spans,t,e),r};i.forEach(function(t){o.push(k(t,c(t),e))})}return o.join("")},asText:function(){for(var t=[],e=0;e<this.blocks.length;e++){var n=this.blocks[e];n.text&&t.push(n.text)}return t.join(" ")}},t.Prismic.Fragments={Image:p,ImageView:m,Text:e,Number:c,Date:l,Timestamp:f,Select:s,Color:a,StructuredText:g,WebLink:r,DocumentLink:n,ImageLink:o,FileLink:i,Group:d,GeoPoint:u,initField:b,insertSpans:y}}("object"==typeof exports&&exports?exports:"object"==typeof module&&module&&"object"==typeof module.exports?module.exports:window),function(t){"use strict";var e={at:function(t,e){return["at",t,e]},any:function(t,e){return["any",t,e]},fulltext:function(t,e){return["fulltext",t,e]},similar:function(t,e){return["similar",t,e]},gt:function(t,e){return["number.gt",t,e]},lt:function(t,e){return["number.lt",t,e]},inRange:function(t,e,n){return["number.inRange",t,e,n]},dateBefore:function(t,e){return["date.before",t,e]},dateAfter:function(t,e){return["date.after",t,e]},dateBetween:function(t,e,n){return["date.between",t,e,n]},dayOfMonth:function(t,e){return["date.day-of-month",t,e]},dayOfMonthAfter:function(t,e){return["date.day-of-month-after",t,e]},dayOfMonthBefore:function(t,e){return["date.day-of-month-before",t,e]},dayOfWeek:function(t,e){return["date.day-of-week",t,e]},dayOfWeekAfter:function(t,e){return["date.day-of-week-after",t,e]},dayOfWeekBefore:function(t,e){return["date.day-of-week-before",t,e]},month:function(t,e){return["date.month",t,e]},monthBefore:function(t,e){return["date.month-before",t,e]},monthAfter:function(t,e){return["date.month-after",t,e]},year:function(t,e){return["date.year",t,e]},hour:function(t,e){return["date.hour",t,e]},hourBefore:function(t,e){return["date.hour-before",t,e]},hourAfter:function(t,e){return["date.hour-after",t,e]},near:function(t,e,n,r){return["geopoint.near",t,e,n,r]}};t.Prismic.Predicates=e}("object"==typeof exports&&exports?exports:"object"==typeof module&&module&&"object"==typeof module.exports?module.exports:window),function(t){"use strict";function e(t){var e=[],r=[];t&&(t.drafts&&t.drafts.forEach(function(t){e.push(new n(t))}),t.running&&t.running.forEach(function(t){r.push(new n(t))})),this.drafts=e,this.running=r,this.cookieName=i}function n(t){this.data=t;var e=[];t.variations&&t.variations.forEach(function(t){e.push(new r(t))}),this.variations=e}function r(t){this.data=t}var i="io.prismic.experiment";e.prototype.current=function(){return this.running.length>0?this.running[0]:null},e.prototype.refFromCookie=function(t){if(!t||""===t.trim())return null;var e=t.trim().split("%20");if(e.length<2)return null;var n=e[0],r=parseInt(e[1],10);return this.running.forEach(function(t){return t.googleId()==n?t.variations.length>r?t.variations[r]:null:void 0}),null},n.prototype.id=function(){return this.data.id},n.prototype.googleId=function(){return this.data.googleId},n.prototype.name=function(){return this.data.name},r.prototype.id=function(){return this.data.id},r.prototype.ref=function(){return this.data.ref},r.prototype.label=function(){return this.data.label},t.Prismic.Experiments=e,t.Prismic.Experiment=n,t.Prismic.Variation=r}("object"==typeof exports&&exports?exports:"object"==typeof module&&module&&"object"==typeof module.exports?module.exports:window),function(t){t.Prismic.version="1.0.21"}("object"==typeof exports&&exports?exports:"object"==typeof module&&module&&"object"==typeof module.exports?module.exports:window);
!function(){Object.create||(Object.create=function(){function t(){}return function(e){if(1!=arguments.length)throw new Error("Object.create implementation only accepts one parameter.");return t.prototype=e,new t}}())}(),function(t,e){"use strict";function n(t,e,n,r,i,o){this.name=t,this.fields=e,this.form_method=n,this.rel=r,this.enctype=i,this.action=o}function r(t,e,n){this.api=t,this.form=e,this.data=n||{};for(var r in e.fields)e.fields[r]["default"]&&(this.data[r]=[e.fields[r]["default"]])}function i(t,e,n,r,i,o,s,a){this.page=t,this.results_per_page=e,this.results_size=n,this.total_results_size=r,this.total_pages=i,this.next_page=o,this.prev_page=s,this.results=a}function o(t,e,n,r){this.id=t,this.slug=e,this.type=n,this.tags=r}function s(t,e,n,r,i){this.ref=t,this.label=e,this.isMaster=n,this.scheduledAt=r,this.id=i}function a(){this.cache={},this.states={}}var u=function(e,n,r,i,o,s){var a=new u.fn.init(e,r,i,o,s);return a.get(function(e,r){return n&&e?n(e):(r&&(a.data=r,a.bookmarks=r.bookmarks,a.experiments=new t.Prismic.Experiments(r.experiments)),n?n(null,a):void 0)}),a};u.fn=u.prototype={AT:"at",ANY:"any",SIMILAR:"similar",FULLTEXT:"fulltext",NUMBER:{GT:"number.gt",LT:"number.lt"},DATE:{AFTER:"date.after",BEFORE:"date.before",BETWEEN:"date.between"},DOCUMENT:{ID:"document.id",TYPE:"document.type",TAGS:"document.tags"},constructor:u,data:null,get:function(t){var e=this,n=this.apiCacheKey;this.apiCache.get(n,function(r,i){return r?t(r):i?t(null,i):void e.requestHandler(e.url,function(r,i,o,s){if(r)return t(r,null,o);var a=e.parse(i);s|=e.apiDataTTL,e.apiCache.set(n,a,s,function(e){return e?t(e,null,o):t(null,a,o)})})})},refresh:function(e){var n=this,r=this.apiCacheKey;this.apiCache.remove(r,function(r){if(e&&r)return e(r);if(!e&&r)throw r;n.get(function(r,i){if(e&&r)return e(r);if(!e&&r)throw r;return n.data=i,n.bookmarks=i.bookmarks,n.experiments=new t.Prismic.Experiments(i.experiments),e?e():void 0})})},parse:function(t){var e,r,i,o,a,u,c,l={};for(c in t.forms)t.forms.hasOwnProperty(c)&&(u=t.forms[c],this.accessToken&&(u.fields.access_token={},u.fields.access_token.type="string",u.fields.access_token["default"]=this.accessToken),i=new n(u.name,u.fields,u.form_method,u.rel,u.enctype,u.action),l[c]=i);if(e=t.refs.map(function(t){return new s(t.ref,t.label,t.isMasterRef,t.scheduledAt,t.id)})||[],r=e.filter(function(t){return t.isMaster===!0}),o=t.types,a=t.tags,0===r.length)throw"No master ref.";return{bookmarks:t.bookmarks||{},refs:e,forms:l,master:r[0],types:o,tags:a,oauthInitiate:t.oauth_initiate,oauthToken:t.oauth_token}},init:function(e,n,r,i,o){return this.url=e+(n?(e.indexOf("?")>-1?"&":"?")+"access_token="+n:""),this.accessToken=n,this.requestHandler=r||t.Prismic.Utils.request(),this.apiCache=i||new a,this.apiCacheKey=this.url+(this.accessToken?"#"+this.accessToken:""),this.apiDataTTL=o||5,this},forms:function(t){return this.form(t)},form:function(t){var e=this.data.forms[t];return e?new r(this,e,{}):void 0},master:function(){return this.data.master.ref},ref:function(t){for(var e=0;e<this.data.refs.length;e++)if(this.data.refs[e].label==t)return this.data.refs[e].ref},currentExperiment:function(){return this.experiments.current()},parseDoc:function(e){var n=[];e.linked_documents&&(n=e.linked_documents.map(function(t){return new o(t.id,t.slug,t.type,t.tags)}));var r={};for(var i in e.data[e.type])r[e.type+"."+i]=e.data[e.type][i];return new t.Prismic.Document(e.id,e.type,e.href,e.tags,e.slugs,n,r)}},u.fn.init.prototype=u.fn,n.prototype={},r.prototype={set:function(t,n){var r=this.form.fields[t];if(!r)throw new Error("Unknown field "+t);var i=this.data[t]||[];return(""===n||n===e)&&(n=null),r.multiple?n&&i.push(n):i=n&&[n],this.data[t]=i,this},ref:function(t){return this.set("ref",t)},query:function(t){if("string"==typeof t)return this.set("q",t);var e=[].slice.apply(arguments),n=[];return e.forEach(function(t){var e=0===t[1].indexOf("my.")||0===t[1].indexOf("document.")?t[1]:'"'+t[1]+'"';n.push("[:d = "+t[0]+"("+e+", "+function(){return t.slice(2).map(function(t){return"string"==typeof t?'"'+t+'"':Array.isArray(t)?"["+t.map(function(t){return'"'+t+'"'}).join(",")+"]":t instanceof Date?t.getTime():t}).join(",")}()+")]")}),this.query("["+n.join("")+"]")},pageSize:function(t){return this.set("pageSize",t)},page:function(t){return this.set("page",t)},orderings:function(t){return this.set("orderings",t)},submit:function(t){var e=this.form.action;if(this.data){var n=e.indexOf("?")>-1?"&":"?";for(var r in this.data)if(this.data.hasOwnProperty(r)){var o=this.data[r];if(o)for(var s=0;s<o.length;s++)e+=n+r+"="+encodeURIComponent(o[s]),n="&"}}var a=e+(this.api.accessToken?"#"+this.api.accessToken:""),c=this.api.apiCache,l=this;c.get(a,function(n,r){return n?t(n):r?t(null,r):void l.api.requestHandler(e,function(e,n,r,o){if(e)return void t(e,null,r);var s=n.results.map(u.fn.parseDoc),l=new i(n.page,n.results_per_page,n.results_size,n.total_results_size,n.total_pages,n.next_page,n.prev_page,s||[]);return o?void c.set(a,l,o,function(e){return e?t(e):t(null,l)}):t(null,l)})})}},s.prototype={},a.prototype={get:function(t,e){var n=this.cache[t];return n&&!this.isExpired(t)?e(null,n.data):e()},set:function(t,e,n,r){return this.cache[t]={data:e,expiredIn:n?Date.now()+1e3*n:0},r()},isExpired:function(t){var e=this.cache[t];return e?0!==e.expiredIn&&e.expiredIn<Date.now():!1},remove:function(t,e){return delete this.cache[t],e()},clear:function(t,e){return this.cache={},e()}},t.Prismic={Api:u}}("object"==typeof exports&&exports?exports:"object"==typeof module&&module&&"object"==typeof module.exports?module.exports:window),function(t,e){"use strict";var n=function(){return"undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest?function(t,e){var n=new XMLHttpRequest,r=function(){var t,r=/max-age\s*=\s*(\d+)/.exec(n.getResponseHeader("Cache-Control"));r&&r.length>1&&(t=parseInt(r[1],10)),e(null,JSON.parse(n.responseText),n,t)},i=function(){var r=n.status;e(new Error("Unexpected status code ["+r+"] on URL "+t),null,n)};n.onreadystatechange=function(){4===n.readyState&&(n.status&&200==n.status?r():i())},n.open("GET",t,!0),n.setRequestHeader("Accept","application/json"),n.send()}:void 0},r=function(){return"undefined"!=typeof XDomainRequest?function(t,e){var n=new XDomainRequest,r=function(){var t,r=/max-age\s*=\s*(\d+)/.exec(xhr.getResponseHeader("Cache-Control"));r&&r.length>1&&(t=parseInt(r[1],10)),e(null,JSON.parse(n.responseText),n,t)},i=function(t){e(new Error(t),null,n)};n.onload=function(){r(n)},n.onerror=function(){i("Unexpected status code on URL "+t)},n.open("GET",t,!0),n.ontimeout=function(){i("Request timeout")},n.onprogress=function(){},n.send()}:void 0},i=function(){if("function"==typeof require&&require("http")){var t=require("http"),n=require("https"),r=require("url"),i=(require("querystring"),require("../package.json"));return function(o,s){var a=r.parse(o),u="https:"==a.protocol?n:t,c={hostname:a.hostname,path:a.path,query:a.query,headers:{Accept:"application/json","User-Agent":"Prismic-javascript-kit/"+i.version+" NodeJS/"+process.version}};u.get(c,function(t){if(t.statusCode&&200==t.statusCode){var n="";t.setEncoding("utf8"),t.on("data",function(t){n+=t}),t.on("end",function(){var r=JSON.parse(n),i=t.headers["cache-control"],o=i&&/max-age=(\d+)/.test(i)?parseInt(/max-age=(\d+)/.exec(i)[1],10):e;s(null,r,t,o)})}else s(new Error("Unexpected status code ["+t.statusCode+"] on URL "+o),null,t)})}}},o=null,s=null,a=function(){var e=n()||r()||i()||function(){throw new Error("No request handler available (tried XMLHttpRequest & NodeJS)")}();return function(){var n=this,r=+new Date,i=arguments;o&&r<o+t.Prismic.Utils.THRESHOLD?(clearTimeout(s),s=setTimeout(function(){o=r,e.apply(n,i)},t.Prismic.Utils.THRESHOLD)):(o=r,e.apply(n,i))}};t.Prismic.Utils={THRESHOLD:50,request:a}}("object"==typeof exports&&exports?exports:"object"==typeof module&&module&&"object"==typeof module.exports?module.exports:window),function(t){"use strict";function e(){}function n(t,e,n,r,i,o,s){this.id=t,this.type=e,this.href=n,this.tags=r,this.slug=i?i[0]:"-",this.slugs=i,this.linkedDocuments=o,this.fragments=s}function r(t){this.fragments=t}function i(t){var e={};return t&&"[object Function]"===e.toString.call(t)}e.prototype={get:function(e){var n=this._getFragments(e);return n.length?t.Prismic.Fragments.initField(n[0]):null},getAll:function(e){return this._getFragments(e).map(function(e){return t.Prismic.Fragments.initField(e)},this)},getImage:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.Image?n:n instanceof t.Prismic.Fragments.StructuredText?n:null},getAllImages:function(e){var n=this.getAll(e);return n.map(function(e){if(e instanceof t.Prismic.Fragments.Image)return e;if(e instanceof t.Prismic.Fragments.StructuredText)throw new Error("Not done.");return null})},getImageView:function(e,n){var r=this.get(e);if(r instanceof t.Prismic.Fragments.Image)return r.getView(n);if(r instanceof t.Prismic.Fragments.StructuredText)for(var i=0;i<r.blocks.length;i++)if("image"==r.blocks[i].type)return r.blocks[i];return null},getAllImageViews:function(t,e){return this.getAllImages(t).map(function(t){return t.getView(e)})},getTimestamp:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.Timestamp?n.value:void 0},getDate:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.Date?n.value:void 0},getBoolean:function(t){var e=this.get(t);return e.value&&("yes"==e.value.toLowerCase()||"on"==e.value.toLowerCase()||"true"==e.value.toLowerCase())},getText:function(e,n){var r=this.get(e);return r instanceof t.Prismic.Fragments.StructuredText?r.blocks.map(function(t){return t.text?t.text+(n?n:""):void 0}).join("\n"):r instanceof t.Prismic.Fragments.Text&&r.value?r.value+(n?n:""):r instanceof t.Prismic.Fragments.Number&&r.value?r.value+(n?n:""):r instanceof t.Prismic.Fragments.Select&&r.value?r.value+(n?n:""):r instanceof t.Prismic.Fragments.Color&&r.value?r.value+(n?n:""):void 0},getStructuredText:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.StructuredText?n:null},getLink:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.WebLink||n instanceof t.Prismic.Fragments.DocumentLink||n instanceof t.Prismic.Fragments.ImageLink?n:null},getNumber:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.Number?n.value:null},getColor:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.Color?n.value:null},getGeoPoint:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.GeoPoint?n:null},getGroup:function(e){var n=this.get(e);return n instanceof t.Prismic.Fragments.Group?n:null},getHtml:function(t,e){if(!i(e)){var n=e;e=function(t,e){return n.linkResolver(n,t,e)}}var r=this.get(t);return r&&r.asHtml?r.asHtml(e):null},asHtml:function(t){if(!i(t)){var e=t;t=function(t,n){return e.linkResolver(e,t,n)}}var n=[];for(var r in this.fragments){var o=this.get(r);n.push(o&&o.asHtml?'<section data-field="'+r+'">'+o.asHtml(t)+"</section>":"")}return n.join("")},asText:function(t){if(!i(t)){var e=t;t=function(t,n){return e.linkResolver(e,t,n)}}var n=[];for(var r in this.fragments){var o=this.get(r);n.push(o&&o.asText?o.asText(t):"")}return n.join("")},_getFragments:function(t){return this.fragments&&this.fragments[t]?Array.isArray(this.fragments[t])?this.fragments[t]:[this.fragments[t]]:[]}},n.prototype=Object.create(e.prototype,{}),r.prototype=Object.create(e.prototype,{}),t.Prismic.Document=n,t.Prismic.GroupDoc=r}("object"==typeof exports&&exports?exports:"object"==typeof module&&module&&"object"==typeof module.exports?module.exports:window),function(t){"use strict";function e(t){this.value=t}function n(t){this.value=t,this.document=t.document,this.isBroken=t.isBroken}function r(t){this.value=t}function i(t){this.value=t}function o(t){this.value=t}function s(t){this.value=t}function a(t){this.value=t}function u(t){this.latitude=t.latitude,this.longitude=t.longitude}function c(t){this.value=t}function l(t){this.value=new Date(t)}function f(t){var e=24==t.length?t.substring(0,22)+":"+t.substring(22,24):t;this.value=new Date(e)}function h(t){this.value=t}function p(t,e){this.main=t,this.views=e||{}}function m(t,e,n,r){this.url=t,this.width=e,this.height=n,this.alt=r}function d(e){this.value=[];for(var n=0;n<e.length;n++)this.value.push(new t.Prismic.GroupDoc(e[n]))}function g(t){this.blocks=t}function v(t){return t&&t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function y(t,e,n,r){if(!e||!e.length)return v(t);var i={},o={};e.forEach(function(t){i[t.start]||(i[t.start]=[]),o[t.end]||(o[t.end]=[]),i[t.start].push(t),o[t.end].unshift(t)});for(var s,a="",u=[],c=0,l=t.length+1;l>c;c++)o[c]&&o[c].forEach(function(){var t=u.pop(),e=k(t.span,t.text,r);0===u.length?a+=e:u[u.length-1].text+=e}),i[c]&&(i[c].sort(function(t,e){return e.end-e.start-(t.end-t.start)}),i[c].forEach(function(t){var e=null;if("hyperlink"==t.type){var r=x(t.data);if(!r)return console&&console.error&&console.error("Impossible to convert span.data as a Fragment",t),"";e=r.url(n),t.url=e}var i={span:t,text:""};u.push(i)})),c<t.length&&(s=t[c],0===u.length?a+=v(s):u[u.length-1].text+=v(s));return a}function x(t){var v={Color:a,Number:c,Date:l,Timestamp:f,Text:e,Embed:h,GeoPoint:u,Select:s,StructuredText:g,"Link.document":n,"Link.web":r,"Link.file":i,"Link.image":o,Group:d};if(v[t.type])return new v[t.type](t.value);if("Image"===t.type){var y=t.value.main,x=new p(new m(y.url,y.dimensions.width,y.dimensions.height,y.alt),{});for(var b in t.value.views)y=t.value.views[b],x.views[b]=new m(y.url,y.dimensions.width,y.dimensions.height,y.alt);return x}console&&console.log&&console.log("Fragment type not supported: ",t.type)}function b(t){var e={};return t&&"[object Function]"===e.toString.call(t)}function k(t,e,n){if(n){var r=n(t,e);if(r)return r}var i={heading1:"h1",heading2:"h2",heading3:"h3",heading4:"h4",heading5:"h5",heading6:"h6",paragraph:"p",preformatted:"pre","list-item":"li","o-list-item":"li","group-list-item":"ul","group-o-list-item":"ol",strong:"strong",em:"em"};if(i[t.type]){var o=i[t.type],s=t.label?' class="'+t.label+'"':"";return"<"+o+s+">"+e+"</"+o+">"}if("image"==t.type){var a=t.label?" "+t.label:"",u='<img src="'+t.url+'" alt="'+t.alt+'">';return'<p class="block-img'+a+'">'+(t.linkUrl?'<a href="'+t.linkUrl+'">'+u+"</a>":u)+"</p>"}return"embed"==t.type?'<div data-oembed="'+t.embed_url+'" data-oembed-type="'+t.type+'" data-oembed-provider="'+t.provider_name+(t.label?'" class="'+t.label:"")+'">'+t.oembed.html+"</div>":"hyperlink"===t.type?'<a href="'+t.url+'">'+e+"</a>":"label"===t.type?'<span class="'+t.data.label+'">'+e+"</span>":"<!-- Warning: "+t.type+" not implemented. Upgrade the Developer Kit. -->"+e}e.prototype={asHtml:function(){return"<span>"+this.value+"</span>"},asText:function(){return this.value}},n.prototype={asHtml:function(t){return'<a href="'+this.url(t)+'">'+this.url(t)+"</a>"},url:function(t){return t(this.document,this.isBroken)},asText:function(t){return this.url(t)}},r.prototype={asHtml:function(){return'<a href="'+this.url()+'">'+this.url()+"</a>"},url:function(){return this.value.url},asText:function(){return this.url()}},i.prototype={asHtml:function(){return'<a href="'+this.url()+'">'+this.value.file.name+"</a>"},url:function(){return this.value.file.url},asText:function(){return this.url()}},o.prototype={asHtml:function(){return'<a href="'+this.url()+'"><img src="'+this.url()+'" alt="'+this.alt+'"></a>'},url:function(){return this.value.image.url},asText:function(){return this.url()}},s.prototype={asHtml:function(){return"<span>"+this.value+"</span>"},asText:function(){return this.value}},a.prototype={asHtml:function(){return"<span>"+this.value+"</span>"},asText:function(){return this.value}},u.prototype={asHtml:function(){return'<div class="geopoint"><span class="latitude">'+this.latitude+'</span><span class="longitude">'+this.longitude+"</span></div>"},asText:function(){return"("+this.latitude+","+this.longitude+")"}},c.prototype={asHtml:function(){return"<span>"+this.value+"</span>"},asText:function(){return this.value.toString()}},l.prototype={asHtml:function(){return"<time>"+this.value+"</time>"},asText:function(){return this.value.toString()}},f.prototype={asHtml:function(){return"<time>"+this.value+"</time>"},asText:function(){return this.value.toString()}},h.prototype={asHtml:function(){return this.value.oembed.html},asText:function(){return""}},p.prototype={getView:function(t){return"main"===t?this.main:this.views[t]},asHtml:function(){return this.main.asHtml()},asText:function(){return""}},m.prototype={ratio:function(){return this.width/this.height},asHtml:function(){return"<img src="+this.url+" width="+this.width+" height="+this.height+' alt="'+this.alt+'">'},asText:function(){return""}},d.prototype={asHtml:function(t){for(var e="",n=0;n<this.value.length;n++)e+=this.value[n].asHtml(t);return e},toArray:function(){return this.value},asText:function(t){for(var e="",n=0;n<this.value.length;n++)for(var r in this.value[n])e+=this.value[n][r].asText(t);return e}},g.prototype={getTitle:function(){for(var t=0;t<this.blocks.length;t++){var e=this.blocks[t];if(0===e.type.indexOf("heading"))return e}},getFirstParagraph:function(){for(var t=0;t<this.blocks.length;t++){var e=this.blocks[t];if("paragraph"==e.type)return e}},getParagraphs:function(){for(var t=[],e=0;e<this.blocks.length;e++){var n=this.blocks[e];"paragraph"==n.type&&t.push(n)}return t},getParagraph:function(t){return this.getParagraphs()[t]},getFirstImage:function(){for(var t=0;t<this.blocks.length;t++){var e=this.blocks[t];if("image"==e.type)return new m(e.url,e.dimensions.width,e.dimensions.height,e.alt)}},asHtml:function(t,e){var n,r,i=[],o=[];if(!b(t)){var s=t;t=function(t,e){return s.linkResolver(s,t,e)}}if(Array.isArray(this.blocks)){for(var a=0;a<this.blocks.length;a++){if(r=this.blocks[a],"image"==r.type&&r.linkTo){var u=x(r.linkTo);r.linkUrl=u.url(t)}"list-item"!==r.type&&"o-list-item"!==r.type?(i.push(r),n=null):n&&n.type=="group-"+r.type?n.blocks.push(r):(n={type:"group-"+r.type,blocks:[r]},i.push(n))}var c=function(n){var r="";return n.blocks?n.blocks.forEach(function(t){r+=k(t,c(t),e)}):r=y(n.text,n.spans,t,e),r};i.forEach(function(t){o.push(k(t,c(t),e))})}return o.join("")},asText:function(){for(var t=[],e=0;e<this.blocks.length;e++){var n=this.blocks[e];n.text&&t.push(n.text)}return t.join(" ")}},t.Prismic.Fragments={Image:p,ImageView:m,Text:e,Number:c,Date:l,Timestamp:f,Select:s,Color:a,StructuredText:g,WebLink:r,DocumentLink:n,ImageLink:o,FileLink:i,Group:d,GeoPoint:u,initField:x,insertSpans:y}}("object"==typeof exports&&exports?exports:"object"==typeof module&&module&&"object"==typeof module.exports?module.exports:window),function(t){"use strict";var e={at:function(t,e){return["at",t,e]},any:function(t,e){return["any",t,e]},fulltext:function(t,e){return["fulltext",t,e]},similar:function(t,e){return["similar",t,e]},gt:function(t,e){return["number.gt",t,e]},lt:function(t,e){return["number.lt",t,e]},inRange:function(t,e,n){return["number.inRange",t,e,n]},dateBefore:function(t,e){return["date.before",t,e]},dateAfter:function(t,e){return["date.after",t,e]},dateBetween:function(t,e,n){return["date.between",t,e,n]},dayOfMonth:function(t,e){return["date.day-of-month",t,e]},dayOfMonthAfter:function(t,e){return["date.day-of-month-after",t,e]},dayOfMonthBefore:function(t,e){return["date.day-of-month-before",t,e]},dayOfWeek:function(t,e){return["date.day-of-week",t,e]},dayOfWeekAfter:function(t,e){return["date.day-of-week-after",t,e]},dayOfWeekBefore:function(t,e){return["date.day-of-week-before",t,e]},month:function(t,e){return["date.month",t,e]},monthBefore:function(t,e){return["date.month-before",t,e]},monthAfter:function(t,e){return["date.month-after",t,e]},year:function(t,e){return["date.year",t,e]},hour:function(t,e){return["date.hour",t,e]},hourBefore:function(t,e){return["date.hour-before",t,e]},hourAfter:function(t,e){return["date.hour-after",t,e]},near:function(t,e,n,r){return["geopoint.near",t,e,n,r]}};t.Prismic.Predicates=e}("object"==typeof exports&&exports?exports:"object"==typeof module&&module&&"object"==typeof module.exports?module.exports:window),function(t){"use strict";function e(t){var e=[],r=[];t&&(t.drafts&&t.drafts.forEach(function(t){e.push(new n(t))}),t.running&&t.running.forEach(function(t){r.push(new n(t))})),this.drafts=e,this.running=r,this.cookieName=i}function n(t){this.data=t;var e=[];t.variations&&t.variations.forEach(function(t){e.push(new r(t))}),this.variations=e}function r(t){this.data=t}var i="io.prismic.experiment";e.prototype.current=function(){return this.running.length>0?this.running[0]:null},e.prototype.refFromCookie=function(t){if(!t||""===t.trim())return null;var e=t.trim().split("%20");if(e.length<2)return null;var n=e[0],r=parseInt(e[1],10);return this.running.forEach(function(t){return t.googleId()==n?t.variations.length>r?t.variations[r]:null:void 0}),null},n.prototype.id=function(){return this.data.id},n.prototype.googleId=function(){return this.data.googleId},n.prototype.name=function(){return this.data.name},r.prototype.id=function(){return this.data.id},r.prototype.ref=function(){return this.data.ref},r.prototype.label=function(){return this.data.label},t.Prismic.Experiments=e,t.Prismic.Experiment=n,t.Prismic.Variation=r}("object"==typeof exports&&exports?exports:"object"==typeof module&&module&&"object"==typeof module.exports?module.exports:window),function(t){t.Prismic.version="1.0.22"}("object"==typeof exports&&exports?exports:"object"==typeof module&&module&&"object"==typeof module.exports?module.exports:window);

@@ -5,3 +5,3 @@ var gulp = require('gulp'),

uglify = require('gulp-uglify'),
qunit = require('gulp-qunit'),
mocha = require('gulp-mocha-phantomjs'),
jsdoc = require('gulp-jsdoc'),

@@ -15,2 +15,3 @@ jshint = require('gulp-jshint'),

'src/api.js',
'src/utils.js',
'src/documents.js',

@@ -86,2 +87,6 @@ 'src/fragments.js',

var mocha_options = {
timeout: 30000
};
gulp.task('jshint', function() {

@@ -96,3 +101,3 @@ gulp.src(SOURCES)

return gulp.src('./test/test.html')
.pipe(qunit({'phantomjs-options': ['--ssl-protocol=tlsv1']}))
.pipe(mocha(mocha_options))
});

@@ -102,3 +107,3 @@

return gulp.src('./test/unit.html')
.pipe(qunit({'phantomjs-options': ['--ssl-protocol=tlsv1']}))
.pipe(mocha(mocha_options))
});

@@ -108,3 +113,3 @@

return gulp.src('./test/fragments.html')
.pipe(qunit({'phantomjs-options': ['--ssl-protocol=tlsv1']}))
.pipe(mocha(mocha_options))
});

@@ -114,3 +119,3 @@

return gulp.src('./test/doc.html')
.pipe(qunit({'phantomjs-options': ['--ssl-protocol=tlsv1']}))
.pipe(mocha(mocha_options))
});

@@ -117,0 +122,0 @@

@@ -12,4 +12,5 @@ {

],
"version": "1.0.21",
"version": "1.0.22",
"devDependencies": {
"codeclimate-test-reporter": "~0.0.4",
"gulp": "~3.8.8",

@@ -19,3 +20,5 @@ "gulp-uglify": "~1.0.1",

"gulp-concat": "~2.4.1",
"gulp-qunit": "~0.3.3",
"chai": "*",
"mocha": "*",
"gulp-mocha-phantomjs": "~0.5.1",
"gulp-jsdoc": "~0.1.4",

@@ -22,0 +25,0 @@ "gulp-jshint": "~1.8.5",

## JavaScript development kit for prismic.io
[![Build Status](https://api.travis-ci.org/prismicio/javascript-kit.png)](https://travis-ci.org/prismicio/javascript-kit)
[![Code Climate](https://codeclimate.com/github/prismicio/javascript-kit.png)](https://codeclimate.com/github/prismicio/javascript-kit)

@@ -5,0 +6,0 @@ * The [source code](https://github.com/prismicio/javascript-kit) is on Github.

@@ -12,12 +12,24 @@ (function (Global, undefined) {

* @param {string} url - The mandatory URL of the prismic.io API endpoint (like: https://lesbonneschoses.prismic.io/api)
* @param {function} callback - Optional callback function that is called after the API was retrieved, to which you may pass three parameters: a potential error (null if no problem), the API object, and the XMLHttpRequest
* @param {string} accessToken - The optional accessToken for the OAuth2 connection
* @param {function} maybeRequestHandler - The kit knows how to handle the HTTP request in Node.js and in the browser (with Ajax); you will need to pass a maybeRequestHandler if you're in another JS environment
* @param {function} callback - Optional callback function that is called after the API was retrieved, which will be called with two parameters: a potential error object and the API object
* @param {string} maybeAccessToken - The accessToken for an OAuth2 connection
* @param {function} maybeRequestHandler - Environment specific HTTP request handling function
* @param {object} maybeApiCache - A cache object with get/set functions for caching API responses
* @param {int} maybeApiDataTTL - How long (in seconds) to cache data used by the client to make calls (e.g. refs). Defaults to 5 seconds
* @returns {Api} - The Api object that can be manipulated
*/
var prismic = function(url, callback, accessToken, maybeRequestHandler, maybeApiCache) {
var api = new prismic.fn.init(url, accessToken, maybeRequestHandler, maybeApiCache);
if (callback) {
api.get(callback);
}
var prismic = function(url, callback, maybeAccessToken, maybeRequestHandler, maybeApiCache, maybeApiDataTTL) {
var api = new prismic.fn.init(url, maybeAccessToken, maybeRequestHandler, maybeApiCache, maybeApiDataTTL);
//Use cached api data if available
api.get(function (err, data) {
if (callback && err) { return callback(err); }
if (data) {
api.data = data;
api.bookmarks = data.bookmarks;
api.experiments = new Global.Prismic.Experiments(data.experiments);
}
if (callback) { return callback(null, api); }
});
return api;

@@ -27,147 +39,2 @@ };

// -- Request handlers
var ajaxRequest = (function() {
if(typeof XMLHttpRequest != 'undefined' && 'withCredentials' in new XMLHttpRequest()) {
return function(url, callback) {
var xhr = new XMLHttpRequest();
// Called on success
var resolve = function() {
callback(null, JSON.parse(xhr.responseText), xhr);
};
// Called on error
var reject = function() {
var status = xhr.status;
callback(new Error("Unexpected status code [" + status + "] on URL "+url), null, xhr);
};
// Bind the XHR finished callback
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if(xhr.status && xhr.status == 200) {
resolve();
} else {
reject();
}
}
};
// Open the XHR
xhr.open('GET', url, true);
// Kit version (can't override the user-agent client side)
// xhr.setRequestHeader("X-Prismic-User-Agent", "Prismic-javascript-kit/%VERSION%".replace("%VERSION%", Global.Prismic.version));
// Json request
xhr.setRequestHeader('Accept', 'application/json');
// Send the XHR
xhr.send();
};
}
});
var xdomainRequest = (function() {
if(typeof XDomainRequest != 'undefined') {
return function(url, callback) {
var xdr = new XDomainRequest();
// Called on success
var resolve = function() {
callback(null, JSON.parse(xdr.responseText), xdr);
};
// Called on error
var reject = function(msg) {
callback(new Error(msg), null, xdr);
};
// Bind the XDR finished callback
xdr.onload = function() {
resolve(xdr);
};
// Bind the XDR error callback
xdr.onerror = function() {
reject("Unexpected status code on URL "+url);
};
// Open the XHR
xdr.open('GET', url, true);
// Bind the XDR timeout callback
xdr.ontimeout = function () {
reject("Request timeout");
};
// Empty callback. IE sometimes abort the reqeust if
// this is not present
xdr.onprogress = function () { };
xdr.send();
};
}
});
var nodeJSRequest = (function() {
if(typeof require == 'function' && require('http')) {
var requestsCache = {},
http = require('http'),
https = require('https'),
url = require('url'),
querystring = require('querystring'),
pjson = require('../package.json');
return function(requestUrl, callback) {
if(requestsCache[requestUrl]) {
callback(null, requestsCache[requestUrl]);
} else {
var parsed = url.parse(requestUrl),
h = parsed.protocol == 'https:' ? https : http,
options = {
hostname: parsed.hostname,
path: parsed.path,
query: parsed.query,
headers: {
'Accept': 'application/json',
'User-Agent': 'Prismic-javascript-kit/' + pjson.version + " NodeJS/" + process.version
}
};
h.get(options, function(response) {
if(response.statusCode && response.statusCode == 200) {
var jsonStr = '';
response.setEncoding('utf8');
response.on('data', function (chunk) {
jsonStr += chunk;
});
response.on('end', function () {
var cacheControl = response.headers['cache-control'],
maxAge = cacheControl && /max-age=(\d+)/.test(cacheControl) ? parseInt(/max-age=(\d+)/.exec(cacheControl)[1]) : undefined,
json = JSON.parse(jsonStr);
if(maxAge) {
requestsCache[requestUrl] = json;
}
callback(null, json, response);
});
} else {
callback(new Error("Unexpected status code [" + response.statusCode + "] on URL "+requestUrl), null, response);
}
});
}
};
}
});
// Defining Api's instance methods; note that the prismic variable is later affected as "Api" while exporting

@@ -204,37 +71,57 @@ prismic.fn = prismic.prototype = {

/**
* Requests (with the proper handler), parses, and returns the /api document.
* This is for internal use, from outside this kit, you should call Prismic.Api()
* Fetches data used to construct the api client, from cache if it's
* present, otherwise from calling the prismic api endpoint (which is
* then cached).
*
* @param {function} callback - Optional callback function that is called after the query is made, to which you may pass three parameters: a potential error (null if no problem), the API object, and the XMLHttpRequest
* @returns {Api} - The Api object that can be manipulated
* @param {function} callback - Callback to receive the data
*/
get: function(callback) {
var self = this;
var cacheKey = this.url + (this.accessToken ? ('#' + this.accessToken) : '');
this.apiCache.getOrSet(
cacheKey,
5, // ttl
function fetchApi (cb) {
self.requestHandler(self.url, function(error, data, xhr) {
if (error) {
if (cb) cb(error, null, xhr);
} else {
if (cb) cb(null, self.parse(data), xhr);
}
var cacheKey = this.apiCacheKey;
this.apiCache.get(cacheKey, function (err, value) {
if (err) { return callback(err); }
if (value) { return callback(null, value); }
self.requestHandler(self.url, function(err, data, xhr, ttl) {
if (err) { return callback(err, null, xhr); }
var parsed = self.parse(data);
ttl = ttl | self.apiDataTTL;
self.apiCache.set(cacheKey, parsed, ttl, function (err) {
if (err) { return callback(err, null, xhr); }
return callback(null, parsed, xhr);
});
},
function done (error, api, xhr) {
if (error) {
if (callback) callback(error, null, xhr);
} else {
self.data = api;
self.bookmarks = api.bookmarks;
self.experiments = new Global.Prismic.Experiments(api.experiments);
if (callback) callback(null, self, xhr);
}
}
);
});
});
},
/**
* Cleans api data from the cache and fetches an up to date copy.
*
* @param {function} callback - Optional callback function that is called after the data has been refreshed
*/
refresh: function (callback) {
var self = this;
var cacheKey = this.apiCacheKey;
this.apiCache.remove(cacheKey, function (err) {
if (callback && err) { return callback(err); }
if (!callback && err) { throw err; }
self.get(function (err, data, xhr) {
if (callback && err) { return callback(err); }
if (!callback && err) { throw err; }
self.data = data;
self.bookmarks = data.bookmarks;
self.experiments = new Global.Prismic.Experiments(data.experiments);
if (callback) { return callback(); }
});
});
},
/**
* Parses and returns the /api document.

@@ -321,7 +208,9 @@ * This is for internal use, from outside this kit, you should call Prismic.Api()

*/
init: function(url, accessToken, maybeRequestHandler, maybeApiCache) {
init: function(url, accessToken, maybeRequestHandler, maybeApiCache, maybeApiDataTTL) {
this.url = url + (accessToken ? (url.indexOf('?') > -1 ? '&' : '?') + 'access_token=' + accessToken : '');
this.accessToken = accessToken;
this.requestHandler = maybeRequestHandler || ajaxRequest() || xdomainRequest() || nodeJSRequest() || (function() {throw new Error("No request handler available (tried XMLHttpRequest & NodeJS)");})();
this.requestHandler = maybeRequestHandler || Global.Prismic.Utils.request();
this.apiCache = maybeApiCache || new ApiCache();
this.apiCacheKey = this.url + (this.accessToken ? ('#' + this.accessToken) : '');
this.apiDataTTL = maybeApiDataTTL || 5;
return this;

@@ -536,3 +425,3 @@ },

*
* @param {number} pageSize - The page size
* @param {number} size - The page size
* @returns {SearchForm} - The SearchForm itself

@@ -547,3 +436,3 @@ */

*
* @param {number} page - The page number
* @param {number} p - The page number
* @returns {SearchForm} - The SearchForm itself

@@ -574,13 +463,14 @@ */

submit: function(callback) {
var self = this,
url = this.form.action;
var url = this.form.action;
if(this.data) {
if (this.data) {
var sep = (url.indexOf('?') > -1 ? '&' : '?');
for(var key in this.data) {
var values = this.data[key];
if(values) {
for(var i=0; i<values.length; i++) {
url += sep + key + '=' + encodeURIComponent(values[i]);
sep = '&';
if (this.data.hasOwnProperty(key)) {
var values = this.data[key];
if (values) {
for (var i = 0; i < values.length; i++) {
url += sep + key + '=' + encodeURIComponent(values[i]);
sep = '&';
}
}

@@ -591,22 +481,36 @@ }

this.api.requestHandler(url, function (err, documents, xhr) {
var cacheKey = url + (this.api.accessToken ? ('#' + this.api.accessToken) : '');
var cache = this.api.apiCache;
var self = this;
if (err) { callback(err, null, xhr); return; }
cache.get(cacheKey, function (err, value) {
if (err) { return callback(err); }
if (value) { return callback(null, value); }
var results = documents.results.map(prismic.fn.parseDoc);
// The cache isn't really useful for in-browser usage because we already have the browser cache,
// but it is there for Node.js and other server-side implementations
self.api.requestHandler(url, function (err, documents, xhr, ttl) {
if (err) { callback(err, null, xhr); return; }
var results = documents.results.map(prismic.fn.parseDoc);
var response = new Response(
documents.page,
documents.results_per_page,
documents.results_size,
documents.total_results_size,
documents.total_pages,
documents.next_page,
documents.prev_page,
results || []);
callback(null, new Response(
documents.page,
documents.results_per_page,
documents.results_size,
documents.total_results_size,
documents.total_pages,
documents.next_page,
documents.prev_page,
results || []), xhr
);
if (ttl) {
cache.set(cacheKey, response, ttl, function (err) {
if (err) { return callback(err); }
return callback(null, response);
});
} else {
return callback(null, response);
}
});
});
}
};

@@ -618,3 +522,3 @@

* It includes all the fields that are useful for pagination (page, total_pages, total_results_size, ...),
* as well as the field "results", which is an array of {@link Doc} objects, the documents themselves.
* as well as the field "results", which is an array of {@link Document} objects, the documents themselves.
*

@@ -661,3 +565,3 @@ * @constructor

/**
* Array of {@link Doc} for the current page
* Array of {@link Document} for the current page
* @type {Array}

@@ -736,10 +640,11 @@ */

get: function(key) {
get: function(key, cb) {
var maybeEntry = this.cache[key];
if(maybeEntry && (!this.isExpired(key) || (this.isExpired(key) && this.isInProgress(key)))) {
return maybeEntry.data;
} else return null;
if(maybeEntry && !this.isExpired(key)) {
return cb(null, maybeEntry.data);
}
return cb();
},
set: function(key, value, ttl) {
set: function(key, value, ttl, cb) {
this.cache[key] = {

@@ -749,17 +654,4 @@ data: value,

};
},
getOrSet: function(key, ttl, fvalue, done) {
var found = this.get(key);
var self = this;
if(!found) {
this.states[key] = 'progress';
var value = fvalue(function(error, value, xhr) {
self.set(key, value, ttl);
delete self.states[key];
if (done) done(error, value, xhr);
});
} else {
if (done) done(null, found);
}
return cb();
},

@@ -776,16 +668,10 @@

isInProgress: function(key) {
return this.states[key] === 'progress';
remove: function(key, cb) {
delete this.cache[key];
return cb();
},
exists: function(key) {
return !!this.cache[key];
},
remove: function(key) {
return delete this.cache[key];
},
clear: function(key) {
clear: function(key, cb) {
this.cache = {};
return cb();
}

@@ -792,0 +678,0 @@ };

@@ -286,3 +286,3 @@ (function (Global, undefined) {

*/
function GeoPoint(latitude, longitude) {
function GeoPoint(data) {
/**

@@ -292,3 +292,3 @@ * @field

*/
this.latitude = latitude;
this.latitude = data.latitude;
/**

@@ -298,3 +298,3 @@ * @field

*/
this.longitude = longitude;
this.longitude = data.longitude;
}

@@ -880,90 +880,47 @@

var output, img;
var classForType = {
"Color": Color,
"Number": Num,
"Date": DateFragment,
"Timestamp": Timestamp,
"Text": Text,
"Embed": Embed,
"GeoPoint": GeoPoint,
"Select": Select,
"StructuredText": StructuredText,
"Link.document": DocumentLink,
"Link.web": WebLink,
"Link.file": FileLink,
"Link.image": ImageLink,
"Group": Group
};
switch (field.type) {
if (classForType[field.type]) {
return new classForType[field.type](field.value);
}
case "Color":
output = new Color(field.value);
break;
case "Number":
output = new Num(field.value);
break;
case "Date":
output = new DateFragment(field.value);
break;
case "Timestamp":
output = new Timestamp(field.value);
break;
case "Text":
output = new Text(field.value);
break;
case "Embed":
output = new Embed(field.value);
break;
case "GeoPoint":
output = new GeoPoint(field.value.latitude, field.value.longitude);
break;
case "Select":
output = new Select(field.value);
break;
case "Image":
img = field.value.main;
output = new ImageEl(
new ImageView(
img.url,
img.dimensions.width,
img.dimensions.height,
img.alt
),
{}
if (field.type === "Image") {
var img = field.value.main;
var output = new ImageEl(
new ImageView(
img.url,
img.dimensions.width,
img.dimensions.height,
img.alt
),
{}
);
for (var name in field.value.views) {
img = field.value.views[name];
output.views[name] = new ImageView(
img.url,
img.dimensions.width,
img.dimensions.height,
img.alt
);
for (var name in field.value.views) {
img = field.value.views[name];
output.views[name] = new ImageView(
img.url,
img.dimensions.width,
img.dimensions.height,
img.alt
);
}
break;
case "StructuredText":
output = new StructuredText(field.value);
break;
case "Link.document":
output = new DocumentLink(field.value);
break;
case "Link.web":
output = new WebLink(field.value);
break;
case "Link.file":
output = new FileLink(field.value);
break;
case "Link.image":
output = new ImageLink(field.value);
break;
case "Group":
output = new Group(field.value);
break;
default:
if (console && console.log) console.log("Fragment type not supported: ", field.type);
break;
}
return output;
}
return output;
if (console && console.log) console.log("Fragment type not supported: ", field.type);

@@ -970,0 +927,0 @@ }

(function(Prismic) {
// Test snippets for the documentation, and keep them in sync with Gist
// Test snippets for the documentation, and keep them in sync with Gist
var testRepository = 'https://lesbonneschoses.prismic.io/api',
Predicates = Prismic.Predicates;
var testRepository = 'https://lesbonneschoses.prismic.io/api',
Predicates = Prismic.Predicates,
assert = chai.assert;
function getLinkResolver(ref) {
return function(doc, isBroken) {
if (isBroken) return '#broken';
return "/testing_url/" + doc.id + "/" + doc.slug + (ref ? ('?ref=' + ref) : '');
function getLinkResolver(ref) {
return function(doc, isBroken) {
if (isBroken) return '#broken';
return "/testing_url/" + doc.id + "/" + doc.slug + (ref ? ('?ref=' + ref) : '');
};
}
}
module('Prismic.io', {
setup: function() {}
});
describe('API', function() {
asyncTest('prismic-api.js', 1, function(){
// startgist:b253d8fddfdd4cceef7a:prismic-api.js
Prismic.Api('https://lesbonneschoses.prismic.io/api', function(err, Api) {
if (err) { console.log(err); start(); } // gisthide
// You can use the Api object inside this block
console.log("References: ", Api.data.refs);
equal(Api.data.refs.length, 1); // gisthide
start(); // gisthide
});
// endgist
});
it('prismic-api.js', function (done) {
// startgist:b253d8fddfdd4cceef7a:prismic-api.js
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) throw err; // gisthide
// You can use the Api object inside this block
console.log("References: ", Api.data.refs);
assert.equal(Api.data.refs.length, 1); // gisthide
done(); // gisthide
});
// endgist
});
asyncTest('prismic-apiPrivate.js', 1, function(){
// startgist:1b2552233271e329b785:prismic-apiPrivate.js
Prismic.Api('https://lesbonneschoses.prismic.io/api', function(err, Api) {
// This will fail because the token is invalid, but this is how to access a private API
equal(err.message, "Unexpected status code [401] on URL https://lesbonneschoses.prismic.io/api?access_token=MC5-XXXXXXX-vRfvv70"); // gisthide
start(); // gisthide
}, "MC5-XXXXXXX-vRfvv70");
// endgist
});
it('prismic-apiPrivate.js', function (done) {
// startgist:1b2552233271e329b785:prismic-apiPrivate.js
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
// This will fail because the token is invalid, but this is how to access a private API
assert.equal(err.message, "Unexpected status code [401] on URL https://lesbonneschoses.prismic.io/api?access_token=MC5-XXXXXXX-vRfvv70"); // gisthide
done(); // gisthide
}, "MC5-XXXXXXX-vRfvv70");
// endgist
});
asyncTest('prismic-references.js', 1, function(){
// startgist:11cb93472bc660d423f6:prismic-references.js
var previewToken = 'MC5VbDdXQmtuTTB6Z0hNWHF3.c--_vVbvv73vv73vv73vv71EA--_vS_vv73vv70T77-9Ke-_ve-_vWfvv70ebO-_ve-_ve-_vQN377-9ce-_vRfvv70';
Prismic.Api('https://lesbonneschoses.prismic.io/api', function(err, Api) {
if (err) { console.log(err); start(); } // gisthide
var stPatrickRef = Api.ref("St-Patrick specials");
// Now we'll use this reference for all our calls
Api.form('everything')
.ref(stPatrickRef)
.query(Prismic.Predicates.at("document.type", "product")).submit(function(err, response) {
if (err) { console.log(err); start(); } // gisthide
// The documents object contains a Response object with all documents of type "product"
// including the new "Saint-Patrick's Cupcake"
equal(response.results.length, 17); // gisthide
start(); // gisthide
});
}, previewToken);
// endgist
});
it('prismic-references.js', function (done) {
// startgist:11cb93472bc660d423f6:prismic-references.js
var previewToken = 'MC5VbDdXQmtuTTB6Z0hNWHF3.c--_vVbvv73vv73vv73vv71EA--_vS_vv73vv70T77-9Ke-_ve-_vWfvv70ebO-_ve-_ve-_vQN377-9ce-_vRfvv70';
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) throw err; // gisthide
var stPatrickRef = Api.ref("St-Patrick specials");
// Now we'll use this reference for all our calls
Api.form('everything')
.ref(stPatrickRef)
.query(Prismic.Predicates.at("document.type", "product")).submit(function (err, response) {
if (err) {
console.log(err);
done();
} // gisthide
// The documents object contains a Response object with all documents of type "product"
// including the new "Saint-Patrick's Cupcake"
assert.equal(response.results.length, 17); // gisthide
done(); // gisthide
});
}, previewToken);
// endgist
});
asyncTest('prismic-simplequery.js', 2, function(){
// startgist:f3f7d4b970e964131271:prismic-simplequery.js
Prismic.Api('https://lesbonneschoses.prismic.io/api', function(err, Api) {
if (err) { console.log(err); start(); } // gisthide
Api.form('everything')
.ref(Api.master())
.query(Prismic.Predicates.at("document.type", "product")).submit(function(err, response) {
if (err) { console.log(err); start(); } // gisthide
// The documents object contains a Response object with all documents of type "product".
var page = response.page; // The current page number, the first one being 1
equal(page, 1); // gisthide
var results = response.results; // An array containing the results of the current page;
// you may need to retrieve more pages to get all results
equal(results.length, 16); // gisthide
var prev_page = response.prev_page; // the URL of the previous page (may be null)
var next_page = response.next_page; // the URL of the next page (may be null)
var results_per_page = response.results_per_page; // max number of results per page
var results_size = response.results_size; // the size of the current page
var total_pages = response.total_pages; // the number of pages
var total_results_size = response.total_results_size; // the total size of results across all pages
start(); // gisthide
});
});
// endgist
});
describe('Query', function() {
asyncTest('prismic-orderings.js', 1, function(){
// startgist:55eb59485855e40680c9:prismic-orderings.js
Prismic.Api('https://lesbonneschoses.prismic.io/api', function(err, Api) {
if (err) { console.log(err); start(); } // gisthide
Api.form('everything')
.ref(Api.master())
.query(Prismic.Predicates.at("document.type", "product"))
.pageSize(100)
.orderings('[my.product.price desc]')
.submit(function(err, response) {
// The products are now ordered by price, highest first
var results = response.results;
equal(response.results_per_page, 100); // gisthide
start(); // gisthide
it('prismic-simplequery.js', function (done) {
// startgist:f3f7d4b970e964131271:prismic-simplequery.js
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) throw err; // gisthide
Api.form('everything')
.ref(Api.master())
.query(Prismic.Predicates.at("document.type", "product")).submit(function (err, response) {
if (err) {
console.log(err);
done();
} // gisthide
// The documents object contains a Response object with all documents of type "product".
var page = response.page; // The current page number, the first one being 1
assert.equal(page, 1); // gisthide
var results = response.results; // An array containing the results of the current page;
// you may need to retrieve more pages to get all results
assert.equal(results.length, 16); // gisthide
var prev_page = response.prev_page; // the URL of the previous page (may be null)
var next_page = response.next_page; // the URL of the next page (may be null)
var results_per_page = response.results_per_page; // max number of results per page
var results_size = response.results_size; // the size of the current page
var total_pages = response.total_pages; // the number of pages
var total_results_size = response.total_results_size; // the total size of results across all pages
done(); // gisthide
});
});
// endgist
});
});
// endgist
});
asyncTest('prismic-predicates.js', 1, function() {
// startgist:2bdf83055d57f35d5d85:prismic-predicates.js
Prismic.Api('https://lesbonneschoses.prismic.io/api', function(err, Api) {
if (err) { console.log(err); start(); } // gisthide
Api.form('everything').ref(Api.master()).query(
Predicates.at("document.type", "blog-post"),
Predicates.dateAfter("my.blog-post.date", new Date(2014, 6, 1))
).submit(function(err, response) {
if (err) { console.log(err); start(); } // gisthide
// All documents of type "product", updated after June 1st, 2014
equal(response.results.length, 0); // gisthide
start(); // gisthide
it('prismic-orderings.js', function (done) {
// startgist:55eb59485855e40680c9:prismic-orderings.js
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) throw err; // gisthide
Api.form('everything')
.ref(Api.master())
.query(Prismic.Predicates.at("document.type", "product"))
.pageSize(100)
.orderings('[my.product.price desc]')
.submit(function (err, response) {
// The products are now ordered by price, highest first
var results = response.results;
assert.equal(response.results_per_page, 100); // gisthide
done(); // gisthide
});
});
// endgist
});
});
// endgist
});
test('prismic-allPredicates.js', 2, function() {
// startgist:ebec155a66db3c1a29b6:prismic-allPredicates.js
// "at" predicate: equality of a fragment to a value.
var at = Predicates.at("document.type", "article");
deepEqual(at, ["at", "document.type", "article"]); // gisthide
// "any" predicate: equality of a fragment to a value.
var any = Predicates.any("document.type", ["article", "blog-post"]);
deepEqual(any, ["any", "document.type", ["article", "blog-post"]]); // gisthide
it('prismic-predicates.js', function (done) {
// startgist:2bdf83055d57f35d5d85:prismic-predicates.js
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) throw err; // gisthide
Api.form('everything').ref(Api.master()).query(
Predicates.at("document.type", "blog-post"),
Predicates.dateAfter("my.blog-post.date", new Date(2014, 6, 1))
).submit(function (err, response) {
if (err) throw err; // gisthide
// All documents of type "product", updated after June 1st, 2014
assert.equal(response.results.length, 0); // gisthide
done(); // gisthide
});
});
// endgist
});
// "fulltext" predicate: fulltext search in a fragment.
var fulltext = Predicates.fulltext("my.article.body", "sausage");
it('prismic-allPredicates.js', function () {
// startgist:ebec155a66db3c1a29b6:prismic-allPredicates.js
// "at" predicate: equality of a fragment to a value.
var at = Predicates.at("document.type", "article");
assert.deepEqual(at, ["at", "document.type", "article"]); // gisthide
// "any" predicate: equality of a fragment to a value.
var any = Predicates.any("document.type", ["article", "blog-post"]);
assert.deepEqual(any, ["any", "document.type", ["article", "blog-post"]]); // gisthide
// "similar" predicate, with a document id as reference
var similar = Predicates.similar("UXasdFwe42D", 10);
// endgist
});
// "fulltext" predicate: fulltext search in a fragment.
var fulltext = Predicates.fulltext("my.article.body", "sausage");
asyncTest('prismic-htmlSerializer.js', 1, function() {
Prismic.Api(testRepository, function (err, Api) {
if (err) { console.log(err); start(); } // gisthide
Api.form('everything').query(Predicates.at("document.id", "UlfoxUnM0wkXYXbl"))
.ref(Api.master()).submit(function (err, documents) {
if (err) { console.log(err); start(); }
var doc = documents.results[0];
// startgist:3e125676868b16fa91b9:prismic-htmlSerializer.js
var htmlSerializer = function (element, content) {
// Don't wrap images in a <p> tag
if (element.type == "image") {
return '<img src="' + element.url + '" alt="' + element.alt + '">';
}
// "similar" predicate, with a document id as reference
var similar = Predicates.similar("UXasdFwe42D", 10);
// endgist
});
// Add a class to hyperlinks
if (element.type == "hyperlink") {
return '<a class="some-link" href="' + element.url + '">' + content + '</a>';
}
});
describe('Fragments', function() {
// Return null to stick with the default behavior
return null;
};
var html = doc.getStructuredText('blog-post.body').asHtml(getLinkResolver(), htmlSerializer);
// endgist
equal(html,
'<h1>Our world-famous Pastry Art Brainstorm event</h1>' +
'<img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg\" alt=\"\">' +
'<p>Each year, <em>Les Bonnes Choses</em> organizes a world-famous two-day event called the \"Pastry Art Brainstorm\", and which is the perfect excuse for every fine pastry artist in the world to exercise their art, and build their skills up. The event is a multiple win-win operation, at many levels: see what the event is, as seen by many point of views.</p>' +
'<h2>As seen by the top pastry artists worldwide</h2>' +
'<p>The event always starts with half a day of conference talks, given by the most insightful pastry artists in the world, selected for having made tremendous achievements in pastry that year. The list of invited guest speakers is decided jointly by the <em>Les Bonnes Choses</em> staff and the Fine Pastry Magazine editors.</p>' +
'<p>This is great for the speakers, who get an occasion to share their work, and have people build up on it with them.</p>' +
'<h2>As seen by the pastry professionals</h2>' +
'<p>After half a day of thoughtful conference, the professionals will get to put what they learned to good use, and mingle with the best artists worldwide to make the most daring pastries together. There are no set rules about who does what during this giant innovation workshop, and many crazy ideas get created out of thin air. As a virtually infinite amount of ingredients is provided by the <em>Les Bonnes Choses</em> staff, many unexpected pastries happen on that day, and professionals taste each other\'s creations, and provide relevant feedback to each other. Most pieces get showcased to the amateur audience as well, who get invited to taste some of the pieces.</p>' +
'<p>At noon on the second day, teams are expected to subscribe to our Pastry Art Challenge, during which they will make the best possible pastry, judged on many aspects (originality, taste, looks, ...) by a jury of amateurs and professionals. The team members of the three winning pieces share a substantial prize, and their pastries may even join the Les Bonnes Choses catalogue, and be offered in all the <em>Les Bonnes Choses</em> shops worldwide!</p>' +
'<h2>As seen by the pastry amateurs</h2>' +
'<p>The conference is limited with a reasonable fee; but the showcase is open to everyone, although visitors are often expected to pay the pastry chefs for the pastries they taste. The educated amateurs spend their day tasting the most daring pieces, giving some appreciated feedback to their chefs, and challenging their own tastebuds. The novice amateurs usually get a once-in-a-lifetime experience, and often mention being blown away by how rich the fine pastry art can be. All in all, every one goes home with a smile on their faces!</p>' +
'<h2>As seen by the Les Bonnes Choses interns</h2>' +
'<p>Every year, we recruit a very limited amount of interns, who get aboard a <a class="some-link" href=\"/testing_url/UlfoxUnM0wkXYXbu/les-bonnes-chosess-internship-a-testimony\">life-defining adventure around fine pastries</a>, discovering <em>Les Bonnes Choses</em> during half a year, with part of this time spent in one of our shops abroad. We always manage to get them on board at a time when we know they will be able to attend a Fine Pastry Brainstorm, because we consider it is a very defining element in the experience of being part of <em>Les Bonnes Choses</em>.</p>' +
'<p>Not only do we invite them to the event (whatever the country they are stationed in when the event happens), but we give them a front-row seat! They are part of the jury for the Fine Pastry Challenge, they are introduced to every speaker as the next generation of pastry (thus having the occasion to learn even more, directly from them).</p>' +
'<h2>As seen by fine pastry as a field</h2>' +
'<p>There wasn\'t really an international occasion for pastry artists to join and share, before <em>Les Bonnes Choses</em> came up with the first Fine Pastry Brainstorm, in 2006. Fine Pastry Magazine\'s first edition was out in 2004, and initiated the idea that pastry art needed to be shared better between professionals. But a proper event to meet up in person was missing, and <em>Les Bonnes Choses</em> is proud to be the one to have come up with it first.</p>' +
'<p>Since then, more local initiatives have been started (notably in Argentina, and Canada), but none comes close to the size of <em>Les Bonnes Choses</em>\'s international Fine Pastry Brainstorm.</p>' +
'<h2>As seen by <em>Les Bonnes Choses</em></h2>' +
'<p>As the almost only sponsor of every edition of the event, <em>Les Bonnes Choses</em> makes sure enough ingredients are available for everyone, rents the premises, makes sure the speakers are as comfortable as possible, and takes care of the whole organization! But through the operation, <em>Les Bonnes Choses</em> gains much more than any sponsoring can buy: not only does it get to secure <em>Les Bonnes Choses</em> as the world reference in pastry arts, but it also allows them to claim rightfully that they do offer in their shops the best pastries, created by the world top artists indeed.</p>');
it('prismic-htmlSerializer.js', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query(Predicates.at("document.id", "UlfoxUnM0wkXYXbl"))
.ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
var doc = documents.results[0];
// startgist:3e125676868b16fa91b9:prismic-htmlSerializer.js
var htmlSerializer = function (element, content) {
// Don't wrap images in a <p> tag
if (element.type == "image") {
return '<img src="' + element.url + '" alt="' + element.alt + '">';
}
start();
});
});
});
// Add a class to hyperlinks
if (element.type == "hyperlink") {
return '<a class="some-link" href="' + element.url + '">' + content + '</a>';
}
asyncTest('prismic-getText.js', 1, function() {
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) { console.log(err); start(); } // gisthide
Api.form('everything').query(Predicates.at("document.id", "UlfoxUnM0wkXYXbl")).ref(Api.master()).submit(function (err, documents) {
if (err) { console.log(err); start(); } // gisthide
var doc = documents.results[0];
// startgist:897048416603f89272bf:prismic-getText.js
var author = doc.getText("blog-post.author");
if (!author) author = "Anonymous";
equal(author, "John M. Martelle, Fine Pastry Magazine"); // gisthide
// endgist
start();
});
});
});
// Return null to stick with the default behavior
return null;
};
var html = doc.getStructuredText('blog-post.body').asHtml(getLinkResolver(), htmlSerializer);
// endgist
assert.equal(html,
'<h1>Our world-famous Pastry Art Brainstorm event</h1>' +
'<img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg\" alt=\"\">' +
'<p>Each year, <em>Les Bonnes Choses</em> organizes a world-famous two-day event called the \"Pastry Art Brainstorm\", and which is the perfect excuse for every fine pastry artist in the world to exercise their art, and build their skills up. The event is a multiple win-win operation, at many levels: see what the event is, as seen by many point of views.</p>' +
'<h2>As seen by the top pastry artists worldwide</h2>' +
'<p>The event always starts with half a day of conference talks, given by the most insightful pastry artists in the world, selected for having made tremendous achievements in pastry that year. The list of invited guest speakers is decided jointly by the <em>Les Bonnes Choses</em> staff and the Fine Pastry Magazine editors.</p>' +
'<p>This is great for the speakers, who get an occasion to share their work, and have people build up on it with them.</p>' +
'<h2>As seen by the pastry professionals</h2>' +
'<p>After half a day of thoughtful conference, the professionals will get to put what they learned to good use, and mingle with the best artists worldwide to make the most daring pastries together. There are no set rules about who does what during this giant innovation workshop, and many crazy ideas get created out of thin air. As a virtually infinite amount of ingredients is provided by the <em>Les Bonnes Choses</em> staff, many unexpected pastries happen on that day, and professionals taste each other\'s creations, and provide relevant feedback to each other. Most pieces get showcased to the amateur audience as well, who get invited to taste some of the pieces.</p>' +
'<p>At noon on the second day, teams are expected to subscribe to our Pastry Art Challenge, during which they will make the best possible pastry, judged on many aspects (originality, taste, looks, ...) by a jury of amateurs and professionals. The team members of the three winning pieces share a substantial prize, and their pastries may even join the Les Bonnes Choses catalogue, and be offered in all the <em>Les Bonnes Choses</em> shops worldwide!</p>' +
'<h2>As seen by the pastry amateurs</h2>' +
'<p>The conference is limited with a reasonable fee; but the showcase is open to everyone, although visitors are often expected to pay the pastry chefs for the pastries they taste. The educated amateurs spend their day tasting the most daring pieces, giving some appreciated feedback to their chefs, and challenging their own tastebuds. The novice amateurs usually get a once-in-a-lifetime experience, and often mention being blown away by how rich the fine pastry art can be. All in all, every one goes home with a smile on their faces!</p>' +
'<h2>As seen by the Les Bonnes Choses interns</h2>' +
'<p>Every year, we recruit a very limited amount of interns, who get aboard a <a class="some-link" href=\"/testing_url/UlfoxUnM0wkXYXbu/les-bonnes-chosess-internship-a-testimony\">life-defining adventure around fine pastries</a>, discovering <em>Les Bonnes Choses</em> during half a year, with part of this time spent in one of our shops abroad. We always manage to get them on board at a time when we know they will be able to attend a Fine Pastry Brainstorm, because we consider it is a very defining element in the experience of being part of <em>Les Bonnes Choses</em>.</p>' +
'<p>Not only do we invite them to the event (whatever the country they are stationed in when the event happens), but we give them a front-row seat! They are part of the jury for the Fine Pastry Challenge, they are introduced to every speaker as the next generation of pastry (thus having the occasion to learn even more, directly from them).</p>' +
'<h2>As seen by fine pastry as a field</h2>' +
'<p>There wasn\'t really an international occasion for pastry artists to join and share, before <em>Les Bonnes Choses</em> came up with the first Fine Pastry Brainstorm, in 2006. Fine Pastry Magazine\'s first edition was out in 2004, and initiated the idea that pastry art needed to be shared better between professionals. But a proper event to meet up in person was missing, and <em>Les Bonnes Choses</em> is proud to be the one to have come up with it first.</p>' +
'<p>Since then, more local initiatives have been started (notably in Argentina, and Canada), but none comes close to the size of <em>Les Bonnes Choses</em>\'s international Fine Pastry Brainstorm.</p>' +
'<h2>As seen by <em>Les Bonnes Choses</em></h2>' +
'<p>As the almost only sponsor of every edition of the event, <em>Les Bonnes Choses</em> makes sure enough ingredients are available for everyone, rents the premises, makes sure the speakers are as comfortable as possible, and takes care of the whole organization! But through the operation, <em>Les Bonnes Choses</em> gains much more than any sponsoring can buy: not only does it get to secure <em>Les Bonnes Choses</em> as the world reference in pastry arts, but it also allows them to claim rightfully that they do offer in their shops the best pastries, created by the world top artists indeed.</p>');
asyncTest('prismic-getNumber.js', 1, function() {
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) { console.log(err); start(); } // gisthide
Api.form('everything').query(Predicates.at("document.id", "UlfoxUnM0wkXYXbO")).ref(Api.master()).submit(function (err, documents) {
if (err) { console.log(err); start(); } // gisthide
var doc = documents.results[0];
// startgist:ea2f95a70621f3e83032:prismic-getNumber.js
// Number predicates
var gt = Predicates.gt("my.product.price", 10);
var lt = Predicates.lt("my.product.price", 20);
var inRange = Predicates.inRange("my.product.price", 10, 20);
done();
});
});
});
// Accessing number fields
var price = doc.getNumber("product.price");
equal(price, 2.5); // gisthide
// endgist
start();
});
});
});
it('prismic-getText.js', function (done) {
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) throw err; // gisthide
Api.form('everything').query(Predicates.at("document.id", "UlfoxUnM0wkXYXbl")).ref(Api.master()).submit(function (err, documents) {
if (err) throw err; // gisthide
var doc = documents.results[0];
// startgist:897048416603f89272bf:prismic-getText.js
var author = doc.getText("blog-post.author");
if (!author) author = "Anonymous";
assert.equal(author, "John M. Martelle, Fine Pastry Magazine"); // gisthide
// endgist
done();
});
});
});
asyncTest('prismic-dateTimestamp.js', 1, function() {
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) { console.log(err); start(); } // gisthide
Api.form('everything').query(Predicates.at("document.id", "UlfoxUnM0wkXYXbl")).ref(Api.master()).submit(function (err, documents) {
if (err) { console.log(err); start(); } // gisthide
var doc = documents.results[0];
// startgist:812b109562731b03cb58:prismic-dateTimestamp.js
// Date and Timestamp predicates
var dateBefore = Predicates.dateBefore("my.product.releaseDate", new Date(2014, 6, 1));
var dateAfter = Predicates.dateAfter("my.product.releaseDate", new Date(2014, 1, 1));
var dateBetween = Predicates.dateBetween("my.product.releaseDate", new Date(2014, 1, 1), new Date(2014, 6, 1));
var dayOfMonth = Predicates.dayOfMonth("my.product.releaseDate", 14);
var dayOfMonthAfter = Predicates.dayOfMonthAfter("my.product.releaseDate", 14);
var dayOfMonthBefore = Predicates.dayOfMonthBefore("my.product.releaseDate", 14);
var dayOfWeek = Predicates.dayOfWeek("my.product.releaseDate", "Tuesday");
var dayOfWeekAfter = Predicates.dayOfWeekAfter("my.product.releaseDate", "Wednesday");
var dayOfWeekBefore = Predicates.dayOfWeekBefore("my.product.releaseDate", "Wednesday");
var month = Predicates.month("my.product.releaseDate", "June");
var monthBefore = Predicates.monthBefore("my.product.releaseDate", "June");
var monthAfter = Predicates.monthAfter("my.product.releaseDate", "June");
var year = Predicates.year("my.product.releaseDate", 2014);
var hour = Predicates.hour("my.product.releaseDate", 12);
var hourBefore = Predicates.hourBefore("my.product.releaseDate", 12);
var hourAfter = Predicates.hourAfter("my.product.releaseDate", 12);
it('prismic-getNumber.js', function (done) {
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) throw err;
Api.form('everything').query(Predicates.at("document.id", "UlfoxUnM0wkXYXbO")).ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
var doc = documents.results[0];
// startgist:ea2f95a70621f3e83032:prismic-getNumber.js
// Number predicates
var gt = Predicates.gt("my.product.price", 10);
var lt = Predicates.lt("my.product.price", 20);
var inRange = Predicates.inRange("my.product.price", 10, 20);
// Accessing Date and Timestamp fields
var date = doc.getDate("blog-post.date");
var year = date ? date.getFullYear() : null;
var updateTime = doc.getTimestamp("blog-post.update");
var hour = updateTime ? updateTime.getHours() : 0;
equal(year, 2013); // gisthide
// endgist
start();
});
});
});
// Accessing number fields
var price = doc.getNumber("product.price");
// endgist
assert.equal(price, 2.5);
done();
});
});
});
test('prismic-group.js', 1, function() {
var doc = Prismic.Api("").parseDoc({
id: "abcd",
type: "article",
data: {
article: {
documents: {
type: "Group",
"value": [
{
"linktodoc": {
"type": "Link.document",
"value": {
"document": {
"id": "UrDejAEAAFwMyrW9",
"type": "doc",
"tags": [ ],
"slug": "installing-meta-micro"
},
"isBroken": false
}
},
"desc": {
"type": "StructuredText",
"value": [
{
"type": "paragraph",
"text": "A detailed step by step point of view on how installing happens.",
"spans": []
it('prismic-images.js', function (done) {
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) throw err;
Api.form('everything').query(Predicates.at("document.id", "UlfoxUnM0wkXYXbO")).ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
var doc = documents.results[0];
// startgist:fb48d850fd28f61fc0fb:prismic-images.js
// Accessing image fields
var image = doc.getImage("product.image");
// Most of the time you will be using the "main" view
var url = image.main.url;
// endgist
assert.equal(url, "https://prismic-io.s3.amazonaws.com/lesbonneschoses/f606ad513fcc2a73b909817119b84d6fd0d61a6d.png");
done();
});
});
});
it('prismic-dateTimestamp.js', function (done) {
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) throw err;
Api.form('everything').query(Predicates.at("document.id", "UlfoxUnM0wkXYXbl")).ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
var doc = documents.results[0];
// startgist:812b109562731b03cb58:prismic-dateTimestamp.js
// Date and Timestamp predicates
var dateBefore = Predicates.dateBefore("my.product.releaseDate", new Date(2014, 6, 1));
var dateAfter = Predicates.dateAfter("my.product.releaseDate", new Date(2014, 1, 1));
var dateBetween = Predicates.dateBetween("my.product.releaseDate", new Date(2014, 1, 1), new Date(2014, 6, 1));
var dayOfMonth = Predicates.dayOfMonth("my.product.releaseDate", 14);
var dayOfMonthAfter = Predicates.dayOfMonthAfter("my.product.releaseDate", 14);
var dayOfMonthBefore = Predicates.dayOfMonthBefore("my.product.releaseDate", 14);
var dayOfWeek = Predicates.dayOfWeek("my.product.releaseDate", "Tuesday");
var dayOfWeekAfter = Predicates.dayOfWeekAfter("my.product.releaseDate", "Wednesday");
var dayOfWeekBefore = Predicates.dayOfWeekBefore("my.product.releaseDate", "Wednesday");
var month = Predicates.month("my.product.releaseDate", "June");
var monthBefore = Predicates.monthBefore("my.product.releaseDate", "June");
var monthAfter = Predicates.monthAfter("my.product.releaseDate", "June");
var year = Predicates.year("my.product.releaseDate", 2014);
var hour = Predicates.hour("my.product.releaseDate", 12);
var hourBefore = Predicates.hourBefore("my.product.releaseDate", 12);
var hourAfter = Predicates.hourAfter("my.product.releaseDate", 12);
// Accessing Date and Timestamp fields
var date = doc.getDate("blog-post.date");
var resultYear = date ? date.getFullYear() : null;
var updateTime = doc.getTimestamp("blog-post.update");
var updateHour = updateTime ? updateTime.getHours() : 0;
assert.equal(resultYear, 2013); // gisthide
// endgist
done();
});
});
});
it('prismic-group.js', function () {
var doc = Prismic.Api("").parseDoc({
id: "abcd",
type: "article",
data: {
article: {
documents: {
type: "Group",
"value": [
{
"linktodoc": {
"type": "Link.document",
"value": {
"document": {
"id": "UrDejAEAAFwMyrW9",
"type": "doc",
"tags": [ ],
"slug": "installing-meta-micro"
},
"isBroken": false
}
},
"desc": {
"type": "StructuredText",
"value": [
{
"type": "paragraph",
"text": "A detailed step by step point of view on how installing happens.",
"spans": []
}
]
}
},
{
"linktodoc": {
"type": "Link.document",
"value": {
"document": {
"id": "UrDmKgEAALwMyrXA",
"type": "doc",
"tags": [ ],
"slug": "using-meta-micro"
},
"isBroken": false
}
}
}
]
}
}
]
}
},
{
"linktodoc": {
"type": "Link.document",
"value": {
"document": {
"id": "UrDmKgEAALwMyrXA",
"type": "doc",
"tags": [ ],
"slug": "using-meta-micro"
},
"isBroken": false
}
});
// startgist:fa204a2784c0747d552b:prismic-group.js
var group = doc.getGroup("article.documents");
var docs = group ? group.toArray() : [];
for (var i = 0; i < docs.length; i++) {
// Desc and Link are Fragments, their type depending on what's declared in the Document Mask
var desc = docs[i].getStructuredText("desc");
var link = docs[i].getLink("linktodoc");
}
// endgist
assert.equal(docs[0].getStructuredText("desc").asHtml(), "<p>A detailed step by step point of view on how installing happens.</p>");
});
it('prismic-link.js', function () {
var doc = Prismic.Api("").parseDoc({
id: "abcd",
type: "article",
data: {
article: {
source: {
type: "Link.document",
value: {
document: {
id: "UlfoxUnM0wkXYXbE",
type: "product",
tags: ["Macaron"],
slug: "dark-chocolate-macaron"
},
isBroken: false
}
}
}
}
}
]
}
}
}
});
// startgist:fa204a2784c0747d552b:prismic-group.js
var group = doc.getGroup("article.documents");
var docs = group ? group.toArray() : [];
for (var i = 0; i < docs.length; i++) {
// Desc and Link are Fragments, their type depending on what's declared in the Document Mask
var desc = docs[i].getStructuredText("desc");
var link = docs[i].getLink("linktodoc");
}
// endgist
equal(docs[0].getStructuredText("desc").asHtml(), "<p>A detailed step by step point of view on how installing happens.</p>");
});
});
// startgist:fa26d9095df192027edf:prismic-link.js
var resolver = function (doc, isBroken) {
if (isBroken) return '#broken';
return "/testing_url/" + doc.id + "/" + doc.slug;
};
var source = doc.getLink("article.source");
var url = source ? source.url(resolver) : null;
// endgist
assert.equal(url, "/testing_url/UlfoxUnM0wkXYXbE/dark-chocolate-macaron");
});
test('prismic-link.js', 1, function() {
var doc = Prismic.Api("").parseDoc({
id: "abcd",
type: "article",
data: {
article: {
source: {
type: "Link.document",
value: {
document: {
id: "UlfoxUnM0wkXYXbE",
type: "product",
tags: ["Macaron"],
slug: "dark-chocolate-macaron"
},
isBroken: false
}
}
}
}
});
// startgist:fa26d9095df192027edf:prismic-link.js
var resolver = function (doc, isBroken) {
if (isBroken) return '#broken';
return "/testing_url/" + doc.id + "/" + doc.slug;
};
var source = doc.getLink("article.source");
var url = source ? source.url(resolver) : null;
// endgist
equal(url, "/testing_url/UlfoxUnM0wkXYXbE/dark-chocolate-macaron");
});
it('prismic-embed.js', function () {
var doc = Prismic.Api("").parseDoc({
id: "abcd",
type: "article",
data: {
article: {
"video": {
"type": "Embed",
"value": {
"oembed": {
"provider_url": "http://www.youtube.com/",
"type": "video",
"thumbnail_height": 360,
"height": 270,
"thumbnail_url": "http://i1.ytimg.com/vi/baGfM6dBzs8/hqdefault.jpg",
"width": 480,
"provider_name": "YouTube",
"html": "<iframe width=\"480\" height=\"270\" src=\"http://www.youtube.com/embed/baGfM6dBzs8?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe>",
"author_name": "Siobhan Wilson",
"version": "1.0",
"author_url": "http://www.youtube.com/user/siobhanwilsonsongs",
"thumbnail_width": 480,
"title": "Siobhan Wilson - All Dressed Up",
"embed_url": "https://www.youtube.com/watch?v=baGfM6dBzs8"
}
}
}
}
}
});
// startgist:67b2d5f4094c54f3f5c0:prismic-embed.js
var video = doc.get("article.video");
// Html is the code to include to embed the object, and depends on the embedded service
var html = video ? video.asHtml() : "";
// endgist
assert.equal(html, "<iframe width=\"480\" height=\"270\" src=\"http://www.youtube.com/embed/baGfM6dBzs8?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe>");
});
test('prismic-embed.js', 1, function() {
var doc = Prismic.Api("").parseDoc({
id: "abcd",
type: "article",
data: {
article: {
"video" : {
"type" : "Embed",
"value" : {
"oembed" : {
"provider_url" : "http://www.youtube.com/",
"type" : "video",
"thumbnail_height" : 360,
"height" : 270,
"thumbnail_url" : "http://i1.ytimg.com/vi/baGfM6dBzs8/hqdefault.jpg",
"width" : 480,
"provider_name" : "YouTube",
"html" : "<iframe width=\"480\" height=\"270\" src=\"http://www.youtube.com/embed/baGfM6dBzs8?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe>",
"author_name" : "Siobhan Wilson",
"version" : "1.0",
"author_url" : "http://www.youtube.com/user/siobhanwilsonsongs",
"thumbnail_width" : 480,
"title" : "Siobhan Wilson - All Dressed Up",
"embed_url" : "https://www.youtube.com/watch?v=baGfM6dBzs8"
}
}
}
}
}
});
// startgist:67b2d5f4094c54f3f5c0:prismic-embed.js
var video = doc.get("article.video");
// Html is the code to include to embed the object, and depends on the embedded service
var html = video ? video.asHtml() : "";
// endgist
equal(html, "<iframe width=\"480\" height=\"270\" src=\"http://www.youtube.com/embed/baGfM6dBzs8?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe>");
});
it('prismic-color.js', function () {
var doc = Prismic.Api("").parseDoc({
id: "abcd",
type: "article",
data: {
article: {
"background": {
"type": "Color",
"value": "#000000"
}
}
}
});
var $ = function (x) {
return { css: function (y, z) {
} };
};
// startgist:9f56474f0946af8ff135:prismic-color.js
var bgcolor = doc.getColor("article.background");
$("#article").css("background-color", bgcolor);
// endgist
assert.equal(bgcolor, "#000000");
});
test('prismic-color.js', 1, function() {
var doc = Prismic.Api("").parseDoc({
id: "abcd",
type: "article",
data: {
article: {
"background" : {
"type" : "Color",
"value": "#000000"
}
}
}
});
var $ = function(x) {
return { css: function (y, z) {} };
};
// startgist:9f56474f0946af8ff135:prismic-color.js
var bgcolor = doc.getColor("article.background");
$("#article").css("background-color", bgcolor);
// endgist
equal(bgcolor, "#000000");
});
it('prismic-geopoint.js', function () {
var doc = Prismic.Api("").parseDoc({
id: "abcd",
type: "article",
data: {
article: {
"location": {
"type": "GeoPoint",
"value": {
"latitude": 48.877108,
"longitude": 2.3338790
}
}
}
}
});
// startgist:1cf4d536f00bb13f1178:prismic-geopoint.js
// "near" predicate for GeoPoint fragments
var near = Predicates.near("my.store.location", 48.8768767, 2.3338802, 10);
test('prismic-geopoint.js', 1, function() {
var doc = Prismic.Api("").parseDoc({
id: "abcd",
type: "article",
data: {
article: {
"location" : {
"type" : "GeoPoint",
"value" : {
"latitude" : 48.877108,
"longitude": 2.3338790
// Accessing GeoPoint fragments
var place = doc.getGeoPoint("article.location");
var coordinates;
if (place) {
coordinates = place.latitude + "," + place.longitude;
}
}
}
}
});
// startgist:1cf4d536f00bb13f1178:prismic-geopoint.js
// "near" predicate for GeoPoint fragments
var near = Predicates.near("my.store.location", 48.8768767, 2.3338802, 10);
// endgist
assert.equal(coordinates, "48.877108,2.333879");
});
// Accessing GeoPoint fragments
var place = doc.getGeoPoint("article.location");
var coordinates;
if (place) {
coordinates = place.latitude + "," + place.longitude;
}
// endgist
equal(coordinates, "48.877108,2.333879");
});
it('prismic-asHtml.js', function (done) {
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) {
console.log(err);
done();
}
Api.form('everything').ref(Api.master()).query(Prismic.Predicates.at("document.id", "UlfoxUnM0wkXYXbX")).submit(function (err, response) {
if (err) {
console.log(err);
done();
}
// startgist:63183c7f26038f884f45:prismic-asHtml.js
var doc = response.results[0];
var html = doc.getStructuredText('blog-post.body').asHtml({
linkResolver: function (ctx, doc, isBroken) {
if (isBroken) return '#broken';
return "/testing_url/" + doc.id + "/" + doc.slug + ( ctx.maybeRef ? '?ref=' + ctx.maybeRef : '' );
}
});
// endgist
assert.equal(html, '<h1>Get the right approach to ganache</h1><p>A lot of people touch base with us to know about one of our key ingredients, and the essential role it plays in our creations: ganache.</p><p>Indeed, ganache is the macaron\'s softener, or else, macarons would be but tough biscuits; it is the cupcake\'s wrapper, or else, cupcakes would be but plain old cake. We even sometimes use ganache within our cupcakes, to soften the cake itself, or as a support to our pies\' content.</p><h2>How to approach ganache</h2><p class=\"block-img\"><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/ee7b984b98db4516aba2eabd54ab498293913c6c.jpg\" alt=\"\"></p><p>Apart from the taste balance, which is always a challenge when it comes to pastry, the tough part about ganache is about thickness. It is even harder to predict through all the phases the ganache gets to meet (how long will it get melted? how long will it remain in the fridge?). Things get a hell of a lot easier to get once you consider that there are two main ways to get the perfect ganache:</p><ul><li><strong>working from the top down</strong>: start with a thick, almost hard material, and soften it by manipulating it, or by mixing it with a more liquid ingredient (like milk)</li><li><strong>working from the bottom up</strong>: start from a liquid-ish state, and harden it by miwing it with thicker ingredients, or by leaving it in the fridge longer.</li></ul><p>We do hope this advice will empower you in your ganache-making skills. Let us know how you did with it!</p><h2>Ganache at <em>Les Bonnes Choses</em></h2><p>We have a saying at Les Bonnes Choses: \"Once you can make ganache, you can make anything.\"</p><p>As you may know, we like to give our workshop artists the ability to master their art to the top; that is why our Preparation Experts always start off as being Ganache Specialists for Les Bonnes Choses. That way, they\'re given an opportunity to focus on one exercise before moving on. Once they master their ganache, and are able to provide the most optimal delight to our customers, we consider they\'ll thrive as they work on other kinds of preparations.</p><h2>About the chocolate in our ganache</h2><p>Now, we\'ve also had a lot of questions about how our chocolate gets made. It\'s true, as you might know, that we make it ourselves, from Columbian cocoa and French cow milk, with a process that much resembles the one in the following Discovery Channel documentary.</p><div data-oembed=\"undefined\" data-oembed-type=\"embed\" data-oembed-provider=\"undefined\"><iframe width=\"459\" height=\"344\" src=\"http://www.youtube.com/embed/Ye78F3-CuXY?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe></div>');
done();
});
});
});
asyncTest('prismic-asHtml.js', 1, function() {
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').ref(Api.master()).query(Prismic.Predicates.at("document.id", "UlfoxUnM0wkXYXbX")).submit(function (err, response) {
if (err) { console.log(err); start(); }
// startgist:63183c7f26038f884f45:prismic-asHtml.js
var doc = response.results[0];
var html = doc.getStructuredText('blog-post.body').asHtml({
linkResolver: function (ctx, doc, isBroken) {
if (isBroken) return '#broken';
return "/testing_url/" + doc.id + "/" + doc.slug + ( ctx.maybeRef ? '?ref=' + ctx.maybeRef : '' );
}
});
// endgist
equal(html, '<h1>Get the right approach to ganache</h1><p>A lot of people touch base with us to know about one of our key ingredients, and the essential role it plays in our creations: ganache.</p><p>Indeed, ganache is the macaron\'s softener, or else, macarons would be but tough biscuits; it is the cupcake\'s wrapper, or else, cupcakes would be but plain old cake. We even sometimes use ganache within our cupcakes, to soften the cake itself, or as a support to our pies\' content.</p><h2>How to approach ganache</h2><p class=\"block-img\"><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/ee7b984b98db4516aba2eabd54ab498293913c6c.jpg\" alt=\"\"></p><p>Apart from the taste balance, which is always a challenge when it comes to pastry, the tough part about ganache is about thickness. It is even harder to predict through all the phases the ganache gets to meet (how long will it get melted? how long will it remain in the fridge?). Things get a hell of a lot easier to get once you consider that there are two main ways to get the perfect ganache:</p><ul><li><strong>working from the top down</strong>: start with a thick, almost hard material, and soften it by manipulating it, or by mixing it with a more liquid ingredient (like milk)</li><li><strong>working from the bottom up</strong>: start from a liquid-ish state, and harden it by miwing it with thicker ingredients, or by leaving it in the fridge longer.</li></ul><p>We do hope this advice will empower you in your ganache-making skills. Let us know how you did with it!</p><h2>Ganache at <em>Les Bonnes Choses</em></h2><p>We have a saying at Les Bonnes Choses: \"Once you can make ganache, you can make anything.\"</p><p>As you may know, we like to give our workshop artists the ability to master their art to the top; that is why our Preparation Experts always start off as being Ganache Specialists for Les Bonnes Choses. That way, they\'re given an opportunity to focus on one exercise before moving on. Once they master their ganache, and are able to provide the most optimal delight to our customers, we consider they\'ll thrive as they work on other kinds of preparations.</p><h2>About the chocolate in our ganache</h2><p>Now, we\'ve also had a lot of questions about how our chocolate gets made. It\'s true, as you might know, that we make it ourselves, from Columbian cocoa and French cow milk, with a process that much resembles the one in the following Discovery Channel documentary.</p><div data-oembed=\"undefined\" data-oembed-type=\"embed\" data-oembed-provider=\"undefined\"><iframe width=\"459\" height=\"344\" src=\"http://www.youtube.com/embed/Ye78F3-CuXY?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe></div>');
start();
});
});
});
/* Temporary deactivate because problem with PhantomJS
asyncTest('prismic-cache.js', 1, function(){
// startgist:647bde5c458c44af0981:prismic-cache.js
var cache = {
get: function (key) {
// Retrieve a value from the key
return null;
},
describe('Cache', function() {
set: function (key, value, ttl) {
// Save a value to the cache
// ttl is the time to live, or expiration in seconds
},
it('prismic-cache.js', function(done) {
// startgist:647bde5c458c44af0981:prismic-cache.js
var cache = {
get: function (key, cb) {
// Retrieve a value from the key
return cb();
},
getOrSet: function (key, ttl, fvalue, done) {
// Retrieve the value if present, otherwise use the fvalue callback to calculate the value,
// save it then return it by calling the "done" callback.
// The done callback takes 2 parameters: error and result.
fvalue(function (error, result, hdr) {
done(null, result);
});
},
set: function (key, value, ttl, cb) {
return cb();
},
isExpired: function (key) {
// Return true if the key exists and is expired, false if the value is either absent or not expired
return false;
},
remove: function (key, cb) {
// Remove a value
return cb();
},
isInProgress: function (key) {
// Return true if the value is being saved currently
return false;
},
clear: function (key, cb) {
return cb();
}
};
exists: function (key) {
// Return true if the value for the key exists
return false;
},
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) return done(err); // gisthide
// The Api in this block will use the custom cache object
assert.notEqual(Api, null); // gisthide
done(); // gisthide
}, null, null, cache);
// endgist
});
remove: function (key) {
// Remove a value
},
});
clear: function (key) {
// Clear the whole cache
}
};
Prismic.Api('https://lesbonneschoses.prismic.io/api', function (err, Api) {
if (err) {
console.log(err);
start();
} // gisthide
// The Api in this block will use the custom cache object
notEqual(Api, null); // gisthide
start(); // gisthide
}, null, null, cache);
// endgist
});
*/
}(window.Prismic));
(function(Prismic) {
var testRepository = 'https://lesbonneschoses.prismic.io/api',
var assert = chai.assert,
testRepository = 'https://lesbonneschoses.prismic.io/api',
previewToken = 'MC5VbDdXQmtuTTB6Z0hNWHF3.c--_vVbvv73vv73vv73vv71EA--_vS_vv73vv70T77-9Ke-_ve-_vWfvv70ebO-_ve-_ve-_vQN377-9ce-_vRfvv70',
microRepository = 'https://micro.prismic.io/api',
Predicates = Prismic.Predicates;
previewToken = 'MC5VbDdXQmtuTTB6Z0hNWHF3.c--_vVbvv73vv73vv73vv71EA--_vS_vv73vv70T77-9Ke-_ve-_vWfvv70ebO-_ve-_ve-_vQN377-9ce-_vRfvv70',
function getLinkResolver(ref) {
return function(doc, isBroken) {
if (isBroken) return '#broken';
return "/testing_url/" + doc.id + "/" + doc.slug + (ref ? ('?ref=' + ref) : '');
}
}
microRepository = 'https://micro.prismic.io/api',
describe('Document manipulation', function() {
Predicates = Prismic.Predicates;
it('Stores and retrieves all document slugs well', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbg")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
var doc = documents.results[0];
assert.equal(doc.slugs.length, 2);
done();
});
});
});
function getLinkResolver(ref) {
return function(doc, isBroken) {
if (isBroken) return '#broken';
return "/testing_url/" + doc.id + "/" + doc.slug + (ref ? ('?ref=' + ref) : '');
}
}
it('Render a document to Html', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
var first = documents.results[0];
assert.notEqual(null, first);
first.asHtml(getLinkResolver());
done();
});
});
});
module('Prismic.io', {
setup: function() {}
});
it('Render a document to Text', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbX")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
function fix(s) {
// remove dates and timezone
return s.replace(/[A-Z][a-z]{2,4} [A-Z][a-z]{2,4} \d{2} \d{4} \d{2}:\d{2}:\d{2} GMT[+-]\d{4} \([^)]+\)/g, '<DATE>');
}
/*************************/
/* Document manipulation */
/*************************/
assert.equal(fix(documents.results[0].asText(getLinkResolver('XXXXX'))), fix("Get the right approach to ganache A lot of people touch base with us to know about one of our key ingredients, and the essential role it plays in our creations: ganache. Indeed, ganache is the macaron's softener, or else, macarons would be but tough biscuits; it is the cupcake's wrapper, or else, cupcakes would be but plain old cake. We even sometimes use ganache within our cupcakes, to soften the cake itself, or as a support to our pies' content. How to approach ganache Apart from the taste balance, which is always a challenge when it comes to pastry, the tough part about ganache is about thickness. It is even harder to predict through all the phases the ganache gets to meet (how long will it get melted? how long will it remain in the fridge?). Things get a hell of a lot easier to get once you consider that there are two main ways to get the perfect ganache: working from the top down: start with a thick, almost hard material, and soften it by manipulating it, or by mixing it with a more liquid ingredient (like milk) working from the bottom up: start from a liquid-ish state, and harden it by miwing it with thicker ingredients, or by leaving it in the fridge longer. We do hope this advice will empower you in your ganache-making skills. Let us know how you did with it! Ganache at Les Bonnes Choses We have a saying at Les Bonnes Choses: \"Once you can make ganache, you can make anything.\" As you may know, we like to give our workshop artists the ability to master their art to the top; that is why our Preparation Experts always start off as being Ganache Specialists for Les Bonnes Choses. That way, they're given an opportunity to focus on one exercise before moving on. Once they master their ganache, and are able to provide the most optimal delight to our customers, we consider they'll thrive as they work on other kinds of preparations. About the chocolate in our ganache Now, we've also had a lot of questions about how our chocolate gets made. It's true, as you might know, that we make it ourselves, from Columbian cocoa and French cow milk, with a process that much resembles the one in the following Discovery Channel documentary.Ganache is a tricky topic, but here's some guidance.Tue Jul 23 2013 17:00:00 GMT-0700 (PDT)Steve Adams, Ganache SpecialistDo it yourselfYes/testing_url/UlfoxUnM0wkXYXbj/triple-chocolate-cupcake?ref=XXXXX/testing_url/UlfoxUnM0wkXYXbm/tips-to-dress-a-pastry?ref=XXXXX"));
done();
});
});
});
asyncTest('Stores and retrieves all document slugs well', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbg")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
var doc = documents.results[0];
equal(doc.slugs.length, 2);
start();
});
});
});
asyncTest('Render a document to Html', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
var first = documents.results[0];
notEqual(null, first);
first.asHtml(getLinkResolver());
start();
});
});
});
describe('StructuredText', function() {
asyncTest('Render a document to Text', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbX")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
function fix(s) {
// remove dates and timezone
return s.replace(/[A-Z][a-z]{2,4} [A-Z][a-z]{2,4} \d{2} \d{4} \d{2}:\d{2}:\d{2} GMT[+-]\d{4} \([^)]+\)/g, '<DATE>');
}
equal(fix(documents.results[0].asText(getLinkResolver('XXXXX'))), fix("Get the right approach to ganache A lot of people touch base with us to know about one of our key ingredients, and the essential role it plays in our creations: ganache. Indeed, ganache is the macaron's softener, or else, macarons would be but tough biscuits; it is the cupcake's wrapper, or else, cupcakes would be but plain old cake. We even sometimes use ganache within our cupcakes, to soften the cake itself, or as a support to our pies' content. How to approach ganache Apart from the taste balance, which is always a challenge when it comes to pastry, the tough part about ganache is about thickness. It is even harder to predict through all the phases the ganache gets to meet (how long will it get melted? how long will it remain in the fridge?). Things get a hell of a lot easier to get once you consider that there are two main ways to get the perfect ganache: working from the top down: start with a thick, almost hard material, and soften it by manipulating it, or by mixing it with a more liquid ingredient (like milk) working from the bottom up: start from a liquid-ish state, and harden it by miwing it with thicker ingredients, or by leaving it in the fridge longer. We do hope this advice will empower you in your ganache-making skills. Let us know how you did with it! Ganache at Les Bonnes Choses We have a saying at Les Bonnes Choses: \"Once you can make ganache, you can make anything.\" As you may know, we like to give our workshop artists the ability to master their art to the top; that is why our Preparation Experts always start off as being Ganache Specialists for Les Bonnes Choses. That way, they're given an opportunity to focus on one exercise before moving on. Once they master their ganache, and are able to provide the most optimal delight to our customers, we consider they'll thrive as they work on other kinds of preparations. About the chocolate in our ganache Now, we've also had a lot of questions about how our chocolate gets made. It's true, as you might know, that we make it ourselves, from Columbian cocoa and French cow milk, with a process that much resembles the one in the following Discovery Channel documentary.Ganache is a tricky topic, but here's some guidance.Tue Jul 23 2013 17:00:00 GMT-0700 (PDT)Steve Adams, Ganache SpecialistDo it yourselfYes/testing_url/UlfoxUnM0wkXYXbj/triple-chocolate-cupcake?ref=XXXXX/testing_url/UlfoxUnM0wkXYXbm/tips-to-dress-a-pastry?ref=XXXXX"));
start();
});
});
});
it('asHtml handles embeds and lists', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbX")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
assert.equal(documents.results[0].getStructuredText('blog-post.body').asHtml(), '<h1>Get the right approach to ganache</h1><p>A lot of people touch base with us to know about one of our key ingredients, and the essential role it plays in our creations: ganache.</p><p>Indeed, ganache is the macaron\'s softener, or else, macarons would be but tough biscuits; it is the cupcake\'s wrapper, or else, cupcakes would be but plain old cake. We even sometimes use ganache within our cupcakes, to soften the cake itself, or as a support to our pies\' content.</p><h2>How to approach ganache</h2><p class=\"block-img\"><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/ee7b984b98db4516aba2eabd54ab498293913c6c.jpg\" alt=\"\"></p><p>Apart from the taste balance, which is always a challenge when it comes to pastry, the tough part about ganache is about thickness. It is even harder to predict through all the phases the ganache gets to meet (how long will it get melted? how long will it remain in the fridge?). Things get a hell of a lot easier to get once you consider that there are two main ways to get the perfect ganache:</p><ul><li><strong>working from the top down</strong>: start with a thick, almost hard material, and soften it by manipulating it, or by mixing it with a more liquid ingredient (like milk)</li><li><strong>working from the bottom up</strong>: start from a liquid-ish state, and harden it by miwing it with thicker ingredients, or by leaving it in the fridge longer.</li></ul><p>We do hope this advice will empower you in your ganache-making skills. Let us know how you did with it!</p><h2>Ganache at <em>Les Bonnes Choses</em></h2><p>We have a saying at Les Bonnes Choses: \"Once you can make ganache, you can make anything.\"</p><p>As you may know, we like to give our workshop artists the ability to master their art to the top; that is why our Preparation Experts always start off as being Ganache Specialists for Les Bonnes Choses. That way, they\'re given an opportunity to focus on one exercise before moving on. Once they master their ganache, and are able to provide the most optimal delight to our customers, we consider they\'ll thrive as they work on other kinds of preparations.</p><h2>About the chocolate in our ganache</h2><p>Now, we\'ve also had a lot of questions about how our chocolate gets made. It\'s true, as you might know, that we make it ourselves, from Columbian cocoa and French cow milk, with a process that much resembles the one in the following Discovery Channel documentary.</p><div data-oembed=\"undefined\" data-oembed-type=\"embed\" data-oembed-provider=\"undefined\"><iframe width=\"459\" height=\"344\" src=\"http://www.youtube.com/embed/Ye78F3-CuXY?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe></div>');
done();
});
}, previewToken);
});
asyncTest('StructuredTexts asHtml handles embeds and lists', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbX")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
equal(documents.results[0].getStructuredText('blog-post.body').asHtml(), '<h1>Get the right approach to ganache</h1><p>A lot of people touch base with us to know about one of our key ingredients, and the essential role it plays in our creations: ganache.</p><p>Indeed, ganache is the macaron\'s softener, or else, macarons would be but tough biscuits; it is the cupcake\'s wrapper, or else, cupcakes would be but plain old cake. We even sometimes use ganache within our cupcakes, to soften the cake itself, or as a support to our pies\' content.</p><h2>How to approach ganache</h2><p class=\"block-img\"><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/ee7b984b98db4516aba2eabd54ab498293913c6c.jpg\" alt=\"\"></p><p>Apart from the taste balance, which is always a challenge when it comes to pastry, the tough part about ganache is about thickness. It is even harder to predict through all the phases the ganache gets to meet (how long will it get melted? how long will it remain in the fridge?). Things get a hell of a lot easier to get once you consider that there are two main ways to get the perfect ganache:</p><ul><li><strong>working from the top down</strong>: start with a thick, almost hard material, and soften it by manipulating it, or by mixing it with a more liquid ingredient (like milk)</li><li><strong>working from the bottom up</strong>: start from a liquid-ish state, and harden it by miwing it with thicker ingredients, or by leaving it in the fridge longer.</li></ul><p>We do hope this advice will empower you in your ganache-making skills. Let us know how you did with it!</p><h2>Ganache at <em>Les Bonnes Choses</em></h2><p>We have a saying at Les Bonnes Choses: \"Once you can make ganache, you can make anything.\"</p><p>As you may know, we like to give our workshop artists the ability to master their art to the top; that is why our Preparation Experts always start off as being Ganache Specialists for Les Bonnes Choses. That way, they\'re given an opportunity to focus on one exercise before moving on. Once they master their ganache, and are able to provide the most optimal delight to our customers, we consider they\'ll thrive as they work on other kinds of preparations.</p><h2>About the chocolate in our ganache</h2><p>Now, we\'ve also had a lot of questions about how our chocolate gets made. It\'s true, as you might know, that we make it ourselves, from Columbian cocoa and French cow milk, with a process that much resembles the one in the following Discovery Channel documentary.</p><div data-oembed=\"undefined\" data-oembed-type=\"embed\" data-oembed-provider=\"undefined\"><iframe width=\"459\" height=\"344\" src=\"http://www.youtube.com/embed/Ye78F3-CuXY?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe></div>');
start();
});
}, previewToken);
});
it('asText works', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbX")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
assert.equal(documents.results[0].getStructuredText('blog-post.body').asText(), "Get the right approach to ganache A lot of people touch base with us to know about one of our key ingredients, and the essential role it plays in our creations: ganache. Indeed, ganache is the macaron's softener, or else, macarons would be but tough biscuits; it is the cupcake's wrapper, or else, cupcakes would be but plain old cake. We even sometimes use ganache within our cupcakes, to soften the cake itself, or as a support to our pies' content. How to approach ganache Apart from the taste balance, which is always a challenge when it comes to pastry, the tough part about ganache is about thickness. It is even harder to predict through all the phases the ganache gets to meet (how long will it get melted? how long will it remain in the fridge?). Things get a hell of a lot easier to get once you consider that there are two main ways to get the perfect ganache: working from the top down: start with a thick, almost hard material, and soften it by manipulating it, or by mixing it with a more liquid ingredient (like milk) working from the bottom up: start from a liquid-ish state, and harden it by miwing it with thicker ingredients, or by leaving it in the fridge longer. We do hope this advice will empower you in your ganache-making skills. Let us know how you did with it! Ganache at Les Bonnes Choses We have a saying at Les Bonnes Choses: \"Once you can make ganache, you can make anything.\" As you may know, we like to give our workshop artists the ability to master their art to the top; that is why our Preparation Experts always start off as being Ganache Specialists for Les Bonnes Choses. That way, they're given an opportunity to focus on one exercise before moving on. Once they master their ganache, and are able to provide the most optimal delight to our customers, we consider they'll thrive as they work on other kinds of preparations. About the chocolate in our ganache Now, we've also had a lot of questions about how our chocolate gets made. It's true, as you might know, that we make it ourselves, from Columbian cocoa and French cow milk, with a process that much resembles the one in the following Discovery Channel documentary.");
done();
});
}, previewToken);
});
asyncTest('StructuredTexts asText works', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbX")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
equal(documents.results[0].getStructuredText('blog-post.body').asText(), "Get the right approach to ganache A lot of people touch base with us to know about one of our key ingredients, and the essential role it plays in our creations: ganache. Indeed, ganache is the macaron's softener, or else, macarons would be but tough biscuits; it is the cupcake's wrapper, or else, cupcakes would be but plain old cake. We even sometimes use ganache within our cupcakes, to soften the cake itself, or as a support to our pies' content. How to approach ganache Apart from the taste balance, which is always a challenge when it comes to pastry, the tough part about ganache is about thickness. It is even harder to predict through all the phases the ganache gets to meet (how long will it get melted? how long will it remain in the fridge?). Things get a hell of a lot easier to get once you consider that there are two main ways to get the perfect ganache: working from the top down: start with a thick, almost hard material, and soften it by manipulating it, or by mixing it with a more liquid ingredient (like milk) working from the bottom up: start from a liquid-ish state, and harden it by miwing it with thicker ingredients, or by leaving it in the fridge longer. We do hope this advice will empower you in your ganache-making skills. Let us know how you did with it! Ganache at Les Bonnes Choses We have a saying at Les Bonnes Choses: \"Once you can make ganache, you can make anything.\" As you may know, we like to give our workshop artists the ability to master their art to the top; that is why our Preparation Experts always start off as being Ganache Specialists for Les Bonnes Choses. That way, they're given an opportunity to focus on one exercise before moving on. Once they master their ganache, and are able to provide the most optimal delight to our customers, we consider they'll thrive as they work on other kinds of preparations. About the chocolate in our ganache Now, we've also had a lot of questions about how our chocolate gets made. It's true, as you might know, that we make it ourselves, from Columbian cocoa and French cow milk, with a process that much resembles the one in the following Discovery Channel documentary.");
start();
});
}, previewToken);
});
it('asHtml handles preformatted', function (done) {
Prismic.Api(microRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UrDejAEAAFwMyrW9")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
assert.equal(
documents.results[0].getStructuredText('doc.content').asHtml(getLinkResolver()),
'<p>Meta-micro gets installed pretty much like any javascript library:</p><ol><li><a href=\"/testing_url/U0w8OwEAACoAQEvB/download-meta-micro\">download</a> the .js file: get the minified one, unless the framework you\'re using minifies your .js files automatically.</li><li>add a link towards the file in your webpage\'s head.</li></ol><p>The link might look like this, anywhere inside your head tag:</p><pre>&lt;script type=\"text/javascript\" src=\"meta-micro.min.js\"&gt;&lt;/script&gt;</pre><p>You\'re all set!</p>');
done();
});
});
});
asyncTest('StructuredTexts asHtml handles preformatted', 1, function() {
Prismic.Api(microRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UrDejAEAAFwMyrW9")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
equal(
documents.results[0].getStructuredText('doc.content').asHtml(getLinkResolver()),
'<p>Meta-micro gets installed pretty much like any javascript library:</p><ol><li><a href=\"/testing_url/U0w8OwEAACoAQEvB/download-meta-micro\">download</a> the .js file: get the minified one, unless the framework you\'re using minifies your .js files automatically.</li><li>add a link towards the file in your webpage\'s head.</li></ol><p>The link might look like this, anywhere inside your head tag:</p><pre>&lt;script type=\"text/javascript\" src=\"meta-micro.min.js\"&gt;&lt;/script&gt;</pre><p>You\'re all set!</p>');
start();
});
});
});
it('Test backward-compatibility with passing a ctx instead of just a linkResolver', function (done) {
Prismic.Api(microRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UrDejAEAAFwMyrW9")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
assert.equal(
documents.results[0].getStructuredText('doc.content').asHtml({
api: undefined,
ref: { ref: 'XXXXX', label: 'Future release', isMaster: false },
maybeRef: 'XXXXX',
oauth: function () {
},
linkResolver: function (ctx, doc, isBroken) {
if (isBroken) return '#broken';
return "/testing_url/" + doc.id + "/" + doc.slug + ( ctx.maybeRef ? '?ref=' + ctx.maybeRef : '' );
}
}),
'<p>Meta-micro gets installed pretty much like any javascript library:</p><ol><li><a href=\"/testing_url/U0w8OwEAACoAQEvB/download-meta-micro?ref=XXXXX\">download</a> the .js file: get the minified one, unless the framework you\'re using minifies your .js files automatically.</li><li>add a link towards the file in your webpage\'s head.</li></ol><p>The link might look like this, anywhere inside your head tag:</p><pre>&lt;script type=\"text/javascript\" src=\"meta-micro.min.js\"&gt;&lt;/script&gt;</pre><p>You\'re all set!</p>');
done();
});
});
});
asyncTest('Test backward-compatibility with passing a ctx instead of just a linkResolver', 1, function() {
Prismic.Api(microRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UrDejAEAAFwMyrW9")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
equal(
documents.results[0].getStructuredText('doc.content').asHtml({
api: undefined,
ref: { ref: 'XXXXX', label: 'Future release', isMaster: false },
maybeRef: 'XXXXX',
oauth: function() { },
linkResolver: function(ctx, doc, isBroken) {
if (isBroken) return '#broken';
return "/testing_url/"+doc.id+"/"+doc.slug+( ctx.maybeRef ? '?ref=' + ctx.maybeRef : '' );
}
}),
'<p>Meta-micro gets installed pretty much like any javascript library:</p><ol><li><a href=\"/testing_url/U0w8OwEAACoAQEvB/download-meta-micro?ref=XXXXX\">download</a> the .js file: get the minified one, unless the framework you\'re using minifies your .js files automatically.</li><li>add a link towards the file in your webpage\'s head.</li></ol><p>The link might look like this, anywhere inside your head tag:</p><pre>&lt;script type=\"text/javascript\" src=\"meta-micro.min.js\"&gt;&lt;/script&gt;</pre><p>You\'re all set!</p>');
start();
});
});
});
it('asHtml handles spans', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbt")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
assert.equal(documents.results[0].getStructuredText('blog-post.body').asHtml(), '<h1>The end of a chapter the beginning of a new one</h1><p class="block-img"><img src="https://prismic-io.s3.amazonaws.com/lesbonneschoses/8181933ff2f5032daff7d732e33a3beb6f57e09f.jpg" alt=\"\"></p><p>Jean-Michel Pastranova, the founder of <em>Les Bonnes Choses</em>, and creator of the whole concept of modern fine pastry, has decided to step down as the CEO and the Director of Workshops of <em>Les Bonnes Choses</em>, to focus on other projects, among which his now best-selling pastry cook books, but also to take on a primary role in a culinary television show to be announced later this year.</p><p>"I believe I\'ve taken the <em>Les Bonnes Choses</em> concept as far as it can go. <em>Les Bonnes Choses</em> is already an entity that is driven by its people, thanks to a strong internal culture, so I don\'t feel like they need me as much as they used to. I\'m sure they are greater ways to come, to innovate in pastry, and I\'m sure <em>Les Bonnes Choses</em>\'s coming innovation will be even more mind-blowing than if I had stayed longer."</p><p>He will remain as a senior advisor to the board, and to the workshop artists, as his daughter Selena, who has been working with him for several years, will fulfill the CEO role from now on.</p><p>"My father was able not only to create a revolutionary concept, but also a company culture that puts everyone in charge of driving the company\'s innovation and quality. That gives us years, maybe decades of revolutionary ideas to come, and there\'s still a long, wonderful path to walk in the fine pastry world."</p>');
done();
});
}, previewToken);
});
asyncTest('StructuredTexts asHtml handles spans', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbt")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
equal(documents.results[0].getStructuredText('blog-post.body').asHtml(), '<h1>The end of a chapter the beginning of a new one</h1><p class="block-img"><img src="https://prismic-io.s3.amazonaws.com/lesbonneschoses/8181933ff2f5032daff7d732e33a3beb6f57e09f.jpg" alt=\"\"></p><p>Jean-Michel Pastranova, the founder of <em>Les Bonnes Choses</em>, and creator of the whole concept of modern fine pastry, has decided to step down as the CEO and the Director of Workshops of <em>Les Bonnes Choses</em>, to focus on other projects, among which his now best-selling pastry cook books, but also to take on a primary role in a culinary television show to be announced later this year.</p><p>"I believe I\'ve taken the <em>Les Bonnes Choses</em> concept as far as it can go. <em>Les Bonnes Choses</em> is already an entity that is driven by its people, thanks to a strong internal culture, so I don\'t feel like they need me as much as they used to. I\'m sure they are greater ways to come, to innovate in pastry, and I\'m sure <em>Les Bonnes Choses</em>\'s coming innovation will be even more mind-blowing than if I had stayed longer."</p><p>He will remain as a senior advisor to the board, and to the workshop artists, as his daughter Selena, who has been working with him for several years, will fulfill the CEO role from now on.</p><p>"My father was able not only to create a revolutionary concept, but also a company culture that puts everyone in charge of driving the company\'s innovation and quality. That gives us years, maybe decades of revolutionary ideas to come, and there\'s still a long, wonderful path to walk in the fine pastry world."</p>');
start();
});
}, previewToken);
});
it('asHtml handles span Link.web', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbW")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
assert.equal(documents.results[0].getStructuredText('job-offer.profile').asHtml(), '<p>As a company whose marketing is very content-centric, we expect our Content Director to have a tremendous experience, both in content strategy, and in content writing. We expect our applicants to show off some of the content strategies they set up themselves, explaining their choices, and to provide amazing contents they personally wrote.</p><p>Our contents get flexibly powerfully shared on various supports: our site, our in-store printed magazine, our mobile apps, our mailings ... Our Content Director must have experience with all of those, and with using modern adaptive content managers such as <a href=\"http://prismic.io\">prismic.io</a>.</p>');
done();
});
}, previewToken);
});
asyncTest('StructuredTexts asHtml handles span Link.web', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbW")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
equal(documents.results[0].getStructuredText('job-offer.profile').asHtml(), '<p>As a company whose marketing is very content-centric, we expect our Content Director to have a tremendous experience, both in content strategy, and in content writing. We expect our applicants to show off some of the content strategies they set up themselves, explaining their choices, and to provide amazing contents they personally wrote.</p><p>Our contents get flexibly powerfully shared on various supports: our site, our in-store printed magazine, our mobile apps, our mailings ... Our Content Director must have experience with all of those, and with using modern adaptive content managers such as <a href=\"http://prismic.io\">prismic.io</a>.</p>');
start();
});
}, previewToken);
});
it('asHtml handles span Link.document', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbl")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
assert.equal(documents.results[0].getStructuredText('blog-post.body').asHtml(getLinkResolver('XXXXX')), '<h1>Our world-famous Pastry Art Brainstorm event</h1><p class=\"block-img\"><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg\" alt=\"\"></p><p>Each year, <em>Les Bonnes Choses</em> organizes a world-famous two-day event called the \"Pastry Art Brainstorm\", and which is the perfect excuse for every fine pastry artist in the world to exercise their art, and build their skills up. The event is a multiple win-win operation, at many levels: see what the event is, as seen by many point of views.</p><h2>As seen by the top pastry artists worldwide</h2><p>The event always starts with half a day of conference talks, given by the most insightful pastry artists in the world, selected for having made tremendous achievements in pastry that year. The list of invited guest speakers is decided jointly by the <em>Les Bonnes Choses</em> staff and the Fine Pastry Magazine editors.</p><p>This is great for the speakers, who get an occasion to share their work, and have people build up on it with them.</p><h2>As seen by the pastry professionals</h2><p>After half a day of thoughtful conference, the professionals will get to put what they learned to good use, and mingle with the best artists worldwide to make the most daring pastries together. There are no set rules about who does what during this giant innovation workshop, and many crazy ideas get created out of thin air. As a virtually infinite amount of ingredients is provided by the <em>Les Bonnes Choses</em> staff, many unexpected pastries happen on that day, and professionals taste each other\'s creations, and provide relevant feedback to each other. Most pieces get showcased to the amateur audience as well, who get invited to taste some of the pieces.</p><p>At noon on the second day, teams are expected to subscribe to our Pastry Art Challenge, during which they will make the best possible pastry, judged on many aspects (originality, taste, looks, ...) by a jury of amateurs and professionals. The team members of the three winning pieces share a substantial prize, and their pastries may even join the Les Bonnes Choses catalogue, and be offered in all the <em>Les Bonnes Choses</em> shops worldwide!</p><h2>As seen by the pastry amateurs</h2><p>The conference is limited with a reasonable fee; but the showcase is open to everyone, although visitors are often expected to pay the pastry chefs for the pastries they taste. The educated amateurs spend their day tasting the most daring pieces, giving some appreciated feedback to their chefs, and challenging their own tastebuds. The novice amateurs usually get a once-in-a-lifetime experience, and often mention being blown away by how rich the fine pastry art can be. All in all, every one goes home with a smile on their faces!</p><h2>As seen by the Les Bonnes Choses interns</h2><p>Every year, we recruit a very limited amount of interns, who get aboard a <a href=\"/testing_url/UlfoxUnM0wkXYXbu/les-bonnes-chosess-internship-a-testimony?ref=XXXXX\">life-defining adventure around fine pastries</a>, discovering <em>Les Bonnes Choses</em> during half a year, with part of this time spent in one of our shops abroad. We always manage to get them on board at a time when we know they will be able to attend a Fine Pastry Brainstorm, because we consider it is a very defining element in the experience of being part of <em>Les Bonnes Choses</em>.</p><p>Not only do we invite them to the event (whatever the country they are stationed in when the event happens), but we give them a front-row seat! They are part of the jury for the Fine Pastry Challenge, they are introduced to every speaker as the next generation of pastry (thus having the occasion to learn even more, directly from them).</p><h2>As seen by fine pastry as a field</h2><p>There wasn\'t really an international occasion for pastry artists to join and share, before <em>Les Bonnes Choses</em> came up with the first Fine Pastry Brainstorm, in 2006. Fine Pastry Magazine\'s first edition was out in 2004, and initiated the idea that pastry art needed to be shared better between professionals. But a proper event to meet up in person was missing, and <em>Les Bonnes Choses</em> is proud to be the one to have come up with it first.</p><p>Since then, more local initiatives have been started (notably in Argentina, and Canada), but none comes close to the size of <em>Les Bonnes Choses</em>\'s international Fine Pastry Brainstorm.</p><h2>As seen by <em>Les Bonnes Choses</em></h2><p>As the almost only sponsor of every edition of the event, <em>Les Bonnes Choses</em> makes sure enough ingredients are available for everyone, rents the premises, makes sure the speakers are as comfortable as possible, and takes care of the whole organization! But through the operation, <em>Les Bonnes Choses</em> gains much more than any sponsoring can buy: not only does it get to secure <em>Les Bonnes Choses</em> as the world reference in pastry arts, but it also allows them to claim rightfully that they do offer in their shops the best pastries, created by the world top artists indeed.</p>');
done();
});
}, previewToken);
});
asyncTest('StructuredTexts asHtml handles span Link.document', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbl")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
equal(documents.results[0].getStructuredText('blog-post.body').asHtml(getLinkResolver('XXXXX')), '<h1>Our world-famous Pastry Art Brainstorm event</h1><p class=\"block-img\"><img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg\" alt=\"\"></p><p>Each year, <em>Les Bonnes Choses</em> organizes a world-famous two-day event called the \"Pastry Art Brainstorm\", and which is the perfect excuse for every fine pastry artist in the world to exercise their art, and build their skills up. The event is a multiple win-win operation, at many levels: see what the event is, as seen by many point of views.</p><h2>As seen by the top pastry artists worldwide</h2><p>The event always starts with half a day of conference talks, given by the most insightful pastry artists in the world, selected for having made tremendous achievements in pastry that year. The list of invited guest speakers is decided jointly by the <em>Les Bonnes Choses</em> staff and the Fine Pastry Magazine editors.</p><p>This is great for the speakers, who get an occasion to share their work, and have people build up on it with them.</p><h2>As seen by the pastry professionals</h2><p>After half a day of thoughtful conference, the professionals will get to put what they learned to good use, and mingle with the best artists worldwide to make the most daring pastries together. There are no set rules about who does what during this giant innovation workshop, and many crazy ideas get created out of thin air. As a virtually infinite amount of ingredients is provided by the <em>Les Bonnes Choses</em> staff, many unexpected pastries happen on that day, and professionals taste each other\'s creations, and provide relevant feedback to each other. Most pieces get showcased to the amateur audience as well, who get invited to taste some of the pieces.</p><p>At noon on the second day, teams are expected to subscribe to our Pastry Art Challenge, during which they will make the best possible pastry, judged on many aspects (originality, taste, looks, ...) by a jury of amateurs and professionals. The team members of the three winning pieces share a substantial prize, and their pastries may even join the Les Bonnes Choses catalogue, and be offered in all the <em>Les Bonnes Choses</em> shops worldwide!</p><h2>As seen by the pastry amateurs</h2><p>The conference is limited with a reasonable fee; but the showcase is open to everyone, although visitors are often expected to pay the pastry chefs for the pastries they taste. The educated amateurs spend their day tasting the most daring pieces, giving some appreciated feedback to their chefs, and challenging their own tastebuds. The novice amateurs usually get a once-in-a-lifetime experience, and often mention being blown away by how rich the fine pastry art can be. All in all, every one goes home with a smile on their faces!</p><h2>As seen by the Les Bonnes Choses interns</h2><p>Every year, we recruit a very limited amount of interns, who get aboard a <a href=\"/testing_url/UlfoxUnM0wkXYXbu/les-bonnes-chosess-internship-a-testimony?ref=XXXXX\">life-defining adventure around fine pastries</a>, discovering <em>Les Bonnes Choses</em> during half a year, with part of this time spent in one of our shops abroad. We always manage to get them on board at a time when we know they will be able to attend a Fine Pastry Brainstorm, because we consider it is a very defining element in the experience of being part of <em>Les Bonnes Choses</em>.</p><p>Not only do we invite them to the event (whatever the country they are stationed in when the event happens), but we give them a front-row seat! They are part of the jury for the Fine Pastry Challenge, they are introduced to every speaker as the next generation of pastry (thus having the occasion to learn even more, directly from them).</p><h2>As seen by fine pastry as a field</h2><p>There wasn\'t really an international occasion for pastry artists to join and share, before <em>Les Bonnes Choses</em> came up with the first Fine Pastry Brainstorm, in 2006. Fine Pastry Magazine\'s first edition was out in 2004, and initiated the idea that pastry art needed to be shared better between professionals. But a proper event to meet up in person was missing, and <em>Les Bonnes Choses</em> is proud to be the one to have come up with it first.</p><p>Since then, more local initiatives have been started (notably in Argentina, and Canada), but none comes close to the size of <em>Les Bonnes Choses</em>\'s international Fine Pastry Brainstorm.</p><h2>As seen by <em>Les Bonnes Choses</em></h2><p>As the almost only sponsor of every edition of the event, <em>Les Bonnes Choses</em> makes sure enough ingredients are available for everyone, rents the premises, makes sure the speakers are as comfortable as possible, and takes care of the whole organization! But through the operation, <em>Les Bonnes Choses</em> gains much more than any sponsoring can buy: not only does it get to secure <em>Les Bonnes Choses</em> as the world reference in pastry arts, but it also allows them to claim rightfully that they do offer in their shops the best pastries, created by the world top artists indeed.</p>');
start();
});
}, previewToken);
});
it('asHtml with custom serializer', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbl")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
var htmlSerializer = function (element, content) {
if (element.type == "image") {
return '<img src="' + element.url + '" alt="' + element.alt + '">';
}
asyncTest('StructuredTexts asHtml with custom serializer', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbl")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
var htmlSerializer = function (element, content) {
if (element.type == "image") {
return '<img src="' + element.url + '" alt="' + element.alt + '">';
}
if (element.type == "hyperlink") {
return '<a class="some-link" href="' + element.url + '">' + content + '</a>';
}
if (element.type == "hyperlink") {
return '<a class="some-link" href="' + element.url + '">' + content + '</a>';
}
return null;
};
assert.equal(documents.results[0].getStructuredText('blog-post.body').asHtml(getLinkResolver(), htmlSerializer),
'<h1>Our world-famous Pastry Art Brainstorm event</h1>' +
'<img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg\" alt=\"\">' +
'<p>Each year, <em>Les Bonnes Choses</em> organizes a world-famous two-day event called the \"Pastry Art Brainstorm\", and which is the perfect excuse for every fine pastry artist in the world to exercise their art, and build their skills up. The event is a multiple win-win operation, at many levels: see what the event is, as seen by many point of views.</p>' +
'<h2>As seen by the top pastry artists worldwide</h2>' +
'<p>The event always starts with half a day of conference talks, given by the most insightful pastry artists in the world, selected for having made tremendous achievements in pastry that year. The list of invited guest speakers is decided jointly by the <em>Les Bonnes Choses</em> staff and the Fine Pastry Magazine editors.</p>' +
'<p>This is great for the speakers, who get an occasion to share their work, and have people build up on it with them.</p>' +
'<h2>As seen by the pastry professionals</h2>' +
'<p>After half a day of thoughtful conference, the professionals will get to put what they learned to good use, and mingle with the best artists worldwide to make the most daring pastries together. There are no set rules about who does what during this giant innovation workshop, and many crazy ideas get created out of thin air. As a virtually infinite amount of ingredients is provided by the <em>Les Bonnes Choses</em> staff, many unexpected pastries happen on that day, and professionals taste each other\'s creations, and provide relevant feedback to each other. Most pieces get showcased to the amateur audience as well, who get invited to taste some of the pieces.</p>' +
'<p>At noon on the second day, teams are expected to subscribe to our Pastry Art Challenge, during which they will make the best possible pastry, judged on many aspects (originality, taste, looks, ...) by a jury of amateurs and professionals. The team members of the three winning pieces share a substantial prize, and their pastries may even join the Les Bonnes Choses catalogue, and be offered in all the <em>Les Bonnes Choses</em> shops worldwide!</p>' +
'<h2>As seen by the pastry amateurs</h2>' +
'<p>The conference is limited with a reasonable fee; but the showcase is open to everyone, although visitors are often expected to pay the pastry chefs for the pastries they taste. The educated amateurs spend their day tasting the most daring pieces, giving some appreciated feedback to their chefs, and challenging their own tastebuds. The novice amateurs usually get a once-in-a-lifetime experience, and often mention being blown away by how rich the fine pastry art can be. All in all, every one goes home with a smile on their faces!</p>' +
'<h2>As seen by the Les Bonnes Choses interns</h2>' +
'<p>Every year, we recruit a very limited amount of interns, who get aboard a <a class="some-link" href=\"/testing_url/UlfoxUnM0wkXYXbu/les-bonnes-chosess-internship-a-testimony\">life-defining adventure around fine pastries</a>, discovering <em>Les Bonnes Choses</em> during half a year, with part of this time spent in one of our shops abroad. We always manage to get them on board at a time when we know they will be able to attend a Fine Pastry Brainstorm, because we consider it is a very defining element in the experience of being part of <em>Les Bonnes Choses</em>.</p>' +
'<p>Not only do we invite them to the event (whatever the country they are stationed in when the event happens), but we give them a front-row seat! They are part of the jury for the Fine Pastry Challenge, they are introduced to every speaker as the next generation of pastry (thus having the occasion to learn even more, directly from them).</p>' +
'<h2>As seen by fine pastry as a field</h2>' +
'<p>There wasn\'t really an international occasion for pastry artists to join and share, before <em>Les Bonnes Choses</em> came up with the first Fine Pastry Brainstorm, in 2006. Fine Pastry Magazine\'s first edition was out in 2004, and initiated the idea that pastry art needed to be shared better between professionals. But a proper event to meet up in person was missing, and <em>Les Bonnes Choses</em> is proud to be the one to have come up with it first.</p>' +
'<p>Since then, more local initiatives have been started (notably in Argentina, and Canada), but none comes close to the size of <em>Les Bonnes Choses</em>\'s international Fine Pastry Brainstorm.</p>' +
'<h2>As seen by <em>Les Bonnes Choses</em></h2>' +
'<p>As the almost only sponsor of every edition of the event, <em>Les Bonnes Choses</em> makes sure enough ingredients are available for everyone, rents the premises, makes sure the speakers are as comfortable as possible, and takes care of the whole organization! But through the operation, <em>Les Bonnes Choses</em> gains much more than any sponsoring can buy: not only does it get to secure <em>Les Bonnes Choses</em> as the world reference in pastry arts, but it also allows them to claim rightfully that they do offer in their shops the best pastries, created by the world top artists indeed.</p>');
done();
});
}, previewToken);
});
return null;
};
equal(documents.results[0].getStructuredText('blog-post.body').asHtml(getLinkResolver(), htmlSerializer),
'<h1>Our world-famous Pastry Art Brainstorm event</h1>' +
'<img src=\"https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg\" alt=\"\">' +
'<p>Each year, <em>Les Bonnes Choses</em> organizes a world-famous two-day event called the \"Pastry Art Brainstorm\", and which is the perfect excuse for every fine pastry artist in the world to exercise their art, and build their skills up. The event is a multiple win-win operation, at many levels: see what the event is, as seen by many point of views.</p>' +
'<h2>As seen by the top pastry artists worldwide</h2>' +
'<p>The event always starts with half a day of conference talks, given by the most insightful pastry artists in the world, selected for having made tremendous achievements in pastry that year. The list of invited guest speakers is decided jointly by the <em>Les Bonnes Choses</em> staff and the Fine Pastry Magazine editors.</p>' +
'<p>This is great for the speakers, who get an occasion to share their work, and have people build up on it with them.</p>' +
'<h2>As seen by the pastry professionals</h2>' +
'<p>After half a day of thoughtful conference, the professionals will get to put what they learned to good use, and mingle with the best artists worldwide to make the most daring pastries together. There are no set rules about who does what during this giant innovation workshop, and many crazy ideas get created out of thin air. As a virtually infinite amount of ingredients is provided by the <em>Les Bonnes Choses</em> staff, many unexpected pastries happen on that day, and professionals taste each other\'s creations, and provide relevant feedback to each other. Most pieces get showcased to the amateur audience as well, who get invited to taste some of the pieces.</p>' +
'<p>At noon on the second day, teams are expected to subscribe to our Pastry Art Challenge, during which they will make the best possible pastry, judged on many aspects (originality, taste, looks, ...) by a jury of amateurs and professionals. The team members of the three winning pieces share a substantial prize, and their pastries may even join the Les Bonnes Choses catalogue, and be offered in all the <em>Les Bonnes Choses</em> shops worldwide!</p>' +
'<h2>As seen by the pastry amateurs</h2>' +
'<p>The conference is limited with a reasonable fee; but the showcase is open to everyone, although visitors are often expected to pay the pastry chefs for the pastries they taste. The educated amateurs spend their day tasting the most daring pieces, giving some appreciated feedback to their chefs, and challenging their own tastebuds. The novice amateurs usually get a once-in-a-lifetime experience, and often mention being blown away by how rich the fine pastry art can be. All in all, every one goes home with a smile on their faces!</p>' +
'<h2>As seen by the Les Bonnes Choses interns</h2>' +
'<p>Every year, we recruit a very limited amount of interns, who get aboard a <a class="some-link" href=\"/testing_url/UlfoxUnM0wkXYXbu/les-bonnes-chosess-internship-a-testimony\">life-defining adventure around fine pastries</a>, discovering <em>Les Bonnes Choses</em> during half a year, with part of this time spent in one of our shops abroad. We always manage to get them on board at a time when we know they will be able to attend a Fine Pastry Brainstorm, because we consider it is a very defining element in the experience of being part of <em>Les Bonnes Choses</em>.</p>' +
'<p>Not only do we invite them to the event (whatever the country they are stationed in when the event happens), but we give them a front-row seat! They are part of the jury for the Fine Pastry Challenge, they are introduced to every speaker as the next generation of pastry (thus having the occasion to learn even more, directly from them).</p>' +
'<h2>As seen by fine pastry as a field</h2>' +
'<p>There wasn\'t really an international occasion for pastry artists to join and share, before <em>Les Bonnes Choses</em> came up with the first Fine Pastry Brainstorm, in 2006. Fine Pastry Magazine\'s first edition was out in 2004, and initiated the idea that pastry art needed to be shared better between professionals. But a proper event to meet up in person was missing, and <em>Les Bonnes Choses</em> is proud to be the one to have come up with it first.</p>' +
'<p>Since then, more local initiatives have been started (notably in Argentina, and Canada), but none comes close to the size of <em>Les Bonnes Choses</em>\'s international Fine Pastry Brainstorm.</p>' +
'<h2>As seen by <em>Les Bonnes Choses</em></h2>' +
'<p>As the almost only sponsor of every edition of the event, <em>Les Bonnes Choses</em> makes sure enough ingredients are available for everyone, rents the premises, makes sure the speakers are as comfortable as possible, and takes care of the whole organization! But through the operation, <em>Les Bonnes Choses</em> gains much more than any sponsoring can buy: not only does it get to secure <em>Les Bonnes Choses</em> as the world reference in pastry arts, but it also allows them to claim rightfully that they do offer in their shops the best pastries, created by the world top artists indeed.</p>');
start();
});
}, previewToken);
});
it('getFirstImage works', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbl")]]').ref(Api.master()).submit(function (err, documents) {
assert.equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().url, "https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg");
assert.equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().alt, "");
assert.equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().height, 427);
assert.equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().width, 640);
assert.equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().asHtml(), '<img src=https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg width=640 height=427 alt="">');
done();
});
}, previewToken);
});
asyncTest('StructuredTexts getFirstImage works', 5, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbl")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().url, "https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg");
equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().alt, "");
equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().height, 427);
equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().width, 640);
equal(documents.results[0].getStructuredText('blog-post.body').getFirstImage().asHtml(), '<img src=https://prismic-io.s3.amazonaws.com/lesbonneschoses/c38f9e5a1a6c43aa7aae516c154013a2cee2bc75.jpg width=640 height=427 alt="">');
start();
});
}, previewToken);
});
it('asHtml handles span Link.file', function () {
var jsonString = '{"type":"StructuredText","value":[{"type":"paragraph","text":"2012 Annual Report","spans":[{"start":0,"end":18,"type":"hyperlink","data":{"type":"Link.file","value":{"file":{"name":"2012_annual.report.pdf","kind":"document","url":"https://prismic-io.s3.amazonaws.com/annual.report.pdf","size":"1282484"}}}}]},{"type":"paragraph","text":"2012 Annual Budget","spans":[{"start":0,"end":18,"type":"hyperlink","data":{"type":"Link.file","value":{"file":{"name":"2012_smec.annual.budget.pdf","kind":"document","url":"https://prismic-io.s3.amazonaws.com/annual.budget.pdf","size":"59229"}}}}]},{"type":"paragraph","text":"2015 Vision & Strategic Plan","spans":[{"start":0,"end":28,"type":"hyperlink","data":{"type":"Link.file","value":{"file":{"name":"2015_vision.strategic.plan_.sm_.pdf","kind":"document","url":"https://prismic-io.s3.amazonaws.com/vision.strategic.plan_.sm_.pdf","size":"1969956"}}}}]}]}';
var jsonObject = JSON.parse(jsonString);
assert.equal(Prismic.Fragments.initField(jsonObject).asHtml(), '<p><a href=\"https://prismic-io.s3.amazonaws.com/annual.report.pdf\">2012 Annual Report</a></p><p><a href=\"https://prismic-io.s3.amazonaws.com/annual.budget.pdf\">2012 Annual Budget</a></p><p><a href=\"https://prismic-io.s3.amazonaws.com/vision.strategic.plan_.sm_.pdf\">2015 Vision &amp; Strategic Plan</a></p>');
});
asyncTest('StructuredTexts asHtml handles span Link.file', 1, function() {
var jsonString = '{"type":"StructuredText","value":[{"type":"paragraph","text":"2012 Annual Report","spans":[{"start":0,"end":18,"type":"hyperlink","data":{"type":"Link.file","value":{"file":{"name":"2012_annual.report.pdf","kind":"document","url":"https://prismic-io.s3.amazonaws.com/annual.report.pdf","size":"1282484"}}}}]},{"type":"paragraph","text":"2012 Annual Budget","spans":[{"start":0,"end":18,"type":"hyperlink","data":{"type":"Link.file","value":{"file":{"name":"2012_smec.annual.budget.pdf","kind":"document","url":"https://prismic-io.s3.amazonaws.com/annual.budget.pdf","size":"59229"}}}}]},{"type":"paragraph","text":"2015 Vision & Strategic Plan","spans":[{"start":0,"end":28,"type":"hyperlink","data":{"type":"Link.file","value":{"file":{"name":"2015_vision.strategic.plan_.sm_.pdf","kind":"document","url":"https://prismic-io.s3.amazonaws.com/vision.strategic.plan_.sm_.pdf","size":"1969956"}}}}]}]}';
var jsonObject = JSON.parse(jsonString);
equal(Prismic.Fragments.initField(jsonObject).asHtml(), '<p><a href=\"https://prismic-io.s3.amazonaws.com/annual.report.pdf\">2012 Annual Report</a></p><p><a href=\"https://prismic-io.s3.amazonaws.com/annual.budget.pdf\">2012 Annual Budget</a></p><p><a href=\"https://prismic-io.s3.amazonaws.com/vision.strategic.plan_.sm_.pdf\">2015 Vision &amp; Strategic Plan</a></p>');
start();
});
it('Proper escaping in asHtml', function (done) {
var jsonString = "{ \"type\": \"StructuredText\", \"value\": [ { \"type\": \"paragraph\", \"text\": \"<not a real tag>\", \"spans\": [] } ]}";
var jsonObject = JSON.parse(jsonString);
var text = Prismic.Fragments.initField(jsonObject);
assert.equal(
text.asHtml(),
"<p>&lt;not a real tag&gt;</p>"
);
done();
});
asyncTest('Proper escaping in asHtml', 1, function() {
var jsonString = "{ \"type\": \"StructuredText\", \"value\": [ { \"type\": \"paragraph\", \"text\": \"<not a real tag>\", \"spans\": [] } ]}";
var jsonObject = JSON.parse(jsonString);
var text = Prismic.Fragments.initField(jsonObject);
equal(
text.asHtml(),
"<p>&lt;not a real tag&gt;</p>"
);
start();
});
});
asyncTest('Handles multiple fields', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbX")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
equal(documents.results[0].getAll('blog-post.relatedpost')[0].asHtml(getLinkResolver()), '<a href="/testing_url/UlfoxUnM0wkXYXbm/tips-to-dress-a-pastry">/testing_url/UlfoxUnM0wkXYXbm/tips-to-dress-a-pastry</a>');
start();
});
}, previewToken);
});
describe('Various fragment types', function() {
asyncTest('ImageViews are well retrieved', 2, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbO")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
equal(documents.results[0].getImageView('product.image', 'main').asHtml(), '<img src=https://prismic-io.s3.amazonaws.com/lesbonneschoses/f606ad513fcc2a73b909817119b84d6fd0d61a6d.png width=500 height=500 alt="">');
equal(documents.results[0].getImageView('product.image', 'icon').asHtml(), '<img src=https://prismic-io.s3.amazonaws.com/lesbonneschoses/fe4f9379ee325456992d48204b8d94aeb60cc976.png width=250 height=250 alt="">');
start();
});
}, previewToken);
});
it('Handles multiple fields', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbX")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
assert.equal(documents.results[0].getAll('blog-post.relatedpost')[0].asHtml(getLinkResolver()), '<a href="/testing_url/UlfoxUnM0wkXYXbm/tips-to-dress-a-pastry">/testing_url/UlfoxUnM0wkXYXbm/tips-to-dress-a-pastry</a>');
done();
});
}, previewToken);
});
asyncTest('GeoPoint is retrieved', 1, function() {
Prismic.Api(microRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "U9pjvjQAADAAehbf")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
var html = '<div class="geopoint"><span class="latitude">48.87687670000001</span><span class="longitude">2.3338801999999825</span></div>';
equal(documents.results[0].getGeoPoint('contributor.location').asHtml(), html);
start();
});
});
});
it('ImageViews are well retrieved', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UlfoxUnM0wkXYXbO")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
assert.equal(documents.results[0].getImageView('product.image', 'main').asHtml(), '<img src=https://prismic-io.s3.amazonaws.com/lesbonneschoses/f606ad513fcc2a73b909817119b84d6fd0d61a6d.png width=500 height=500 alt="">');
assert.equal(documents.results[0].getImageView('product.image', 'icon').asHtml(), '<img src=https://prismic-io.s3.amazonaws.com/lesbonneschoses/fe4f9379ee325456992d48204b8d94aeb60cc976.png width=250 height=250 alt="">');
done();
});
}, previewToken);
});
test('Date and Timestamp are parsed correctly', 2, function() {
var json = JSON.parse('{ "id": "UlfoxUnM0wkXYXbm", "type": "blog-post", "href": "https://lesbonneschoses-vcerzcwaaohojzo.prismic.io/api/documents/...",' +
'"tags": [], "slugs": [], "linked_documents": [],' +
'"data": { "blog-post": {' +
'"date": { "type": "Date", "value": "2013-08-17" },' +
'"timestamp": { "type": "Timestamp", "value": "2014-10-06T12:24:36+0000" } ' +
'}}}');
var doc = Prismic.Api("").parseDoc(json);
var date = doc.getDate("blog-post.date");
equal(date.getFullYear(), 2013);
var ts = doc.getTimestamp("blog-post.timestamp");
equal(ts.getFullYear(), 2014);
});
it('GeoPoint is retrieved', function (done) {
Prismic.Api(microRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "U9pjvjQAADAAehbf")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
var html = '<div class="geopoint"><span class="latitude">48.87687670000001</span><span class="longitude">2.3338801999999825</span></div>';
assert.equal(documents.results[0].getGeoPoint('contributor.location').asHtml(), html);
done();
});
});
});
asyncTest('Block fragments are accessible, loopable, and serializable', 4, function() {
Prismic.Api(microRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = at(document.id, "UrDndQEAALQMyrXF")]]').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); start(); }
// Group fragments are accessible
equal(documents.results[0].getGroup('docchapter.docs').toArray()[0].getLink('linktodoc').value.document.type, 'doc');
// Group fragments are loopable
var slugs = "";
for (var i = 0; i<documents.results[0].getGroup('docchapter.docs').toArray().length; i++) {
slugs += documents.results[0].getGroup('docchapter.docs').toArray()[i].getLink('linktodoc').value.document.slug + ' ';
}
equal(slugs.trim(), 'with-jquery with-bootstrap');
// Group fragments are serializable when asHtml is called directly on them
equal(documents.results[0].getGroup('docchapter.docs').asHtml(getLinkResolver()),
'<section data-field=\"linktodoc\"><a href=\"/testing_url/UrDofwEAALAdpbNH/with-jquery\">/testing_url/UrDofwEAALAdpbNH/with-jquery</a></section>' +
'<section data-field=\"linktodoc\"><a href=\"/testing_url/UrDp8AEAAPUdpbNL/with-bootstrap\">/testing_url/UrDp8AEAAPUdpbNL/with-bootstrap</a></section>');
// Group fragments are serializable when as Html is called on a document
equal(documents.results[0].asHtml(getLinkResolver()),
'<section data-field=\"docchapter.title\"><h1>Using with other projects</h1></section>' +
'<section data-field=\"docchapter.intro\"><p>As advertised, meta-micro knows how to stay out of the way of the rest of your application. Here are some cases of how to use it with some of the most used open-source projects in JavaScript.</p></section>' +
'<section data-field=\"docchapter.priority\"><span>500</span></section>' +
'<section data-field=\"docchapter.docs\">' +
'<section data-field=\"linktodoc\"><a href=\"/testing_url/UrDofwEAALAdpbNH/with-jquery\">/testing_url/UrDofwEAALAdpbNH/with-jquery</a></section>' +
'<section data-field=\"linktodoc\"><a href=\"/testing_url/UrDp8AEAAPUdpbNL/with-bootstrap">/testing_url/UrDp8AEAAPUdpbNL/with-bootstrap</a></section>' +
'</section>');
start();
});
it('Date and Timestamp are parsed correctly', function () {
var json = JSON.parse('{ "id": "UlfoxUnM0wkXYXbm", "type": "blog-post", "href": "https://lesbonneschoses-vcerzcwaaohojzo.prismic.io/api/documents/...",' +
'"tags": [], "slugs": [], "linked_documents": [],' +
'"data": { "blog-post": {' +
'"date": { "type": "Date", "value": "2013-08-17" },' +
'"timestamp": { "type": "Timestamp", "value": "2014-10-06T12:24:36+0000" } ' +
'}}}');
var doc = Prismic.Api("").parseDoc(json);
var date = doc.getDate("blog-post.date");
assert.equal(date.getFullYear(), 2013);
var ts = doc.getTimestamp("blog-post.timestamp");
assert.equal(ts.getFullYear(), 2014);
});
it('Block fragments are accessible, loopable, and serializable', function (done) {
Prismic.Api(microRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').query('[[:d = at(document.id, "UrDndQEAALQMyrXF")]]').ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
// Group fragments are accessible
assert.equal(documents.results[0].getGroup('docchapter.docs').toArray()[0].getLink('linktodoc').value.document.type, 'doc');
// Group fragments are loopable
var slugs = "";
for (var i = 0; i < documents.results[0].getGroup('docchapter.docs').toArray().length; i++) {
slugs += documents.results[0].getGroup('docchapter.docs').toArray()[i].getLink('linktodoc').value.document.slug + ' ';
}
assert.equal(slugs.trim(), 'with-jquery with-bootstrap');
// Group fragments are serializable when asHtml is called directly on them
assert.equal(documents.results[0].getGroup('docchapter.docs').asHtml(getLinkResolver()),
'<section data-field=\"linktodoc\"><a href=\"/testing_url/UrDofwEAALAdpbNH/with-jquery\">/testing_url/UrDofwEAALAdpbNH/with-jquery</a></section>' +
'<section data-field=\"linktodoc\"><a href=\"/testing_url/UrDp8AEAAPUdpbNL/with-bootstrap\">/testing_url/UrDp8AEAAPUdpbNL/with-bootstrap</a></section>');
// Group fragments are serializable when as Html is called on a document
assert.equal(documents.results[0].asHtml(getLinkResolver()),
'<section data-field=\"docchapter.title\"><h1>Using with other projects</h1></section>' +
'<section data-field=\"docchapter.intro\"><p>As advertised, meta-micro knows how to stay out of the way of the rest of your application. Here are some cases of how to use it with some of the most used open-source projects in JavaScript.</p></section>' +
'<section data-field=\"docchapter.priority\"><span>500</span></section>' +
'<section data-field=\"docchapter.docs\">' +
'<section data-field=\"linktodoc\"><a href=\"/testing_url/UrDofwEAALAdpbNH/with-jquery\">/testing_url/UrDofwEAALAdpbNH/with-jquery</a></section>' +
'<section data-field=\"linktodoc\"><a href=\"/testing_url/UrDp8AEAAPUdpbNL/with-bootstrap">/testing_url/UrDp8AEAAPUdpbNL/with-bootstrap</a></section>' +
'</section>');
done();
});
});
});
});
});
}(window.Prismic));
(function(Prismic) {
/* === TESTS ARE RUN OVER "LES BONNES CHOSES" EXAMPLE REPOSITORY === */
var assert = chai.assert;
var testRepository = 'https://lesbonneschoses.prismic.io/api',
/* === TESTS ARE RUN OVER "LES BONNES CHOSES" EXAMPLE REPOSITORY === */
previewToken = 'MC5VbDdXQmtuTTB6Z0hNWHF3.c--_vVbvv73vv73vv73vv71EA--_vS_vv73vv70T77-9Ke-_ve-_vWfvv70ebO-_ve-_ve-_vQN377-9ce-_vRfvv70',
var testRepository = 'https://lesbonneschoses.prismic.io/api',
previewToken = 'MC5VbDdXQmtuTTB6Z0hNWHF3.c--_vVbvv73vv73vv73vv71EA--_vS_vv73vv70T77-9Ke-_ve-_vWfvv70ebO-_ve-_ve-_vQN377-9ce-_vRfvv70',
microRepository = 'https://micro.prismic.io/api',
Predicates = Prismic.Predicates;
microRepository = 'https://micro.prismic.io/api',
describe('API retrieval and parsing', function(){
Predicates = Prismic.Predicates;
it('Retrieve the API', function(done) {
Prismic.Api(testRepository, function(err, Api) {
if (err) throw err;
assert.equal(Api.data.refs.length, 1);
assert.equal(Api.url, testRepository);
done();
});
});
module('Prismic.io', {
setup: function() {}
});
it('Correctly handles the error if the URL is wrong', function(done) {
console.log('\n*** Note by tester: The following error is a "normal" error (see note in test.js): ');
// We can't help it because whatever you do, the JS engine contains a "console.error" statement when this error occurs,
// and we're exactly trying to test how the kit reacts when this error occurs.
Prismic.Api(testRepository+"/errormaker", function(err, Api) {
assert.equal(err.message, "Unexpected status code [0] on URL https://lesbonneschoses.prismic.io/api/errormaker");
done();
});
});
/************************************/
/* API document retrieval & parsing */
/************************************/
it('Parsing stores types and tags', function(done) {
Prismic.Api(testRepository, function(err, Api) {
if (err) throw err;
assert.equal(Object.keys(Api.data.types).length, 6);
assert.equal(Api.data.tags.length, 4);
done();
});
});
asyncTest('Retrieve the API', 2, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
equal(Api.data.refs.length, 1);
equal(Api.url, testRepository);
start();
it('Retrieve the API with master+releases privilege', function(done) {
Prismic.Api(testRepository, function(err, Api) {
if (err) throw err;
assert.equal(Api.data.refs.length, 3);
done();
}, previewToken);
});
});
});
asyncTest('Correctly handles the error if the URL is wrong', 2, function() {
console.log('\n*** Note by tester: The following error is a "normal" error (see note in test.js): ');
// We can't help it because whatever you do, the JS engine contains a "console.error" statement when this error occurs,
// and we're exactly trying to test how the kit reacts when this error occurs.
Prismic.Api(testRepository+"/errormaker", function(err, Api) {
ok(err);
equal(err.message, "Unexpected status code [0] on URL https://lesbonneschoses.prismic.io/api/errormaker");
start();
});
});
describe('API form submissions', function() {
asyncTest('Parsing stores types and tags', 2, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
equal(Object.keys(Api.data.types).length, 6);
equal(Api.data.tags.length, 4);
start();
});
});
it('Submit the `everything` form', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) {
console.log(err);
done();
}
Api.form('everything').ref(Api.master()).submit(function (err, documents) {
if (err) {
console.log(err);
return;
}
assert.equal(documents.results.length, 20);
assert.equal(documents.next_page, "https://lesbonneschoses.prismic.io/api/documents/search?ref=UlfoxUnM08QWYXdl&page=2&pageSize=20");
assert.equal(documents.page, 1);
assert.equal(documents.prev_page, null);
assert.equal(documents.results_per_page, 20);
assert.equal(documents.results_size, 20);
assert.equal(documents.total_pages, 2);
assert.equal(documents.total_results_size, 40);
done();
});
});
});
asyncTest('Retrieve the API with master+releases privilege', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
equal(Api.data.refs.length, 3);
start();
}, previewToken);
});
it('Get linked documents', function (done) {
Prismic.Api(microRepository, function (err, Api) {
if (err) {
console.log(err);
done();
}
Api.form('everything').query('[[:d = any(document.type, ["doc","docchapter"])]]').ref(Api.master()).submit(function (err, response) {
if (err) {
console.log(err);
return;
}
var document = response.results[0];
assert.equal(document.linkedDocuments.length, 1);
assert.equal(document.linkedDocuments[0].id, 'U0w8OwEAACoAQEvB');
done();
});
});
});
/************************/
/* API form submissions */
/************************/
it('Use an Array to query', function (done) {
Prismic.Api(microRepository, function (err, Api) {
if (err) {
console.log(err);
done();
}
Api.form('everything')
.query(Predicates.any("document.type", ["doc", "docchapter"]))
.ref(Api.master())
.submit(function (err, response) {
if (err) {
console.log(err);
return;
}
var document = response.results[0];
assert.equal(document.linkedDocuments.length, 1);
assert.equal(document.linkedDocuments[0].id, 'U0w8OwEAACoAQEvB');
done();
});
});
});
asyncTest('Submit the `everything` form', 8, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); return; }
equal(documents.results.length, 20);
equal(documents.next_page, "https://lesbonneschoses.prismic.io/api/documents/search?ref=UlfoxUnM08QWYXdl&page=2&pageSize=20");
equal(documents.page, 1);
equal(documents.prev_page, null);
equal(documents.results_per_page, 20);
equal(documents.results_size, 20);
equal(documents.total_pages, 2);
equal(documents.total_results_size, 40);
start();
});
});
});
it('Submit the `everything` form with an ordering', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) {
console.log(err);
done();
}
Api.form('everything').ref(Api.master()).orderings('[my.product.price desc]').submit(function (err, documents) {
if (err) {
console.log(err);
return;
}
assert.equal(documents.results.length, 20);
assert.equal(documents.results[0].id, 'UlfoxUnM0wkXYXbj');
done();
});
});
});
asyncTest('Get linked documents', 2, function() {
Prismic.Api(microRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').query('[[:d = any(document.type, ["doc","docchapter"])]]').ref(Api.master()).submit(function(err, response) {
if (err) { console.log(err); return; }
var document = response.results[0];
equal(document.linkedDocuments.length, 1);
equal(document.linkedDocuments[0].id, 'U0w8OwEAACoAQEvB');
start();
});
});
});
it('Get page 2 of the `everything` form', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) {
console.log(err);
done();
}
Api.form('everything').page(2).ref(Api.master()).submit(function (err, documents) {
if (err) {
console.log(err);
return;
}
assert.equal(documents.results.length, 20);
assert.equal(documents.next_page, null);
assert.equal(documents.page, 2);
assert.equal(documents.prev_page, "https://lesbonneschoses.prismic.io/api/documents/search?ref=UlfoxUnM08QWYXdl&page=1&pageSize=20");
assert.equal(documents.results_per_page, 20);
assert.equal(documents.results_size, 20);
assert.equal(documents.total_pages, 2);
assert.equal(documents.total_results_size, 40);
done();
});
});
});
asyncTest('Use an Array to query', 2, function() {
Prismic.Api(microRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything')
.query(Predicates.any("document.type", ["doc", "docchapter"]))
.ref(Api.master())
.submit(function(err, response) {
if (err) { console.log(err); return; }
var document = response.results[0];
equal(document.linkedDocuments.length, 1);
equal(document.linkedDocuments[0].id, 'U0w8OwEAACoAQEvB');
start();
});
});
});
it('Get page 1 of the `everything` form with pagination set at 10', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) {
console.log(err);
done();
}
Api.form('everything').pageSize(10).ref(Api.master()).submit(function (err, documents) {
if (err) throw err;
assert.equal(documents.results.length, 10);
assert.equal(documents.next_page, "https://lesbonneschoses.prismic.io/api/documents/search?ref=UlfoxUnM08QWYXdl&page=2&pageSize=10");
assert.equal(documents.page, 1);
assert.equal(documents.prev_page, null);
assert.equal(documents.results_per_page, 10);
assert.equal(documents.results_size, 10);
assert.equal(documents.total_pages, 4);
assert.equal(documents.total_results_size, 40);
done();
});
});
});
asyncTest('Submit the `everything` form with an ordering', 2, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').ref(Api.master()).orderings('[my.product.price desc]').submit(function(err, documents) {
if (err) { console.log(err); return; }
equal(documents.results.length, 20);
equal(documents.results[0].id, 'UlfoxUnM0wkXYXbj');
start();
});
});
});
it('Get page 2 of the `everything` form with pagination set at 10', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').pageSize(10).page(2).ref(Api.master()).submit(function (err, documents) {
if (err) {
console.log(err);
return;
}
assert.equal(documents.results.length, 10);
assert.equal(documents.next_page, "https://lesbonneschoses.prismic.io/api/documents/search?ref=UlfoxUnM08QWYXdl&page=3&pageSize=10");
assert.equal(documents.page, 2);
assert.equal(documents.prev_page, "https://lesbonneschoses.prismic.io/api/documents/search?ref=UlfoxUnM08QWYXdl&page=1&pageSize=10");
assert.equal(documents.results_per_page, 10);
assert.equal(documents.results_size, 10);
assert.equal(documents.total_pages, 4);
assert.equal(documents.total_results_size, 40);
done();
});
});
});
asyncTest('Get page 2 of the `everything` form', 8, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').page(2).ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); return; }
equal(documents.results.length, 20);
equal(documents.next_page, null);
equal(documents.page, 2);
equal(documents.prev_page, "https://lesbonneschoses.prismic.io/api/documents/search?ref=UlfoxUnM08QWYXdl&page=1&pageSize=20");
equal(documents.results_per_page, 20);
equal(documents.results_size, 20);
equal(documents.total_pages, 2);
equal(documents.total_results_size, 40);
start();
});
});
});
it('Correctly handles the error if wrong submission', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').ref(Api.master()).query("wrongpredicate").submit(function (err, _) {
assert.equal(err.message, "Unexpected status code [400] on URL https://lesbonneschoses.prismic.io/api/documents/search?page=1&pageSize=20&ref=UlfoxUnM08QWYXdl&q=wrongpredicate");
done();
});
});
});
asyncTest('Get page 1 of the `everything` form with pagination set at 10', 8, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').pageSize(10).ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); return; }
equal(documents.results.length, 10);
equal(documents.next_page, "https://lesbonneschoses.prismic.io/api/documents/search?ref=UlfoxUnM08QWYXdl&page=2&pageSize=10");
equal(documents.page, 1);
equal(documents.prev_page, null);
equal(documents.results_per_page, 10);
equal(documents.results_size, 10);
equal(documents.total_pages, 4);
equal(documents.total_results_size, 40);
start();
});
});
});
it('Submit the `everything` form with a predicate', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').ref(Api.master()).query(["at", "document.type", "product"]).submit(function (err, documents) {
if (err) {
console.log(err);
return;
}
assert.equal(documents.results.length, 16);
done();
});
});
});
asyncTest('Get page 2 of the `everything` form with pagination set at 10', 8, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').pageSize(10).page(2).ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); return; }
equal(documents.results.length, 10);
equal(documents.next_page, "https://lesbonneschoses.prismic.io/api/documents/search?ref=UlfoxUnM08QWYXdl&page=3&pageSize=10");
equal(documents.page, 2);
equal(documents.prev_page, "https://lesbonneschoses.prismic.io/api/documents/search?ref=UlfoxUnM08QWYXdl&page=1&pageSize=10");
equal(documents.results_per_page, 10);
equal(documents.results_size, 10);
equal(documents.total_pages, 4);
equal(documents.total_results_size, 40);
start();
});
});
});
it('Submit the `everything` form with a predicate that give no results', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').ref(Api.master()).query('[[:d = at(document.type, "youhou")]]').submit(function (err, documents) {
if (err) {
console.log(err);
return;
}
assert.equal(documents.results.length, 0);
done();
});
});
});
asyncTest('Correctly handles the error if wrong submission', 2, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').ref(Api.master()).query("wrongpredicate").submit(function(err, _) {
ok(err);
equal(err.message, "Unexpected status code [400] on URL https://lesbonneschoses.prismic.io/api/documents/search?page=1&pageSize=20&ref=UlfoxUnM08QWYXdl&q=wrongpredicate");
start();
});
});
});
asyncTest('Submit the `everything` form with a predicate', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').ref(Api.master()).query(["at", "document.type", "product"]).submit(function(err, documents) {
if (err) { console.log(err); return; }
equal(documents.results.length, 16);
start();
});
});
});
describe('Fragments', function() {
asyncTest('Submit the `everything` form with a predicate that give no results', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').ref(Api.master()).query('[[:d = at(document.type, "youhou")]]').submit(function(err, documents) {
if (err) { console.log(err); return; }
equal(documents.results.length, 0);
start();
});
});
});
it('Group fragments', function (done) {
Prismic.Api(microRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').ref(Api.master()).query(["at", "document.id", "UrOaNwEAAM2OpbPy"]).submit(function (err, documents) {
if (err) {
console.log(err);
return;
}
var links = documents.results[0].getGroup("contributor.links");
assert.equal(links.toArray().length, 2);
done();
});
});
});
asyncTest('Group fragments', 1, function() {
Prismic.Api(microRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').ref(Api.master()).query(["at", "document.id", "UrOaNwEAAM2OpbPy"]).submit(function(err, documents) {
if (err) { console.log(err); return; }
var links = documents.results[0].getGroup("contributor.links");
equal(links.toArray().length, 2);
start();
});
});
});
it('Similarity search', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').ref(Api.master()).query(["similar", "U9pjvjQAADAAehbf", 10]).submit(function (err, documents) {
if (err) {
console.log(err);
return;
}
assert.equal(documents.results.length, 0);
done();
});
});
});
asyncTest('Similarity search', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').ref(Api.master()).query(["similar", "U9pjvjQAADAAehbf", 10]).submit(function(err, documents) {
if (err) { console.log(err); return; }
equal(documents.results.length, 0);
start();
});
});
});
it('Multiple predicates', function (done) {
Prismic.Api(microRepository, function (err, Api) {
if (err) throw err;
Api.form('everything').ref(Api.master()).query(
Predicates.at("document.type", "article"),
Predicates.fulltext("my.article.title", "meta")
).submit(function (err, documents) {
if (err) {
console.log(err);
return;
}
assert.equal(documents.results.length, 1);
done();
});
});
});
asyncTest('Multiple predicates', 1, function() {
Prismic.Api(microRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('everything').ref(Api.master()).query(
Predicates.at("document.type", "article"),
Predicates.fulltext("my.article.title", "meta")
).submit(function(err, documents) {
if (err) { console.log(err); return; }
equal(documents.results.length, 1);
start();
});
});
});
it('Submit the `products` form', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('products').ref(Api.master()).submit(function (err, documents) {
if (err) {
console.log(err);
return;
}
assert.equal(documents.results.length, 16);
done();
});
});
});
asyncTest('Submit the `products` form', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('products').ref(Api.master()).submit(function(err, documents) {
if (err) { console.log(err); return; }
equal(documents.results.length, 16);
start();
});
});
});
it('Submit the `products` form with a predicate', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('products').ref(Api.master()).query('[[:d = at(my.product.flavour, "Chocolate")]]').submit(function (err, documents) {
if (err) {
console.log(err);
return;
}
assert.equal(documents.results.length, 5);
done();
});
});
});
asyncTest('Submit the `products` form with a predicate', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('products').ref(Api.master()).query('[[:d = at(my.product.flavour, "Chocolate")]]').submit(function(err, documents) {
if (err) { console.log(err); return; }
equal(documents.results.length, 5);
start();
});
});
});
it('Submit the `products` form with an empty query', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('products').ref(Api.master()).query('').submit(function (err, documents) {
if (err) {
console.log(err);
return;
}
assert.equal(documents.results.length, 16);
done();
});
});
});
asyncTest('Submit the `products` form with an empty query', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('products').ref(Api.master()).query('').submit(function(err, documents) {
if (err) { console.log(err); return; }
equal(documents.results.length, 16);
start();
});
it('Submit the `products` form in the future', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) throw err;
Api.form('products').ref(Api.ref('Announcement of new SF shop')).submit(function (err, documents) {
if (err) {
console.log(err);
return;
}
assert.equal(documents.results.length, 17);
done();
});
}, previewToken);
});
it('Test cache', function (done) {
Prismic.Api(testRepository, function (err, Api) {
if (err) return done(err);
var form = Api.form('products').ref(Api.master()).query('');
form.submit(function (err, response) {
if (err) {
console.log(err);
return done(err);
}
var keys = Object.keys(Api.apiCache.cache);
var key = keys[0] === 'https://lesbonneschoses.prismic.io/api' ? keys[1] : keys[0];
Api.apiCache.get(key, function (err, value) {
assert.equal(value.results.length, response.results.length);
done();
});
});
});
});
});
});
asyncTest('Submit the `products` form in the future', 1, function() {
Prismic.Api(testRepository, function(err, Api) {
if (err) { console.log(err); start(); }
Api.form('products').ref(Api.ref('Announcement of new SF shop')).submit(function(err, documents) {
if (err) { console.log(err); return; }
equal(documents.results.length, 17);
start();
});
}, previewToken);
});
}(window.Prismic));
(function(Prismic) {
var assert = chai.assert;
var structuredText = {

@@ -27,97 +30,100 @@ type: 'StructuredText',

function getLinkResolver(ref) {
return function(doc, isBroken) {
if (isBroken) return '#broken';
return "/testing_url/" + doc.id + "/" + doc.slug + (ref ? ('?ref=' + ref) : '');
function getLinkResolver(ref) {
return function(doc, isBroken) {
if (isBroken) return '#broken';
return "/testing_url/" + doc.id + "/" + doc.slug + (ref ? ('?ref=' + ref) : '');
}
}
}
module('Prismic.io', {
setup: function() {}
});
describe("Unit tests", function() {
test('should init and render StructuredText', function () {
var html = '<p><strong>Hi <em>everyone</em></strong>, <strong>I am</strong><em> an awesome</em> text!</p>';
var fragment = Prismic.Fragments.initField(structuredText);
it('should init and render StructuredText', function () {
var html = '<p><strong>Hi <em>everyone</em></strong>, <strong>I am</strong><em> an awesome</em> text!</p>';
var fragment = Prismic.Fragments.initField(structuredText);
equal(html, fragment.asHtml());
assert.equal(html, fragment.asHtml());
});
});
test('HTML content (2 spans on the same text - one bigger 1)', 1, function() {
var text = 'abcdefghijklmnopqrstuvwxyz';
var spans = [{
"type": "em",
"start": 2,
"end": 6
}, {
"type": "strong",
"start": 2,
"end": 4
}];
var html = Prismic.Fragments.insertSpans(text, spans, {});
equal(html, 'ab<em><strong>cd</strong>ef</em>ghijklmnopqrstuvwxyz');
});
describe("HTML content", function() {
test('HTML content (2 spans on the same text - one bigger 2)', 1, function() {
var text = 'abcdefghijklmnopqrstuvwxyz';
var spans = [{
"type": "em",
"start": 2,
"end": 4
}, {
"type": "strong",
"start": 2,
"end": 6
}];
var html = Prismic.Fragments.insertSpans(text, spans, {});
equal(html, 'ab<strong><em>cd</em>ef</strong>ghijklmnopqrstuvwxyz');
});
it('2 spans on the same text - one bigger 1', function() {
var text = 'abcdefghijklmnopqrstuvwxyz';
var spans = [{
"type": "em",
"start": 2,
"end": 6
}, {
"type": "strong",
"start": 2,
"end": 4
}];
var html = Prismic.Fragments.insertSpans(text, spans, {});
assert.equal(html, 'ab<em><strong>cd</strong>ef</em>ghijklmnopqrstuvwxyz');
});
test("HTML content with span labels", 1, function() {
var text = 'abcdefghijklmnopqrstuvwxyz';
var spans = [{
"type": "label",
"start": 2,
"end": 6,
"data": {
"label": "tip"
}
}];
var html = Prismic.Fragments.insertSpans(text, spans, {});
equal(html, 'ab<span class="tip">cdef</span>ghijklmnopqrstuvwxyz');
it('2 spans on the same text - one bigger 2', function() {
var text = 'abcdefghijklmnopqrstuvwxyz';
var spans = [{
"type": "em",
"start": 2,
"end": 4
}, {
"type": "strong",
"start": 2,
"end": 6
}];
var html = Prismic.Fragments.insertSpans(text, spans, {});
assert.equal(html, 'ab<strong><em>cd</em>ef</strong>ghijklmnopqrstuvwxyz');
});
});
it ("with span labels", function() {
var text = 'abcdefghijklmnopqrstuvwxyz';
var spans = [{
"type": "label",
"start": 2,
"end": 6,
"data": {
"label": "tip"
}
}];
var html = Prismic.Fragments.insertSpans(text, spans, {});
assert.equal(html, 'ab<span class="tip">cdef</span>ghijklmnopqrstuvwxyz');
});
test('List items are correctly grouped', function() {
var jsonString = '{ "type":"StructuredText", "value":[ { "spans":[], "text":"Here is some introductory text.", "type":"paragraph" }, { "spans":[], "text":"first item", "type":"list-item" }, { "spans":[], "text":"second item", "type":"list-item" }, { "spans":[], "text":"The following image is linked.", "type":"paragraph" }, { "spans":[], "text":"first item 2", "type":"list-item" }, { "spans":[], "text":"second item 2", "type":"list-item" } ] }';
var jsonObject = JSON.parse(jsonString);
var text = Prismic.Fragments.initField(jsonObject);
equal(text.asHtml(getLinkResolver()), '<p>Here is some introductory text.</p><ul><li>first item</li><li>second item</li></ul><p>The following image is linked.</p><ul><li>first item 2</li><li>second item 2</li></ul>');
});
});
it('List items are correctly grouped', function() {
var jsonString = '{ "type":"StructuredText", "value":[ { "spans":[], "text":"Here is some introductory text.", "type":"paragraph" }, { "spans":[], "text":"first item", "type":"list-item" }, { "spans":[], "text":"second item", "type":"list-item" }, { "spans":[], "text":"The following image is linked.", "type":"paragraph" }, { "spans":[], "text":"first item 2", "type":"list-item" }, { "spans":[], "text":"second item 2", "type":"list-item" } ] }';
var jsonObject = JSON.parse(jsonString);
var text = Prismic.Fragments.initField(jsonObject);
assert.equal(text.asHtml(getLinkResolver()), '<p>Here is some introductory text.</p><ul><li>first item</li><li>second item</li></ul><p>The following image is linked.</p><ul><li>first item 2</li><li>second item 2</li></ul>');
});
test('Dates are well retrieved', function() {
var timestampHtml = Prismic.Fragments.initField({"type" : "Date", "value" : "2014-04-01"}).asHtml();
equal(
(new RegExp('<time>... ... \\d\\d 2014 \\d\\d:00:00 GMT[-+]\\d\\d00 \\(.+\\)</time>')).test(timestampHtml),
true
);
});
test('Timestamps are well retrieved', function() {
var timestampHtml = Prismic.Fragments.initField({"type" : "Timestamp", "value" : "2014-06-18T15:30:00+0000"}).asHtml();
equal(
(new RegExp('<time>... ... \\d\\d 2014 \\d\\d:30:00 GMT[-+]\\d\\d00 \\(.+\\)</time>')).test(timestampHtml),
true,
timestampHtml
);
});
it('Dates are well retrieved', function() {
var timestampHtml = Prismic.Fragments.initField({"type" : "Date", "value" : "2014-04-01"}).asHtml();
assert.equal(
(new RegExp('<time>... ... \\d\\d 2014 \\d\\d:00:00 GMT[-+]\\d\\d00 \\(.+\\)</time>')).test(timestampHtml),
true
);
});
test('Link in images are parsed', function() {
var jsonString = '{ "type": "StructuredText", "value": [ { "spans": [], "text": "Here is some introductory text.", "type": "paragraph" }, { "spans": [], "text": "The following image is linked.", "type": "paragraph" }, { "alt": "", "copyright": "", "dimensions": { "height": 129, "width": 260 }, "linkTo": { "type": "Link.web", "value": { "url": "http://google.com/" } }, "type": "image", "url": "http://fpoimg.com/129x260" }, { "spans": [ { "end": 20, "start": 0, "type": "strong" } ], "text": "More important stuff", "type": "paragraph" }, { "spans": [], "text": "The next is linked to a valid document:", "type": "paragraph" }, { "alt": "", "copyright": "", "dimensions": { "height": 400, "width": 400 }, "linkTo": { "type": "Link.document", "value": { "document": { "id": "UxCQFFFFFFFaaYAH", "slug": "something-fantastic", "type": "lovely-thing" }, "isBroken": false } }, "type": "image", "url": "http://fpoimg.com/400x400" }, { "spans": [], "text": "The next is linked to a broken document:", "type": "paragraph" }, { "alt": "", "copyright": "", "dimensions": { "height": 250, "width": 250 }, "linkTo": { "type": "Link.document", "value": { "document": { "id": "UxERPAEAAHQcsBUH", "slug": "-", "type": "event-calendar" }, "isBroken": true } }, "type": "image", "url": "http://fpoimg.com/250x250" }, { "spans": [], "text": "One more image, this one is not linked:", "type": "paragraph" }, { "alt": "", "copyright": "", "dimensions": { "height": 199, "width": 300 }, "type": "image", "url": "http://fpoimg.com/199x300" } ] }';
var jsonObject = JSON.parse(jsonString);
var text = Prismic.Fragments.initField(jsonObject);
equal(text.asHtml(getLinkResolver()), '<p>Here is some introductory text.</p><p>The following image is linked.</p><p class=\"block-img\"><a href=\"http://google.com/\"><img src=\"http://fpoimg.com/129x260\" alt=\"\"></a></p><p><strong>More important stuff</strong></p><p>The next is linked to a valid document:</p><p class=\"block-img\"><a href=\"/testing_url/UxCQFFFFFFFaaYAH/something-fantastic\"><img src=\"http://fpoimg.com/400x400\" alt=\"\"></a></p><p>The next is linked to a broken document:</p><p class=\"block-img\"><a href=\"#broken\"><img src=\"http://fpoimg.com/250x250\" alt=\"\"></a></p><p>One more image, this one is not linked:</p><p class=\"block-img\"><img src=\"http://fpoimg.com/199x300\" alt=\"\"></p>');
});
it('Timestamps are well retrieved', function() {
var timestampHtml = Prismic.Fragments.initField({"type" : "Timestamp", "value" : "2014-06-18T15:30:00+0000"}).asHtml();
assert.equal(
(new RegExp('<time>... ... \\d\\d 2014 \\d\\d:30:00 GMT[-+]\\d\\d00 \\(.+\\)</time>')).test(timestampHtml),
true,
timestampHtml
);
});
it('Link in images are parsed', function() {
var jsonString = '{ "type": "StructuredText", "value": [ { "spans": [], "text": "Here is some introductory text.", "type": "paragraph" }, { "spans": [], "text": "The following image is linked.", "type": "paragraph" }, { "alt": "", "copyright": "", "dimensions": { "height": 129, "width": 260 }, "linkTo": { "type": "Link.web", "value": { "url": "http://google.com/" } }, "type": "image", "url": "http://fpoimg.com/129x260" }, { "spans": [ { "end": 20, "start": 0, "type": "strong" } ], "text": "More important stuff", "type": "paragraph" }, { "spans": [], "text": "The next is linked to a valid document:", "type": "paragraph" }, { "alt": "", "copyright": "", "dimensions": { "height": 400, "width": 400 }, "linkTo": { "type": "Link.document", "value": { "document": { "id": "UxCQFFFFFFFaaYAH", "slug": "something-fantastic", "type": "lovely-thing" }, "isBroken": false } }, "type": "image", "url": "http://fpoimg.com/400x400" }, { "spans": [], "text": "The next is linked to a broken document:", "type": "paragraph" }, { "alt": "", "copyright": "", "dimensions": { "height": 250, "width": 250 }, "linkTo": { "type": "Link.document", "value": { "document": { "id": "UxERPAEAAHQcsBUH", "slug": "-", "type": "event-calendar" }, "isBroken": true } }, "type": "image", "url": "http://fpoimg.com/250x250" }, { "spans": [], "text": "One more image, this one is not linked:", "type": "paragraph" }, { "alt": "", "copyright": "", "dimensions": { "height": 199, "width": 300 }, "type": "image", "url": "http://fpoimg.com/199x300" } ] }';
var jsonObject = JSON.parse(jsonString);
var text = Prismic.Fragments.initField(jsonObject);
assert.equal(text.asHtml(getLinkResolver()), '<p>Here is some introductory text.</p><p>The following image is linked.</p><p class=\"block-img\"><a href=\"http://google.com/\"><img src=\"http://fpoimg.com/129x260\" alt=\"\"></a></p><p><strong>More important stuff</strong></p><p>The next is linked to a valid document:</p><p class=\"block-img\"><a href=\"/testing_url/UxCQFFFFFFFaaYAH/something-fantastic\"><img src=\"http://fpoimg.com/400x400\" alt=\"\"></a></p><p>The next is linked to a broken document:</p><p class=\"block-img\"><a href=\"#broken\"><img src=\"http://fpoimg.com/250x250\" alt=\"\"></a></p><p>One more image, this one is not linked:</p><p class=\"block-img\"><img src=\"http://fpoimg.com/199x300\" alt=\"\"></p>');
});
})(window.Prismic);

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc