HtmlStore.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /*
  2. Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
  3. Available via Academic Free License >= 2.1 OR the modified BSD license.
  4. see: http://dojotoolkit.org/license for details
  5. */
  6. if(!dojo._hasResource["dojox.data.HtmlStore"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
  7. dojo._hasResource["dojox.data.HtmlStore"] = true;
  8. dojo.provide("dojox.data.HtmlStore");
  9. dojo.require("dojo.data.util.simpleFetch");
  10. dojo.require("dojo.data.util.filter");
  11. dojo.require("dojox.xml.parser");
  12. dojo.declare("dojox.data.HtmlStore", null, {
  13. constructor: function(/*Object*/args){
  14. // summary:
  15. // Initializer for the HTML table store.
  16. // description:
  17. // The HtmlStore can be created in one of two ways: a) by parsing an existing
  18. // table or list DOM node on the current page or b) by referencing an external url and giving
  19. // the id of the table or list in that page. The remote url will be parsed as an html page.
  20. //
  21. // The HTML table or list should be of the following form:
  22. //
  23. // | <table id="myTable">
  24. // | <thead>
  25. // | <tr>
  26. // | <th>Attribute1</th>
  27. // | <th>Attribute2</th>
  28. // | </tr>
  29. // | </thead>
  30. // | <tbody>
  31. // | <tr>
  32. // | <td>Value1.1</td>
  33. // | <td>Value1.2</td>
  34. // | </tr>
  35. // | <tr>
  36. // | <td>Value2.1</td>
  37. // | <td>Value2.2</td>
  38. // | </tr>
  39. // | </tbody>
  40. // | </table>
  41. //
  42. // -or-
  43. //
  44. // | <ul id="myUnorderedList">
  45. // | <li>Value.1</li>
  46. // | <li>Value.2</li>
  47. // | </ul>
  48. //
  49. // -or-
  50. //
  51. // | <ol id="myOrderedList">
  52. // | <li>Value.1</li>
  53. // | <li>Value.2</li>
  54. // | </ol>
  55. //
  56. // args:
  57. // An anonymous object to initialize properties. It expects the following values:
  58. // dataId: The id of the HTML table to use.
  59. // OR
  60. // url: The url of the remote page to load
  61. // dataId: The id of the table element in the remote page
  62. // and the option:
  63. // trimWhitespace: Trim off any surrounding whitespace from the headers (attribute
  64. // names) and text content of the items in question. Default is false for
  65. // backwards compatibility.
  66. if(args && "urlPreventCache" in args){
  67. this.urlPreventCache = args.urlPreventCache?true:false;
  68. }
  69. if(args && "trimWhitespace" in args){
  70. this.trimWhitespace = args.trimWhitespace?true:false;
  71. }
  72. if(args.url){
  73. if(!args.dataId){
  74. throw new Error("dojo.data.HtmlStore: Cannot instantiate using url without an id!");
  75. }
  76. this.url = args.url;
  77. this.dataId = args.dataId;
  78. }else{
  79. if(args.dataId){
  80. this.dataId = args.dataId;
  81. }
  82. }
  83. if(args && "fetchOnCreate" in args){
  84. this.fetchOnCreate = args.fetchOnCreate?true:false;
  85. }
  86. if(this.fetchOnCreate && this.dataId){
  87. this.fetch();
  88. }
  89. },
  90. // url: [public] string
  91. // The URL from which to load an HTML document for data loading
  92. url: "",
  93. // dataId: [public] string
  94. // The id in the document for an element from which to get the data.
  95. dataId: "",
  96. // trimWhitepace: [public] boolean
  97. // Boolean flag to denote if the store should trim whitepace around
  98. // header and data content of a node. This matters if reformatters
  99. // alter the white spacing around the tags. The default is false for
  100. // backwards compat.
  101. trimWhitespace: false,
  102. // urlPreventCache: [public] boolean
  103. // Flag to denote if peventCache should be used on xhrGet calls.
  104. urlPreventCache: false,
  105. // fetchOnCreate: [public] boolean
  106. // Flag to denote if it should try to load from a data id (nested in the page)
  107. // The moment the store is created, instead of waiting for first
  108. // fetch call.
  109. fetchOnCreate: false,
  110. _indexItems: function(){
  111. // summary:
  112. // Function to index items found under the id.
  113. // tags:
  114. // private
  115. this._getHeadings();
  116. if(this._rootNode.rows){//tables
  117. if(this._rootNode.tBodies && this._rootNode.tBodies.length > 0){
  118. this._rootNode = this._rootNode.tBodies[0];
  119. }
  120. var i;
  121. for(i=0; i<this._rootNode.rows.length; i++){
  122. this._rootNode.rows[i]._ident = i+1;
  123. }
  124. }else{//lists
  125. var c=1;
  126. for(i=0; i<this._rootNode.childNodes.length; i++){
  127. if(this._rootNode.childNodes[i].nodeType === 1){
  128. this._rootNode.childNodes[i]._ident = c;
  129. c++;
  130. }
  131. }
  132. }
  133. },
  134. _getHeadings: function(){
  135. // summary:
  136. // Function to load the attribute names from the table header so that the
  137. // attributes (cells in a row), can have a reasonable name.
  138. // For list items, returns single implicit heading, ["name"]
  139. this._headings = [];
  140. if(this._rootNode.tHead){
  141. dojo.forEach(this._rootNode.tHead.rows[0].cells, dojo.hitch(this, function(th){
  142. var text = dojox.xml.parser.textContent(th);
  143. this._headings.push(this.trimWhitespace?dojo.trim(text):text);
  144. }));
  145. }else{
  146. this._headings = ["name"];
  147. }
  148. },
  149. _getAllItems: function(){
  150. // summary:
  151. // Function to return all rows in the table as an array of items.
  152. var items = [];
  153. var i;
  154. if(this._rootNode.rows){//table
  155. for(i=0; i<this._rootNode.rows.length; i++){
  156. items.push(this._rootNode.rows[i]);
  157. }
  158. }else{ //list
  159. for(i=0; i<this._rootNode.childNodes.length; i++){
  160. if(this._rootNode.childNodes[i].nodeType === 1){
  161. items.push(this._rootNode.childNodes[i]);
  162. }
  163. }
  164. }
  165. return items; //array
  166. },
  167. _assertIsItem: function(/* item */ item){
  168. // summary:
  169. // This function tests whether the item passed in is indeed an item in the store.
  170. // item:
  171. // The item to test for being contained by the store.
  172. if(!this.isItem(item)){
  173. throw new Error("dojo.data.HtmlStore: a function was passed an item argument that was not an item");
  174. }
  175. },
  176. _assertIsAttribute: function(/* String */ attribute){
  177. // summary:
  178. // This function tests whether the item passed in is indeed a valid 'attribute' like type for the store.
  179. // attribute:
  180. // The attribute to test for being contained by the store.
  181. //
  182. // returns:
  183. // Returns the index (column) that the attribute resides in the row.
  184. if(typeof attribute !== "string"){
  185. throw new Error("dojo.data.HtmlStore: a function was passed an attribute argument that was not an attribute name string");
  186. return -1;
  187. }
  188. return dojo.indexOf(this._headings, attribute); //int
  189. },
  190. /***************************************
  191. dojo.data.api.Read API
  192. ***************************************/
  193. getValue: function( /* item */ item,
  194. /* attribute-name-string */ attribute,
  195. /* value? */ defaultValue){
  196. // summary:
  197. // See dojo.data.api.Read.getValue()
  198. var values = this.getValues(item, attribute);
  199. return (values.length > 0)?values[0]:defaultValue; //Object || int || Boolean
  200. },
  201. getValues: function(/* item */ item,
  202. /* attribute-name-string */ attribute){
  203. // summary:
  204. // See dojo.data.api.Read.getValues()
  205. this._assertIsItem(item);
  206. var index = this._assertIsAttribute(attribute);
  207. if(index>-1){
  208. var text;
  209. if(item.cells){
  210. text = dojox.xml.parser.textContent(item.cells[index]);
  211. }else{//return Value for lists
  212. text = dojox.xml.parser.textContent(item);
  213. }
  214. return [this.trimWhitespace?dojo.trim(text):text];
  215. }
  216. return []; //Array
  217. },
  218. getAttributes: function(/* item */ item){
  219. // summary:
  220. // See dojo.data.api.Read.getAttributes()
  221. this._assertIsItem(item);
  222. var attributes = [];
  223. for(var i=0; i<this._headings.length; i++){
  224. if(this.hasAttribute(item, this._headings[i]))
  225. attributes.push(this._headings[i]);
  226. }
  227. return attributes; //Array
  228. },
  229. hasAttribute: function( /* item */ item,
  230. /* attribute-name-string */ attribute){
  231. // summary:
  232. // See dojo.data.api.Read.hasAttribute()
  233. return this.getValues(item, attribute).length > 0;
  234. },
  235. containsValue: function(/* item */ item,
  236. /* attribute-name-string */ attribute,
  237. /* anything */ value){
  238. // summary:
  239. // See dojo.data.api.Read.containsValue()
  240. var regexp = undefined;
  241. if(typeof value === "string"){
  242. regexp = dojo.data.util.filter.patternToRegExp(value, false);
  243. }
  244. return this._containsValue(item, attribute, value, regexp); //boolean.
  245. },
  246. _containsValue: function( /* item */ item,
  247. /* attribute-name-string */ attribute,
  248. /* anything */ value,
  249. /* RegExp?*/ regexp){
  250. // summary:
  251. // Internal function for looking at the values contained by the item.
  252. // description:
  253. // Internal function for looking at the values contained by the item. This
  254. // function allows for denoting if the comparison should be case sensitive for
  255. // strings or not (for handling filtering cases where string case should not matter)
  256. //
  257. // item:
  258. // The data item to examine for attribute values.
  259. // attribute:
  260. // The attribute to inspect.
  261. // value:
  262. // The value to match.
  263. // regexp:
  264. // Optional regular expression generated off value if value was of string type to handle wildcarding.
  265. // If present and attribute values are string, then it can be used for comparison instead of 'value'
  266. var values = this.getValues(item, attribute);
  267. for(var i = 0; i < values.length; ++i){
  268. var possibleValue = values[i];
  269. if(typeof possibleValue === "string" && regexp){
  270. return (possibleValue.match(regexp) !== null);
  271. }else{
  272. //Non-string matching.
  273. if(value === possibleValue){
  274. return true; // Boolean
  275. }
  276. }
  277. }
  278. return false; // Boolean
  279. },
  280. isItem: function(/* anything */ something){
  281. // summary:
  282. // See dojo.data.api.Read.isItem()
  283. return something && dojo.isDescendant(something, this._rootNode);
  284. },
  285. isItemLoaded: function(/* anything */ something){
  286. // summary:
  287. // See dojo.data.api.Read.isItemLoaded()
  288. return this.isItem(something);
  289. },
  290. loadItem: function(/* Object */ keywordArgs){
  291. // summary:
  292. // See dojo.data.api.Read.loadItem()
  293. this._assertIsItem(keywordArgs.item);
  294. },
  295. _fetchItems: function(request, fetchHandler, errorHandler){
  296. // summary:
  297. // Fetch items (XML elements) that match to a query
  298. // description:
  299. // If '_fetchUrl' is specified, it is used to load an XML document
  300. // with a query string.
  301. // Otherwise and if 'url' is specified, the XML document is
  302. // loaded and list XML elements that match to a query (set of element
  303. // names and their text attribute values that the items to contain).
  304. // A wildcard, "*" can be used to query values to match all
  305. // occurrences.
  306. // If '_rootItem' is specified, it is used to fetch items.
  307. // request:
  308. // A request object
  309. // fetchHandler:
  310. // A function to call for fetched items
  311. // errorHandler:
  312. // A function to call on error
  313. if(this._rootNode){
  314. this._finishFetchItems(request, fetchHandler, errorHandler);
  315. }else{
  316. if(!this.url){
  317. this._rootNode = dojo.byId(this.dataId);
  318. this._indexItems();
  319. this._finishFetchItems(request, fetchHandler, errorHandler);
  320. }else{
  321. var getArgs = {
  322. url: this.url,
  323. handleAs: "text",
  324. preventCache: this.urlPreventCache
  325. };
  326. var self = this;
  327. var getHandler = dojo.xhrGet(getArgs);
  328. getHandler.addCallback(function(data){
  329. var findNode = function(node, id){
  330. if(node.id == id){
  331. return node; //object
  332. }
  333. if(node.childNodes){
  334. for(var i=0; i<node.childNodes.length; i++){
  335. var returnNode = findNode(node.childNodes[i], id);
  336. if(returnNode){
  337. return returnNode; //object
  338. }
  339. }
  340. }
  341. return null; //null
  342. }
  343. var d = document.createElement("div");
  344. d.innerHTML = data;
  345. self._rootNode = findNode(d, self.dataId);
  346. self._indexItems();
  347. self._finishFetchItems(request, fetchHandler, errorHandler);
  348. });
  349. getHandler.addErrback(function(error){
  350. errorHandler(error, request);
  351. });
  352. }
  353. }
  354. },
  355. _finishFetchItems: function(request, fetchHandler, errorHandler){
  356. // summary:
  357. // Internal function for processing the passed in request and locating the requested items.
  358. var items = [];
  359. var arrayOfAllItems = this._getAllItems();
  360. if(request.query){
  361. var ignoreCase = request.queryOptions ? request.queryOptions.ignoreCase : false;
  362. items = [];
  363. //See if there are any string values that can be regexp parsed first to avoid multiple regexp gens on the
  364. //same value for each item examined. Much more efficient.
  365. var regexpList = {};
  366. var key;
  367. var value;
  368. for(key in request.query){
  369. value = request.query[key]+'';
  370. if(typeof value === "string"){
  371. regexpList[key] = dojo.data.util.filter.patternToRegExp(value, ignoreCase);
  372. }
  373. }
  374. for(var i = 0; i < arrayOfAllItems.length; ++i){
  375. var match = true;
  376. var candidateItem = arrayOfAllItems[i];
  377. for(key in request.query){
  378. value = request.query[key]+'';
  379. if(!this._containsValue(candidateItem, key, value, regexpList[key])){
  380. match = false;
  381. }
  382. }
  383. if(match){
  384. items.push(candidateItem);
  385. }
  386. }
  387. fetchHandler(items, request);
  388. }else{
  389. // We want a copy to pass back in case the parent wishes to sort the array. We shouldn't allow resort
  390. // of the internal list so that multiple callers can get listsand sort without affecting each other.
  391. if(arrayOfAllItems.length> 0){
  392. items = arrayOfAllItems.slice(0,arrayOfAllItems.length);
  393. }
  394. fetchHandler(items, request);
  395. }
  396. },
  397. getFeatures: function(){
  398. // summary:
  399. // See dojo.data.api.Read.getFeatures()
  400. return {
  401. 'dojo.data.api.Read': true,
  402. 'dojo.data.api.Identity': true
  403. };
  404. },
  405. close: function(/*dojo.data.api.Request || keywordArgs || null */ request){
  406. // summary:
  407. // See dojo.data.api.Read.close()
  408. // nothing to do here!
  409. },
  410. getLabel: function(/* item */ item){
  411. // summary:
  412. // See dojo.data.api.Read.getLabel()
  413. if(this.isItem(item)){
  414. if(item.cells){
  415. return "Item #" + this.getIdentity(item);
  416. }else{
  417. return this.getValue(item,"name");
  418. }
  419. }
  420. return undefined;
  421. },
  422. getLabelAttributes: function(/* item */ item){
  423. // summary:
  424. // See dojo.data.api.Read.getLabelAttributes()
  425. if(item.cells){
  426. return null;
  427. }else{
  428. return ["name"];
  429. }
  430. },
  431. /***************************************
  432. dojo.data.api.Identity API
  433. ***************************************/
  434. getIdentity: function(/* item */ item){
  435. // summary:
  436. // See dojo.data.api.Identity.getIdentity()
  437. this._assertIsItem(item);
  438. if(this.hasAttribute(item, "name")){
  439. return this.getValue(item,"name");
  440. }else{
  441. return item._ident;
  442. }
  443. },
  444. getIdentityAttributes: function(/* item */ item){
  445. // summary:
  446. // See dojo.data.api.Identity.getIdentityAttributes()
  447. //Identity isn't taken from a public attribute.
  448. return null;
  449. },
  450. fetchItemByIdentity: function(keywordArgs){
  451. // summary:
  452. // See dojo.data.api.Identity.fetchItemByIdentity()
  453. var identity = keywordArgs.identity;
  454. var self = this;
  455. var item = null;
  456. var scope = null;
  457. if(!this._rootNode){
  458. if(!this.url){
  459. this._rootNode = dojo.byId(this.dataId);
  460. this._indexItems();
  461. if(self._rootNode.rows){ //Table
  462. item = this._rootNode.rows[identity + 1];
  463. }else{ //Lists
  464. for(var i = 0; i < self._rootNode.childNodes.length; i++){
  465. if(self._rootNode.childNodes[i].nodeType === 1 && identity === dojox.xml.parser.textContent(self._rootNode.childNodes[i])){
  466. item = self._rootNode.childNodes[i];
  467. }
  468. }
  469. }
  470. if(keywordArgs.onItem){
  471. scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
  472. keywordArgs.onItem.call(scope, item);
  473. }
  474. }else{
  475. var getArgs = {
  476. url: this.url,
  477. handleAs: "text"
  478. };
  479. var getHandler = dojo.xhrGet(getArgs);
  480. getHandler.addCallback(function(data){
  481. var findNode = function(node, id){
  482. if(node.id == id){
  483. return node; //object
  484. }
  485. if(node.childNodes){
  486. for(var i=0; i<node.childNodes.length; i++){
  487. var returnNode = findNode(node.childNodes[i], id);
  488. if(returnNode){
  489. return returnNode; //object
  490. }
  491. }
  492. }
  493. return null; //null
  494. }
  495. var d = document.createElement("div");
  496. d.innerHTML = data;
  497. self._rootNode = findNode(d, self.dataId);
  498. self._indexItems();
  499. if(self._rootNode.rows && identity <= self._rootNode.rows.length){ //Table
  500. item = self._rootNode.rows[identity-1];
  501. }else{ //List
  502. for(var i = 0; i < self._rootNode.childNodes.length; i++){
  503. if(self._rootNode.childNodes[i].nodeType === 1 && identity === dojox.xml.parser.textContent(self._rootNode.childNodes[i])){
  504. item = self._rootNode.childNodes[i];
  505. break;
  506. }
  507. }
  508. }
  509. if(keywordArgs.onItem){
  510. scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
  511. keywordArgs.onItem.call(scope, item);
  512. }
  513. });
  514. getHandler.addErrback(function(error){
  515. if(keywordArgs.onError){
  516. scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
  517. keywordArgs.onError.call(scope, error);
  518. }
  519. });
  520. }
  521. }else{
  522. if(this._rootNode.rows[identity+1]){
  523. item = this._rootNode.rows[identity+1];
  524. if(keywordArgs.onItem){
  525. scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
  526. keywordArgs.onItem.call(scope, item);
  527. }
  528. }
  529. }
  530. }
  531. });
  532. dojo.extend(dojox.data.HtmlStore,dojo.data.util.simpleFetch);
  533. }