home *** CD-ROM | disk | FTP | other *** search
/ Practical Internet Web Designer 86 / PIWD86.iso / pc / contents / dreamweaver / software / dwmx2004.exe / Disk1 / data1.cab / Configuration_En / Commands / Tabular Data.js < prev    next >
Encoding:
JavaScript  |  2003-09-05  |  14.3 KB  |  448 lines

  1. // Copyright 2000, 2001, 2002, 2003 Macromedia, Inc. All rights reserved
  2.  
  3. //---------------   GLOBAL VARIABLES   ---------------
  4.  
  5. var helpDoc = MM.HELP_objTabularData;
  6.  
  7. //---------------     API FUNCTIONS    ---------------
  8.  
  9. function isDOMRequired() { 
  10.     // Return false, indicating that this object is available in code view.
  11.     // This means this object/command is guaranteed to not use the DOM of the current document,
  12.     // except for dw.getDocumentDOM().source...
  13.     return false;
  14. }
  15.  
  16. function commandButtons(){
  17.    return new Array(MM.BTN_OK,         "createTableStr()",
  18.                     MM.BTN_Cancel,     "window.close()",
  19.                     MM.BTN_Help,       "displayHelp()" );
  20. }
  21.  
  22. //---------------    LOCAL FUNCTIONS   ---------------
  23.  
  24. function setTableFileToImport() {
  25.   var fName = dw.browseForFileURL('open','', false, true);
  26.   if (fName) {
  27.     document.forms[0].DataFile.value =  fName;
  28.     setDelimiter(fName);
  29.   }
  30. }
  31.  
  32. //function:setDelimiter
  33. //description: after choosing a file, set delimiter select menu
  34. //based on file type, e.g.: set it to Comma if a *.csv file is chosen
  35.  
  36. function setDelimiter(fileName){
  37.    var selDelimiter = document.forms[0].Delimiter;
  38.    var extension = fileName.substring(  fileName.indexOf(".")  );
  39.    
  40.    if (extension==".csv")   selDelimiter.selectedIndex = 1; //comma
  41.    if (extension==".xls")   alert( ERROR_Unsupported_Format + ERROR_Supported_Formats);
  42.    //if we support more formats in the future
  43.    //such as space-delimited (.csv), more checks may be added here
  44. }
  45.  
  46. //function:getDelimiter
  47. //description: returns user-chosen delimiter based on form parameters
  48.  
  49. function getDelimiter(theForm){
  50.    var retVal;
  51.    var selInd = theForm.Delimiter.selectedIndex;
  52.    
  53.    switch (selInd){
  54.       case 0:
  55.         retVal = "\t";   
  56.         break;
  57.      case 1:
  58.         retVal = ",";
  59.         break;
  60.      case 2:
  61.         retVal = ";";
  62.         break;
  63.      case 3:
  64.         retVal = ":";
  65.         break;
  66.      case 4:
  67.         retVal = theForm.CustomDelimiter.value;
  68.         break;
  69.    }
  70.    return retVal;
  71. }
  72.  
  73. //function: getNewLineChar
  74. //description: returns newline character
  75.  
  76. function getNewLineChar(dataStr){
  77.    var retVal;
  78.    
  79.    if (  dataStr.search("\r\n")!= -1)
  80.       retVal = "\r\n";
  81.    else if (  dataStr.search("\n")!= -1)
  82.       retVal="\n";
  83.    else
  84.       retVal="\r";
  85.      
  86.    return retVal;
  87.    
  88. }
  89.  
  90.  
  91. //function: getFormatTags
  92. //description: returns a two-item array representing opening and closing 
  93. //format tags to be used in the first row based on FormatTopRow form parameter
  94.  
  95. function getFormatTags(theForm){
  96.    var retVal = new Array("","");
  97.    var selInd = theForm.FormatTopRow.selectedIndex;
  98.    
  99.    switch (selInd){
  100.       case 1:
  101.         retVal[0] = "<b>";
  102.          retVal[1] = "</b>";
  103.        break;
  104.      case 2:
  105.         retVal[0] = "<i>";
  106.         retVal[1] = "</i>";
  107.        break;
  108.      case 3:
  109.         retVal[0] = "<b><i>";
  110.         retVal[1] = "</i></b>";
  111.        break;  
  112.    }
  113.    return retVal;
  114. }
  115.  
  116.  
  117. //function: createTableStr
  118. //description: creates the html table based on the form parameters
  119.  
  120. function createTableStr(){
  121.    var theForm = document.forms[0];
  122.    var delimiter = getDelimiter(theForm);
  123.    if (!delimiter){
  124.       alert(ERROR_No_Delimiter);
  125.      return;
  126.    }
  127.    if (delimiter.length>1){
  128.       alert(ERROR_Incorrect_Delimiter);
  129.      return;
  130.    }
  131.    var bAutoWidth = theForm.Width[0].checked;
  132.    if (!bAutoWidth){
  133.       var unitChoice = (theForm.WidthUnit.selectedIndex==0)?'%':'';
  134.      var width = theForm.WidthValue.value + unitChoice;
  135.    }
  136.    var cellSpacing = theForm.CellSpacing.value;
  137.    var cellPadding = theForm.CellPadding.value;
  138.    var border = theForm.Border.value;
  139.    var formatFirstRowArr = getFormatTags(theForm);   
  140.    var openTag = createOpenTableTag(width,border,cellSpacing,cellPadding);
  141.    
  142.    var dataFile = theForm.DataFile.value;
  143.    if ( dataFile && dataFile.substring(dataFile.lastIndexOf(".")) == ".xls"){
  144.       alert(ERROR_Unsupported_Format + ERROR_Supported_Formats);
  145.      return;
  146.    }
  147.    
  148.    var tableFileURL = getFullPath(dataFile);
  149.    if (  !verifyFilePath(tableFileURL)  )
  150.       return;
  151.      
  152.    MM.setBusyCursor();
  153.    var dataStr = DWfile.read(tableFileURL);
  154.    var newline = getNewLineChar(dataStr);
  155.    
  156.    if (dw.getFocus(true) == "html" || dw.getFocus() == "textView") {
  157.          selArray = dw.getDocumentDOM().source.getSelection();
  158.       dw.getDocumentDOM().source.replaceRange(selArray[0], selArray[1], 
  159.           openTag + createTableBody(dataStr,delimiter,newline,formatFirstRowArr) + 
  160.                "</TABLE>");
  161.    } else {    
  162.          dw.getDocumentDOM().insertHTML( openTag + createTableBody(dataStr,delimiter,newline,formatFirstRowArr) + 
  163.                "</TABLE>" );
  164.    }
  165.  
  166.    MM.clearBusyCursor();
  167.  
  168.    // save settings for next time
  169.    dwscripts.saveExtension(document,["DataFile"]);
  170.  
  171.    window.close();
  172.   
  173. }
  174.  
  175. //function: verifyFilePath
  176. //description: verify that file path is not null and is correct
  177. //and alert correct error message in each case
  178. //returns: true if valid, false if invalid
  179.  
  180. function verifyFilePath(fileURL){
  181.    retVal = true;
  182.    
  183.    //if no file path or incorrect file path, alert error message
  184.    if ( !fileURL ){
  185.       alert(ERROR_No_File)
  186.       retVal=false;
  187.    } else if (  !DWfile.exists( fileURL)  ){
  188.       alert(ERROR_Incorrect_File_Path)
  189.       retVal=false;
  190.    }
  191.    return retVal;
  192. }
  193.  
  194. //function: createOpenTableTag
  195. //description: creates an open table tag based on argument values
  196.  
  197.  function createOpenTableTag(width,border,cellSpacing,cellPadding){
  198.     var openTag = '<TABLE';
  199.    
  200.    if (width)         openTag +=' width="' + width + '"';
  201.    if (border)        openTag +=' border="' + border + '"';
  202.    if (cellSpacing)   openTag +=' cellspacing="' + cellSpacing + '"';
  203.    if (cellPadding)   openTag +=' cellpadding="' + cellPadding + '"';
  204.    
  205.    return openTag + '>';
  206.  
  207.  }
  208.  
  209. //function: getTableCells
  210. //description:returns an array of the table cell data.
  211. //Parses row data to take into account cases where
  212. //the delimiter is included in the cell.
  213. //For example, if the delimiter is a comma
  214. //ensures we don't divide the data at the comma in "Doe, Jane".
  215. //Note:Excel places double quotes around data with reserved characters
  216. //and surrounds double quotes with quotes.
  217. //Examples:
  218. //Excel (.xls file)  ->  Delimited file
  219. //Doe,Jane    ->       "Doe,Jane"
  220. //My name is "Jane" ->  "My name is ""Jane"""
  221. //
  222. //Arguments:
  223. //rowData - text string from original file that represents
  224. //one row of data
  225. //delimiter - character used to separate entries
  226.  
  227.  
  228.  function getTableCells(rowData,delimiter){
  229.     var retArr = new Array();
  230.    var startingOffset = 0;
  231.    var endingOffset = 0;
  232.    var cellData="";
  233.    var qualifier='"'; //qualifer is double quotes
  234.    var dataLen=0;
  235.    var rowDataLen = 0;
  236.    var qualifierCount = 0;
  237.    var i,j;
  238.    var lastInd;
  239.    
  240.    // Optimization
  241.    //if tab-delimited, just split data at tabs and return.
  242.    if (delimiter == "\t") {
  243.       retArr = rowData.split(delimiter);
  244.       return retArr;
  245.    }
  246.    
  247.    
  248.    //When we encounter a delimiter, we want to determine if the
  249.    //the delimiter is separating data: e.g: a,b,c, or
  250.    //if it included in the cell data: "Doe, Jane"
  251.    //To accomplish this goal, we count the number of double quotes
  252.    //between the beginning of the data and the delimiter character 
  253.    //that we find.
  254.    //If this number is even, we have completed getting the cell data.
  255.    //If it is odd, the cell data is not complete so we step
  256.    //through until reaching the next delimiter and repeat the 
  257.    //double-quote test.
  258.    
  259.    rowDataLen = rowData.length;
  260.    lastInd = rowDataLen - 1;
  261.    for (i=0;i<rowDataLen;i++){
  262.  
  263.       if (  rowData.charAt(i)==delimiter || i == lastInd ){
  264.          endingOffset = i;
  265.         if (  i!=lastInd || rowData.charAt(lastInd) == delimiter  ){
  266.            cellData = rowData.substring(startingOffset,endingOffset);
  267.         } else {
  268.            cellData = rowData.substring(startingOffset);
  269.         }       
  270.         //The way we are dividing the data, the delimiter character
  271.         //is the first character in all but the first data string
  272.         //We want to delete it.
  273.         if ( cellData[0] == delimiter ){
  274.            if (  cellData.charAt(1)  )
  275.              cellData = cellData.substring(1);
  276.            else
  277.              cellData = "";
  278.         }
  279.       
  280.         //Go through the cell data and count the number of double quotes
  281.         //I've assigned the double quotes to a qualifier variable
  282.         //to make it easy to allow custom qualifiers in future versions
  283.         if (cellData){
  284.            dataLen = cellData.length;
  285.            for (j=0;j<dataLen;j++){
  286.               if (cellData.charAt(j) == qualifier)
  287.                 qualifierCount++;
  288.            }
  289.         }
  290.  
  291.         //if this is the complete cell data, add it to the return array
  292.         //and reset start offset to the end of the cell data we have
  293.         //just processed
  294.         if (qualifierCount%2==0){ 
  295.            retArr[retArr.length] = cellData;  
  296.           startingOffset = endingOffset; 
  297.         } 
  298.       }
  299.       qualifierCount=0;
  300.    }
  301.    //if far right cell is blank, add last cell to return array:
  302.    if (  rowData.charAt( lastInd )==delimiter  )
  303.       retArr[retArr.length] = "";
  304.  
  305.    return retArr; // Note: optimization return at beginning of function.
  306. }
  307.  
  308.  
  309.  //function: createTable
  310.  //description: creates the body of the table based on the contents of the
  311.  //tabular data file. Parses contents of tabular data file.
  312.  
  313. function createTableBody(dataStr, colDelim, rowDelim, formatFirstRowArr) {
  314.   var openCellFormat = '<td>' + formatFirstRowArr[0];
  315.   var closeCellFormat = formatFirstRowArr[1] + '</td>';
  316.   var emptyFormat = '<td> </td>';
  317.   var escapeChar = '"';
  318.   var rtnArr = new Array();
  319.   var startLoc = 0, curRow = new Array();
  320.   var curRow = new Array();
  321.   var curChar, escapedStr = '';
  322.   var cellContents = '';
  323.   
  324.   // Collect rows of data.
  325.   for (var curLoc = 0; curLoc < dataStr.length; curLoc++) {
  326.     curChar = dataStr.charAt(curLoc);
  327.     if (curChar == escapeChar) {
  328.       escapedStr = '';
  329.       // Ignore everything until we get to the ending escape character.
  330.       for (curLoc++; curLoc < dataStr.length; curLoc++) {
  331.         curChar = dataStr.charAt(curLoc);
  332.         // Look for the ending escape character
  333.         if (curChar == escapeChar) { // Possibly ending escape character
  334.           if (dataStr.charAt(curLoc) == dataStr.charAt(curLoc+1)) {
  335.             // Nope, just the escaped escape character.
  336.             escapedStr += dataStr.substring(startLoc+1,curLoc+1);
  337.             // Save the string and keep looking.
  338.             curLoc++; // Throw away the extra escape character.
  339.             startLoc = curLoc;
  340.           } else {
  341.             // Found the terminating escape
  342.             escapedStr += dataStr.substring(startLoc+1,curLoc).replace(/(\r\n)|[\r\n]/g,'<br>');
  343.             startLoc = curLoc+1;
  344.             break; // Break out of inner for loop.
  345.           }
  346.         }
  347.       }
  348.     } else if (curChar == colDelim) {
  349.       cellContents = escapedStr + dataStr.substring(startLoc,curLoc);
  350.       if (cellContents) {
  351.          curRow.push(openCellFormat + cellContents + closeCellFormat);
  352.       } else {
  353.          curRow.push(emptyFormat);
  354.       }
  355.       escapedStr = '';
  356.       startLoc = curLoc+1;
  357.  
  358.     } else if (curChar == rowDelim.charAt(0)) {
  359.       cellContents = escapedStr + dataStr.substring(startLoc,curLoc);
  360.       if (cellContents) {
  361.          curRow.push(openCellFormat + cellContents + closeCellFormat);
  362.       } else {
  363.          curRow.push(emptyFormat);
  364.       }
  365.       openCellFormat = '<td>';
  366.       closeCellFormat = '</td>';
  367.       escapedStr = '';
  368.       startLoc = curLoc + rowDelim.length;
  369.       rtnArr.push('<tr>' + curRow.join('') + '</tr>');
  370.       curRow = new Array();
  371.     }
  372.   }
  373.   cellContents = escapedStr + dataStr.substring(startLoc,curLoc);
  374.   if (cellContents) {
  375.      curRow.push(openCellFormat + cellContents + closeCellFormat);
  376.   } else if (curRow.length > 0) {
  377.      curRow.push(emptyFormat);
  378.   }
  379.   if (curRow.length > 0) {
  380.     rtnArr.push('<tr>' + curRow.join('') + '</tr>');
  381.   }
  382.   return rtnArr.join('');
  383. }
  384.  
  385.  
  386. //function: toggleCustomField
  387. //description: if Other is chosen in the Delimiter Type select list,
  388. //this function makes a text entry field dynamically appear. Also
  389. //hides it if Other is not chosen
  390.  
  391. function toggleCustomField(optionText){
  392.    // Ignore OptionText because it is localized.
  393.    var theForm = document.forms[0];
  394.    // The "other" option is always last, check if the last option is selected.
  395.    if (theForm.Delimiter.options.length==(theForm.Delimiter.selectedIndex+1)){
  396.       findObject("DelimiterSpan").innerHTML = '<input type="text" maxlength="1" name="CustomDelimiter" size="7">';
  397.    } else {
  398.       findObject("DelimiterSpan").innerHTML = '';
  399.    }
  400. }
  401.  
  402.  
  403. //function: innitializeUI
  404. //description: loads the select menus with localized text strings
  405. //and performs other tasks relating to initializing the UI
  406.  
  407. function initializeUI(){
  408.  
  409.    var theForm = document.forms[0];
  410.  
  411.    //If "other" is chosen in the delimiter type select widget, a
  412.    //text field is dynamically added allowing the user to enter a
  413.    //custom delimiter.
  414.    //If this happens, the height of the table cell is re-calculated
  415.    //(which is visually jarring) unless we include a text field in the 
  416.    //table row when loading the file. the line below hides this field:
  417.    findObject("DelimiterSpan").innerHTML="";
  418.    
  419.    //put focus in data file name field
  420.    theForm.DataFile.focus();
  421.    
  422.    //place localized text strings in select widgets
  423.    //variable name note: variable names preceded by sel
  424.    //indicate a select widget object
  425.    
  426.    var selDelimiter = theForm.Delimiter;
  427.    var selFormatTopRow = theForm.FormatTopRow;
  428.    var selWidthUnit = theForm.WidthUnit;
  429.    
  430.    loadSelectList(selDelimiter,OPTIONS_Delimiters);
  431.    loadSelectList(selFormatTopRow,OPTIONS_Formatting);
  432.    loadSelectList(selWidthUnit,OPTIONS_Units);
  433.    enableBuddy("true")
  434. }
  435.  
  436. function enableBuddy(OnOff){
  437.    var theForm = document.forms[0];
  438.    var selWidthUnit = theForm.WidthUnit;
  439.  
  440.    if (OnOff=="true") {
  441.       selWidthUnit.setAttribute("disabled","disabled");
  442.       theForm.WidthValue.setAttribute("disabled","disabled");    
  443.    } else {
  444.       selWidthUnit.removeAttribute("disabled");
  445.       theForm.WidthValue.removeAttribute("disabled");    
  446.    }
  447. }
  448.