Best JavaScript code snippet using storybook-root
jquery.simpleFilePreview.js
Source:jquery.simpleFilePreview.js
1/* Copyright (c) 2012 Jordan Kasper2 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)3 * Copyright notice and license must remain intact for legal use4 * Requires: jQuery 1.2+5 *6 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 7 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 8 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 9 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 10 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 11 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 12 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.13 * 14 * Fore more usage documentation and examples, visit:15 * http://jordankasper.com/jquery16 * 17 * Basic usage (shown with defaults, except for "existingFiles"):18 * 19 <form ... enctype='multipart/form-data'>20 ...21 <input type='file' name='upload' id='upload' multiple="multiple" />22 ...23 </form>24 25 var files = {"file_id": "file_name", ...};26 $('input[type=file]').simpleFilePreview({27 'buttonContent': 'Add File', // String HTML content for the button to add a new file28 'removeContent': 'X', // String HTML content for the removal icon shown on hover when a file is selected (or for existing files)29 'existingFiles': files, // array | object If an object, key is used in the remove hidden input (defaults to null)30 'shiftLeft': '<<', // String HTML content for the button to shift left for multiple file inputs31 'shiftRight': '>>', // String HTML content for the button to shift right for multiple file inputs32 'iconPath': '', // String The path to the folder containing icon images (when a preview is unavailable) - should be absolute, but if relative, must be relative to the page the file input is on33 'defaultIcon': 'preview_file.png', // String The file name to use for the defualt preview icon (when a proper file-type-specific icon cannot be found)34 'icons': {'png': 'preview_png.png', ...} // Object A mapping of file type (second half of mime type) to icon image file (used in combination with the "iconPath" option)35 });36 * 37 * TODO:38 * - add events for binding to various actions39 * - add example of html produced40 * 41 * REVISIONS:42 * 0.1 Initial release43 * 44 */45;(function($) {46 47 $.fn.simpleFilePreview = function(o) {48 var n = this;49 if (!n || !n.length) { return n; }50 51 // Set up options (and defaults)52 o = (o)?o:{};53 o = $.extend({}, $.simpleFilePreview.defaults, o);54 55 n.each(function() {56 setup($(this), o);57 });58 59 // set up global events60 if (!$.simpleFilePreview.init) {61 $.simpleFilePreview.init = true;62 $('body')63 64 // open file browser dialog on click of styled "button"65 .on('click', '.simpleFilePreview_input', function(e) {66 $(this).parents('.simpleFilePreview').find('input.simpleFilePreview_formInput').trigger('click');67 e.preventDefault();68 return false;69 })70 71 // on click of the actual input (which is invisible), check to see if 72 // we need to clear the input (which is the default action for this plugin)73 .on('click', '.simpleFilePreview input.simpleFilePreview_formInput', function(e) {74 if ($(this).val().length) {75 e.preventDefault();76 $(this).parents('.simpleFilePreview').find('.simpleFilePreview_preview').click();77 return false;78 }79 })80 81 // when file input changes, get file contents and show preview (if it's an image)82 .on('change', '.simpleFilePreview input.simpleFilePreview_formInput', function(e) {83 var p = $(this).parents('.simpleFilePreview');84 85 // if it's a multi-select, add another selection box to the end86 // NOTE: this is done first since we clone the previous input87 // NOTE: the second check is there because IE 8 fires multiple change events for no good reason88 if (p.attr('data-sfpallowmultiple') == 1 && !p.find('.simpleFilePreview_preview').length) {89 var newId = $.simpleFilePreview.uid++;90 var newN = p.clone(true).attr('id', "simpleFilePreview_"+newId);91 newN.find('input.simpleFilePreview_formInput').attr('id', newN.find('input.simpleFilePreview_formInput').attr('id')+'_'+newId).val('');92 p.after(newN);93 var nw = p.parents('.simpleFilePreview_multi').width('+='+newN.outerWidth(true)).width();94 if (nw > p.parents('.simpleFilePreview_multiClip').width()) {95 p.parents('.simpleFilePreview_multiUI')96 .find('.simpleFilePreview_shiftRight')97 .click();98 }99 }100 101 if (this.files && this.files[0]) {102 if ((new RegExp("^image\/("+$.simpleFilePreview.previewFileTypes+")$")).test(this.files[0].type.toLowerCase())) {103 104 if (window.FileReader) {105 if ((new RegExp("^image\/("+$.simpleFilePreview.previewFileTypes+")$")).test(this.files[0].type.toLowerCase())) {106 // show preview of image file107 var r = new FileReader();108 r.onload = function (e) {109 addOrChangePreview(p, e.target.result);110 };111 r.readAsDataURL(this.files[0]);112 113 }114 }115 116 } else {117 // show icon if not an image upload118 var m = this.files[0].type.toLowerCase().match(/^\s*[^\/]+\/([a-zA-Z0-9\-\.]+)\s*$/);119 if (m && m[1] && o.icons[m[1]]) {120 addOrChangePreview(p, o.iconPath+o.icons[m[1]], getFilename(this.value));121 } else {122 addOrChangePreview(p, o.iconPath+o.defaultIcon, getFilename(this.value));123 }124 }125 126 } else {127 // Any browser not supporting the File API (and FileReader)128 129 // Some versions of IE don't have real paths, and can't support130 // any other way to do file preview without uploading to the server131 // If a browser does report a valid path (IE or otherwise), then 132 // we'll try to get the file preview133 134 var e = getFileExt(this.value);135 e = (e)?e.toLowerCase():null;136 if (e && !(/fakepath/.test(this.value.toLowerCase())) && (new RegExp("^("+$.simpleFilePreview.previewFileTypes+")$")).test(e)) {137 // older versions of IE (and some other browsers) report the local 138 // file path, so try to get a preview that way139 addOrChangePreview(p, "file://"+this.value);140 141 } else {142 // not an image (or using fakepath), so no preview anyway143 if (o.icons[e]) {144 addOrChangePreview(p, o.iconPath+o.icons[e], getFilename(this.value));145 } else {146 addOrChangePreview(p, o.iconPath+o.defaultIcon, getFilename(this.value));147 }148 }149 }150 })151 152 // show or hide "remove" icon for file preview/icon153 .on('mouseover', '.simpleFilePreview_preview, .simpleFilePreview input.simpleFilePreview_formInput', function() {154 var p = $(this).parents('.simpleFilePreview');155 if (p.find('.simpleFilePreview_preview').is(':visible')) {156 p.find('.simpleFilePreview_remove').show();157 }158 })159 .on('mouseout', '.simpleFilePreview_preview, .simpleFilePreview input.simpleFilePreview_formInput', function() {160 $(this).parents('.simpleFilePreview').find('.simpleFilePreview_remove').hide();161 })162 163 // remove file when preview/icon is clicked164 .on('click', '.simpleFilePreview_preview', function() {165 var p = $(this).parents('.simpleFilePreview');166 167 if (p.attr('data-sfpallowmultiple') == 1 && p.siblings('.simpleFilePreview').length) {168 if (p.hasClass('simpleFilePreview_existing')) {169 p.parent().append("<input type='hidden' id='"+p.attr('id')+"_remove' name='removeFiles[]' value='"+p.attr('data-sfprid')+"' />");170 }171 172 p.parents('.simpleFilePreview_multi').width('-='+p.width());173 p.remove();174 175 } else {176 // if it was an existing file, show file input and add "removeFiles" hidden input177 if (p.hasClass('simpleFilePreview_existing')) {178 p.find('input.simpleFilePreview_formInput').show();179 p.append("<input type='hidden' id='"+p.attr('id')+"_remove' name='removeFiles[]' value='"+p.attr('data-sfprid')+"' />");180 p.removeClass('simpleFilePreview_existing'); // no longer needed181 }182 183 // kill value in the input184 var i = p.find('input.simpleFilePreview_formInput').val('');185 186 // Some browsers (*cough*IE*cough*) do not allow us to set val() 187 // on a file input, so we have to clone it without the value188 if (i && i.length && i.val().length) {189 var attr = i.get(0).attributes;190 var a = "";191 for (var j=0, l=attr.length; j<l; ++j) {192 if (attr[j].name != 'value' && attr[j].name != 'title') {193 a += attr[j].name+"='"+i.attr(attr[j].name)+"' ";194 }195 }196 var ni = $("<input "+a+" />");197 i.before(ni);198 i.remove();199 }200 201 // remove the preview element202 $(this).remove();203 p.find('.simpleFilePreview_filename').remove();204 // show styled input "button"205 p.find('.simpleFilePreview_remove').hide().end()206 .find('.simpleFilePreview_input').show();207 }208 })209 210 // shift buttons for multi-selects211 .on('click', '.simpleFilePreview_shiftRight', function() {212 var ul = $(this).parents('.simpleFilePreview_multiUI').find('.simpleFilePreview_multi');213 var r = parseInt(ul.css('left')) + ul.width();214 if (r > ul.parent().width()) {215 var li = ul.find('li:first');216 ul.animate({'left': '-='+li.outerWidth(true)});217 }218 })219 .on('click', '.simpleFilePreview_shiftLeft', function() {220 var ul = $(this).parents('.simpleFilePreview_multiUI').find('.simpleFilePreview_multi');221 var l = parseInt(ul.css('left'));222 if (l < 0) {223 var w = ul.find('li:first').outerWidth(true);224 ul.animate({'left': ((l+w)<1)?'+='+w:0});225 }226 });227 }228 229 // return node for fluid chain calling230 return n;231 };232 233 var setup = function(n, o) {234 var isMulti = n.is('[multiple]');235 // "multiple" removed because it's handled later manually236 n = n.removeAttr('multiple').addClass('simpleFilePreview_formInput');237 238 // wrap input with necessary structure239 var c = $("<"+((isMulti)?'li':'div')+" id='simpleFilePreview_"+($.simpleFilePreview.uid++)+"' class='simpleFilePreview' data-sfpallowmultiple='"+((isMulti)?1:0)+"'>" +240 "<a class='simpleFilePreview_input'><span class='simpleFilePreview_inputButtonText'>"+o.buttonContent+"</span></a>" +241 "<span class='simpleFilePreview_remove'>"+o.removeContent+"</span>"+242 "</"+((isMulti)?'li':'div')+">");243 n.before(c);244 c.append(n);245 // mostly for IE, the file input must be sized the same as the container, 246 // opacity 0, and z-indexed above other elements within the preview container247 n.css({248 width: c.width()+'px',249 height: c.height()+'px'250 });251 252 // if it's a multi-select we use multiple separate inputs instead to support file preview253 if (isMulti) {254 c.wrap("<div class='simpleFilePreview_multiUI'><div class='simpleFilePreview_multiClip'><ul class='simpleFilePreview_multi'></ul></div></div>");255 c.parents('.simpleFilePreview_multiUI')256 .prepend("<span class='simpleFilePreview_shiftRight simpleFilePreview_shifter'>"+o.shiftRight+"</span>")257 .append("<span class='simpleFilePreview_shiftLeft simpleFilePreview_shifter'>"+o.shiftLeft+"</span>");258 }259 260 var ex = o.existingFiles;261 if (ex) {262 if (isMulti) {263 // add all of the existing files to preview block264 var arr = ($.isArray(ex))?1:0;265 for (var i in ex) {266 var ni = $.simpleFilePreview.uid++;267 var nn = c.clone(true).attr('id', "simpleFilePreview_"+ni);268 nn.addClass('simpleFilePreview_existing')269 .attr('data-sfprid', (arr)?ex[i]:i)270 .find('input.simpleFilePreview_formInput').remove();271 c.before(nn);272 273 var e = getFileExt(ex[i]);274 e = (e)?e.toLowerCase():null;275 if (e && (new RegExp("^("+$.simpleFilePreview.previewFileTypes+")$")).test(e)) {276 addOrChangePreview(nn, ex[i]);277 } else if (o.icons[e]) {278 addOrChangePreview(nn, o.iconPath+o.icons[e], getFilename(ex[i]));279 } else {280 addOrChangePreview(nn, o.iconPath+o.defaultIcon, getFilename(ex[i]));281 }282 }283 284 } else {285 // for single inputs we only take the last file286 var f = null;287 var arr = ($.isArray(ex))?1:0;288 for (var i in ex) {289 f = {id: (arr)?ex[i]:i, file: ex[i]};290 }291 if (f) {292 // hide file input, will be shown if existing file is removed293 c.attr('data-sfprid', f['id'])294 .addClass('simpleFilePreview_existing')295 .find('input.simpleFilePreview_formInput').hide();296 297 var e = getFileExt(f['file']);298 e = (e)?e.toLowerCase():null;299 if (e && (new RegExp("^("+$.simpleFilePreview.previewFileTypes+")$")).test(e)) {300 addOrChangePreview(c, f['file']);301 } else if (o.icons[e]) {302 addOrChangePreview(c, o.iconPath+o.icons[e], getFilename(f['file']));303 } else {304 addOrChangePreview(c, o.iconPath+o.defaultIcon, getFilename(f['file']));305 }306 }307 }308 }309 310 if (isMulti) {311 $('.simpleFilePreview_multi').width(c.outerWidth(true) * c.parent().find('.simpleFilePreview').length);312 }313 314 };315 316 var addOrChangePreview = function(p, src, fn) {317 fn = (fn)?(""+fn):null;318 319 p.find('.simpleFilePreview_input').hide();320 var i = p.find('.simpleFilePreview_preview');321 if (i && i.length) {322 i.attr('src', src);323 } else {324 p.append("<img src='"+src+"' class='simpleFilePreview_preview "+((fn)?'simpleFilePreview_hasFilename':'')+"' alt='"+((fn)?fn:'File Preview')+"' title='Remove "+((fn)?fn:'this file')+"' />");325 // for tooltips326 p.find('input.simpleFilePreview_formInput').attr('title', "Remove "+((fn)?fn:'this file'));327 }328 329 if (fn) {330 var f = p.find('.simpleFilePreview_filename');331 if (f && f.length) {332 f.text(fn);333 } else {334 f = p.append("<span class='simpleFilePreview_filename'>"+fn+"</span>")335 .find('.simpleFilePreview_filename');336 }337 }338 };339 340 var getFilename = function(p) {341 var m = p.match(/[\/\\]([^\/\\]+)$/);342 if (m && m[1] && m[1].length) {343 return m[1];344 }345 return null;346 };347 348 var getFileExt = function(p) {349 var m = p.match(/[\.]([^\/\\\.]+)$/);350 if (m && m[1] && m[1].length) {351 return m[1];352 }353 return null;354 };355 356 // Static properties357 $.simpleFilePreview = {358 defaults: {359 'buttonContent': 'Add File',360 'removeContent': 'X',361 'existingFiles': null, // array or object. if object, key is used in the remove hidden input362 'shiftLeft': '<<',363 'shiftRight': '>>',364 'iconPath': '',365 'defaultIcon': 'preview_file.png',366 'icons': {367 'png': 'preview_png.png',368 'gif': 'preview_png.png',369 'bmp': 'preview_png.png',370 'svg': 'preview_png.png',371 'jpg': 'preview_png.png',372 'jpeg': 'preview_png.png',373 'pjpg': 'preview_png.png',374 'pjpeg': 'preview_png.png',375 'tif': 'preview_png.png',376 'tiff': 'preview_png.png',377 'mp3': 'preview_mp3.png',378 'mp4': 'preview_mp3.png',379 'wav': 'preview_mp3.png',380 'wma': 'preview_mp3.png',381 'pdf': 'preview_pdf.png',382 'txt': 'preview_txt.png',383 'rtf': 'preview_txt.png',384 'text': 'preview_txt.png',385 'plain': 'preview_txt.png',386 'zip': 'preview_zip.png',387 'tgz': 'preview_zip.png',388 'x-rar-compressed': 'preview_zip.png',389 'octet-stream': 'preview_zip.png',390 'odf': 'preview_doc.png',391 'odt': 'preview_doc.png',392 'doc': 'preview_doc.png',393 'msword': 'preview_doc.png',394 'vnd.openxmlformats-officedocument.wordprocessingml.document': 'preview_doc.png',395 'doc': 'preview_doc.png',396 'docx': 'preview_doc.png',397 'ods': 'preview_xls.png',398 'vnd.ms-excel': 'preview_xls.png',399 'xls': 'preview_xls.png',400 'xlx': 'preview_xls.png',401 'msexcel': 'preview_xls.png',402 'x-excel': 'preview_xls.png',403 'x-ms-excel': 'preview_xls.png',404 'vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'preview_xls.png'405 }406 },407 uid: 0,408 init: false,409 previewFileTypes: 'p?jpe?g|png|gif|bmp|svg'410 };411 ...
anchor-preview.js
Source:anchor-preview.js
1(function () {2 'use strict';3 var AnchorPreview = MediumEditor.Extension.extend({4 name: 'anchor-preview',5 // Anchor Preview Options6 /* hideDelay: [number] (previously options.anchorPreviewHideDelay)7 * time in milliseconds to show the anchor tag preview after the mouse has left the anchor tag.8 */9 hideDelay: 500,10 /* previewValueSelector: [string]11 * the default selector to locate where to put the activeAnchor value in the preview12 */13 previewValueSelector: 'a',14 /* showWhenToolbarIsVisible: [boolean]15 * determines whether the anchor tag preview shows up when the toolbar is visible16 */17 showWhenToolbarIsVisible: false,18 /* showOnEmptyLinks: [boolean]19 * determines whether the anchor tag preview shows up on links with href="" or href="#something"20 */21 showOnEmptyLinks: true,22 init: function () {23 this.anchorPreview = this.createPreview();24 this.getEditorOption('elementsContainer').appendChild(this.anchorPreview);25 this.attachToEditables();26 },27 getInteractionElements: function () {28 return this.getPreviewElement();29 },30 // TODO: Remove this function in 6.0.031 getPreviewElement: function () {32 return this.anchorPreview;33 },34 createPreview: function () {35 var el = this.document.createElement('div');36 el.id = 'medium-editor-anchor-preview-' + this.getEditorId();37 el.className = 'medium-editor-anchor-preview';38 el.innerHTML = this.getTemplate();39 this.on(el, 'click', this.handleClick.bind(this));40 return el;41 },42 getTemplate: function () {43 return '<div class="medium-editor-toolbar-anchor-preview" id="medium-editor-toolbar-anchor-preview">' +44 ' <a class="medium-editor-toolbar-anchor-preview-inner"></a>' +45 '</div>';46 },47 destroy: function () {48 if (this.anchorPreview) {49 if (this.anchorPreview.parentNode) {50 this.anchorPreview.parentNode.removeChild(this.anchorPreview);51 }52 delete this.anchorPreview;53 }54 },55 hidePreview: function () {56 if (this.anchorPreview) {57 this.anchorPreview.classList.remove('medium-editor-anchor-preview-active');58 }59 this.activeAnchor = null;60 },61 showPreview: function (anchorEl) {62 if (this.anchorPreview.classList.contains('medium-editor-anchor-preview-active') ||63 anchorEl.getAttribute('data-disable-preview')) {64 return true;65 }66 if (this.previewValueSelector) {67 this.anchorPreview.querySelector(this.previewValueSelector).textContent = anchorEl.attributes.href.value;68 this.anchorPreview.querySelector(this.previewValueSelector).href = anchorEl.attributes.href.value;69 }70 this.anchorPreview.classList.add('medium-toolbar-arrow-over');71 this.anchorPreview.classList.remove('medium-toolbar-arrow-under');72 if (!this.anchorPreview.classList.contains('medium-editor-anchor-preview-active')) {73 this.anchorPreview.classList.add('medium-editor-anchor-preview-active');74 }75 this.activeAnchor = anchorEl;76 this.positionPreview();77 this.attachPreviewHandlers();78 return this;79 },80 positionPreview: function (activeAnchor) {81 activeAnchor = activeAnchor || this.activeAnchor;82 var containerWidth = this.window.innerWidth,83 buttonHeight = this.anchorPreview.offsetHeight,84 boundary = activeAnchor.getBoundingClientRect(),85 diffLeft = this.diffLeft,86 diffTop = this.diffTop,87 elementsContainer = this.getEditorOption('elementsContainer'),88 elementsContainerAbsolute = ['absolute', 'fixed'].indexOf(window.getComputedStyle(elementsContainer).getPropertyValue('position')) > -1,89 relativeBoundary = {},90 halfOffsetWidth, defaultLeft, middleBoundary, elementsContainerBoundary, top;91 halfOffsetWidth = this.anchorPreview.offsetWidth / 2;92 var toolbarExtension = this.base.getExtensionByName('toolbar');93 if (toolbarExtension) {94 diffLeft = toolbarExtension.diffLeft;95 diffTop = toolbarExtension.diffTop;96 }97 defaultLeft = diffLeft - halfOffsetWidth;98 // If container element is absolute / fixed, recalculate boundaries to be relative to the container99 if (elementsContainerAbsolute) {100 elementsContainerBoundary = elementsContainer.getBoundingClientRect();101 ['top', 'left'].forEach(function (key) {102 relativeBoundary[key] = boundary[key] - elementsContainerBoundary[key];103 });104 relativeBoundary.width = boundary.width;105 relativeBoundary.height = boundary.height;106 boundary = relativeBoundary;107 containerWidth = elementsContainerBoundary.width;108 // Adjust top position according to container scroll position109 top = elementsContainer.scrollTop;110 } else {111 // Adjust top position according to window scroll position112 top = this.window.pageYOffset;113 }114 middleBoundary = boundary.left + boundary.width / 2;115 top += buttonHeight + boundary.top + boundary.height - diffTop - this.anchorPreview.offsetHeight;116 this.anchorPreview.style.top = Math.round(top) + 'px';117 this.anchorPreview.style.right = 'initial';118 if (middleBoundary < halfOffsetWidth) {119 this.anchorPreview.style.left = defaultLeft + halfOffsetWidth + 'px';120 this.anchorPreview.style.right = 'initial';121 } else if ((containerWidth - middleBoundary) < halfOffsetWidth) {122 this.anchorPreview.style.left = 'auto';123 this.anchorPreview.style.right = 0;124 } else {125 this.anchorPreview.style.left = defaultLeft + middleBoundary + 'px';126 this.anchorPreview.style.right = 'initial';127 }128 },129 attachToEditables: function () {130 this.subscribe('editableMouseover', this.handleEditableMouseover.bind(this));131 this.subscribe('positionedToolbar', this.handlePositionedToolbar.bind(this));132 },133 handlePositionedToolbar: function () {134 // If the toolbar is visible and positioned, we don't need to hide the preview135 // when showWhenToolbarIsVisible is true136 if (!this.showWhenToolbarIsVisible) {137 this.hidePreview();138 }139 },140 handleClick: function (event) {141 var anchorExtension = this.base.getExtensionByName('anchor'),142 activeAnchor = this.activeAnchor;143 if (anchorExtension && activeAnchor) {144 event.preventDefault();145 this.base.selectElement(this.activeAnchor);146 // Using setTimeout + delay because:147 // We may actually be displaying the anchor form, which should be controlled by delay148 this.base.delay(function () {149 if (activeAnchor) {150 var opts = {151 value: activeAnchor.attributes.href.value,152 target: activeAnchor.getAttribute('target'),153 buttonClass: activeAnchor.getAttribute('class')154 };155 anchorExtension.showForm(opts);156 activeAnchor = null;157 }158 }.bind(this));159 }160 this.hidePreview();161 },162 handleAnchorMouseout: function () {163 this.anchorToPreview = null;164 this.off(this.activeAnchor, 'mouseout', this.instanceHandleAnchorMouseout);165 this.instanceHandleAnchorMouseout = null;166 },167 handleEditableMouseover: function (event) {168 var target = MediumEditor.util.getClosestTag(event.target, 'a');169 if (false === target) {170 return;171 }172 // Detect empty href attributes173 // The browser will make href="" or href="#top"174 // into absolute urls when accessed as event.target.href, so check the html175 if (!this.showOnEmptyLinks &&176 (!/href=["']\S+["']/.test(target.outerHTML) || /href=["']#\S+["']/.test(target.outerHTML))) {177 return true;178 }179 // only show when toolbar is not present180 var toolbar = this.base.getExtensionByName('toolbar');181 if (!this.showWhenToolbarIsVisible && toolbar && toolbar.isDisplayed && toolbar.isDisplayed()) {182 return true;183 }184 // detach handler for other anchor in case we hovered multiple anchors quickly185 if (this.activeAnchor && this.activeAnchor !== target) {186 this.detachPreviewHandlers();187 }188 this.anchorToPreview = target;189 this.instanceHandleAnchorMouseout = this.handleAnchorMouseout.bind(this);190 this.on(this.anchorToPreview, 'mouseout', this.instanceHandleAnchorMouseout);191 // Using setTimeout + delay because:192 // - We're going to show the anchor preview according to the configured delay193 // if the mouse has not left the anchor tag in that time194 this.base.delay(function () {195 if (this.anchorToPreview) {196 this.showPreview(this.anchorToPreview);197 }198 }.bind(this));199 },200 handlePreviewMouseover: function () {201 this.lastOver = (new Date()).getTime();202 this.hovering = true;203 },204 handlePreviewMouseout: function (event) {205 if (!event.relatedTarget || !/anchor-preview/.test(event.relatedTarget.className)) {206 this.hovering = false;207 }208 },209 updatePreview: function () {210 if (this.hovering) {211 return true;212 }213 var durr = (new Date()).getTime() - this.lastOver;214 if (durr > this.hideDelay) {215 // hide the preview 1/2 second after mouse leaves the link216 this.detachPreviewHandlers();217 }218 },219 detachPreviewHandlers: function () {220 // cleanup221 clearInterval(this.intervalTimer);222 if (this.instanceHandlePreviewMouseover) {223 this.off(this.anchorPreview, 'mouseover', this.instanceHandlePreviewMouseover);224 this.off(this.anchorPreview, 'mouseout', this.instanceHandlePreviewMouseout);225 if (this.activeAnchor) {226 this.off(this.activeAnchor, 'mouseover', this.instanceHandlePreviewMouseover);227 this.off(this.activeAnchor, 'mouseout', this.instanceHandlePreviewMouseout);228 }229 }230 this.hidePreview();231 this.hovering = this.instanceHandlePreviewMouseover = this.instanceHandlePreviewMouseout = null;232 },233 // TODO: break up method and extract out handlers234 attachPreviewHandlers: function () {235 this.lastOver = (new Date()).getTime();236 this.hovering = true;237 this.instanceHandlePreviewMouseover = this.handlePreviewMouseover.bind(this);238 this.instanceHandlePreviewMouseout = this.handlePreviewMouseout.bind(this);239 this.intervalTimer = setInterval(this.updatePreview.bind(this), 200);240 this.on(this.anchorPreview, 'mouseover', this.instanceHandlePreviewMouseover);241 this.on(this.anchorPreview, 'mouseout', this.instanceHandlePreviewMouseout);242 this.on(this.activeAnchor, 'mouseover', this.instanceHandlePreviewMouseover);243 this.on(this.activeAnchor, 'mouseout', this.instanceHandlePreviewMouseout);244 }245 });246 MediumEditor.extensions.anchorPreview = AnchorPreview;...
hint-preview.js
Source:hint-preview.js
1/*2 * Your installation or use of this SugarCRM file is subject to the applicable3 * terms available at4 * http://support.sugarcrm.com/Resources/Master_Subscription_Agreements/.5 * If you do not agree to all of the applicable terms or do not have the6 * authority to bind the entity as an authorized representative, then do not7 * install or use this SugarCRM file.8 *9 * Copyright (C) SugarCRM Inc. All rights reserved.10 */11/**12 * Extends `clients/base/layouts/preview/preview.js` in a way that allows 13 * a safe uninstall. The purpose of this extension is to add custom views14 * to the existing preview layout so the users would be able to view15 * enriched data more easily.16 */17(function (app) {18 /**19 * Check the type of the main layout.20 * 21 * @param {String} layoutName The name of the expected layout.22 * @returns {Boolean} True if the expected layout is rendered.23 */24 function isGivenLayout(layoutName) {25 return app.controller.layout && app.controller.layout.name === layoutName;26 }27 /**28 * Will try to lookup and return a view based on a hierarchy tree,29 * where the last item is the name of the target view.30 * 31 * @param {View.Layout} rootCmp A layout representing the root element.32 * @param {Array} hierarchyPath A path through the component hierarchy tree.33 * Given a root element and the navigation path we should be able to34 * access the target component.35 * @returns {View.Layout/View.View/undefined} Returns the target view or undefined if not found.36 */37 function getView(component, hierarchyPath) {38 while (component && hierarchyPath.length) {39 component = component.getComponent(hierarchyPath.shift());40 }41 return component;42 }43 /**44 * Will attempt to get the preview layout. There may be 2 preview layouts simultaneously45 * (one on the base layout and one in a create drawer). In order to get the relevant layout46 * we will assume that the drawer is active and get the layout from it. If we don't succeed,47 * it means that we have the preview layout on the base layout.48 * 49 * @returns {View.Layout/undefined} A preview layout or undefined if not found.50 */51 function getPreview() {52 var previewCmpPath = ['sidebar', 'preview-pane', 'preview'];53 return getView(app.drawer, ['create'].concat(previewCmpPath)) ||54 getView(app.controller.layout, previewCmpPath);55 }56 /**57 * Will add a child component meta to the preview indicated.58 * 59 * @param {View.Layout} preview The parent of the components to be added.60 * @param {Object} cmp The definition of a component to be added.61 * @param {String/undefined} type The type of the component, optional, defaults to 'view'.62 */63 function addViewToPanelMeta(preview, cmp, type) {64 var component = {65 context: {66 forceNew: true67 }68 };69 component[type || 'view'] = cmp;70 preview._componentsMeta.push(component);71 }72 /**73 * Checks if the model is enriched by hint.74 * 75 * @param {Data.Bean} model The model used to populate the preview.76 * @returns {Boolean} True if it's enriched.77 */78 function isEnrichedModel(model) {79 var enrichedModules = ['Leads', 'Contacts', 'Accounts'];80 return _.contains(enrichedModules, model.module);81 }82 /**83 * Checks if the preview has been triggered from a module which may be related84 * to a hint enriched module. This may happen if a record view has a subpanel85 * related to a module enriched by hint. The given modules may hold such subpanel entries.86 *87 * @param {Data.Bean} model The model to populate the preview with.88 * @returns {Boolean} True if the given model appears in the subpanel89 * of the active record view.90 */91 function isTriggeredOnSubpanel(model) {92 if (model.byPassHint == true) {93 return false;94 }95 var hasModelFromSubpanel = false;96 var recordModel = app.controller.layout.model;97 var moduleLink = model.link && model.link.name;98 if (moduleLink && isGivenLayout('record') && recordModel) {99 var relatedCollection = recordModel.getRelatedCollection(moduleLink);100 var relatedModel = relatedCollection && relatedCollection.get(model.cid);101 hasModelFromSubpanel = !!relatedModel;102 }103 return hasModelFromSubpanel;104 }105 /**106 * Checks if the preview has been triggered from a list view. Have to consider107 * the case when the user opens a merge preview, since the underlieing active108 * layout is still the list view.109 *110 * @param {Data.Bean} preview The preview being subjct of the render event.111 * @returns {Boolean} True if the preview meant to be rendered on a list view.112 */113 function isTriggeredOnListview(preview) {114 if (preview.byPassHint == true) {115 return false;116 }117 return isGivenLayout('records') && !isInMergeView(preview);118 }119 /**120 * Checks if the given preview exists in scope of a merge duplicate process.121 * 122 * @param {View.Layout} preview The active preview layout.123 * @returns {Boolean} True of the merge duplicates layout is opened.124 */125 function isInMergeView(preview) {126 return preview.options.type === 'merge-duplicates-preview';127 }128 /**129 * Checks if the base layout is the create layout.130 * Create layout may exist in scope of a drawer, but in case the user hits131 * refresh Sugar reloads and renders the create layout as it is, without drawer.132 * @returns {Boolean} True if the create layout is opened.133 */134 function isCreateLayout() {135 return !!(getView(app.drawer, ['create']) || isGivenLayout('create'));136 }137 /**138 * Checks if preview is triggered from an enriched record view. Since by default preview139 * is not available on a record view, we check if the appropriate preview id has been set.140 * For more details about preview id please check the `hint-dashboardtitle` field.141 * 142 * @param {Data.Bean} model The model to populate the preview with.143 * @returns {Boolean} True if the preview has been triggered by the Hint dashboard button.144 */145 function isEnrichedRecordView(model) {146 if (model.byPassHint == true) {147 return false;148 }149 var isEnrichedRecord = isGivenLayout('record') && isEnrichedModel(model);150 var dashBoardHeaderPath = ['sidebar', 'dashboard-pane', 'dashboard', 'dashboard-headerpane'];151 var dashBoardHeader = getView(app.controller.layout, dashBoardHeaderPath);152 if (isEnrichedRecord && dashBoardHeader) {153 var dashboardTitle = _.findWhere(dashBoardHeader.fields, {type: 'hint-dashboardtitle'});154 isEnrichedRecord = dashboardTitle && dashboardTitle.getHintState(dashboardTitle.hintStateKey);155 }156 return isEnrichedRecord;157 }158 /**159 * Checks if the hint preview should be rendered instead of default preview. There are four cases, when160 * hint preview should be applied (for each case we need to have a hint enriched model):161 * 1. Preview is triggered from the create layout.162 * 2. Preview is triggered through a global search result.163 * 3. Preview is triggered from a regular list view.164 * 4. Preview is triggered from a subpanel of a module which is not enriched by hint.165 * 5. Preview is triggered from an enriched record view.166 * 167 * @param {View.Layout} preview The active preview layout.168 * @param {Data.Bean} model The model used to populate the given preview, but returned through an event.169 * The difference is that it holds extra information compared to the model directly accessible through preview.170 * @returns {Boolean} True if the hint preview should be rendered.171 */172 function isHintPreview(preview, model) {173 var doesHintApply = false;174 if (isEnrichedModel(model)) {175 doesHintApply = isCreateLayout() || isGivenLayout('search') ||176 isTriggeredOnListview(preview) || isTriggeredOnSubpanel(model) || isEnrichedRecordView(model);177 }178 return doesHintApply;179 }180 /**181 * In case of Accounts we need to display any related accounts, but only on list view.182 * 183 * @returns {Boolean} True if related contacts should be displayed.184 */185 function shouldShowRelatedContacts(model) {186 return model.module === 'Accounts' && isGivenLayout('records');187 }188 /**189 * Will add metadata to the preview so the preview would be able to190 * render components specific to the hint data-enrichment.191 * 192 * @param {View.Layout} preview The active preview layout.193 * @param {Data.Bean} model The model used to populate the preview layout.194 */195 function addHintPreviewComponents(preview, model) {196 preview._componentsMeta = [];197 addViewToPanelMeta(preview, 'hint-preview-header');198 preview._componentsMeta.push({199 view: 'stage2-preview',200 });201 if (!isCreateLayout()) {202 if (shouldShowRelatedContacts(model)) {203 addViewToPanelMeta(preview, {204 type: 'hint-panel-header',205 icon: 'user',206 title: 'LBL_HINT_CONTACTS_TITLE'207 });208 addViewToPanelMeta(preview, 'stage2-related-contacts');209 }210 addViewToPanelMeta(preview, 'hint-news-panel', 'layout');211 addViewToPanelMeta(preview, {212 type: 'hint-panel-header',213 icon: 'history',214 title: 'LBL_HINT_HISTORY_TITLE'215 });216 addViewToPanelMeta(preview, 'stage2-history');217 }218 }219 /**220 * Will add back the default metadata to the preview layout.221 * This needs to be done after a non-enriched module's record222 * is previewed after an enriched model has been.223 * 224 * @param {String} moduleName Module name to be supplied for the getLayout method to work correctly.225 * @param {View.Layout} preview The active preview layout.226 */227 function addDefaultPreviewComponents(moduleName, preview) {228 preview._componentsMeta = app.metadata.getLayout(moduleName, 'preview').components;229 }230 /**231 * Event listener which is triggered by the `preview:render` event.232 * In case an active preview layout is found and the model also has been changed,233 * it will check which kind of preview should be rendered (default or hint).234 * This listener is executed before the default listener from the original preview;235 * by modifying the metadata we can indicate which components need to be rendered.236 * 237 * @param {Data.Bean} model The model used to populate the active preview layout.238 */239 function togglePreview(model, collection) {240 var preview = getPreview();241 if (!preview || !preview._isActive()) {242 return;243 }244 if (model.byPassHint == true) {245 preview.byPassHint = true;246 }247 var hasComponents = !_.isEmpty(preview._components);248 var isSameModel = model == preview.context.get('model');249 var modelChanged = preview.context.get('module') !== model.module;250 if (!isSameModel && (!hasComponents || modelChanged)) {251 if (isHintPreview(preview, model)) {252 addHintPreviewComponents(preview, model);253 } else {254 addDefaultPreviewComponents(model.module, preview);255 }256 }257 }258 app.events.on('preview:render', togglePreview);...
Preview.query.ts
Source:Preview.query.ts
1import gql from 'graphql-tag';2import RichTextFragment from '../fragments/RichText.fragment';3export const Preview_Query = gql`4 ${RichTextFragment}5 query Preview($id: String!, $locale: String) {6 content(id: $id, locale: $locale, preview: true) {7 id8 __typename9 ...Preview_PageContentFragment10 ...Preview_HeaderFragment11 ...Preview_HeroFragment12 ...Preview_BaseSectionFragment13 ...Preview_CollectionFragment14 ...Preview_SectionFragment15 ...Preview_MediaFragment16 ...Preview_TextFragment17 ...Preview_CardFragment18 ...Preview_LinkFragment19 ...Preview_NavigationItemFragment20 ...Preview_CategoryBlogContentFragment21 ...Preview_BlogContentFragment22 ...Preview_ModuleIntegrationFragment23 }24 }25 fragment Preview_PageContentFragment on Page {26 seo27 sidekickLookup28 header {29 __typename30 ...Preview_HeaderFragment31 navigationItems {32 ...Preview_CollectionFragment33 }34 }35 footer {36 ...Preview_SectionFragment37 }38 hero {39 ...Preview_HeroFragment40 }41 contents {42 ...Preview_BaseContentFragment43 ...Preview_SectionFragment44 # ...Preview_ArtDirectedMediaFragment45 ...Preview_TextFragment46 ...Preview_CardFragment47 ...Preview_CollectionFragment48 }49 }50 fragment Preview_CategoryBlogContentFragment on CategoryBlog {51 seo52 title53 slug54 sidekickLookup55 header {56 __typename57 ...Preview_HeaderFragment58 navigationItems {59 ...Preview_CollectionFragment60 }61 }62 footer {63 ...Preview_SectionFragment64 }65 hero {66 ...Preview_HeroFragment67 }68 contents {69 ...Preview_BaseContentFragment70 ...Preview_SectionFragment71 # ...Preview_ArtDirectedMediaFragment72 ...Preview_TextFragment73 ...Preview_CardFragment74 ...Preview_CollectionFragment75 }76 }77 fragment Preview_BlogContentFragment on Blog {78 __typename79 id80 slug81 title82 author {83 ...Preview_PersonFragment84 }85 tags86 sidekickLookup87 seo88 footer {89 ...Preview_SectionFragment90 }91 header {92 __typename93 ...Preview_HeaderFragment94 navigationItems {95 ...Preview_CollectionFragment96 }97 }98 featuredMedia {99 ...Preview_MediaFragment100 }101 body {102 ...RichText_RichTextFragment103 }104 categories {105 id106 slug107 title108 }109 relatedLinks {110 ...Preview_LinkFragment111 }112 contents {113 ...Preview_BaseContentFragment114 ...Preview_SectionFragment115 ...Preview_MediaFragment116 ...Preview_TextFragment117 ...Preview_CardFragment118 ...Preview_CollectionFragment119 }120 seo121 }122 fragment Preview_LinkFragment on Link {123 ...Preview_BaseContentFragment124 text125 href126 variant127 icon128 iconPosition129 }130 fragment Preview_HeaderFragment on Header {131 ...Preview_BaseContentFragment132 logo {133 ...Preview_MediaFragment134 }135 logoUrl136 navigationItems {137 id138 }139 }140 fragment Preview_HeroFragment on Hero {141 ...Preview_BaseContentFragment142 backgroundColor143 # theme144 contentWidth145 contentHeight146 variant147 internalTitle148 title149 subtitle150 body {151 ...RichText_RichTextFragment152 }153 image {154 ...Preview_MediaFragment155 }156 actions {157 ...Preview_LinkFragment158 }159 }160 fragment Preview_BaseSectionFragment on Section {161 ...Preview_BaseContentFragment162 variant163 styles164 # Style fields165 backgroundColor166 contentWidth167 contentDirection168 contentSpacing169 theme {170 id171 components172 typography173 }174 background {175 ...Preview_MediaFragment176 }177 }178 fragment Preview_CollectionFragment on Collection {179 ...Preview_BaseContentFragment180 variant181 itemsVariant182 itemsWidth183 itemsSpacing184 theme {185 id186 components187 typography188 }189 settings190 items {191 ...Preview_CardFragment192 ...Preview_LinkFragment193 ...Preview_NavigationItemFragment194 }195 }196 # This will go 3 levels deep recursive197 fragment Preview_SectionFragment on Section {198 ...Preview_BaseSectionFragment199 contents {200 ...Preview_ContentSectionFragment201 ... on Section {202 ...Preview_BaseSectionFragment203 contents {204 ...Preview_ContentSectionFragment205 ... on Section {206 ...Preview_BaseSectionFragment207 contents {208 ...Preview_ContentSectionFragment209 ... on Section {210 ...Preview_BaseSectionFragment211 }212 }213 }214 }215 }216 }217 }218 # This fragment is almost identical to the Preview_Fragment but skips Section219 # Preview_SectionFragment recursion is handled in Preview_SectionFragment220 fragment Preview_ContentSectionFragment on Content {221 ...Preview_BaseContentFragment222 theme {223 id224 components225 typography226 }227 ... on Section {228 ...Preview_BaseSectionFragment229 }230 # ...Preview_ArtDirectedMediaFragment231 ... on Text {232 ...Preview_TextFragment233 }234 ... on Card {235 ...Preview_CardFragment236 }237 ... on Media {238 ...Preview_MediaFragment239 }240 ... on Link {241 ...Preview_LinkFragment242 }243 ... on Collection {244 ...Preview_CollectionFragment245 }246 ... on ModuleIntegration {247 ...Preview_ModuleIntegrationFragment248 }249 }250 fragment Preview_MediaFragment on Media {251 # ...Preview_BaseContentFragment252 id253 __typename254 title255 variant256 file {257 url258 extension259 fileName260 }261 }262 # fragment Preview_ArtDirectedMediaFragment on Media {263 # # ...Preview_BaseContentFragment264 # desktop {265 # title266 # file {267 # url268 # }269 # }270 # }271 fragment Preview_TextFragment on Text {272 ...Preview_BaseContentFragment273 variant274 align275 body {276 ...RichText_RichTextFragment277 }278 # body {279 # raw280 # }281 }282 fragment Preview_CardRichTextFragment on RichText {283 json284 links {285 entries {286 __typename287 id288 # ...Preview_ArtDirectedMediaFragment289 ...Preview_LinkFragment290 }291 assets {292 ...Preview_MediaFragment293 }294 }295 }296 fragment Preview_CardFragment on Card {297 ...Preview_BaseContentFragment298 variant299 media {300 ...Preview_MediaFragment301 }302 title303 subtitle304 body {305 ...Preview_CardRichTextFragment306 }307 actions {308 ...Preview_LinkFragment309 }310 link {311 ...Preview_LinkFragment312 }313 }314 fragment Preview_NavigationItemFragment on NavigationItem {315 ...Preview_BaseContentFragment316 text317 href318 variant319 subNavigation {320 ...Preview_BaseContentFragment321 ... on NavigationItem {322 id323 __typename324 text325 href326 variant327 }328 ... on Link {329 id330 __typename331 text332 href333 variant334 }335 }336 }337 fragment Preview_BaseContentFragment on Content {338 id339 __typename340 sidekickLookup341 }342 fragment Preview_ModuleIntegrationFragment on ModuleIntegration {343 variant344 settings345 }346 fragment Preview_PersonFragment on Person {347 name348 jobTitle349 image {350 ...Preview_MediaFragment351 }352 }...
preview.js
Source:preview.js
...3GenePattern.preview.id = GenePattern.preview.id || '';4GenePattern.preview.project = GenePattern.preview.project || {};5class Preview {6 constructor() {7 this.initialize_preview(); // Initialize the preview8 }9 static query_preview() {10 return fetch(`/services/projects/library/${GenePattern.preview.id}/?files=true`)11 .then(response => response.json())12 .then(response => {13 GenePattern.preview.project = response;14 });15 }16 static draw_preview() {17 // Add basic project information to the page18 $('#nb-preview-name').text(GenePattern.preview.project.name);19 $('#nb-preview-description').text(GenePattern.preview.project.description);20 $('#nb-preview-author').text(GenePattern.preview.project.author);21 $('#nb-preview-quality').text(GenePattern.preview.project.quality);22 $('#nb-preview-image').text(GenePattern.preview.project.image);23 $('#nb-preview-owner').text(GenePattern.preview.project.owner);24 $('#nb-preview-updated').text(GenePattern.preview.project.updated);25 $('#nb-preview-comment').text(GenePattern.preview.project.comment);26 // Add tags27 GenePattern.preview.project.tags.split(',')28 .forEach(t => $('#nb-preview-tags').append($(`<span class="badge">${t}</span>`)).append(' '));29 // Add button links30 $('#nb-preview-download').attr('href', `/services/projects/library/${GenePattern.preview.id}/download/`);31 $('#nb-preview-run').attr('href', `/hub/login?next=%2Fservices%2Fprojects%2Flibrary%2F${GenePattern.preview.id}%2Fcopy%2F`);32 // Add files to the table33 GenePattern.preview.project.files34 .forEach(f => $('#nb-preview-files').append($(`<tr><td>${Preview.icon(f.filename)} ${f.filename}</td><td>${f.modified}</td><td>${f.size}</td></tr>`)));35 // Add the citation36 $('#nb-citation-notebook').text(Preview.generate_citation());37 }38 static generate_citation() {39 // If a project has a custom citation provided, return it40 if (GenePattern.preview.project.citation) return GenePattern.preview.project.citation;41 // Otherwise, generate a project citation42 const now = (new Date()).toDateString();43 return `${GenePattern.preview.project.author}, "${GenePattern.preview.project.name}", GenePattern Notebook Workspace, ${location.href}, accessed ${now}.`;44 }45 static icon(filename) {46 if (filename.endsWith('.ipynb')) return '<i class="fa fa-book" title="Notebook"></i>';47 else if (filename.endsWith('/')) return '<i class="fa fa-folder-open" title="Directory"></i>';48 else return '<i class="fa fa-file" title="Supporting File"></i>';49 }50 static error_message(message) {51 $('#messages').empty().append(52 $(`<div class="alert alert-danger">${message}</div>`)53 );54 $('table, .nb-preview-buttons').hide(); // Hide blank tables and buttons55 }56 static extract_parameters() {57 return new Promise((resolve, reject) => {58 // Extract the GET parameters from the URL59 const params = new URLSearchParams(window.location.search);60 GenePattern.preview.id = params.get('id');61 // If there are problems extracting the parameters, show an error message62 if (!GenePattern.preview.id) {63 Preview.error_message('Cannot render preview, missing required parameters');64 reject();65 }66 // Otherwise, continue67 else resolve();68 });69 }70 initialize_preview() {71 Preview.extract_parameters() // Extract the GET parameters72 .then(() => Preview.query_preview() // Query the preview service using those parameters73 .then(() => Preview.draw_preview())) // Draw the preview on the page74 .catch(e => {75 Preview.error_message('Error retrieving project data.');76 console.error(e);77 })78 }79}...
Using AI Code Generation
1import { preview } from 'storybook-root';2const { preview } = require('storybook-root');3import { preview } from 'storybook-root';4const { preview } = require('storybook-root');5import { preview } from 'storybook-root';6const { preview } = require('storybook-root');7import { preview } from 'storybook-root';8const { preview } = require('storybook-root');9import { preview } from 'storybook-root';
Using AI Code Generation
1const preview = require('storybook-root');2const { storiesOf } = preview;3storiesOf('test', module)4 .add('test', () => {5 return 'test';6 });7const preview = require('storybook-root');8const { storiesOf } = preview;9storiesOf('test', module)10 .add('test', () => {11 return 'test';12 });13MIT © [hupili](
Using AI Code Generation
1import { preview } from 'storybook-root';2preview({3});4import React from 'react';5import { storiesOf } from '@storybook/react';6import { MyComponent } from 'storybook-root';7storiesOf('MyComponent', module).add('default', () => <MyComponent />);8import React from 'react';9import { storiesOf } from '@storybook/react';10import { MyOtherComponent } from 'storybook-root';11storiesOf('MyOtherComponent', module).add('default', () => <MyOtherComponent />);12import React from 'react';13import { storiesOf } from '@storybook/react';14import { MyThirdComponent } from 'storybook-root';15storiesOf('MyThirdComponent', module).add('default', () => <MyThirdComponent />);16import React from 'react';17import { storiesOf } from '@storybook/react';18import { MyFourthComponent } from 'storybook-root';19storiesOf('MyFourthComponent', module).add('default', () => <MyFourthComponent />);20import React from 'react';21import { storiesOf } from '@storybook/react';22import { MyFifthComponent } from 'storybook-root';23storiesOf('MyFifthComponent', module).add('default', () => <MyFifthComponent />);24import React from 'react';25import { storiesOf } from '@storybook/react';26import { MySixthComponent } from 'storybook-root';27storiesOf('MySixthComponent', module).add('default', () => <MySixthComponent />);28import React from 'react';29import { storiesOf } from '@storybook/react';30import { MySeventhComponent } from 'storybook-root';31storiesOf('MySeventhComponent', module).add('default', () => <MySeventhComponent />);32import React from 'react';33import { storiesOf } from '@storybook/react';34import { MyEighthComponent } from 'storybook-root';35storiesOf('My
Using AI Code Generation
1import { preview } from 'storybook-root';2import { stories } from './stories';3preview(stories, { name: 'My App' });4import { storiesOf } from 'storybook-root';5export const stories = storiesOf('My App', module)6 .add('default', () => (7 .add('with props', () => (8 <div>{props.text}</div>9 ));10{11 "scripts": {12 }13}14export const stories = storiesOf('My App', module)15 .add('default', () => (16 .add('with props', () => (17 <div>{props.text}</div>18 ));19import { stories } from './stories';20import { stories } from './stories';21import { preview } from 'storybook-root';22preview(stories, { name: 'My App' });23"scripts": {24}25import { storiesOf } from 'storybook-root';26export const stories = storiesOf('My App', module)27 .add('default', () => (28 .add('with props', () => (29 <div>{props.text}</div>30 ));31import { stories } from './stories';32import { preview } from 'storybook-root';33preview(stories, { name: 'My App' });
Using AI Code Generation
1const { preview } = require('storybook-root');2preview('test story', () => {3 return 'test';4});5preview('test story', () => {6 return 'test';7}, { theme: 'light' });8preview('test story', () => {9 return 'test';10}, { theme: 'dark' });11preview('test story', () => {12 return 'test';13}, { theme: 'light', layout: 'centered' });14preview('test story', () => {15 return 'test';16}, { theme: 'light', layout: 'fullscreen' });17preview('test story', () => {18 return 'test';19}, { theme: 'light', layout: 'padded' });20preview('test story', () => {21 return 'test';22}, { theme: 'light', layout: 'padded', background: 'white' });23preview('test story', () => {24 return 'test';25}, { theme: 'light', layout: 'padded', background: 'black' });26preview('test story', () => {27 return 'test';28}, { theme: 'light', layout: 'padded', background: 'grey' });29preview('test story', () => {30 return 'test';31}, { theme: 'light', layout: 'padded', background: 'red' });32preview('test story', () => {33 return 'test';34}, { theme: 'light', layout: 'padded', background: 'green' });35preview('test story', () => {36 return 'test';37}, { theme: 'light', layout: 'padded', background: 'blue' });38preview('test story', () => {39 return 'test';40}, { theme: '
Using AI Code Generation
1import { preview } from 'storybook-root';2const render = () => {3 const { stories, Storybook } = preview();4 storiesOf('Component', module)5 .addDecorator(withKnobs)6 .add('default', () => (7 stories={stories}8 knobs={{ name: text('name', 'name') }}9 ));10};11export default render;
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!